=B$'+' '+r'$tanh(\\frac{B}{kT})$', fontsize=20, bbox=dict(facecolor='b', alpha=0.3))\nplt.legend(loc='upper left',numpoints=1)\nplt.show()\n\n","sub_path":"bin/a) sin acople/EvsT.py","file_name":"EvsT.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"486584199","text":"class Link:\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\n def __str__(self):\n if not self.next:\n return f\"Link({self.val})\"\n return f\"Link({self.val}, {self.next})\"\n\n\ndef merge_k_linked_lists(linked_lists):\n '''\n Merge k sorted linked lists into one\n sorted linked list.\n >>> print(merge_k_linked_lists([\n ... Link(1, Link(2)),\n ... Link(3, Link(4))\n ... ]))\n Link(1, Link(2, Link(3, Link(4))))\n >>> print(merge_k_linked_lists([\n ... Link(1, Link(2)),\n ... Link(2, Link(4)),\n ... Link(3, Link(3)),\n ... ]))\n Link(1, Link(2, Link(2, Link(3, Link(3, Link(4))))))\n '''\n # brute force solution\n # put all the values of all the linked list into a list\n # sort the list and create a final list from those values\n # k - length of linked_lists\n # n - max length of any linked list\n # k*n - upper bound of the number of values in all linked lists\n values = []\n # O(k*n)\n for link in linked_lists: # O(k)\n # O(n)\n while link:\n values.append(link.val)\n link = link.next\n\n # O(k*n*log(k*n))\n sorted_vals = sorted(values)\n\n result = Link(0)\n pointer = result\n # O(k*n)\n for val in sorted_vals:\n pointer.next = Link(val)\n pointer = pointer.next\n\n # Final runtime: O(k*n*log(k*n))\n return result.next\n","sub_path":"Interview-Preparation/Section 4 Part 3 - Hard Interview Question - Brute Force.py","file_name":"Section 4 Part 3 - Hard Interview Question - Brute Force.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"65979797","text":"# coding=utf-8\n\n\"\"\"\n1. 考虑守门员,+ 前锋/中场组合 + 后卫组合 = 最终形成足球团队\n2. 考虑constraint, 对足球团队进行剪枝\n\"\"\"\n\n\nfrom PES2018 import Players_Graph, Players_Attr\nimport openpyxl\nimport math\nimport sys\n\n\n# 定义守门员类\nclass Goalkeeper:\n\n def __init__(self, g_id):\n self.id = g_id\n self.ability = []\n self.rating = 0\n self.salary = 0\n\n def get_id(self):\n return self.id\n\n def get_ability(self):\n return self.ability\n\n def get_rating(self):\n return self.rating\n\n def get_salary(self):\n return self.salary\n\n\n# 定义被剪枝球员类\nclass CutPlayer:\n\n def __init__(self, key):\n self.id = key # 球员ID\n self.cut_pos = \"\" # 球员所属的网络\n self.cut_position = \"\" # 球员的位置\n self.cut_salary = 0 # 球员的工资\n\n def get_id(self):\n return self.id\n\n def get_cut_pos(self):\n return self.cut_pos\n\n def get_cut_position(self):\n return self.cut_position\n\n def get_cut_salary(self):\n return self.cut_salary\n\n\n# 选择守门员\ndef select_goalkeeper(path, file_name):\n # open source\n wb = openpyxl.load_workbook(path+file_name)\n ws = wb[\"GoalKeeper\"]\n\n goal_keepers = read_goalkeeper(ws)\n\n # find the best goalkeeper\n opt_gk = ''\n score_max = 0\n for gk in goal_keepers:\n # 计算守门员的平均分\n gk_score = sum(gk.ability) / len(gk.ability)\n if score_max < gk_score:\n score_max = gk_score\n opt_gk = gk\n\n print(\"无约束条件下选择出的最佳守门员是:\", opt_gk.id)\n\n return opt_gk, goal_keepers\n\n\n# 读取Goalkeeper文件\ndef read_goalkeeper(ws):\n\n goal_keepers = []\n\n for row in range(2, ws.max_row+1): # 第二行起表示球员信息\n gk_id = ws.cell(row=row, column=1).value\n gk = Goalkeeper(gk_id)\n # 守门员的能力值\n gk.rating = ws.cell(row=row, column=10).value\n # 计算守门员的salary\n gk.salary = 0.0006375 * math.exp(0.1029*gk.rating)\n # 读取守门员的技能数据\n for column in range(29, ws.max_column+1):\n gk.ability.append(ws.cell(row=row, column=column).value)\n\n goal_keepers.append(gk)\n\n return goal_keepers\n\n\n# 选择后卫或者前锋/中场组合\ndef select_back_forward(path, file_name, criteria, alpha, beta):\n\n # 获取到所属网络的名字\n network_name = file_name.split(\".\")[0]\n # 返回球员的相似性矩阵和球员各项能力的平均值\n sim_matrix, abi_avg, player_num_id = \\\n Players_Graph.base_info_collect(path, file_name)\n # 构建球员网络\n pg = Players_Graph.players_graph_construction(sim_matrix, abi_avg)\n # 返回选择出的最佳球员组合\n opt_players = Players_Graph.player_opt_subgraph(player_num_id, pg, path,\n criteria, alpha, beta,\n network_name)\n\n # 返回最佳球员组合,球员网络结构以及球员-ID对照表\n return opt_players, pg, player_num_id\n\n\n# 1. 让网络无条件生成,达到“最优的”队伍;\n# 2. 计算队伍的COST,如果不满足budget,则进行剪枝\ndef team_cut(path, criteria_back, criteria_forward, budget, alpha, beta):\n\n print(\"招募球员的Budget为:%.3f\" % budget)\n\n # 获取到能力名字和能力ID的映射表\n ability_name_id = Players_Attr.ability_name_id\n\n # 读取技能值及其相应的权重\n # 后卫Criteria\n cri_back = read_criteria(path, criteria_back)\n cri_back_nor = Players_Graph.normalize(cri_back) # 归一化\n # 前锋/中场Criteria\n cri_for = read_criteria(path, criteria_forward)\n cri_for_nor = Players_Graph.normalize(cri_for) # 归一化\n\n team = {} # 初始化足球队队员\n\n \"\"\"\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n + +\n + 1. 让网络无条件自由生成,达到\"最优\"结构 \n + +\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n \"\"\"\n\n # 选择守门员\n team[\"GK\"] = list()\n gk, gks = select_goalkeeper(PATH_REMOTE, FILE_GOALKEEPER)\n team[\"GK\"].append(gk.get_id())\n\n # 选择后卫\n team[\"Back\"] = list()\n back, pg_back, player_num_id_back = \\\n select_back_forward(PATH_REMOTE, FILE_BACK, CRITERIA_BACK, AlPHA, BETA)\n team[\"Back\"] = back\n\n # 选择前锋/中场\n team[\"Forward\"] = list()\n forward, pg_forward, player_num_id_forward = \\\n select_back_forward(PATH_REMOTE, FILE_FORWARD, CRITERIA_FORWARD, AlPHA, BETA)\n team[\"Forward\"] = forward\n\n # 1. 计算team的总工资\n # 2. 计算团队的 average team ability\n # 3. 计算团队的同质性/异质性\n team_cost, team_ability, homo_back, homo_forward, opt_player_cf \\\n = cal_cost_abi_homo(team, gks, pg_back, pg_forward, cri_back_nor, cri_for_nor, ability_name_id)\n\n \"\"\"\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n + +\n + 2. 比较team cost和给定的budget之间的差距,如果不满足则进行\"剪枝\"操作 +\n + +\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n \"\"\"\n team_real = {\"GK\": [], \"Back\": [], \"Forward\": []}\n\n while True:\n\n if team_cost < budget:\n # 输出足球队员真实的信息\n team_real[\"GK\"].append(team[\"GK\"][0]) # 守门员ID\n # 后卫网络ID\n for i in team[\"Back\"]:\n team_real[\"Back\"].append(player_num_id_back[i])\n # 前锋/中场ID\n for j in team[\"Forward\"]:\n team_real[\"Forward\"].append(player_num_id_forward[j])\n print(\"\\n\",\n \"\\t\", \"选择出的最终足球团队为:\", team_real, \"\\n\",\n \"\\t\", \"总工资为:\", round(team_cost, 3), \"\\n\",\n \"\\t\", \"能力平均值为:\", round(team_ability, 3), \"\\n\",\n \"\\t\", \"球员的性价比为:\", opt_player_cf, \"\\n\",\n \"\\t\", \"后卫网络的同质性为:%.4f\" % homo_back, \"\\n\",\n \"\\t\", \"前锋网络的异质性为: %.4f\" % homo_forward,\n \"\\n\")\n\n break\n else:\n # 剪枝操作\n # 在剪枝时锁定alpha和beta值\n team_update = cut_base_cf(opt_player_cf, team, pg_back, pg_forward, gks,\n cri_back_nor, cri_for_nor, ability_name_id,\n alpha=0.7, beta=0.15)\n # 计算team_update的cost, average ability and homogeneity\n team_up_cost, team_up_ability, homo_up_back, homo_up_forward, opt_player_cf_up\\\n = cal_cost_abi_homo(team, gks, pg_back, pg_forward, cri_back_nor, cri_for_nor, ability_name_id)\n\n # 更新足球队信息\n team = team_update\n team_cost = team_up_cost\n team_ability = team_up_ability\n homo_back = homo_up_back\n homo_forward = homo_up_forward\n opt_player_cf = opt_player_cf_up\n\n return team_real\n\n\ndef cal_cost_abi_homo(team, gks, pg_back, pg_forward, cri_back, cri_for, abi_name_id):\n\n # 初始化足球队的总工资\n team_cost = 0\n # 初始化足球队的 team ability\n team_ability = 0\n # 初始化同质性/异质性\n homo_back = 0\n homo_forward = 0\n # 足球队员的性价比 cost performance = ability / salary\n opt_player_cf = {}\n\n for pos in team.keys():\n if pos == \"GK\":\n # 取出守门员\n gk = [gk for gk in gks if gk.id == team[pos][0]][0]\n cost = gk.get_salary()\n team_cost += cost\n abi = sum(gk.ability)/len(gk.ability)\n team_ability += abi\n # 计算性价比\n opt_player_cf[gk.id] = round(abi/cost, 3)\n\n elif pos == \"Back\":\n homo_back = cal_homo(team[pos], pg_back)\n for i in team[pos]:\n cost = pg_back.vertexList[i].salary\n team_cost += cost\n abi = \\\n Players_Graph.cal_player_ability(pg_back.vertexList[i].abilities,\n cri_back,\n abi_name_id)\n team_ability += abi\n opt_player_cf[i] = round(abi/cost, 3)\n\n elif pos == \"Forward\":\n homo_forward = cal_homo(team[pos], pg_forward)\n for j in team[pos]:\n cost = pg_forward.vertexList[j].salary\n team_cost += cost\n abi = \\\n Players_Graph.cal_player_ability(pg_forward.vertexList[j].abilities,\n cri_for,\n abi_name_id)\n team_ability += abi\n opt_player_cf[j] = round(abi/cost, 3)\n\n team_ability = team_ability / 11\n\n return team_cost, team_ability, homo_back, homo_forward, opt_player_cf\n\n\n# 根据球员的性价比排序进行剪枝操作\ndef cut_base_cf(player_cf, team, pg_back, pg_forward,\n gks, cri_back, cri_for, abi_name_id, alpha, beta):\n\n # ******** 找到性价比最低的球员 ********\n cut_player = CutPlayer(None)\n cf_min = sys.maxsize\n for p, cf in player_cf.items():\n if cf < cf_min:\n cf_min = cf\n cut_player.id = p\n\n# cut_pos = \"\" # 记录被删除球员所属的网络\n# cut_position = \"\" # 记录被删除球员的位置\n# cut_salary = 0 # 记录被删除球员的salary\n\n # ******** 移除性价比最低球员 ********\n for pos, players in team.items():\n if cut_player.id in players:\n players.remove(cut_player.id)\n cut_player.cut_pos = pos\n break\n\n # ******** 加入候选人 ********\n candidate = \"\" # 初始化候选人\n# position = \"\" # 初始化候选人的位置\n\n if cut_player.get_cut_pos() == \"Back\":\n\n # 被剪掉的是后卫\n\n cut_player.cut_salary = pg_back.vertexList[cut_player.get_id()].salary\n cut_player.cut_position = pg_back.vertexList[cut_player.get_id()].position\n\n # 在后卫网络的邻居中去寻找到合适的候选人\n candidate = select_candidate(team[cut_player.get_cut_pos()], pg_back, cut_player,\n cri_back, abi_name_id, alpha, beta)\n\n# position = pg_back.vertexList[candidate].position\n\n # 加入到团队中\n team[cut_player.get_cut_pos()].append(candidate)\n\n elif cut_player.get_cut_pos() == \"Forward\":\n\n # 被剪掉的是前锋/中场\n\n cut_player.cut_salary = pg_forward.vertexList[cut_player.get_id()].salary\n cut_player.cut_position = pg_forward.vertexList[cut_player.get_id()].position\n\n # 在前锋/中场网络的邻居中去寻找到合适的候选人\n candidate = select_candidate(team[cut_player.get_cut_pos()], pg_forward, cut_player,\n cri_for, abi_name_id, alpha, beta)\n\n# position = pg_forward.vertexList[candidate].position\n\n # 加入到团队中\n team[cut_player.get_cut_pos()].append(candidate)\n\n else:\n\n # 被剪掉的是守门员\n\n opt_abi = 0 # 初始化能力值\n\n for gk in gks:\n if gk.id == cut_player.get_id():\n cut_player.cut_salary = gk.get_salary()\n continue\n\n abi = sum(gk.ability)/len(gk.ability)\n\n # 直接按照能力值降序选择合适的候选人\n if opt_abi < abi and gk.get_salary() < cut_player.get_cut_salary():\n opt_abi = abi\n candidate = gk.id\n\n# position = \"GK\"\n\n # 加入到团队中\n team[\"GK\"].append(candidate)\n\n return team\n\n\ndef select_candidate(team_sub, pg, cut_player, criteria, abi_name_id, alpha, beta):\n\n # 取出后卫其他球员所连接的邻居\n neighbor = list()\n for player in team_sub:\n for key in pg.vertexList[player].connectedTo.keys():\n # 1. 只选择被cut的位置上的球员\n # 2. 排除被cut的球员以及已经被选中的球员\n if key.id not in neighbor and\\\n key.id not in team_sub and\\\n key.id != cut_player.get_id() and\\\n key.position == cut_player.get_cut_position():\n neighbor.append(key.id)\n\n # 遍历邻居,计算代价\n # function = ability + density + homogeneity\n density = {} # 邻居与team的密度\n team_ability = {} # 邻居与team的team ability\n team_gini = {} # 邻居与team的Gini coefficient\n team_homo = {} # 邻居与team的homogeneity\n for ne in neighbor:\n # 计算邻居的能力值\n ne_abi = Players_Graph.cal_player_ability(\n pg.vertexList[ne].abilities, criteria, abi_name_id)\n # 计算邻居到team所组成的图的连接权重\n weight = 0 # 权重和\n te_abi = ne_abi # 团队能力值\n for op in team_sub:\n if pg.vertexList[op] in pg.vertexList[ne].connectedTo:\n # 邻居与team的权重之和\n weight += pg.vertexList[ne].get_weight(pg.vertexList[op])\n # 计算邻居与team的team ability\n te_abi += Players_Graph.cal_player_ability(\n pg.vertexList[op].abilities, criteria, abi_name_id)\n\n # 计算邻居与team的team Gini coefficient\n gini = Players_Graph.cal_homogeneity(pg.vertexList, ne, team_sub)\n\n d = weight / (len(team_sub) + 1) # 计算密度\n density[ne] = d\n team_ability[ne] = te_abi\n team_gini[ne] = gini\n\n # 将基尼系数转换成同质性\n if cut_player.get_cut_pos() == \"Back\":\n for key, value in team_gini.items():\n team_homo[key] = 1 / value # 取倒数\n elif cut_player.get_cut_pos() == \"Forward\":\n for key, value in team_gini.items():\n team_homo[key] = value # 直接赋值\n\n # 计算出最高team ability + density + homogeneity 的candidate加入到团队中\n score_final = {} # 存储每个球员最终得分-->{ID:score}\n score_max = 0\n candidate = ''\n # min-max 将team ability归一化\n team_ability_nor = Players_Graph.normalize_min_max(team_ability)\n # min-max 将同质性-homogeneity归一化\n team_homo_nor = Players_Graph.normalize_min_max(team_homo)\n\n for player_id, value in team_ability_nor.items():\n # score = abilities + density + homogeneity\n score = alpha * team_ability_nor[player_id] +\\\n beta * density[player_id] +\\\n (1 - alpha - beta) * (team_homo_nor[player_id])\n\n score_final[player_id] = score\n\n # 分数要最大并且工资要比被cut的球员低\n if score_max < score and \\\n pg.vertexList[player_id].salary < cut_player.get_cut_salary():\n score_max = score\n candidate = player_id\n\n return candidate\n\n\n# 读取CRITERIA\ndef read_criteria(path, criteria_file):\n criteria = {}\n with open(path + criteria_file, 'r') as cf:\n while True:\n line = cf.readline()\n if not line:\n break\n name = line.split(\":\")[0]\n value = line.split(\":\")[1][:-1]\n\n criteria[name] = int(value)\n\n return criteria\n\n\n# 计算团队的同质性/异质性\ndef cal_homo(team, pg):\n homo = 0\n diff = {}\n avg_tmp = {}\n avg = {}\n gini_co = {}\n\n # 计算两两球员每个技能的能力差值\n for i in range(0, len(team)):\n for j in range(0, len(team)):\n for abi_id in pg.vertexList[i].abilities.keys():\n d = abs(pg.vertexList[team[i]].abilities[abi_id] -\n pg.vertexList[team[j]].abilities[abi_id])\n if abi_id not in diff:\n diff[abi_id] = d\n else:\n diff[abi_id] += d\n\n # 计算每个技能的平均值\n for player in team:\n for abi_id in pg.vertexList[player].abilities.keys():\n if abi_id not in avg_tmp:\n avg_tmp[abi_id] = pg.vertexList[player].abilities[abi_id]\n else:\n avg_tmp[abi_id] += pg.vertexList[player].abilities[abi_id]\n\n for abi_id, value in avg_tmp.items():\n avg[abi_id] = avg_tmp[abi_id]/len(team)\n\n # 计算每个技能的 Gini coefficient\n for abi_id in diff.keys():\n gini_co[abi_id] = (1 / (2 * pow(len(team), 2) * avg[abi_id])) * diff[abi_id]\n\n # 计算平均的 Gini coefficient\n for value in gini_co.values():\n homo += value\n\n homo = homo / len(gini_co)\n\n return homo\n\n\nif __name__ == \"__main__\":\n\n PATH = \"E:\\\\Team Composition\\\\dataset-PES2018\\\\\"\n PATH_REMOTE = \"./\" # 远程服务器文件地址\n FILE_GOALKEEPER = \"Goalkeeper.xlsx\"\n FILE_BACK = \"Back.xlsx\"\n FILE_FORWARD = \"Forward.xlsx\"\n CRITERIA_BACK = \"Criteria_Back.txt\"\n CRITERIA_FORWARD = \"Criteria_Forward.txt\"\n\n AlPHA = 0.6\n BETA = 0.2\n BUDGET = 58\n\n print(\" ******* Begin ******* \")\n team_cut(PATH_REMOTE, CRITERIA_BACK, CRITERIA_FORWARD, BUDGET, AlPHA, BETA)\n print(\" ####### End.. ******* \")\n","sub_path":"PES2018/Team_Compo_Cut.py","file_name":"Team_Compo_Cut.py","file_ext":"py","file_size_in_byte":17596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"466187874","text":"import sys\r\nimport re\r\n\r\ntimere = re.compile('^\\[(\\d+)-(\\d+)-(\\d+) (\\d+):(\\d+)\\] (wakes|falls|Guard #(\\d+))')\r\n\r\nclass Guard:\r\n def __init__(self):\r\n self.days = {}\r\n self.counter = {}\r\n self.mincounts = [0] * 60\r\n\r\n def wake(self, y, m, d, M):\r\n start = self.counter[(y,m,d)]\r\n self.days.setdefault((y,m,d), 0)\r\n self.days[(y,m,d)] += (M - start)\r\n for i in range(start, M + 1):\r\n self.mincounts[i] += 1\r\n\r\n def sleep(self, y, m, d, M):\r\n self.counter[(y,m,d)] = M\r\n\r\n def total(self):\r\n return sum(self.days.values())\r\n\r\n def most(self):\r\n return max(enumerate(self.mincounts), key=lambda e: e[1])[0]\r\n\r\n def maxcount(self):\r\n return max(self.mincounts)\r\n\r\ntimes = {}\r\n\r\nguard = None\r\nlines = list(sys.stdin)\r\nlines = sorted(lines)\r\nfor line in lines:\r\n match = timere.match(line)\r\n y,m,d,H,M = map(int, match.group(*range(1, 6)))\r\n action, arg = match.group(6, 7)\r\n if arg:\r\n guard = arg\r\n times.setdefault(arg, Guard())\r\n continue\r\n if action == 'wakes':\r\n times[guard].wake(y, m, d, M)\r\n if action == 'falls':\r\n times[guard].sleep(y, m, d, M)\r\n\r\nid, obj = max(times.items(), key=lambda i: i[1].maxcount())\r\nprint(int(id) * obj.most())\r\n\r\n","sub_path":"04/solution_p2.py","file_name":"solution_p2.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"31551795","text":"import time\nimport json\nimport traceback\nimport hmac\nimport hashlib\n\nfrom ..base.websocket import WebsocketBase\n\n\nclass BitmexWebsocket(WebsocketBase):\n ENDPOINT = 'wss://www.bitmex.com/realtime'\n\n def __init__(self, key=None, secret=None):\n super().__init__(self.ENDPOINT)\n self.__key = key\n self.__secret = secret\n self.__request_table = {} # (msg, cb, description)\n self.__ch_cb_map = {}\n\n if self.__key and self.__secret:\n self.add_after_open_callback(\n lambda: self.authenticate(self.__key, self.__secret))\n\n def command(self, op, args=[], cb=None, description=None):\n msg = {\"op\": op, \"args\": args}\n self.send(msg)\n id_ = json.dumps(msg)\n self.__request_table[id_] = (msg, cb, description)\n return id_\n\n def subscribe(self, ch, cb):\n key = ch.split(':')[0]\n if key in self.__ch_cb_map:\n raise Exception(f'channel \"{key}\" is already subscribed')\n\n self.command('subscribe', [ch])\n self.__ch_cb_map[key] = cb\n\n def authenticate(self, key, secret):\n expires = int(time.time() * 1000)\n sign = hmac.new(\n self.__secret.encode(), f'GET/realtime{expires}'.encode(),\n hashlib.sha256).hexdigest()\n self.command(\n 'authKeyExpires', [self.__key, expires, sign],\n lambda msg: self._set_auth_result('success' in msg))\n\n def _on_open(self):\n self.__request_table = {}\n self.__ch_cb_map = {}\n super()._on_open()\n\n def _on_message(self, msg):\n try:\n msg = json.loads(msg)\n table = msg.get('table')\n if table:\n self.__ch_cb_map[table](msg)\n else:\n self.log.debug(f'revc: {msg}')\n if 'request' in msg:\n id_ = json.dumps(msg['request'])\n smsg, cb, desc = self.__request_table[id_]\n req = desc or smsg\n if 'success' in msg:\n res = msg['success']\n self.log.info(f'{req} => {res}')\n elif 'error' in msg:\n status, error = msg['status'], msg['error']\n self.log.error(f'{req} => {status}, {error}')\n\n if cb:\n cb(msg)\n else:\n self.log.warning(f'Unknown message: {msg}')\n except Exception:\n self.log.error(traceback.format_exc())\n","sub_path":"botfw/bitmex/websocket.py","file_name":"websocket.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"228097425","text":"\"\"\" Einsum utility functions. \"\"\"\n\nimport torch\n\n\ndef eingroup(equation, operand, dim=None):\n \"\"\"Use einsum-like notation for (un-)grouping dimensions.\n\n Dimensions that cannot be inferred can be handed in via a mapping `dim`.\n\n Arguments:\n equation (str): Equation specifying the (un-)grouping of axes.\n operand (torch.Tensor): The tensor that `equation` will be applied to.\n dim (dict, optional): A mapping from letters in `equation` to\n dimensions. Only required if `eingroup` cannot infer the dimension.\n For instance, consider you want to interpret a vector with 10\n elements as a 5x2 matrix. The equation `\"i,j->ij\"` is not\n sufficient, you need to specify `dim = {\"i\": 5, \"j\": 2}`.\n\n Note:\n Many operations in `backpack` require that certain axes of a tensor\n be treated identically, and will therefore be grouped into a single\n dimension. One way to do that is using `view`s or `reshape`s.\n `eingroup` helps facilitate this process. It can be used in roughly\n the same way as `einsum`, but acts only on a single tensor at\n a time (although this could be fixed with an improved syntax and\n equation analysis).\n\n Idea:\n * `\"a,b,c->ab,c\"`: group dimension `a` and `b` into a single one.\n * `\"a,b,c->ba,c\"` to transpose, then group `b` and `a` dimension.\n\n Examples:\n Different reshapes of a [2 x 2 x 2] tensor:\n >>> t = torch.Tensor([0, 1, 2, 3, 4, 5, 6, 7]).reshape(2, 2, 2)\n >>> t_flat = t.reshape(-1)\n >>> # group all dimensions\n >>> eingroup(\"i,j,k->ijk\", t)\n torch.Tensor([0, 1, 2, 3, 4, 5, 6, 7])\n >>> # interpret as 2 x 4 matrix\n >>> eingroup(\"i,j,k->i,jk\", t)\n torch.Tensor([[0, 1, 2, 3], [4, 5, 6, 7]])\n >>> # grouping (specifying grouping dimensions)\n >>> eingroup(\"ijk->i,j,k\", dim={\"i\": 2, \"j\": 2, \"k\": 2})\n torch.Tensor([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])\n >>> # grouping with additional contraction\n >>> eingroup(\"ijk->j,k\", dim={\"j\": 2, \"k\": 2})\n torch.Tensor([[[4, 5], [8, 10]])\n\n Returns:\n torch.Tensor: Result of the (un-)grouping operation.\n\n Raises:\n KeyError: If information about a dimension in `dim` is missing\n or can be removed. # noqa: DAR402\n RuntimeError: If the groups inferred from `equation` do not match\n the number of axes of `operand` # noqa: DAR402\n\n \"\"\"\n dim = {} if dim is None else dim\n in_shape, out_shape, einsum_eq = _eingroup_preprocess(equation, operand, dim=dim)\n\n operand_in = operand.reshape(in_shape)\n result = torch.einsum(einsum_eq, operand_in)\n return result.reshape(out_shape)\n\n\ndef _eingroup_preprocess(equation, operand, dim):\n \"\"\"Process `eingroup` equation.\n\n Return the `reshape`s and `einsum` equations that have to\n be performed.\n \"\"\"\n split, sep = \"->\", \",\"\n\n def groups(string):\n return string.split(sep)\n\n lhs, rhs = equation.split(split)\n in_groups, out_groups = groups(lhs), groups(rhs)\n\n dim = __eingroup_infer(in_groups, operand, dim)\n in_shape_flat, out_shape = __eingroup_shapes(in_groups, out_groups, dim)\n\n return in_shape_flat, out_shape, equation.replace(sep, \"\")\n\n\ndef __eingroup_shapes(in_groups, out_groups, dim):\n \"\"\"Return shape the input needs to be reshaped, and the output shape.\"\"\"\n\n def shape(groups, dim):\n return [group_dim(group, dim) for group in groups]\n\n def product(nums):\n assert len(nums) > 0\n\n result = 1\n for num in nums:\n result *= num\n return result\n\n def group_dim(group, dim):\n try:\n return product([dim[g] for g in group])\n except KeyError as e:\n raise KeyError(\"Unknown dimension for an axis {}\".format(e))\n\n out_shape = shape(out_groups, dim)\n\n in_groups_flat = []\n for group in in_groups:\n for letter in group:\n in_groups_flat.append(letter)\n in_shape_flat = shape(in_groups_flat, dim)\n\n return in_shape_flat, out_shape\n\n\ndef __eingroup_infer(in_groups, operand, dim):\n \"\"\"Infer the size of each axis.\"\"\"\n if not len(in_groups) == len(operand.shape):\n raise RuntimeError(\n \"Got {} input groups {}, but tensor has {} axes.\".format(\n len(in_groups), in_groups, len(operand.shape)\n )\n )\n\n for group, size in zip(in_groups, operand.shape):\n if len(group) == 1:\n axis = group[0]\n if axis in dim.keys():\n raise KeyError(\n \"Can infer dimension of axis {}.\".format(axis),\n \"Remove from dim = {}.\".format(dim),\n )\n dim[axis] = size\n\n return dim\n","sub_path":"backpack/utils/ein.py","file_name":"ein.py","file_ext":"py","file_size_in_byte":4803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"316093095","text":"import math\n\nfrom .util import update_querystring\n\n\n\nPAGESIZES = [10, 20, 50, 100]\nDEFAULT_PAGESIZE = 20\n\n\n\ndef from_request(request):\n \"\"\"\n Given a request, return tuple (pagesize, pagenumber).\n\n \"\"\"\n pagesize = positive_integer(\n request.GET.get(\"pagesize\", DEFAULT_PAGESIZE), DEFAULT_PAGESIZE)\n pagenumber = positive_integer(\n request.GET.get(\"pagenumber\", 1), 1)\n return pagesize, pagenumber\n\n\n\ndef pagesize_url(url, pagesize):\n return update_querystring(url, pagesize=pagesize, pagenumber=1)\n\n\n\ndef pagenumber_url(url, pagenumber):\n return update_querystring(url, pagenumber=pagenumber)\n\n\n\nclass Pager(object):\n \"\"\"\n Given a total number of objects and a current page size and page number,\n can calculate various bits of data handy for displaying pagination\n controls.\n\n \"\"\"\n def __init__(self, total, pagesize, pagenumber):\n \"\"\"\n The ``total`` argument can either be an integer, or a callable that\n when called returns an integer (this is to allow for lazy total\n calculation in cases when the Pager is constructed before the list of\n results is fully ready.)\n\n \"\"\"\n self._total = total\n self._cached_total = None\n self.pagesize = pagesize\n self.pagenumber = pagenumber\n\n\n def sizes(self):\n \"\"\"\n Returns an ordered list of pagesize links to display. Includes all\n default page sizes, plus the current page size.\n\n \"\"\"\n return sorted(set(PAGESIZES + [self.pagesize]))\n\n\n def pages(self):\n \"\"\"\n Returns an iterable of valid page numbers.\n\n \"\"\"\n return xrange(1, self.num_pages + 1)\n\n\n def display_pages(self):\n \"\"\"\n Returns an iterable of page numbers to display, eliding some ranges of\n page numbers with None in long lists.\n\n \"\"\"\n MIN_SKIP = 3 # don't bother eliding just one or two pages\n FROM_CURRENT = 2 # always show two to either side of current page\n FROM_END = 2 # always show two from each end\n\n skip = []\n ret = []\n for p in self.pages():\n if (abs(p - self.pagenumber) > FROM_CURRENT and\n p > FROM_END and (self.num_pages - p) > (FROM_END - 1)):\n skip.append(p)\n continue\n if len(skip) < MIN_SKIP:\n ret.extend(skip)\n else:\n ret.append(None)\n ret.append(p)\n skip = []\n return ret\n\n\n @property\n def total(self):\n \"\"\"\n The total number of objects. Handles calling the callable that may have\n been passed in initially, and caching that result so the callable is\n only called once.\n\n \"\"\"\n if self._cached_total is None:\n if callable(self._total):\n self._cached_total = self._total()\n else:\n self._cached_total = self._total\n return self._cached_total\n\n\n @property\n def num_pages(self):\n \"\"\"\n Returns the total number of pages.\n\n \"\"\"\n return max(1, int(math.ceil(float(self.total) / self.pagesize)))\n\n\n @property\n def low(self):\n \"\"\"\n Returns the ordinal of the first object to be displayed on the current\n page.\n\n \"\"\"\n return self._constrain((self.pagesize * (self.pagenumber - 1)) + 1)\n\n\n @property\n def high(self):\n \"\"\"\n Returns the ordinal of the last object to be displayed on the current\n page.\n\n \"\"\"\n return self._constrain(self.pagesize * self.pagenumber)\n\n\n def _constrain(self, num):\n return min(self.total, max(0, num))\n\n\n @property\n def prev(self):\n \"\"\"\n The page number of the previous page, or None if there is no previous\n page.\n\n \"\"\"\n prev = self.pagenumber - 1\n if prev < 1:\n return None\n return prev\n\n\n @property\n def next(self):\n \"\"\"\n The page number of the next page, or None if there is no next page.\n\n \"\"\"\n next = self.pagenumber + 1\n if next > self.num_pages:\n return None\n return next\n\n\n\ndef positive_integer(val, default):\n try:\n val = int(val)\n except (AttributeError, TypeError, ValueError):\n val = default\n\n if val < 1:\n val = 1\n\n return val\n","sub_path":"ccui/core/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":4375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"339853005","text":"import json\nqdata = json.load(open(\"test_data/vk_v_with_SSS.json\"))\nprocessed_data = {}\nid_quest ={}\nfor k,v in qdata.items():\n id_quest[k]= v\n\ncontext_data = json.load(open(\"test_data/vk_Google_v_with_SSS.json\"))\nid_context = {}\n\nfor k,v in context_data.items():\n id_context[k] = v\nfor k,v in id_quest.items():\n data ={}\n data[\"question\"] = id_quest[k]\n if k not in id_context.keys():\n continue\n data[\"context\"] = id_context[k]\n processed_data[k] = data\njson.dump(processed_data,open(\"test_data/test_v_with_SSS.json\",\"w\"))\n\n\n\n","sub_path":"preprocess_test.py","file_name":"preprocess_test.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"56514675","text":"import math\n\n\n# Check if the params for calculating the area are correct\ndef validate_input(params_type: str, user_params: list):\n if params_type == \"base_and_height\":\n if len(user_params) != 2 or not all(param.isdigit() for param in user_params):\n return False\n else:\n return True\n elif params_type == \"sides_and_angle\":\n if len(user_params) != 3 or not all(param.isdigit() for param in user_params):\n return False\n else:\n return True\n return False\n\n\n# Calculate the area using the selected method\ndef calculate_area(calculate_type: int):\n if calculate_type == 1:\n params = input(\"Enter base and height divided by comma:\")\n base_and_height = params.replace(\" \", \"\").split(\",\")\n if not validate_input(\"base_and_height\", base_and_height):\n print(\"Please, enter the correct base and height.\")\n return calculate_area(1)\n\n b = int(base_and_height[0])\n h = int(base_and_height[1])\n\n area = b * h / 2\n print(\"\\nThe area calculated by base and height is {}\".format(area))\n return prepare_to_calculate()\n else:\n params = input(\"Enter 2 sides and angle(degrees) between them, divided by comma:\")\n sides_and_angle = params.replace(\" \", \"\").split(\",\")\n if not validate_input(\"sides_and_angle\", sides_and_angle):\n print(\"Please, enter the correct sides and angle.\")\n return calculate_area(2)\n\n side_a = int(sides_and_angle[0])\n side_b = int(sides_and_angle[1])\n angle = math.sin(math.radians(int(sides_and_angle[2])))\n\n area = (side_a * side_b / 2) * angle\n print(\"\\nThe area calculated by sides and angle is {}\".format(area))\n return prepare_to_calculate()\n\n\n# Show the menu for choosing the method\ndef prepare_to_calculate():\n menu_items = {\n \"1\": \"Calculate triangle area by base and height\",\n \"2\": \"Calculate triangle area by 2 sides and angle between them\",\n \"3\": \"Exit\"\n }\n\n print(\"\\nWelcome to the triangle area calculation tool.\")\n print(\"Menu:\")\n\n for key, value in menu_items.items():\n print(\"{}: {}\".format(key, value))\n\n menu_item = input(\"Enter menu item number:\")\n if menu_item not in menu_items.keys():\n print(\"\\nPlease, enter the correct menu item number.\")\n return prepare_to_calculate()\n else:\n if menu_item == \"1\":\n calculate_area(1)\n elif menu_item == \"2\":\n calculate_area(2)\n else:\n print(\"Goodbye!\")\n\n\nprepare_to_calculate()\n","sub_path":"tasks/task02/task02.py","file_name":"task02.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"262032429","text":"# !/usr/bin/python\n# -*- coding:utf-8 -*-\n\nimport subprocess, shlex\nimport time, logging\n\ndef switch(stkN,cmd):\n logging.basicConfig(filename='logger.log',level=logging.DEBUG)\n cmdOn = shlex.split(\"sudo /home/pi/raspberry-remote/send 11111 \" +\n str(stkN) + \" 1\")\n cmdOff = shlex.split(\"sudo /home/pi/raspberry-remote/send 11111 \" +\n str(stkN) + \" 0\")\n logging.info(time.strftime(\"%d.%m.%Y_%H:%M:%S\") +\n ' (fkStk): Switching socket ' +\n str(stkN) + \" \" + cmd)\n if cmd == \"on\":\n successOn = subprocess.Popen(cmdOn,stdout=subprocess.PIPE)\n elif cmd == \"off\":\n successOff = subprocess.Popen(cmdOff,stdout=subprocess.PIPE)\n","sub_path":"final_tex/code/fkSt.py","file_name":"fkSt.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"18340799","text":"# Django imports\nfrom django import forms\n\n\nclass ContactForm(forms.Form):\n \"\"\" Form for processing and validating contact message \"\"\"\n\n subject = forms.CharField(max_length=100, widget=forms.TextInput(attrs={\n \"class\": \"form-control\", \"id\": \"name\",\n \"type\": \"text\", \"placeholder\": \"Your Subject *\",\n \"required\": \"required\",\n \"data - validation - required - message\":\n \"Please enter your subject.\"\n }))\n\n sender_email = forms.EmailField(widget=forms.EmailInput(attrs={\n \"class\": \"form-control\", \"id\":\"email\",\n \"type\": \"email\", \"placeholder\": \"Your Email *\",\n \"required\": \"required\",\n \"data - validation - required - message\":\n \"Please enter your email address.\"\n }))\n\n message = forms.CharField(widget=forms.Textarea(attrs={\n \"class\": \"form-control\", \"id\":\"message\",\n \"placeholder\": \"Your Message *\",\n \"required\": \"required\",\n \"data - validation - required - message\":\n \"Please enter a message.\"\n }))\n","sub_path":"contact/forms/contact_form.py","file_name":"contact_form.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"362065959","text":"from mylib import sqrt\n\n\ndef euler_sum(N):\n Imax = int((N + 0.5)**(1 / 3))\n D = N // Imax\n\n # compute S1\n prime = [1] * (D + 1)\n mobius = [1] * (D + 1)\n\n for i in range(2, D + 1):\n if not prime[i]:\n continue\n mobius[i] = -1\n for j in range(2, D // i + 1):\n prime[i * j] = 0\n mobius[i * j] *= -1\n for j in range(1, D // (i * i) + 1):\n mobius[j * i * i] = 0\n\n s1 = 0\n for i in range(1, D + 1):\n k = N // i\n s1 += mobius[i] * (k * (k + 1) // 2)\n\n # compute M(d), d = 1, ..., D\n M_list = [0]\n M = 0\n for m in mobius[1:]:\n M += m\n M_list.append(M)\n\n # compute M(n // i), i = Imax - 1, ..., 1\n Mxi_list = []\n Mxi_sum = 0\n for i in range(Imax - 1, 0, -1):\n Mxi = 1\n xi = N // i\n\n sqd = int(sqrt(xi))\n # we know that sqd < D <= xi\n for j in range(1, xi // (sqd + 1) + 1):\n Mxi -= (xi // j - xi // (j + 1)) * M_list[j]\n\n for j in range(2, sqd + 1):\n if xi // j <= D:\n Mxi -= M_list[xi // j]\n else:\n Mxi -= Mxi_list[Imax - j * i - 1]\n\n Mxi_list.append(Mxi)\n Mxi_sum += i * Mxi\n\n # compute S2\n s2 = Mxi_sum - Imax * (Imax - 1) // 2 * M_list[-1]\n return s1 + s2\n\n\ndef main(n):\n return ((n + 1) * n // 2 - euler_sum(n)) * 6\n\n\nif __name__ == \"__main__\":\n print(main(5))\n print(main(10))\n print(main(1000))\n print(main(100000000))\n","sub_path":"problems/problem_351/Hexagonal_orchards.py","file_name":"Hexagonal_orchards.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"364427520","text":"import os\nimport json\n\n\ndef del_file(file_path):\n file_list = os.listdir(file_path)\n for file in file_list:\n size = os.path.getsize(\"./ICO_Sanitized_Htmls/\" + file)\n if size < 10 * 1024:\n print(\"remove\", file)\n os.remove(\"./ICO_Sanitized_Htmls/\" + file)\n\ndef clean_tech(file_path):\n result_list = []\n with open(file_path) as f:\n data = json.load(f)\n for item in data:\n if len(item['Tech Profile']) >= 5:\n result_list.append(item)\n data_str = json.dumps(result_list, indent=4)\n print(len(result_list))\n with open('SanitizedIcoBackendStackList.json', 'w') as f:\n f.write(data_str)\n\nif __name__ == \"__main__\":\n file_path = \"IcoWebTechProfileList.json\"\n clean_tech(file_path)\n dir_path = \"./ICO_Sanitized_Htmls\"\n del_file(dir_path)\n\n\n","sub_path":"PreprocessDataset.py","file_name":"PreprocessDataset.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"413688212","text":"#-*- coding:utf-8 -*-\n#Filename:Base58Demo.py\n#Date :2018/7/24 上午11:22\n#auther :mudy\n#E-mail :2808050775@qq.com\n#Blog :txmudy.cn\n\n\nBase58Alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\n\n\n# 解码\ndef base58decode(data):\n result = 0\n\n for d in data:\n charIndex = Base58Alphabet.find(d)\n result = result * len(Base58Alphabet)\n result = result + charIndex\n\n decode = hex(result)\n\n return decode\n\n\n# 编码\ndef base58encode(data):\n res = []\n\n x = int(data, 16)#转换成十六进制\n base = 58\n\n zero = 0\n\n while x != zero:\n x, mod = divmod(x, base)\n res.append(Base58Alphabet[mod])\n\n return \"\".join(reverse(res))\n\n#反转 第一个元素跟最后一个交换就行了,以此类推\ndef reverse(res):\n if len(res) <= 1:\n return res\n\n len_half = int(len(res)/2) #数组的长度的一半\n length = len(res) - 1\n\n\n for i in range(len_half):\n\n tmp = res[i]\n res[i] = res[length - i]\n res[length - i] = tmp\n return res\n","sub_path":"python/EOS专栏/crypto/Base58Demo.py","file_name":"Base58Demo.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"91805545","text":"from odoo import api, fields, models, _\n\nclass Lead(models.Model):\n _inherit = 'crm.lead'\n\n @api.multi\n def _get_email_count(self):\n for record in self:\n record.email_count = self.env['mail.inbox'].sudo().search_count([('crm_lead_id','=',self.id)])\n\n email_count = fields.Integer(compute='_get_email_count', string='Emails')\n\n @api.multi\n def action_emails(self):\n action = self.env.ref('email_management.action_mail_inbox')\n result = action.read()[0]\n email_ids = self.env['mail.inbox'].sudo().search([('crm_lead_id','=',self.id)])\n if len(email_ids) != 1:\n result['domain'] = [('crm_lead_id', '=', self.id)]\n elif len(email_ids) == 1:\n result['views'] = [[False, 'form']]\n result['res_id'] = email_ids.id\n result['context'] = {'default_crm_lead_id': self.id, 'default_state': 'inbox'}\n return result\n\nLead()","sub_path":"beta-dev1/opt/odoo/odoo/addons/core/pipeline_email/models/crm_lead.py","file_name":"crm_lead.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"296952570","text":"# -*- coding:utf-8 -*-\n__author__ = 'Kang'\n\n\ndef getfirst_url(num):\n return r\"http://sou.zhaopin.com/jobs/searchresult.ashx?jl=%E9%80%89%E6%8B%A9%E5%9C%B0%E5%8C%BA&kw=hadoop&isadv=0&sg=e0d2b22730bc420ba1ca897506617ea2&p\" + \"=%d\" % num\n\n\ndef parse_item(item):\n item = str(item)\n import re\n str_zwmc = \"\"\"| \n<(.+)>(.+)(.+)\n | \"\"\"\n zwmc = re.compile(str_zwmc)\n gsmc = re.compile(r'(.+) | ')\n zwyx = re.compile(r'(.+) | ')\n gzdd = re.compile(r'(.+) | ')\n fbrq = re.compile(r'(.+)')\n m_zwmc = zwmc.search(item)\n m_gsmc = gsmc.search(item)\n m_zwyx = zwyx.search(item)\n m_gzdd = gzdd.search(item)\n m_fbrq = fbrq.search(item)\n wt = list()\n count = 0\n # 职位名称\n if m_zwmc:\n wt.append(m_zwmc.group(5) + m_zwmc.group(6) + '\\t')\n else:\n wt.append('' + '\\t')\n count += 1\n # 职位详细介绍url\n if m_zwmc:\n wt.append(m_zwmc.group(3) + '\\t')\n else:\n wt.append('' + '\\t')\n count += 1\n # 公司名称\n if m_gsmc:\n wt.append(m_gsmc.group(2) + '\\t')\n else:\n wt.append('' + '\\t')\n count += 1\n # 职位月薪\n if m_zwyx:\n wt.append(m_zwyx.group(1) + '\\t')\n else:\n wt.append('' + '\\t')\n\n # 工作地点\n if m_gzdd:\n wt.append(m_gzdd.group(1) + '\\t')\n else:\n wt.append('' + '\\t')\n count += 1\n # 发布日期\n if m_fbrq:\n wt.append(m_fbrq.group(1))\n else:\n wt.append('')\n count += 1\n\n import os\n os.chdir('/Users/Kang/Desktop/')\n bw = open('zlzp.txt', 'a')\n if count < 3:\n bw.writelines(wt)\n bw.write(\"\\r\\n\")\n bw.close()\n else:\n bw.close()\n return\n\n\n\ndef get_onPager(num):\n import urllib2\n source = urllib2.urlopen(getfirst_url(num)).read()\n from bs4 import BeautifulSoup\n soup = BeautifulSoup(source, 'html')\n for item in soup.find_all('table'):\n parse_item(item)\n\n\n # def parse_gs(gs_str):\n # import sys\n # reload(sys)\n # sys.setdefaultencoding('utf-8')\n # x=gs_str.index('工作地点:',0)\n # print x\n # relx = r''\n # import re\n # par = re.compile(relx)\n # match = par.search(gs_str)\n # print match\n # atr_dt = dict()\n # atr_rs = dict()\n # ls = ['职位月薪', '工作地点', '发布日期', '工作性质', '工作经验', '最低学历', '招聘人数', '职位类别']\n # for key in ls:\n # try:\n # # print key\n # point = gs_str.index(key, 0)\n # atr_dt[key] = point\n # except:\n # atr_dt[key] = 0\n # # atr_list=list.sort()\n # # dd = gs_str[atr_list[0]:atr_list[1]]\n # for k, v in atr_dt.items():\n # if v != 0:\n # tmp=list()\n # tmp.append()\n # else:\n # atr_rs[key]=''\n\n\n# def get_gsms_Pager(url):\n# import urllib2\n# source = urllib2.urlopen(url).read()\n# parse_gs(source)\n# # print soup.get_text()\n\nfor x in xrange(0, 500):\n get_onPager(x)\n","sub_path":"python/spiderdata/url_source.py","file_name":"url_source.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"483831820","text":"import sys,os\r\nfrom PyQt5.QtWidgets import QApplication,QMainWindow,QSystemTrayIcon,QAction,QMenu,QPushButton,QLineEdit,QCheckBox,QDateTimeEdit,QHeaderView \r\nfrom MainWinUI import Ui_MainWindow\r\nfrom PyQt5.QtCore import Qt, QDateTime\r\nfrom PyQt5.QtGui import QIcon\r\nfrom pandas import DataFrame\r\nfrom StorageSystem import DataBase\r\nfrom threading import Thread\r\nfrom plyer import notification\r\nfrom time import sleep,time\r\nfrom datetime import datetime\r\nfrom urllib.request import urlopen\r\nfrom pywinauto.application import Application\r\n\r\nusername = os.getlogin()\r\npath_to_exe = f\"C:/Users/{username}/AppData/Roaming/Zoom/bin/Zoom.exe\"\r\n\r\nclass ZoomBotUI(QMainWindow):\r\n \r\n closeBtns = []\r\n curMeetingCount = 0\r\n meetingData = []\r\n cols = ['Text','Text','Text','DateTime','CheckBox','CheckBox']\r\n sql = DataBase()\r\n flag = None\r\n \r\n def __init__(self):\r\n super(ZoomBotUI,self).__init__()\r\n \r\n #Setting up the UI\r\n self.ui = Ui_MainWindow()\r\n self.ui.setupUi(self)\r\n self.setWindowFlags(Qt.FramelessWindowHint)\r\n self.setAttribute(Qt.WA_TranslucentBackground)\r\n self.restoreData()\r\n self.startThread()\r\n \r\n #Adding Functions to Buttons\r\n self.ui.closeBtn.clicked.connect(self.hide)\r\n self.ui.minBtn.clicked.connect(self.showMinimized)\r\n self.ui.closeBtn.setToolTip(\"Close\")\r\n self.ui.minBtn.setToolTip(\"Minimize\")\r\n self.ui.addBtn.clicked.connect(self.addMeeting)\r\n self.ui.saveBtn.clicked.connect(self.saveTable)\r\n \r\n self.ui.appIcon.setIcon(QIcon(\"./icons/ZoomAuto.png\"))\r\n \r\n # Changing Headers of the Table\r\n stylesheet = \"::section{background-color:rgb(204,204,204);border-radius:14px}\"\r\n self.ui.tableWidget.horizontalHeader().setStyleSheet(stylesheet)\r\n self.ui.tableWidget.verticalHeader().setStyleSheet(stylesheet)\r\n \r\n #Setting Up the Tray Menu\r\n self.tray_icon = QSystemTrayIcon(self)\r\n self.tray_icon.setIcon(QIcon(\"./icons/ZoomAuto.png\"))\r\n show_action = QAction(\"Show\",self)\r\n hide_action = QAction(\"Hide\",self)\r\n quit_action = QAction(\"Quit\",self)\r\n show_action.triggered.connect(self.show)\r\n hide_action.triggered.connect(self.hide)\r\n quit_action.triggered.connect(self.closeEvent)\r\n tray_menu = QMenu()\r\n tray_menu.addAction(show_action)\r\n tray_menu.addAction(hide_action)\r\n tray_menu.addAction(quit_action)\r\n self.tray_icon.setContextMenu(tray_menu)\r\n self.tray_icon.show()\r\n\r\n #Display the UI on Screen\r\n self.show()\r\n \r\n def closeEvent(self,event):\r\n self.saveTable()\r\n self.flag = False\r\n self.tray_icon.hide()\r\n self.close()\r\n \r\n def mousePressEvent(self,event):\r\n self.dragPos = event.globalPos()\r\n \r\n def mouseMoveEvent(self, event):\r\n if event.buttons() == Qt.LeftButton:\r\n self.move(self.pos()+event.globalPos()-self.dragPos)\r\n self.dragPos = event.globalPos()\r\n event.accept()\r\n \r\n def addMeeting(self):\r\n name = QLineEdit(self)\r\n Id = QLineEdit(self)\r\n passwd = QLineEdit(self)\r\n datetime = QDateTimeEdit(self)\r\n audio = QCheckBox(self)\r\n video = QCheckBox(self)\r\n close = QPushButton(self)\r\n \r\n datetime.setDisplayFormat('dd-MMM , hh:mm')\r\n datetime.setDateTime(QDateTime().currentDateTime())\r\n \r\n close.setIcon(QIcon('./icons/close-button.png'))\r\n close.setFlat(True)\r\n \r\n self.ui.tableWidget.insertRow(self.curMeetingCount)\r\n close.setObjectName(str(self.curMeetingCount))\r\n close.released.connect(lambda: self.deleteMeeting(close.objectName()))\r\n self.closeBtns.append(close)\r\n self.elements = [name,Id,passwd,datetime,audio,video,close]\r\n col = 0\r\n for element in self.elements:\r\n self.ui.tableWidget.setCellWidget(self.curMeetingCount, col, element)\r\n col+=1\r\n \r\n header = self.ui.tableWidget.horizontalHeader()\r\n header.setSectionResizeMode(6,QHeaderView.ResizeToContents)\r\n \r\n self.elements.remove(close)\r\n row = []\r\n for element,name in zip(self.elements,self.cols):\r\n element.setObjectName(name)\r\n row.append(element)\r\n self.meetingData.append(row)\r\n self.curMeetingCount += 1\r\n \r\n def deleteMeeting(self,button_id):\r\n self.ui.tableWidget.removeRow(int(button_id))\r\n self.curMeetingCount -= 1\r\n self.closeBtns.remove(self.closeBtns[int(button_id)])\r\n for i in range(self.curMeetingCount):\r\n self.closeBtns[i].setObjectName(str(i))\r\n self.meetingData.remove(self.meetingData[int(button_id)])\r\n \r\n def saveTable(self):\r\n if self.checkData():\r\n data = []\r\n rows = []\r\n for x in range(len(self.meetingData)):\r\n for i in range(6):\r\n if self.meetingData[x][i].objectName() == \"Text\":\r\n data.append(self.meetingData[x][i].text())\r\n elif self.meetingData[x][i].objectName() == \"DateTime\":\r\n data.append(self.meetingData[x][i].text())\r\n elif self.meetingData[x][i].objectName() == \"CheckBox\":\r\n data.append(self.meetingData[x][i].checkState())\r\n rows.append(data)\r\n data = []\r\n meeting = DataFrame(rows,columns=('Name','ID','Password','DateTime','Audio','Video'))\r\n self.sql.enterData(meeting)\r\n self.startThread()\r\n else:\r\n return\r\n \r\n def checkData(self):\r\n checked = True\r\n for x in range(len(self.meetingData)):\r\n \r\n length = len(self.meetingData[x][1].text().replace(\" \",\"\"))\r\n if 9 > length or length > 11:\r\n self.meetingData[x][1].setStyleSheet(\"color: red;\")\r\n checked = False\r\n else:\r\n self.meetingData[x][1].setStyleSheet(\"color: black;\")\r\n \r\n curTime = datetime.now()\r\n meetingTime = str(curTime.year)+'-'+self.meetingData[x][3].text()+':00'\r\n meetingTime = datetime.strptime(meetingTime, '%Y-%d-%b , %H:%M:%S')\r\n if meetingTime < curTime:\r\n self.meetingData[x][3].setStyleSheet(\"color: red;\") \r\n checked = False\r\n else:\r\n self.meetingData[x][3].setStyleSheet(\"color: black;\") \r\n \r\n return checked\r\n \r\n def restoreData(self):\r\n data = self.sql.readData()\r\n for x in range(len(data)):\r\n self.addMeeting()\r\n for y in range(len(data.columns)):\r\n if self.meetingData[x][y].objectName() == \"Text\":\r\n self.meetingData[x][y].setText(data.loc[x][y])\r\n if self.meetingData[x][y].objectName() == \"DateTime\":\r\n dateTime = QDateTime().fromString(data.loc[x][y],'dd-MMM , hh:mm')\r\n self.meetingData[x][y].setDateTime(dateTime)\r\n if self.meetingData[x][y].objectName() == \"CheckBox\":\r\n self.meetingData[x][y].setCheckState(int(data.loc[x][y]))\r\n \r\n def startThread(self):\r\n meetingList = self.sql.readData()\r\n self.flag = False\r\n self.timerThread = Thread(target=self.timer,args=(meetingList,))\r\n sleep(1)\r\n self.timerThread.start()\r\n \r\n def timer(self,meetings):\r\n self.flag = True\r\n while self.flag:\r\n curTime = str(datetime.now().strftime('%d-%b , %H:%M:%S'))\r\n self.ui.displayTime.setText(f\"Time : {curTime}\")\r\n for meetingTime in meetings['DateTime']:\r\n if curTime == (meetingTime+':00'):\r\n if not self.checkNetwork():\r\n self.startMeeting(meetingTime,meetings)\r\n else:\r\n notification.notify(\"ZoomAuto\",\"Failed To Join Meeting, Bad Internet Connection\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n self.closeBtns[list(meetings['DateTime']).index(meetingTime)].click()\r\n self.saveTable()\r\n sleep(1)\r\n \r\n def checkNetwork(self):\r\n not_connected = True\r\n timeout = time()+30\r\n while not_connected and timeout > time():\r\n try:\r\n urlopen('http://google.com')\r\n not_connected = False\r\n except:\r\n not_connected = True\r\n sleep(1)\r\n return not_connected\r\n \r\n def startMeeting(self,time,meeting):\r\n meetingDetails = meeting.set_index('DateTime')\r\n name = meetingDetails['Name'][time]\r\n Id = meetingDetails['ID'][time]\r\n passwd = meetingDetails['Password'][time]\r\n no_audio = meetingDetails['Audio'][time]\r\n no_video = meetingDetails['Video'][time]\r\n \r\n notification.notify(\"ZoomAuto\",\"Meeting has started\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n try:\r\n zoomWin = Application(backend='uia').start(path_to_exe).connect(title='Zoom',timeout=15)\r\n except:\r\n try:\r\n zoomWin = Application(backend='uia').start(path_to_exe).connect(title='Zoom - Not connected')\r\n notification.notify(\"ZoomAuto\",\"Bad Internet Connection\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n except:\r\n notification.notify(\"ZoomAuto\",\"Zoom Not Installed, Meeting Failed\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n \r\n homeTab = zoomWin.Zoom.child_window(title=\"Home\", control_type=\"TabItem\").wrapper_object()\r\n homeTab.click_input()\r\n joinBtn = zoomWin.Zoom.child_window(title=\"Join\", control_type=\"Button\").wrapper_object()\r\n joinBtn.click_input()\r\n \r\n joinWin = Application(backend='uia').connect(title = \"Join Meeting\",timeout = 15)\r\n idBox = joinWin.JoinMeeting.child_window(title=\"Please enter your Meeting ID or Personal Link Name\", control_type=\"Edit\").wrapper_object()\r\n idBox.type_keys(Id,with_spaces=True)\r\n \r\n nameBox = joinWin.JoinMeeting.child_window(title=\"Please enter your name\", control_type=\"Edit\").wrapper_object()\r\n nameBox.click_input()\r\n nameBox.type_keys(\"^a{BACKSPACE}\")\r\n nameBox.type_keys(name,with_spaces=True)\r\n \r\n audio = joinWin.JoinMeeting.child_window(title='Do not connect to audio', control_type = \"CheckBox\").wrapper_object()\r\n video = joinWin.JoinMeeting.child_window(title='Turn off my video', control_type = \"CheckBox\").wrapper_object()\r\n audio_ts = audio.get_toggle_state()\r\n video_ts = video.get_toggle_state()\r\n \r\n if no_audio == 0 and audio_ts == 1:\r\n audio.toggle()\r\n if no_audio == 2 and audio_ts == 0:\r\n audio.toggle()\r\n \r\n if no_video == 0 and video_ts == 1:\r\n video.toggle()\r\n if no_video == 2 and video_ts == 0:\r\n video.toggle()\r\n \r\n joinBtn = joinWin.JoinMeeting.child_window(title=\"Join\", control_type=\"Button\").wrapper_object()\r\n joinBtn.click_input()\r\n \r\n try:\r\n passwdWin = Application(backend='uia').connect(title = \"Enter meeting passcode\",timeout = 15)\r\n passwdBox = passwdWin.EnterMeetingPasscode.child_window(title='Please enter meeting passcode', control_type=\"Edit\")\r\n passwdBox.type_keys(passwd,with_spaces=True)\r\n meetingJoinBtn = passwdWin.EnterMeetingPasscode.child_window(title='Join Meeting', control_type=\"Button\")\r\n meetingJoinBtn.click_input()\r\n notification.notify(\"ZoomAuto\",\"Meeting Joined\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n except:\r\n try:\r\n Application(backend='uia').connect(title = \"Zoom,Invalid meeting ID,Please check and try again\")\r\n notification.notify(\"ZoomAuto\",\"Invalid Meeting ID\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n except:\r\n notification.notify(\"ZoomAuto\",\"Bad Internet Connection\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n \r\n \r\n \r\n \r\n \r\nif __name__ == \"__main__\":\r\n app = QApplication(sys.argv)\r\n mainWin = ZoomBotUI()\r\n sys.exit(app.exec_())","sub_path":"Part 7/ZoomAutoUI.py","file_name":"ZoomAutoUI.py","file_ext":"py","file_size_in_byte":12515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"244790080","text":"##############################################\n# ############### 1st method ############### #\ndef LUdecomposition(mat, b):\n \"\"\"\n :param mat: the coefficients matrix\n :param b: the solution vector\n :return: none\n \"\"\"\n inversL, L, counter = toUpperTriangularMat(mat) # calculate the L matrix and the inverse L\n print(\"-----------------------------\")\n string = \"L = \"\n for i in range(1, counter):\n if i < counter - 1:\n string += \"invJ\" + str(i) + \" * \"\n else:\n string += \"invJ\" + str(i)\n print(string)\n printMatrix(L, \"L\") # print the L matrix\n print(\"-----------------------------\")\n string = \"inverse L = \"\n for i in range(counter - 1, 0, -1):\n if i > 1:\n string += \"J\" + str(i) + \" * \"\n else:\n string += \"J\" + str(i)\n print(string)\n printMatrix(inversL, \"inverse L\")\n print(\"-----------------------------\")\n print(\"U = invL * A\")\n U = multMat(inversL, mat) # calculate the U matrix\n inversU, counter = FromUpperToInvers(U, createIdentityMatrix(len(U))) # calculate thr inverse of U\n print(\"-----------------------------\")\n string = \"inverse U = \"\n for i in range(counter - 1, 0, -1):\n string += \"E\" + str(i) + \" * \"\n string += \"U\"\n print(string)\n printMatrix(U, \"U\") # print the U matrix\n print(\"-----------------------------\")\n print(\"x = invU * invL * b\")\n x = multMat(inversL, b) # finding the result vector\n x = multMat(inversU, x) # finding the result vector\n printMatrix(x, \"x\") # print the X matrix\n return x\n\n\ndef FromUpperToInvers(A, inverseMat, counter=1):\n \"\"\"\n :param A: upper matrix\n :param inverseMat: the matrix that will become the inverse\n :return: Inverse matrix\n \"\"\"\n elemntarMat = createIdentityMatrix(len(A)) # identity matrix\n for i in range(len(A) - 1, -1, -1): # run over the columns\n for j in range(i): # run over the lines above the pivot\n elemntarMat[j][i] = -(A[j][i] / A[i][i])\n A = multMat(elemntarMat, A)\n inverseMat = multMat(elemntarMat, inverseMat)\n printMatrix(elemntarMat, \"E\" + str(counter))\n counter += 1\n elemntarMat[j][i] = 0\n if A[i][i] != 1: # convert the pivots to one\n elemntarMat[i][i] = 1 / A[i][i]\n A = multMat(elemntarMat, A)\n inverseMat = multMat(elemntarMat, inverseMat)\n printMatrix(elemntarMat, \"E\" + str(counter))\n counter += 1\n elemntarMat[i][i] = 1\n return inverseMat, counter\n\n\ndef toUpperTriangularMat(A):\n \"\"\"\n :param A: the matrix we want to turn into a upper triangle matrics\n :return: the multiplication of the elementary matrics that create U\n \"\"\"\n L = createIdentityMatrix(len(A)) # create indetity matrix\n InL = createIdentityMatrix(len(A)) # create indetity matrix\n counter = 1\n for i in range(len(A)): # run over the lines\n if A[i][i] == 0: # if the pivot is 0\n for j in range(i + 1, len(A)): # run over the columns\n if A[j][i] != 0: # if the element under the pivot is not 0\n elementary = linesExchange(A, i, j)\n L = multMat(L, elementary) # make lines exchange and multiply\n printMatrix(elementary, \"J\" + str(counter))\n InL = multMat((linesExchange(A, i, j)), InL) # make lines exchange and multiply\n printMatrix(identity, \"inverse J\" + str(counter))\n A = multMat((linesExchange(A, i, j)), A)\n counter += 1\n break\n if A[i][i] != 0: # check if B is regular\n for j in range(i + 1, len(A)): # run over the columns\n identity = createIdentityMatrix(len(A))\n identity[j][i] = -(A[j][i] / A[i][i]) # elementary matrix\n printMatrix(identity, \"J\" + str(counter))\n InL = multMat(identity, InL) # L^(-1)\n A = multMat(identity, A)\n identity[j][i] *= -1 # changing the element in order to find L\n printMatrix(identity, \"inverse J\" + str(counter))\n L = multMat(L, identity)\n counter += 1\n return InL, L, counter\n\n\ndef linesExchange(A, line1, line2):\n \"\"\"\n :param A: A matrix\n :param line1: A line\n :param line2: The line we want to exchange with\n :return: elementry matrix\n \"\"\"\n idendityMax = createIdentityMatrix(len(A)) # create identity matrix\n\n # exchange the members in line1\n temp = idendityMax[line1][line1]\n idendityMax[line1][line1] = idendityMax[line2][line1]\n idendityMax[line2][line1] = temp\n\n # exchange the members in line2\n temp = idendityMax[line2][line2]\n idendityMax[line2][line2] = idendityMax[line1][line2]\n idendityMax[line1][line2] = temp\n return idendityMax\n\n\ndef createIdentityMatrix(size):\n \"\"\"\n :param size: the size of the square matrix\n :return:\n \"\"\"\n identityMat = newMat(size, size) # create a zero matrix in the required size\n for index in range(size): # go over the main diagonal\n identityMat[index][index] = 1 # change the elements in the main diagonal to 1\n return identityMat\n\n\ndef multMat(A, B):\n \"\"\"\n :param A: a matrix in sise n*m\n :param B: a mtrix in size m*k\n :return: A*B (in size n*k)\n \"\"\"\n if len(A[1]) == len(B): # check if A and B have the same number of rows and columns\n C = newMat(len(A), len(B[0])) # the matrix the function returns\n for i in range(len(C)):\n for j in range(len(C[1])):\n for k in range(len(B)):\n C[i][j] += A[i][k] * B[k][j]\n return C\n else:\n return None # the multiplication is impossible\n\n\n# ############### 1st method ############### #\n\n##############################################\n# ############### 2nd method ############### #\ndef GausssElimination(A, b):\n \"\"\"\n :param A: the coefficients matrix\n :param b: the solution vector\n :return: none\n \"\"\"\n print(\"** Gauss Elimination **\")\n tempMatrix = Invers(A) # A^(-1)\n condA = infinityNorma(tempMatrix) # calculate the infinity norma of A^(-1)\n printMatrix(tempMatrix, \"inverse A\") # print the inverse A\n tempMatrix = multMat(tempMatrix, b)\n printMatrix(tempMatrix, \"x\") # print x vector\n condA *= infinityNorma(A) # calculate the infinity norma of A and find condA\n print(\"-----------------------------\")\n print(\"condA = \" + str(condA))\n print(\"-----------------------------\")\n return tempMatrix\n\n\ndef infinityNorma(mat):\n \"\"\"\n :param mat: a list - matrix\n :return: the infinity norma\n \"\"\"\n maximum = 0\n for i in range(len(mat)): # rum over the lines\n newSum = lineSum(mat[i]) # send to function that calculate the line sum\n maximum = max(maximum, newSum) # choose the maximum\n return maximum\n\n\ndef lineSum(line):\n \"\"\"\n :param line: A list od numbers - line for the matrix\n :return: the sum of all the numbers in abs in the list\n \"\"\"\n lineSum = 0\n for index in range(len(line)): # run over all the line`s members\n lineSum += abs(line[index])\n return lineSum\n\n\ndef Invers(A):\n \"\"\"\n :param A: a list - matrix\n :return: the invers of the matrix\n \"\"\"\n if det(A) is 0:\n print(\"A is singular\")\n return\n inverseMat, counter = toUpperWithPivoting(A) # return the multiplication of the elementary matrices that create U\n printMatrix(inverseMat, \"E\" + str(counter))\n counter += 1\n tempMatrix = multMat(inverseMat, A) # upper triangle matrix\n mat, c = FromUpperToInvers(tempMatrix, inverseMat, counter) # return inverse matrix\n return mat\n\n\ndef det(A):\n \"\"\"\n :param A: a square matrix\n :return: the determinant of A\n \"\"\"\n if len(A[0]) is not len(A): # check if A is a square matrix\n return None\n if len(A) == 2: # if the matrix size is 2*2\n return (A[0][0] * A[1][1]) - (A[0][1] * A[1][0])\n sum = 0 # will save the determinant\n for j in range(len(A)):\n sum += (-1) ** (0 + j) * A[0][j] * det(minor(A, 0, j))\n return sum\n\n\ndef minor(A, i, j):\n \"\"\"\n :param A: a square matrix\n :param i: a row index for the minor\n :param j: a column index for the minor\n :return: the minor that is created from deleting row i and column j from A\n \"\"\"\n matSize = len(A)\n mat = newMat(matSize - 1, matSize - 1) # the mat for the minor\n iMinor = 0\n jMinor = 0\n for iIndex in range(matSize): # go over the rows of the matrix\n for jIndex in range(matSize): # go over the columns of the matrix\n if iIndex == i: # don't copy the row we want to delete\n iMinor -= 1\n break\n elif jIndex != j: # don't copy the row we want to delete\n mat[iMinor][jMinor] = A[iIndex][jIndex] # copy the rest of the elements in the matrix\n jMinor += 1\n jMinor = 0\n iMinor += 1\n return mat\n\n\ndef toUpperWithPivoting(A):\n \"\"\"\n :param A: the matrix we want to turn into a upper triangle matrics\n :return: the multiplication of the elementary matrics that create U\n \"\"\"\n InL = createIdentityMatrix(len(A)) # creating a identity matrix\n counter = 1\n for i in range(len(A) - 1): # run over the columns\n maxPivot = abs(A[i][i])\n lineIndex = i\n for j in range(i + 1, len(A)): # run over the elements undet the pivot\n if abs(A[j][i]) > maxPivot: # if the element is greater then the pivot\n maxPivot = abs(A[j][i])\n lineIndex = j\n elementary = linesExchange(A, i, lineIndex)\n InL = multMat(elementary, InL)\n printMatrix(elementary, \"E\" + str(counter))\n counter += 1\n A = multMat(elementary, A)\n if A[i][i] != 0: # check if B is regular\n for j in range(i + 1, len(A)): # run over the lines\n identity = createIdentityMatrix(len(A)) # creating identity matrix\n identity[j][i] = -(A[j][i] / A[i][i]) # elementary matrix\n printMatrix(identity, \"E\" + str(counter))\n counter += 1\n InL = multMat(identity, InL) # L^(-1)\n A = multMat(identity, A)\n return InL, counter\n\n\ndef multMat(A, B):\n \"\"\"\n :param A: a matrix in sise n*m\n :param B: a mtrix in size m*k\n :return: A*B (in size n*k)\n \"\"\"\n if len(A[1]) == len(B): # check if A and B have the same number of rows and columns\n C = newMat(len(A), len(B[0])) # the matrix the function returns\n for i in range(len(C)):\n for j in range(len(C[1])):\n for k in range(len(B)):\n C[i][j] += A[i][k] * B[k][j]\n return C\n else:\n return None # the multiplication is impossible\n\n\ndef createIdentityMatrix(size):\n \"\"\"\n :param size: the size of the square matrix\n :return:\n \"\"\"\n identityMat = newMat(size, size) # create a zero matrix in the required size\n for index in range(size): # go over the main diagonal\n identityMat[index][index] = 1 # change the elements in the main diagonal to 1\n return identityMat\n\n\ndef linesExchange(A, line1, line2):\n \"\"\"\n :param A: A matrix\n :param line1: A line\n :param line2: The line we want to exchange with\n :return: elementry matrix\n \"\"\"\n idendityMax = createIdentityMatrix(len(A)) # create identity matrix\n\n # exchange the members in line1\n temp = idendityMax[line1][line1]\n idendityMax[line1][line1] = idendityMax[line2][line1]\n idendityMax[line2][line1] = temp\n\n # exchange the members in line2\n temp = idendityMax[line2][line2]\n idendityMax[line2][line2] = idendityMax[line1][line2]\n idendityMax[line1][line2] = temp\n return idendityMax\n\n\n# ############### 2nd method ############### #\n\n##############################################\n\n# ############### 3rd method ############### #\ndef iterativGuassSeidel(A, b, epsilon, flagD):\n \"\"\"\n :param A: a matrix\n :param b: the result vector\n :param epsilon: the mistake\n :param flagD: tell us if the system have dominant diagonal\n :return: vector x if found\n \"\"\"\n print(\"** Iterative Guass Seidel **\")\n flagC = False # flagC = false if the linear equations does not converge\n x = newMat(len(b), 1) # create the result vector\n print(\"The results are:\\nThe first guess is: \")\n printMatrix(x)\n for _ in range(99): # max number of iterations is 99\n oldX1 = x[0][0] # copy the old x value of the current iteration\n for i in range(len(x)): # go over the all variables\n if A[i][i] == 0: # preventing division by zero\n return None\n temp = b[i][0] / A[i][i]\n for j in range(len(x)): # calculate the value of the variable in the new iteration\n if i != j:\n temp -= (A[i][j] * x[j][0]) / A[i][i]\n x[i][0] = temp # update the calculated value\n print(\"The result of the \" + str(_ + 1) + \" iteration is: \")\n printMatrix(x)\n if abs(oldX1 - x[0][0]) < epsilon: # check stop condition\n flagC = True\n break\n if flagC is True:\n print(\"***********\") # print final results\n if flagD is False:\n print(\"Although there is no dominant diagonal, the results are: \\n\")\n print(\"The final result is: x = \")\n printMatrix(x)\n print(\"The number of the iteration is : \" + str(_ + 1))\n return x\n else:\n print(\"The system of linear equations does not converge :(\")\n\n\n# ############### 3rd method ############### #0\n\n\ndef printMatrix(a, name=None):\n \"\"\"\n :param a: a matrix to print\n :return: prints in matrix format\n \"\"\"\n print(\"-----------------------------\")\n if name is not None:\n print(name + \" = \")\n for i in range(len(a)):\n if i is len(a) - 1:\n print(\" \" + str(a[i]) + \"]\")\n elif i is 0:\n print(\"[\" + str(a[i]))\n else:\n print(\" \" + str(a[i]))\n print(\"\")\n\n\ndef newMat(numRow, numCol):\n \"\"\"\n :param numRow: the number of rows in the mat\n :param numCol: the number of columns in the mat\n :return: a zero matrix in the required size\n \"\"\"\n mat = [] # the zero matrix the function returns\n for i in range(numRow):\n mat.append([]) # create a new row\n for j in range(numCol):\n mat[i].append(0) # fill the row with\n return mat\n\n\ndef dominantDiagonal(A):\n \"\"\"\n :param A: a list - matrix\n :return: true if the matrix have dominant diagonal else return false\n \"\"\"\n for i in range(len(A)):\n lineSum = 0 # sum of every line except to the element in the diagonal\n for j in range(len(A)):\n if i != j:\n lineSum += A[i][j]\n if A[i][i] <= lineSum:\n # print(\"There is no dominant diagonal ...\")\n return False\n print(\"There is a dominant diagonal :)\")\n return True\n\n\n# dominant diagonal part\n\ndef copyMat(A):\n \"\"\"\n :param A: a matrix\n :return: a copy of the matrix\n \"\"\"\n B = newMat(len(A), len(A[0])) # create a zero matrix of the same size as A\n for i in range(len(A)): # copy A\n for j in range(len(A[0])):\n B[i][j] = A[i][j]\n return B\n\n\ndef createDominantDiagonal(A, b=None):\n \"\"\"\n :param A: a coefficients matrix\n :param b: the column vector of constant terms.\n :return: matrix A with dominant diagonal\n \"\"\"\n max = 0 # the max value in the current row or column in the matrix\n maxIndex = 0 # the index of the max value\n for i in range((len(A))): # calc the max value for each member on the main diagonal\n sum = 0 # the sum of the members in the current row in A\n for j in range(len(A)): # go over the current row\n sum += abs(A[i][j]) # add the value of each member in the row\n if abs(A[i][j]) > max: # search for the max value in the current row\n max = abs(A[i][j])\n maxIndex = j\n if (sum - max) <= max: # if the max value in the row meets the condition of a dominant diagonal\n A = manualSwapCol(A, maxIndex,\n i) # swap between the columns of the current value on the main diagonal and the max value in that row\n else: # look for the max value in the current column\n max = 0\n maxIndex = 0\n for j in range(len(A)): # go over the current column\n # sum += abs(A[j][i])\n if abs(A[j][i]) > max: # search for the max value in the current column\n max = abs(A[j][i])\n maxIndex = j\n if rowSum(A[j]) - max <= max: # if the max value in the row meets the condition of a dominant diagonal\n A, b = manualSwapRow(A, b, i,\n maxIndex) # swap between the rows of the current value on the main diagonal and the max value in that column\n else:\n print(\"ERROR - no dominant diagonal\") # A can't be changed into dominant diagonal matrix\n return None, None\n return A, b\n\n\ndef manualSwapRow(a, b, r1, r2):\n \"\"\"\n manaul rows exchange (without e)\n :param a: The coefficient matrix\n :param b: The column vector of constant terms\n :param r1: the first row to swap\n :param r2: the second row to swap\n :return: the matrix after the swap, The column vector of constant terms after swap\n \"\"\"\n\n if r2 < len(a) and r1 < len(a):\n temp = a[r1]\n a[r1] = a[r2]\n a[r2] = temp\n if b is not None: # if the result vector is not none swap him too\n temp = b[r1]\n b[r1] = b[r2]\n b[r2] = temp\n return a, b\n\n\ndef manualSwapCol(a, c1, c2):\n \"\"\"\n :param a: The coefficient matrix\n :param c1: the first column to swap\n :param c2: the second column to swap\n :return: the matrix after the swap\n \"\"\"\n if c2 < len(a) and c1 < len(a):\n for i in range(len(a)):\n temp = a[i][c1]\n a[i][c1] = a[i][c2]\n a[i][c2] = temp\n return a\n\n\ndef rowSum(line):\n \"\"\"\n :param line: A list od numbers - line for the matrix\n :return: the sum of all the numbers in abs in the list\n \"\"\"\n lineSum = 0\n for index in range(len(line)): # run over all the line`s members\n lineSum += abs(line[index])\n return lineSum\n\n\n# end dominant part\n\n\ndef checkDifferPart3(l, d, name1, name2, epsilon):\n print(\"check the difference between the methods:\")\n flag = True\n for i in range(len(l)):\n print(\"x\" + str(i + 1) + \" - \" + name1 + \": \" + str(l[i][0]) + \"\\nx\" +\n str(i + 1) + \" - \" + name2 + \": \" + str(d[i][0]))\n if abs(l[i][0] - d[i][0]) > epsilon:\n flag = False\n print(\"The difference is bigger than epsilon for some of the components\\n\")\n return\n print(\"The difference is smaller than epsilon for all the components\\n\")\n\n\ndef calcFinalResult(result, epsilon, day, hour, minutes):\n \"\"\"\n :param result: the result\n :param epsilon: the epsilon we decided on for the question\n :param day: the day of the calculation in str\n :param hour: the hour of the calculation in str\n :param minutes: the minutes of the calculation in str\n :return: the result by the requested format\n \"\"\"\n stringRes = str(result) # cast the result to string\n i = 0\n while stringRes[i] is not \".\": # run over the string while we get to the point\n i += 1 # count how many digits there is before the point\n i += 1\n count = 1\n while epsilon < 1: # checking how digit needs after the point\n epsilon *= 10\n count += 1\n stringRes = stringRes[:i + count] + \"00000\" + day + hour + minutes\n return stringRes\n\n\ndef calcFinalResultVector(vector, name, epsilon, day, hour, minutes):\n \"\"\"\n :param vector: vector x\n :param epsilon: allowed error\n :param day: dd\n :param hour: hh\n :param minutes: mm\n :return: prints the formatted result vector x\n \"\"\"\n for i in range(len(vector)):\n vector[i][0] = calcFinalResult(vector[i][0], epsilon, day, hour, minutes)\n printMatrix(vector, name + \" - Final Result in Format\")\n\n\n# ############## main ###############\ndef driver():\n \"\"\"\n main function for iterative isolation of variables method\n :return: prints results\n \"\"\"\n A = [[10, 8, 1],\n [4, 10, -5],\n [5, 1, 10]]\n\n b = [[-7],\n [2],\n [1.5]]\n\n epsilon = 10 ** (-4)\n\n flagDom = dominantDiagonal(A) # check if there is a dominant diagonal\n name1 = \"LUdecomposition\"\n name2 = \"iterativGuassSeidel\"\n name3 = \"GausssElimination\"\n # check\n if flagDom is False:\n copyA = copyMat(A)\n copyB = copyMat(b)\n copyA, copyB = createDominantDiagonal(copyA, copyB) # change the matrix to be with dominant diagonal\n if (copyA is not None) and (copyB is not None): # check if the return matrices are not none\n A = copyA\n b = copyB\n flagDom = True\n\n # end check\n x1 = LUdecomposition(A, b)\n x2 = iterativGuassSeidel(A, b, epsilon, flagDom)\n x3 = GausssElimination(A, b)\n checkDifferPart3(x1, x2, name1, name2, epsilon)\n checkDifferPart3(x1, x3, name1, name3, epsilon)\n calcFinalResultVector(x1, name1, epsilon, \"14\", \"00\", \"40\")\n calcFinalResultVector(x2, name2, epsilon, \"14\", \"00\", \"41\")\n calcFinalResultVector(x3, name3, epsilon, \"14\", \"00\", \"42\")\n\n\ndriver()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"598317025","text":"from blueprints import db\nfrom flask_restful import fields\nimport datetime\n\nclass Checkouts(db.Model):\n __tablename__= \"Checkout\"\n id = db.Column(db.Integer, primary_key = True, autoincrement = True)\n cart_id = db.Column(db.Integer, db.ForeignKey(\"Cart.id\"), nullable = False)\n nama_penerima = db.Column(db.String(255), nullable = False)\n alamat = db.Column(db.String(255), nullable = False)\n kode_pos = db.Column(db.String(255), nullable = False)\n nomor_telepon = db.Column(db.String(255), nullable = False)\n metode_pengiriman = db.Column(db.String(255), nullable = False)\n jumlah_barang = db.Column(db.Integer, nullable = True, default = 0)\n total_harga = db.Column(db.Integer, nullable = True, default = 0)\n created_at = db.Column(db.DateTime, default = datetime.datetime.now())\n update_at = db.Column(db.DateTime, onupdate = datetime.datetime.now())\n deleted = db.Column(db.Boolean, default = False)\n\n response_fields = {\n 'id' : fields.Integer,\n 'cart_id' : fields.Integer,\n 'nama_penerima' : fields.String,\n 'alamat' : fields.String,\n 'kode_pos' : fields.String,\n 'nomor_telepon' : fields.String,\n 'metode_pengiriman' : fields.String,\n 'jumlah_barang' : fields.Integer,\n 'total_harga' : fields.Integer,\n 'created_at' : fields.DateTime,\n 'updated_at' : fields.DateTime,\n 'deleted' : fields.Boolean,\n }\n\n def __init__(self, cart_id, nama_penerima, alamat, kode_pos, nomor_telepon, metode_pengiriman,\n jumlah_barang,total_harga):\n self.cart_id = cart_id\n self.nama_penerima = nama_penerima\n self.alamat = alamat\n self.kode_pos = kode_pos\n self.nomor_telepon = nomor_telepon\n self.metode_pengiriman = metode_pengiriman\n self.jumlah_barang = jumlah_barang\n self.total_harga = total_harga\n\n def __repr_(self):\n return '' %self.id","sub_path":"Alta Batch 4/Phase 2/Liburan/portofolio/ecomerce/blueprints/Checkout/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"367187451","text":"# Copyright 2019 Red Hat\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.\nfrom __future__ import absolute_import\n\nfrom collections import abc\nimport os\nimport sys\nimport typing\n\nfrom heatclient.common import template_utils\n\nimport tobiko\n\n\nTEMPLATE_SUFFIX = '.yaml'\n\nTEMPLATE_DIRS = list(sys.path)\n\n\nclass HeatTemplateFixture(tobiko.SharedFixture):\n\n template_yaml: str\n\n def __init__(self,\n template: typing.Mapping[str, typing.Any] = None,\n template_files: typing.Mapping = None):\n super(HeatTemplateFixture, self).__init__()\n self.template: typing.Dict[str, typing.Any] = {}\n if template is not None:\n self.template.update(template)\n self.template_files: typing.Dict[str, typing.Any] = {}\n if template_files is not None:\n self.template_files.update(template_files)\n\n def setup_fixture(self):\n self.setup_template()\n\n def setup_template(self):\n # Ensure main sections are dictionaries\n tobiko.check_valid_type(self.outputs, abc.Mapping)\n tobiko.check_valid_type(self.parameters, abc.Mapping)\n tobiko.check_valid_type(self.resources, abc.Mapping)\n self.template_yaml = tobiko.dump_yaml(self.template)\n\n @property\n def outputs(self) -> typing.Dict[str, typing.Any]:\n return dict(self.template.get('outputs', {}))\n\n @property\n def parameters(self) -> typing.Dict[str, typing.Any]:\n return dict(self.template.get('parameters', {}))\n\n @property\n def resources(self) -> typing.Dict[str, typing.Any]:\n return dict(self.template.get('resources', {}))\n\n\nclass HeatTemplateFileFixture(HeatTemplateFixture):\n\n def __init__(self,\n template_file: str,\n template_dirs: typing.Iterable[str] = None):\n super(HeatTemplateFileFixture, self).__init__()\n self.template_file = template_file\n if template_dirs is None:\n template_dirs = TEMPLATE_DIRS\n self.template_dirs: typing.List[str] = list(template_dirs)\n\n def setup_template(self):\n template_file = self.template_file\n if self.template_dirs or not os.path.isfile(template_file):\n template_dirs = self.template_dirs or TEMPLATE_DIRS\n template_file = find_heat_template_file(\n template_file=self.template_file,\n template_dirs=template_dirs)\n template_files, template = template_utils.get_template_contents(\n template_file=template_file)\n self.template = template\n self.template_files = template_files\n super(HeatTemplateFileFixture, self).setup_template()\n\n\nHeatTemplateType = typing.Union[typing.Mapping[str, typing.Any],\n HeatTemplateFixture]\n\n\ndef heat_template(obj: HeatTemplateType,\n template_files: typing.Mapping = None) \\\n -> HeatTemplateFixture:\n if isinstance(obj, abc.Mapping):\n template = HeatTemplateFixture(template=obj,\n template_files=template_files)\n else:\n template = tobiko.get_fixture(obj)\n\n tobiko.check_valid_type(template, HeatTemplateFixture)\n return template\n\n\ndef heat_template_file(template_file: str,\n template_dirs: typing.Iterable[str] = None):\n return HeatTemplateFileFixture(template_file=template_file,\n template_dirs=template_dirs)\n\n\ndef find_heat_template_file(template_file: str,\n template_dirs: typing.Iterable[str]):\n for template_dir in template_dirs:\n template_path = os.path.join(template_dir, template_file)\n if os.path.exists(template_path):\n return template_path\n\n msg = \"Template file {!r} not found in directories {!r}\".format(\n template_file, template_dirs)\n raise IOError(msg)\n","sub_path":"tobiko/openstack/heat/_template.py","file_name":"_template.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"400255362","text":"# -*- coding: utf-8 -*-\nfrom unittest import TestCase\nfrom pymongo import Connection\nfrom tori.db.session import Session\nfrom tori.db.entity import entity\nfrom tori.db.mapper import link, CascadingType, AssociationType\n\n@link(\n mapped_by='region',\n target='testcase.test_db_uow_cascade_on_refresh.Region',\n association=AssociationType.MANY_TO_ONE,\n cascading=[CascadingType.REFRESH, CascadingType.PERSIST]\n)\n@entity('countries')\nclass Country(object):\n def __init__(self, name, region):\n self.name = name\n self.region = region\n\n@link(\n mapped_by='countries',\n target='testcase.test_db_uow_cascade_on_refresh.Country',\n inverted_by='region',\n association=AssociationType.ONE_TO_MANY,\n cascading=[CascadingType.REFRESH],\n read_only=True\n)\n@entity('regions')\nclass Region(object):\n def __init__(self, name, countries=[]):\n self.name = name\n self.countries = countries\n\nclass TestDbUowCascadeOnRefresh(TestCase):\n connection = Connection()\n\n def setUp(self):\n self.session = Session(0, self.connection['test_tori_db_uow_cascade_on_refresh'])\n\n data_set = {\n 'regions': [\n {'_id': 1, 'name': 'Asia'},\n {'_id': 2, 'name': 'Europe'},\n {'_id': 3, 'name': 'North America'}\n ],\n 'countries': [\n {'_id': 1, 'region': 3, 'name': 'Canada'},\n {'_id': 2, 'region': 2, 'name': 'England'},\n {'_id': 3, 'region': 1, 'name': 'Japan'},\n {'_id': 4, 'region': 1, 'name': 'Thailand'}\n ]\n }\n\n self.session.collection(Region)._api.remove()\n\n for region in data_set['regions']:\n self.session.collection(Region)._api.insert(region)\n\n self.session.collection(Country)._api.remove()\n\n for country in data_set['countries']:\n self.session.collection(Country)._api.insert(country)\n\n def test_cascade_from_owning_side(self):\n japan = self.session.collection(Country).get(3)\n\n self.assertEqual('Japan', japan.name)\n self.assertEqual('Asia', japan.region.name)\n\n # At this point, Region 1 is loaded into the memory.\n # Bypass the identity map and then update the data manually.\n self.session.collection(Region)._api.update({'_id': 1}, {'$set': {'name': 'Asia and Oceanic'}})\n\n # Now, try to persist the data.\n japan.name = u'日本'\n\n self.session.persist(japan)\n self.session.flush()\n\n # Confirm that only the name of the country is updated\n self.assertEqual(u'日本', japan.name)\n self.assertEqual('Asia', japan.region.name)\n\n # Refresh the entity\n self.session.refresh(japan)\n\n # Confirm that only the name of the region is updated after refreshing\n self.assertEqual(u'日本', japan.name)\n self.assertEqual('Asia and Oceanic', japan.region.name)\n\n def _test_cascade_from_inverted_side(self):\n europe = self.session.collection(Region).get(2)\n\n self.assertEqual('Europe', europe.name)\n self.assertEqual('England', europe.countries[0].name)\n\n # At this point, Region 1 is loaded into the memory.\n # Bypass the identity map and then update the data manually.\n self.session.collection(Region)._api.update({'_id': 2}, {'$set': {'name': 'United Kingdom of Great Britain and Ireland'}})\n\n # Now, try to persist the data.\n europe.name = 'Europian Union'\n\n self.session.persist(europe)\n self.session.flush()\n\n # Confirm that only the name of the country is updated\n self.assertEqual('Europian Union', europe.name)\n self.assertEqual('England', europe.countries[0].name)\n\n # Refresh the entity\n self.session.refresh(europe)\n\n # Confirm that refreshing doesn't work with reverse-mapping properties.\n self.assertEqual('Europian Union', europe.name)\n self.assertEqual('England', europe.countries[0].name)","sub_path":"test/testcase/test_db_uow_cascade_on_refresh.py","file_name":"test_db_uow_cascade_on_refresh.py","file_ext":"py","file_size_in_byte":4017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"117973345","text":"# import MySQLdb\nfrom sqlalchemy import create_engine, MetaData\nfrom sqlalchemy.orm import sessionmaker\n\nmetadata = MetaData()\n\n\nclass EngineFactory:\n @staticmethod\n def create_engine_to_center(echo=True):\n engine = create_engine(\"mysql+pymysql://root:root@10.141.221.87/domainkg?charset=utf8\", encoding='utf-8',\n echo=echo)\n return engine\n\n\n @staticmethod\n def create_engine_by_schema_name(schema_name, echo=True):\n if schema_name == 'stackoverflow':\n engine = create_engine(\"mysql+pymysql://root:root@10.131.252.160/stackoverflow?charset=utf8\",\n encoding='utf-8',\n echo=echo)\n return engine\n elif schema_name == 'knowledgeGraph':\n engine = create_engine(\"mysql+pymysql://root:root@10.141.221.75/knowledgeGraph?charset=utf8\",\n encoding='utf-8',\n echo=echo)\n return engine\n elif schema_name == 'codehub':\n engine = create_engine(\"mysql+pymysql://root:root@10.141.221.73/codehub?charset=utf8\", encoding='utf-8',\n echo=echo)\n return engine\n elif schema_name == 'domainkg':\n engine = create_engine(\"mysql+pymysql://root:root@10.141.221.87/domainkg?charset=utf8\", encoding='utf-8',\n echo=echo)\n return engine\n else:\n return None\n\n @staticmethod\n def create_session(engine=None, autocommit=False,echo=True):\n if engine is None:\n engine = EngineFactory.create_engine_to_center(echo=echo)\n\n Session = sessionmaker(bind=engine, autocommit=autocommit)\n session = Session()\n return session\n\n","sub_path":"engine_factory.py","file_name":"engine_factory.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"24286874","text":"from flask import Flask, request\r\n#from OpenSSL import SSL\r\nimport os\r\nimport json\r\n\r\nfilename = 'C:\\\\webhook\\\\webhookPayloads.json' #file that webhook payloads will be written\r\n\r\nif os.path.exists(filename):\r\n append_write = 'a' # append if already exists\r\nelse:\r\n append_write = 'w' # make a new file if not\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/', methods=['POST','GET'])\r\ndef index():\r\n if request.method == 'GET':\r\n f = open(filename, 'r')\r\n return f.read()\r\n \r\n if request.method == 'POST':\r\n f = open(filename,append_write)\r\n req_data = request.get_json()\r\n str_obj = json.dumps(req_data)\r\n f.write(str_obj+'\\n')\r\n f.close()\r\n return '{\"success\":\"true\"}'\r\n\r\nif __name__ == \"__main__\": \r\n #context = ('ssl.cert', 'ssl.key') # certificate and key file. Cannot be self signed certs \r\n app.run(host='0.0.0.0', port=5000, threaded=True) # will listen on port 5000\r\n","sub_path":"python/receiver/flask/webhook-test.py","file_name":"webhook-test.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"65573605","text":"#!/usr/bin/env python3\n\n\"\"\"Main.\"\"\"\n\nimport sys\nfrom cpu import *\n\nif len(sys.argv) is not 2:\n print(\"Missing second argument. Try typing python ls8.py example/mult.ls8\")\n sys.exit(1)\n\ncpu = CPU()\n\ncpu.load(sys.argv[1])\ncpu.run()\n","sub_path":"ls8/ls8.py","file_name":"ls8.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"267015319","text":"from django.conf.urls import patterns, include, url\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = patterns('',\n # Captcha URLS\n url(r'^captcha/', include('captcha.urls')),\n # Static URLS\n url(r'^$', 'icodeviruses.views.index', name='index'),\n # Forum Urls\n url(r'^forum/(\\d+)/$', 'forum.views.forum_id', name='forum_id'),\n url(r'^forum/','forum.views.forum', name='forum'),\n # Authentication Urls\n url(r'^register/', 'registration.views.register', name='register'),\n url(r'^loginuser/','authentication.views.login_user', name='loginuser'),\n url(r'^logoutuser/','authentication.views.logout_user', name='logoutuser'),\n # Admin Urls\n url(r'^admin/users/','admin.views.admin_users', name='admin_users'),\n url(r'^admin/forums/','admin.views.admin_forums', name='admin_forums'),\n)\n\n# Uncomment the next line to serve media files in dev.\n# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns += patterns('',\n url(r'^__debug__/', include(debug_toolbar.urls)),\n )\n","sub_path":"icodeviruses/icodeviruses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"286832848","text":"#Problem : 2016 Qualifiers - Lost in the Pantry\n#Language : Python\n#Compiled Using : py_compile\n#Version : Python 2.7.8\n#Input for your program will be provided from STDIN\n#Print out all output from your program to STDOUT\n\nfrom __future__ import print_function\nfrom collections import deque\nimport sys\n\nclass Point:\n def __init__(self, row, col):\n self.row = row\n self.col = col\n self.val = 0\n self.checked = False\n\n def goTo(self, end):\n self.checked = True\n if end.row == self.row and end.col == self.col:\n res = 1\n elif end.val != self.val:\n res = 0\n else:\n i, j = [self.row, self.col]\n res = self.call(i-1, j, end) + self.call(i, j-1, end) + self.call(i+1, j, end) + self.call(i, j+1, end)\n\n self.checked = False\n return res\n\n def call(self, row, col, end):\n if 0 <= row < nbRow and 0 <= col < nbCol:\n if not maze[row][col].checked:\n res = maze[row][col].goTo(end)\n if res > 0:\n return res + 1\n return 0\n\n def printPoint(self, full=False):\n res = \"(\"+str(self.row)+\",\"+str(self.col)+\")\"\n if (full):\n res += \", val=\"+str(self.val)\n return res\n\n\ndata = deque(sys.stdin.read().splitlines())\nnbRow, nbCol = map(lambda i: int(i), data.popleft().split(\" \"))\n\nmaze = [[Point(i, j) for j in range(0,nbCol)] for i in range(0,nbRow)]\n\nfor i in range(0, nbRow):\n row = data.popleft()\n for j in range(0, nbCol):\n maze[i][j].val = row[j]\n\nrow, col = map(lambda i: int(i), data.popleft().split(\" \"))\nstart = maze[row][col]\nrow, col = map(lambda i: int(i), data.popleft().split(\" \"))\nend = maze[row][col]\n\nlength = start.goTo(end)\n\nprint(length)","sub_path":"lost_in_the_pantry.py","file_name":"lost_in_the_pantry.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"651431443","text":"\"\"\"\nReads PLD file in IBA format and convert to sobp.dat\nwhich is readable by FLUKA with source_sampler.f and by SHIELD-HIT12A.\n\nTODO: Translate energy to spotsize.\n\"\"\"\nimport sys\nimport logging\nimport argparse\nfrom math import exp, log\n\nlogger = logging.getLogger(__name__)\n\n\ndef dedx_air(energy):\n \"\"\"\n Calculate the mass stopping power of protons in air following ICRU 49.\n Valid from 1 to 500 MeV only.\n\n :params energy: Proton energy in MeV\n :returns: mass stopping power in MeV cm2/g\n \"\"\"\n if energy > 500.0 or energy < 1.0:\n logger.error(\"Proton energy must be between 1 and 500 MeV.\")\n raise ValueError(\"Energy = {:.2f} out of bounds.\".format(energy))\n\n x = log(energy)\n y = 5.4041 - 0.66877 * x - 0.034441 * (x**2) - 0.0010707 * (x**3) + 0.00082584 * (x**4)\n return exp(y)\n\n\nclass Layer(object):\n \"\"\"\n Class for handling Layers.\n \"\"\"\n def __init__(self, spotsize, energy, meterset, elsum, repaints, elements):\n self.spotsize = float(spotsize)\n self.energy = float(energy)\n self.meterset = float(meterset) # MU sum of this + all previous layers\n self.elsum = float(elsum) # sum of elements in this layer\n self.repaints = int(repaints) # number of repaints\n self.elements = elements # number of elements\n self.spots = int(len(elements) / 2) # there are two elements per spot\n\n self.x = [0.0] * self.spots\n self.y = [0.0] * self.spots\n self.w = [0.0] * self.spots # MU weight\n self.rf = [0.0] * self.spots # fluence weight\n\n j = 0\n for element in elements:\n token = element.split(\",\")\n if token[3] != \"0.0\":\n self.x[j] = float(token[1].strip())\n self.y[j] = float(token[2].strip())\n self.w[j] = float(token[3].strip()) # meterset weight of this spot\n self.rf[j] = self.w[j]\n j += 1 # only every second token has a element we need.\n\n\nclass PLDRead(object):\n \"\"\"\n Class for handling PLD files.\n \"\"\"\n\n def __init__(self, fpld):\n \"\"\" Read the rst file.\"\"\"\n\n pldlines = fpld.readlines()\n pldlen = len(pldlines)\n logger.info(\"Read {} lines of data.\".format(pldlen))\n\n self.layers = []\n\n # parse first line\n token = pldlines[0].split(\",\")\n self.beam = token[0].strip()\n self.patient_iD = token[1].strip()\n self.patient_name = token[2].strip()\n self.patient_initals = token[3].strip()\n self.patient_firstname = token[4].strip()\n self.plan_label = token[5].strip()\n self.beam_name = token[6].strip()\n self.mu = float(token[7].strip())\n self.csetweight = float(token[8].strip())\n self.nrlayers = int(token[9].strip()) # number of layers\n\n for i in range(1, pldlen): # loop over all lines starting from the second one\n line = pldlines[i]\n if \"Layer\" in line:\n header = line\n\n token = header.split(\",\")\n # extract the subsequent lines with elements\n el_first = i + 1\n el_last = el_first + int(token[4])\n\n elements = pldlines[el_first:el_last]\n\n # read number of repaints only if 5th column is present, otherwise set to 0\n repaints_no = 0\n if 5 in token:\n repaints_no = token[5].strip()\n\n self.layers.append(Layer(token[1].strip(), # Spot1\n token[2].strip(), # energy\n token[3].strip(), # cumulative meter set weight including this layer\n token[4].strip(), # number of elements in this layer\n repaints_no, # number of repaints.\n elements)) # array holding all elements for this layer\n\n\ndef main(args=None):\n \"\"\" Main function of the pld2sobp script.\n \"\"\"\n if args is None:\n args = sys.argv[1:]\n\n import pymchelper\n\n # _scaling holds the number of particles * dE/dx / MU = some constant\n # _scaling = 8.106687e7 # Calculated Nov. 2016 from Brita's 32 Gy plan. (no dE/dx)\n _scaling = 5.1821e8 # Estimated calculation Apr. 2017 from Brita's 32 Gy plan.\n\n parser = argparse.ArgumentParser()\n parser.add_argument('fin', metavar=\"input_file.pld\", type=argparse.FileType('r'),\n help=\"path to .pld input file in IBA format.\",\n default=sys.stdin)\n parser.add_argument('fout', nargs='?', metavar=\"output_file.dat\", type=argparse.FileType('w'),\n help=\"path to the SHIELD-HIT12A/FLUKA output file, or print to stdout if not given.\",\n default=sys.stdout)\n parser.add_argument('-f', '--flip', action='store_true', help=\"flip XY axis\", dest=\"flip\", default=False)\n parser.add_argument('-d', '--diag', action='store_true', help=\"prints additional diagnostics\",\n dest=\"diag\", default=False)\n parser.add_argument('-s', '--scale', type=float, dest='scale',\n help=\"number of particles*dE/dx per MU.\", default=_scaling)\n parser.add_argument('-v', '--verbosity', action='count', help=\"increase output verbosity\", default=0)\n parser.add_argument('-V', '--version', action='version', version=pymchelper.__version__)\n args = parser.parse_args(args)\n\n if args.verbosity == 1:\n logging.basicConfig(level=logging.INFO)\n if args.verbosity > 1:\n logging.basicConfig(level=logging.DEBUG)\n\n pld_data = PLDRead(args.fin)\n args.fin.close()\n\n # SH12A takes any form of list of values, as long as the line is shorter than 78 Chars.\n outstr = \"{:-10.6f} {:-10.2f} {:-10.2f} {:-10.2f} {:-16.6E}\\n\"\n\n meterset_weight_sum = 0.0\n particles_sum = 0.0\n\n for layer in pld_data.layers:\n spotsize = 2.354820045 * layer.spotsize * 0.1 # 1 sigma im mm -> 1 cm FWHM\n\n for spot_x, spot_y, spot_w, spot_rf in zip(layer.x, layer.y, layer.w, layer.rf):\n\n weight = spot_rf * pld_data.mu / pld_data.csetweight\n # Need to convert to weight by fluence, rather than weight by dose\n # for building the SOBP. Monitor Units (MU) = \"meterset\", are per dose\n # in the monitoring Ionization chamber, which returns some signal\n # proportional to dose to air. D = phi * S => MU = phi * S(air)\n phi_weight = weight / dedx_air(layer.energy)\n\n # add number of paricles in this spot\n particles_spot = args.scale * phi_weight\n particles_sum += particles_spot\n\n meterset_weight_sum += spot_w\n\n layer_xy = [spot_x * 0.1, spot_y * 0.1]\n\n if args.flip:\n layer_xy.reverse()\n\n args.fout.writelines(outstr.format(layer.energy * 0.001, # MeV -> GeV\n layer_xy[0],\n layer_xy[1],\n spotsize,\n particles_spot))\n\n logger.info(\"Data were scaled with a factor of {:e} particles*S/MU.\".format(args.scale))\n if args.flip:\n logger.info(\"Output file was XY flipped.\")\n\n if args.diag:\n energy_list = [layer.energy for layer in pld_data.layers]\n\n # double loop over all layers and over all spots in a layer\n spot_x_list = [x for layer in pld_data.layers for x in layer.x]\n spot_y_list = [y for layer in pld_data.layers for y in layer.y]\n spot_w_list = [w for layer in pld_data.layers for w in layer.w]\n\n print(\"\")\n print(\"Diagnostics:\")\n print(\"------------------------------------------------\")\n print(\"Total MUs : {:10.4f}\".format(pld_data.mu))\n print(\"Total meterset weigths : {:10.4f}\".format(meterset_weight_sum))\n print(\"Total particles : {:10.4e} (estimated)\".format(particles_sum))\n print(\"------------------------------------------------\")\n for i, energy in enumerate(energy_list):\n print(\"Energy in layer {:3} : {:10.4f} MeV\".format(i, energy))\n print(\"------------------------------------------------\")\n print(\"Highest energy : {:10.4f} MeV\".format(max(energy_list)))\n print(\"Lowest energy : {:10.4f} MeV\".format(min(energy_list)))\n print(\"------------------------------------------------\")\n print(\"Spot X min/max : {:10.4f} {:10.4f} mm\".format(min(spot_x_list), max(spot_x_list)))\n print(\"Spot Y min/max : {:10.4f} {:10.4f} mm\".format(min(spot_y_list), max(spot_y_list)))\n print(\"Spot meterset min/max : {:10.4f} {:10.4f} \".format(min(spot_w_list), max(spot_w_list)))\n print(\"\")\n args.fout.close()\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n","sub_path":"pymchelper/utils/pld2sobp.py","file_name":"pld2sobp.py","file_ext":"py","file_size_in_byte":9020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"608162469","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/wb_vandalism/feature_lists/wikidata.py\n# Compiled at: 2015-12-19 13:27:28\n# Size of source mod 2**32: 6094 bytes\nfrom revscoring.features import user\nfrom revscoring.features.modifiers import not_, log\nfrom ..features import diff, revision\n\nclass properties:\n __doc__ = '\\n Mapping of english descriptions to property identifiers\\n '\n IMAGE = 'P18'\n SEX_OR_GENDER = 'P21'\n COUNTRY_OF_CITIZENSHIP = 'P27'\n INSTANCE_OF = 'P31'\n MEMBER_OF_SPORTS_TEAM = 'P54'\n SIGNATURE = 'P109'\n COMMONS_CATEGORY = 'P373'\n DATE_OF_BIRTH = 'P569'\n DATE_OF_DEATH = 'P570'\n OFFICIAL_WEBSITE = 'P856'\n\n\nclass items:\n __doc__ = '\\n Mapping of english descriptions to item idenifiers\\n '\n HUMAN = 'Q5'\n\n\nis_client_delete = revision.comment_matches('^\\\\/\\\\* clientsitelink\\\\-remove\\\\:', name='revision.is_client_delete')\nis_client_move = revision.comment_matches('^\\\\/\\\\* clientsitelink\\\\-update\\\\:', name='revision.is_client_move')\nis_merge_into = revision.comment_matches('^\\\\/\\\\* wbmergeitems\\\\-to\\\\:', name='revision.is_merge_into')\nis_merge_from = revision.comment_matches('^\\\\/\\\\* wbmergeitems\\\\-from\\\\:', name='revision.is_merge_from')\nis_revert = revision.comment_matches('^Reverted edits by \\\\[\\\\[Special\\\\:Contributions', name='revision.is_revert')\nis_rollback = revision.comment_matches('^Undid revision ', name='revision.is_rollback')\nis_restore = revision.comment_matches('^Restored revision ', name='revision.is_restore')\nis_item_creation = revision.comment_matches('^\\\\/\\\\* (wbsetentity|wbeditentity-create\\\\:0\\\\|) \\\\*\\\\/', name='revision.is_item_creation')\nsex_or_gender_changed = diff.property_changed(properties.SEX_OR_GENDER, name='diff.sex_or_gender_changed')\ncountry_of_citizenship_changed = diff.property_changed(properties.COUNTRY_OF_CITIZENSHIP, name='diff.country_of_citizenship_changed')\nmember_of_sports_team_changed = diff.property_changed(properties.MEMBER_OF_SPORTS_TEAM, name='diff.member_of_sports_team_changed')\ndate_of_birth_changed = diff.property_changed(properties.DATE_OF_BIRTH, name='diff.date_of_birth_changed')\nimage_changed = diff.property_changed(properties.IMAGE, name='diff.image_changed')\nsignature_changed = diff.property_changed(properties.SIGNATURE, name='diff.signature_changed')\ncommons_category_changed = diff.property_changed(properties.COMMONS_CATEGORY, name='diff.commons_category_changed')\nofficial_website_changed = diff.property_changed(properties.OFFICIAL_WEBSITE, name='diff.official_website_changed')\nis_human = revision.has_property_value(properties.INSTANCE_OF, items.HUMAN, name='revision.is_human')\nhas_birthday = revision.has_property(properties.DATE_OF_BIRTH, name='revision.has_birthday')\ndead = revision.has_property(properties.DATE_OF_BIRTH, name='revision.dead')\nis_blp = has_birthday.and_(not_(dead))\nreverted = [\n log(user.age + 1),\n diff.number_added_sitelinks,\n diff.number_removed_sitelinks,\n diff.number_changed_sitelinks,\n diff.number_added_labels,\n diff.number_removed_labels,\n diff.number_changed_labels,\n diff.number_added_descriptions,\n diff.number_removed_descriptions,\n diff.number_changed_descriptions,\n diff.number_added_aliases,\n diff.number_removed_aliases,\n diff.number_added_claims,\n diff.number_removed_claims,\n diff.number_changed_claims,\n diff.number_changed_identifiers,\n diff.en_label_touched,\n diff.number_added_sources,\n diff.number_removed_sources,\n diff.number_added_qualifiers,\n diff.number_removed_qualifiers,\n diff.number_added_badges,\n diff.number_removed_badges,\n diff.proportion_of_qid_added,\n diff.proportion_of_language_added,\n diff.proportion_of_links_added,\n is_client_move,\n is_client_delete,\n is_merge_into,\n is_merge_from,\n is_revert,\n is_rollback,\n is_restore,\n is_item_creation,\n sex_or_gender_changed,\n country_of_citizenship_changed,\n member_of_sports_team_changed,\n date_of_birth_changed,\n image_changed,\n signature_changed,\n commons_category_changed,\n official_website_changed,\n log(revision.number_claims + 1),\n log(revision.number_aliases + 1),\n log(revision.number_sources + 1),\n log(revision.number_qualifiers + 1),\n log(revision.number_badges + 1),\n log(revision.number_labels + 1),\n log(revision.number_sitelinks + 1),\n log(revision.number_descriptions + 1),\n is_human,\n is_blp,\n user.is_bot,\n user.is_anon]","sub_path":"pycfiles/wb_vandalism-0.1.8-py3.4/wikidata.cpython-34.py","file_name":"wikidata.cpython-34.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"265062561","text":"import os\nimport shutil\nimport unittest\nfrom contextlib import contextmanager\n\nimport time\nimport json\nimport subprocess\n\nfrom shapeflow import settings, ROOTDIR, save_settings\n\nCACHE = os.path.join(ROOTDIR, 'test_main-cache')\nDB = os.path.join(ROOTDIR, 'test_main-history.db')\nSTATE = os.path.join(ROOTDIR, 'test_main-state')\nSETTINGS = os.path.join(ROOTDIR, 'settings')\n\nHOST = \"127.0.0.1\"\nPORT = 7951\n\n\n\ndef api(*args):\n return \"/\".join([f\"http://{HOST}:{PORT}/api\"] + list(args))\n\n\ndef get(url):\n with subprocess.Popen(['curl', '-X', 'GET', url], stdout=subprocess.PIPE) as p:\n response, error = p.communicate()\n return response\n\n\ndef post(url, data=None):\n if data is None:\n with subprocess.Popen(['curl', '-X', 'POST', url], stdout=subprocess.PIPE) as p:\n response, error = p.communicate()\n else:\n with subprocess.Popen(['curl', '-X', 'POST', url, '--header', \"Content-Type: application/json\", '--data', data], stdout=subprocess.PIPE) as p:\n response, error = p.communicate()\n return response\n\n\ndef start_server():\n return subprocess.Popen(\n ['python', 'sf.py', 'serve', '--background', '--host', HOST, '--port', str(PORT)],\n cwd='..'\n )\n\n@contextmanager\ndef override_settings():\n # Clean up after previous runs (just in case)\n if os.path.exists(CACHE):\n shutil.rmtree(CACHE)\n if os.path.exists(DB):\n os.remove(DB)\n if os.path.exists(STATE):\n os.remove(STATE)\n\n try:\n with settings.cache.override({\"dir\": CACHE}), \\\n settings.db.override({\"path\": DB}), \\\n settings.app.override({\"state_path\": STATE}):\n save_settings()\n yield\n finally:\n save_settings()\n\n if os.path.exists(CACHE):\n shutil.rmtree(CACHE)\n if os.path.exists(DB):\n os.remove(DB)\n if os.path.exists(STATE):\n os.remove(STATE)\n\n@unittest.skip(\"Unreliable\")\nclass ServerTest(unittest.TestCase):\n def setUp(self) -> None:\n r = post(api('quit'))\n if r:\n time.sleep(5)\n\n def tearDown(self) -> None:\n r = post(api('quit'))\n if r:\n time.sleep(5)\n\n \"\"\"Test server-level methods\"\"\"\n def test_startup(self):\n with override_settings():\n # Server is down, no response\n self.assertEqual(b'', get(api('ping')))\n\n # Start server & wait a bit\n start_server()\n time.sleep(5)\n\n # Server is up, some response\n self.assertNotEqual(b'', get(api('ping')))\n\n # Quit server & wait a bit\n post(api('quit'))\n time.sleep(5)\n\n # Server is down, no response again\n self.assertEqual(b'', get(api('ping')))\n\n def test_unload_shutdown(self):\n with override_settings():\n # Start server & wait a bit\n start_server()\n time.sleep(5)\n\n # Server is up, some response\n self.assertNotEqual(b'', get(api('ping')))\n\n # Post unload trigger\n post(api('unload'))\n\n # Wait for 10 seconds, server should have quit\n time.sleep(10)\n self.assertEqual(b'', get(api('ping')))\n\n def test_unload_keepup(self):\n with override_settings():\n # Start server & wait a bit\n start_server()\n time.sleep(5)\n\n # Server is up, some response\n self.assertNotEqual(b'', get(api('ping')))\n\n # Post unload trigger\n post(api('unload'))\n\n # Wait for 1 seconds, server should still be up\n time.sleep(1)\n self.assertNotEqual(b'', get(api('ping')))\n\n # Wait for 10 seconds, server should still be up\n time.sleep(10)\n self.assertNotEqual(b'', get(api('ping')))\n\n def test_set_settings_restart(self):\n with override_settings():\n # Start server & wait a bit\n p = start_server()\n time.sleep(5)\n\n # Server is up, some response\n self.assertNotEqual(b'', get(api('ping')))\n\n first_pid = get(api('pid_hash'))\n first_settings = json.loads(get(api('get_settings')))\n\n # Post set_settings trigger & wait a bit\n post(api('set_settings'), data=json.dumps({'settings': {'log': {'keep': 0}}}))\n time.sleep(10)\n\n # Server is up on the same address, some response\n self.assertNotEqual(b'', get(api('ping')))\n second_settings = json.loads(get(api('get_settings')))\n\n # Server is on a different PID\n self.assertNotEqual(first_pid, get(api('pid_hash')))\n\n # second_settings.log.keep == 0\n self.assertEqual(0, second_settings['log']['keep'])\n\n # Set settings gack to first_settings\n post(api('set_settings'), data=json.dumps({'settings': first_settings}))\n time.sleep(10)\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"test/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"32132963","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 5 14:41:11 2021\n\n@author: 66441\n\"\"\"\n\nimport numpy as np\n\na = np.arange(0,10).reshape(2,-1)\nprint(\"a:\\n\", a)\nnp.save(\"a.npy\", a)\nb = np.load(\"a.npy\")\nprint(\"b:\\n\", b)","sub_path":"save_txt.py","file_name":"save_txt.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"499508037","text":"import keras.backend as k\n\n\ndef iou(pre_min, pre_max, true_min, true_max):\n\n intersect_min = k.maximum(pre_min, true_min) # batch * 7 * 7 * 2 * 2\n intersect_max = k.minimum(pre_max, true_max) # batch * 7 * 7 * 2 * 2\n\n intersect_wh = k.maximum(intersect_max - intersect_min, 0.) # batch * 7 * 7 * 2 * 2\n intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1] # batch * 7 * 7 * 2\n\n pre_wh = pre_max - pre_min # batch * 7 * 7 * 2 * 2\n true_wh = true_max - true_min # batch * 7 * 7 * 1 * 2\n pre_area = pre_wh[..., 0] * pre_wh[..., 1] # batch * 7 * 7 * 2\n true_area = true_wh[..., 0] * true_wh[..., 1] # batch * 7 * 7 * 1\n\n union_area = pre_area + true_area - intersect_area # batch * 7 * 7 * 2\n iou_score = intersect_area / union_area # batch * 7 * 7 * 2\n\n return iou_score\n\n\ndef yolo_loss(y_true, y_pre):\n\n true_class = y_true[..., :1] # batch * 7 * 7 * 1\n true_confidence = y_true[..., 1] # batch * 7 * 7\n true_confidence1 = k.expand_dims(true_confidence) # batch * 7 * 7 * 1\n true_location = y_true[..., 2:6] # batch * 7 * 7 * 4\n\n pre_class = y_pre[..., :1] # batch * 7 * 7 * 1\n pre_confidence = y_pre[..., 1:3] # batch * 7 * 7 * 2\n pre_location = y_pre[..., 3:11] # batch * 7 * 7 * 8\n\n true_location1 = k.reshape(true_location, [-1, 7, 7, 1, 4]) # batch * 7 * 7 * 1 * 4\n pre_location1 = k.reshape(pre_location, [-1, 7, 7, 2, 4]) # batch * 7 * 7 * 2 * 4\n\n true_xy = true_location1[..., :2] * 448 / 7 # batch * 7 * 7 * 1 * 2\n true_wh = true_location1[..., 2:4] * 448 # batch * 7 * 7 * 1 * 2\n true_xy_min = true_xy - true_wh / 2 # batch * 7 * 7 * 1 * 2\n true_xy_max = true_xy + true_wh / 2 # batch * 7 * 7 * 1 * 2\n\n pre_xy = pre_location1[..., :2] * 448 / 7 # batch * 7 * 7 * 2 * 2\n pre_wh = pre_location1[..., 2:4] * 448 # batch * 7 * 7 * 2 * 2\n pre_xy_min = pre_xy - pre_wh / 2 # batch * 7 * 7 * 2 * 2\n pre_xy_max = pre_xy + pre_wh / 2 # batch * 7 * 7 * 2 * 2\n\n iou_score = iou(pre_xy_min, pre_xy_max, true_xy_min, true_xy_max) # batch * 7 * 7 * 2\n best_score = k.max(iou_score, axis=3, keepdims=True) # batch * 7 * 7 * 1\n box_mask = k.cast(iou_score >= best_score, k.dtype(iou_score)) # batch * 7 * 7 * 2\n\n no_object_loss = 0.5 * (1 - box_mask * true_confidence1) * k.square(0 - pre_confidence)\n object_loss = box_mask * true_confidence1 * k.square(1 - pre_confidence)\n confidence_loss = no_object_loss + object_loss\n confidence_loss = k.sum(confidence_loss)\n\n class_loss = true_confidence1 * k.square(true_class - pre_class)\n class_loss = k.sum(class_loss)\n\n box_mask1 = k.expand_dims(box_mask) # batch * 7 * 7 * 2 * 1\n true_confidence2 = k.expand_dims(true_confidence1) # batch * 7 * 7 * 1 * 1\n\n location_loss_xy = 5 * box_mask1 * true_confidence2 * k.square((true_xy - pre_xy) / 448)\n location_loss_wh = 5 * box_mask1 * true_confidence2 * k.square((k.sqrt(true_wh) - k.sqrt(pre_wh)) / 448)\n location_loss = k.sum(location_loss_xy) + k.sum(location_loss_wh)\n\n total_loss = confidence_loss + class_loss + location_loss\n\n return total_loss\n\n\n","sub_path":"yolo_loss.py","file_name":"yolo_loss.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"332628994","text":"from urllib.request import urlopen\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport re\nfrom datetime import datetime\nimport time\nimport random\nfrom tqdm import tqdm\nimport numpy as np\n\n\nclass newsletter_crawler:\n\n def __init__(self, newsletter_name, archive_url, archive_front_page):\n self.archive_url = archive_url\n self.archive_front_page = archive_front_page\n self.issue_args = ['h1']\n self.date_args = ['time', {'class': 'published'}]\n self.category_args = ['section', {'class':re.compile(\"(category cc).\")}]\n self.category_title_args = ['span', {'class':'category__title__text'}]\n self.item_title_args = ['h3', {'class':'item__title'}]\n self.item_link_args = ['h3', {'class':'item__title'}]\n self.item_summary_args = ['span', {'class':'item__summary'}]\n self.issue_data = set([])\n\n self.session = requests.session()\n self.headers = {'User-Agent': 'Chrome66.0'}\n\n def extract_child(self, find_func, tag, attribs, regex = '[^(A-Za-z0-9.,>!?\\s+)]+'):\n '''\n general function that finds children elements that are defined by {tag, {attribs} and returns cleaned up corresponding text\n \n parameters:\n find_func: find or find_all function of a parent element. e.g. category.find\n tag: element tag to find. e.g. 'h2'\n attribs: element attributes to find e.g. 'class: text\n \n '''\n \n children = find_func(tag, attribs)\n if regex is not None:\n children = [re.sub(regex, '', child.get_text()) for child in children]\n\n return children\n \n def parse_category_data(self, category):\n '''\n extracts category title, list item title, and list item summary in a dataelixir newsletter\n '''\n\n cat_title = self.extract_child(category.find_all, *self.category_title_args)\n\n titles = self.extract_child(category.find_all, *self.item_title_args)\n\n links = self.extract_child(category.find, *self.item_link_args, regex = None)\n if links.a is not None:\n links = links.a.attrs['href']\n else:\n links = [np.nan]*len(titles)\n\n summaries = self.extract_child(category.find_all, *self.item_summary_args)\n\n\n category_data = {'category_title':cat_title[0], 'item_title': titles, 'item_summary':summaries, 'link':links}\n return pd.DataFrame(category_data)\n \n def get_latest_issue(self):\n '''\n extracts the latest issue number\n '''\n \n session = requests.session()\n headers = {'User-Agent': 'Chrome66.0'}\n url = self.archive_front_page\n req = session.get(url, headers=headers)\n bs = BeautifulSoup(req.text, 'lxml')\n issue_headers = bs.find_all('h2', {'class': 'item__heading'})\n latest_issue = next(issue_headers[0].children)\n latest_issue_num = int(latest_issue[-3:])\n \n return latest_issue_num\n \n def get_issue_data(self, bs):\n '''gets issue number and date'''\n \n if self.issue_args is not None:\n issue = bs.find(*self.issue_args).children\n issue_num = re.sub('[^A-Za-z0-9]+', '',next(issue))\n else:\n issue_num = np.nan\n\n if self.date_args is not None:\n \tdate = bs.find(self.date_args).get_text()\n \tdate = re.sub('[^A-Za-z0-9]+', '',date)\n else:\n \tdate = np.nan\n\n issue_data = {name:data for name, data in zip(['issue_num', 'date'], [issue_num, date])}\n self.issue_data.add(issue_num)\n return issue_data\n \n def scrape_issue(self, url):\n\n '''takes in url of a newsletter issue and returns a dataframe containing info about the issue number,date, as well as\n newsletter categories,titles,links, and summaries'''\n\n headers = {'User-Agent': 'Chrome66.0'}\n req = self.session.get(url, headers=headers)\n bs = BeautifulSoup(req.text, 'lxml')\n \n categories = bs.find_all(*self.category_args)\n issue_df = pd.concat([self.parse_category_data(category = category) for category in categories]).reset_index(drop=True)\n \n issue_data = self.get_issue_data(bs)\n issue_df['date'] = issue_data['date']\n issue_df['issue_num'] = issue_data['issue_num']\n issue_df = issue_df[['issue_num', 'date', 'category_title', 'item_title', 'item_summary', 'link']]\n return issue_df\n\n def crawl_archive(self, issue_suffixes = None):\n '''crawls through each issue in a newsletter archive and extracts the relevant data pertaining to each issue'''\n\n newsletter_df = pd.DataFrame()\n if issue_suffixes is None:\n latest_issue_num = self.get_latest_issue()\n issue_suffixes = [str(num) for num in range(1,latest_issue_num,1)]\n urls = [self.archive_url+suffix for suffix in issue_suffixes]\n for url in tqdm(urls):\n newsletter_df = pd.concat([newsletter_df, self.scrape_issue(url)]).reset_index(drop = True)\n r = random.uniform(0.5,2)\n time.sleep(r)\n\n return newsletter_df","sub_path":"dataelixir_crawler.py","file_name":"dataelixir_crawler.py","file_ext":"py","file_size_in_byte":5142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"331705991","text":"class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n self.ans = []\n candidates.sort()\n self.dfs(candidates, target, 0, [], 0)\n return self.ans\n \n def dfs(self, candidates, target, currSum, path, index):\n if currSum == target:\n self.ans.append(path[:])\n return\n \n for i in range(index, len(candidates)):\n if candidates[i] > target - currSum:\n return\n path.append(candidates[i])\n self.dfs(candidates, target, currSum+candidates[i], path, i)\n path.pop()","sub_path":"LC39CombinationSum.py","file_name":"LC39CombinationSum.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"330887987","text":"# -*- coding: utf-8 -*-\n\"\"\"Utilities for preprocessing sequence data.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import division\nfrom __future__ import absolute_import\n\nimport numpy as np\nimport random\nfrom six.moves import range\nfrom keras.utils.data_utils import Sequence\nimport warnings\n\n\nclass TimeseriesGenerator(Sequence):\n \"\"\"Utility class for generating batches of temporal data.\n This class takes in a sequence of data-points gathered at\n equal intervals, along with time series parameters such as\n stride, length of history, etc., to produce batches for\n training/validation.\n # Arguments\n data: Indexable generator (such as list or Numpy array)\n containing consecutive data points (timesteps).\n The data should be convertible into a 1D numpy array,\n if 2D or more, axis 0 is expected to be the time dimension.\n targets: Targets corresponding to timesteps in `data`.\n It should have at least the same length as `data`.\n length: length of the output sub-sequence before sampling (use hlength instead).\n sampling_rate: Period between successive individual timesteps\n within sequences, `length` has to be a multiple of `sampling_rate`.\n stride: Period between successive output sequences.\n For stride `s`, consecutive output samples would\n be centered around `data[i]`, `data[i+s]`, `data[i+2*s]`, etc.\n start_index, end_index: Data points earlier than `start_index`\n or later than `end_index` will not be used in the output sequences.\n This is useful to reserve part of the data for test or validation.\n shuffle: Whether to shuffle output samples,\n or instead draw them in chronological order.\n reverse: Boolean: if `True`, timesteps in each output sample will be\n in reverse chronological order.\n batch_size: Number of timeseries samples in each batch.\n hlength: Effective \"history\" length of the output sub-sequences after sampling (in number of timesteps).\n gap: prediction gap, i.e. numer of timesteps ahead (usually same as samplig_rate)\n `x=data[i - (hlength-1)*sampling_rate - gap:i-gap+1:sampling_rate]` and `y=targets[i]`\n are used respectively as sample sequence `x` and target value `y`.\n target_seq: Boolean: if 'True', produces full shifted sequence targets:\n If target_seq is set, for sampling rate `r`, timesteps\n `data[i - (hlength-1)*r - gap]`, ..., `data[i-r-gap]`, `data[i-gap]` and\n `targets[i - (hlength-1)*r]`, ..., `data[i-r]`, `data[i]`\n are used respectively as sample sequence `x` and target sequence `y`.\n dtype: force sample/target dtype (default is None)\n stateful: helper to set parameters for stateful learning (experimental).\n\n\n # Returns\n A [Sequence](/utils/#sequence) instance of tuples (x,y)\n where x is a numpy array of shape (batch_size, hlength, ...)\n and y is a numpy array of shape (batch_size, ...) if target_seq is `False`\n or (batch_size, hlength, ...) if target_seq is `True`.\n If not specified, output dtype is infered from data dtype.\n\n # Examples\n ```python\n from keras.preprocessing.sequence import TimeseriesGenerator\n import numpy as np\n data = np.array([[i] for i in range(50)])\n targets = np.array([[i] for i in range(50)])\n\n data_gen = TimeseriesGenerator(data, targets,\n length=5, sampling_rate=2,\n batch_size=2, shuffle=False)\n x, y = data_gen[0]\n assert len(data_gen) == 20\n assert np.array_equal(x, np.array([[[0], [2], [4], [6], [8]],\n [[1], [3], [5], [7], [9]]]))\n assert np.array_equal(y, np.array([[10], [11]]))\n\n x, y = data_gen[-1]\n\n assert np.array_equal(x, np.array([[[38], [40], [42], [44], [46]],\n [[39], [41], [43], [45], [47]]]))\n assert np.array_equal(y, np.array([[48], [49]]))\n\n txt = bytearray(\"Keras is simple.\", 'utf-8')\n data_gen = TimeseriesGenerator(txt, txt, length=10, batch_size=1)\n\n for i in range(len(data_gen)):\n print(data_gen[i][0].tostring(), \"->'%s'\" % data_gen[i][1].tostring())\n\n assert data_gen[-1][0].shape == (1, 10) and data_gen[-1][1].shape==(1,)\n assert data_gen[-1][0].tostring() == u\" is simple\"\n assert data_gen[-1][1].tostring() == u\".\"\n\n data_gen = TimeseriesGenerator(txt, txt, length=10, target_seq=True)\n\n assert data_gen[-1][0].shape == (1, 10) and data_gen[-1][1].shape==(1,10,1)\n for i in range(len(data_gen)):\n print(data_gen[i][0].tostring(), \"->'%s'\" % data_gen[i][1].tostring())\n\n assert data_gen[0][1].tostring() == u\"eras is si\"\n\n\n ```\n \"\"\"\n\n def __init__(self, data, targets, length=None,\n sampling_rate=1,\n stride=1,\n start_index=0, end_index=None,\n shuffle=False,\n reverse=False,\n batch_size=32,\n hlength=None,\n target_seq=False,\n gap=None,\n dtype=None,\n stateful=False):\n\n # Sanity check\n assert sampling_rate > 0\n assert batch_size > 0\n assert len(data) <= len(targets)\n\n if hlength is None:\n warnings.warn(\n '`length` parameter is depreciated, use `hlength` instead.', DeprecationWarning)\n if length % sampling_rate is not 0:\n raise RuntimeError(\n 'length must be a multiple of sampling_rate')\n hlength = length // sampling_rate\n\n self.hlength = hlength\n assert self.hlength > 0\n\n self.data = np.asarray(data)\n self.targets = np.asarray(targets)\n\n # FIXME: targets must be 2D, seems required by sparse losses on integer seq output\n if target_seq and len(self.targets.shape) < 2:\n self.targets = np.expand_dims(self.targets, axis=-1)\n\n if dtype is None:\n self.data_type = self.data.dtype\n self.targets_type = self.targets.dtype\n else:\n self.data_type = dtype\n self.targets_type = dtype\n\n # force stateful-compatible parameters\n if stateful:\n shuffle = False\n gap = sampling_rate\n b = batch_size\n while self.hlength % b > 0:\n b -= 1\n batch_size = b\n stride = (self.hlength // batch_size) * sampling_rate\n\n self.sampling_rate = sampling_rate\n self.batch_size = batch_size\n assert stride > 0\n self.stride = stride\n if gap is None:\n gap = sampling_rate\n self.gap = gap\n\n sliding_win_size = (self.hlength - 1) * sampling_rate + gap\n self.start_index = start_index + sliding_win_size\n if end_index is None:\n end_index = len(data)\n assert end_index <= len(data)\n self.end_index = end_index\n self.reverse = reverse\n self.target_seq = target_seq\n\n assert self.start_index < self.end_index\n assert self.batch_size * self.stride > 0\n assert self.batch_size * self.stride < self.end_index - self.start_index\n self.len = (self.end_index -\n self.start_index) // (self.batch_size * self.stride)\n assert self.len > 0\n\n self.perm = np.arange(self.start_index, self.end_index)\n if shuffle:\n np.random.shuffle(self.perm)\n\n def __len__(self):\n return self.len\n\n def _empty_batch(self, num_rows):\n samples_shape = [num_rows, self.hlength]\n samples_shape.extend(self.data.shape[1:])\n if self.target_seq:\n targets_shape = [num_rows, self.hlength]\n else:\n targets_shape = [num_rows]\n targets_shape.extend(self.targets.shape[1:])\n\n return np.empty(samples_shape, dtype=self.data_type), np.empty(targets_shape, dtype=self.targets_type)\n\n def __getitem__(self, index):\n while index < 0:\n index += self.len\n assert index < self.len\n i = self.batch_size * self.stride * index\n assert i + self.batch_size * self.stride <= self.end_index\n rows = np.arange(i, i + self.batch_size * self.stride, self.stride)\n rows = self.perm[rows]\n\n samples, targets = self._empty_batch(len(rows))\n for j, row in enumerate(rows):\n indices = range(rows[j] - self.gap - (self.hlength - 1) * self.sampling_rate,\n rows[j] - self.gap + 1, self.sampling_rate)\n samples[j] = self.data[indices]\n if self.target_seq:\n shifted_indices = range(rows[j] - (self.hlength - 1) * self.sampling_rate,\n rows[j] + 1, self.sampling_rate)\n targets[j] = self.targets[shifted_indices]\n else:\n targets[j] = self.targets[rows[j]]\n if self.reverse:\n return samples[:, ::-1, ...], targets\n return samples, targets\n","sub_path":"keras_contrib/preprocessing/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":9211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"240321578","text":"import math\n\nfrom RLBotFramework.agents.base_agent import BaseAgent\nfrom RLBotFramework.utils.structures.quick_chats import QuickChats\n\nURotationToRadians = math.pi / float(32768)\n\n\nclass Atba(BaseAgent):\n flip_turning = False\n\n def get_output_vector(self, game_tick_packet):\n\n ball_location = Vector2(game_tick_packet.gameball.Location.X, game_tick_packet.gameball.Location.Y)\n\n my_car = game_tick_packet.gamecars[self.index]\n car_location = Vector2(my_car.Location.X, my_car.Location.Y)\n car_direction = get_car_facing_vector(my_car)\n car_to_ball = ball_location - car_location\n\n steer_correction_radians = car_direction.correction_to(car_to_ball)\n\n if steer_correction_radians > 0:\n # Positive radians in the unit circle is a turn to the left.\n turn = -1.0 # Negative value for a turn to the left.\n else:\n turn = 1.0\n\n if self.flip_turning:\n self.flip_turning = not self.flip_turning\n turn *= -1.0\n\n #self.send_quick_chat(QuickChats.CHAT_EVERYONE, QuickChats.Information_IGotIt)\n\n return [\n 1.0, # throttle\n turn, # steer\n 0.0, # pitch\n 0.0, # yaw\n 0.0, # roll\n 0, # jump\n 0, # boost\n 0 # handbrake\n ]\n\n def load_config(self, config_header):\n self.flip_turning = config_header.getboolean('flip_turning')\n\n @staticmethod\n def create_agent_configurations():\n config = super(Atba, Atba).create_agent_configurations()\n config.add_header_name('Bot Parameters').add_value('flip_turning', bool, default=False,\n description='if true bot will turn opposite way')\n return config\n\n\nclass Vector2:\n def __init__(self, x=0, y=0):\n self.x = float(x)\n self.y = float(y)\n\n def __add__(self, val):\n return Vector2(self.x + val.x, self.y + val.y)\n\n def __sub__(self, val):\n return Vector2(self.x - val.x, self.y - val.y)\n\n def correction_to(self, ideal):\n # The in-game axes are left handed, so use -x\n current_in_radians = math.atan2(self.y, -self.x)\n ideal_in_radians = math.atan2(ideal.y, -ideal.x)\n\n correction = ideal_in_radians - current_in_radians\n\n # Make sure we go the 'short way'\n if abs(correction) > math.pi:\n if correction < 0:\n correction += 2 * math.pi\n else:\n correction -= 2 * math.pi\n\n return correction\n\n\ndef get_car_facing_vector(car):\n pitch = float(car.Rotation.Pitch)\n yaw = float(car.Rotation.Yaw)\n\n facing_x = math.cos(pitch * URotationToRadians) * math.cos(yaw * URotationToRadians)\n facing_y = math.cos(pitch * URotationToRadians) * math.sin(yaw * URotationToRadians)\n\n return Vector2(facing_x, facing_y)\n","sub_path":"agents/atba/atba.py","file_name":"atba.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"318149702","text":"#coding=utf-8\n\nfrom contextlib import contextmanager\nfrom redis import StrictRedis\nfrom .local import LocalStack, release_local\nfrom .compat.connections import patch_connection\nfrom .utils import funclog\n\nclass NoRedisConnectionException(Exception):\n pass\n\n# contextmanager 用于构造 with 语句的生成器。\n# 在这里 yield 没有具体的迭代值,整个生成器为 [None],在这里的目的主要是使 Connection 支持 with 语法,\n# 实现是在 try 之前的 push_connection() 初始化了变量 _connection_stack,最后在 finnaly 进行 assert,\n# 这个 _connection_stack 变量可以在 queue.py 中通过本文件定义的函数进行使用。\n# 参考:http://www.python.org/dev/peps/pep-0343/\n@contextmanager\ndef Connection(connection=None):\n funclog()\n if connection is None:\n connection = StrictRedis()\n push_connection(connection)\n try:\n yield\n finally:\n popped = pop_connection()\n assert popped == connection, \\\n 'Unexpected Redis connection was popped off the stack. ' \\\n 'Check your Redis connection setup.'\n\n\ndef push_connection(redis):\n \"\"\"Pushes the given connection on the stack.\"\"\"\n funclog()\n _connection_stack.push(patch_connection(redis))\n\n\ndef pop_connection():\n \"\"\"Pops the topmost connection from the stack.\"\"\"\n funclog()\n return _connection_stack.pop()\n\n\ndef use_connection(redis=None):\n \"\"\"Clears the stack and uses the given connection. Protects against mixed\n use of use_connection() and stacked connection contexts.\n \"\"\"\n assert len(_connection_stack) <= 1, \\\n 'You should not mix Connection contexts with use_connection().'\n release_local(_connection_stack)\n\n if redis is None:\n redis = StrictRedis()\n push_connection(redis)\n\n\ndef get_current_connection():\n \"\"\"Returns the current Redis connection (i.e. the topmost on the\n connection stack).\n \"\"\"\n funclog()\n return _connection_stack.top\n\n\ndef resolve_connection(connection=None):\n \"\"\"Convenience function to resolve the given or the current connection.\n Raises an exception if it cannot resolve a connection now.\n\n 获取 connection\n 如果传入 Redis 对象,则用 partail 附加上 StrictRedis 对应的方法\n 如果传入 StrictRedis 对象,不做改变\n 如果不传参数(仅在 with Connection() 与语法下可用),由 rq 默认生成\n \"\"\"\n funclog()\n if connection is not None:\n return patch_connection(connection)\n\n connection = get_current_connection()\n if connection is None:\n raise NoRedisConnectionException('Could not resolve a Redis connection.')\n return connection\n\n\n_connection_stack = LocalStack()\n\n__all__ = ['Connection', 'get_current_connection', 'push_connection',\n 'pop_connection', 'use_connection']\n","sub_path":"rq/connections.py","file_name":"connections.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"469222601","text":"##圖案轉換點\nimport cv2 \nimport numpy as np \nfrom matplotlib import pyplot as plt\n\n#轉換點格式\npts1 = np.float32([[0,0],[0,0],[0,0],[0,0]]) #預設4個點為0\n\ni=0\n#定義滑鼠要幹嘛\ndef savexy(event,x,y,flags,param):\n global pst1\n global i\n if event==cv2.EVENT_LBUTTONDBLCLK:\n print(x,y) #可印在程式裡面\n #cv2.circle(img,(x,y), 3, (0,0,0) ,3)也可以換畫點點\n pts1[i]=[x,y]#按下滑鼠會將原本預設的數值更改\n i+=1\n\nimg=cv2.imread('test2.jpg')\nrows,cols,ch=img.shape\n\n#第二條線為對齊線\npts2 = np.float32([[0,0],[400,0],[0,400],[400,400]])#向中間線對齊\n\n\n#先開一張圖image\ncv2.namedWindow('image')\ncv2.setMouseCallback('image',savexy)\nwhile(1):\n cv2.imshow('image',img)\n if cv2.waitKey(20)&0xFF==27 or i>3:\n break\ncv2.destroyAllWindows()\n\nM=cv2.getPerspectiveTransform(pts1,pts2)\ndst=cv2.warpPerspective(img,M,(300,300))\ndst1 = cv2.cvtColor(dst,cv2.COLOR_BGR2RGB)\nplt.subplot(121), plt.imshow(img), plt.title('Input')\nplt.subplot(122), plt.imshow(dst1), plt.title('Output')\nplt.show()\n\n","sub_path":"test-13.py","file_name":"test-13.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"424729744","text":"\"\"\"\nVersion 2 of Grid world.\n\"\"\"\n\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\n\nclass State:\n beta = 1.\n \n mask = 65535\n \n @staticmethod\n def to_token(a, b):\n \"\"\"\n a and b: are int(s) or numpy arrays of dtype=int of same shape\n \"\"\"\n return np.array(a*State.mask + b, dtype=int)\n \n @staticmethod\n def to_coord(token):\n \n return np.array([token//State.mask, token%State.mask], dtype=int).T\n \n @classmethod\n def set_beta(cls, beta):\n cls.beta = beta\n \n @classmethod\n def set_params(cls, agents=None, n_row=10, n_col=10):\n \"\"\"\n Parameters\n ----------\n targets: iterable of targets' original coordinates from (1,1) to (n,m)\n agents: iterable of agents' original coordinates\n \"\"\"\n cls.n_row = n_row\n cls.n_col = n_col\n \n if agents is None:\n cls.agents = np.array([State.to_token(np.random.randint(0,cls.n_row),np.random.randint(0,cls.n_col))])\n else:\n cls.agents = State.to_token(*np.array(agents).T)\n \n def __init__(self, i, j):\n self.coord = np.array([i, j])\n self.token = State.to_token(i, j)\n \n self.Q = []\n self.value = -2.\n self.action = []\n self.cost = []\n # self.map = {}\n \n def set_targets(self, targets=None):\n if targets is None:\n self.targets = np.array([State.to_token(np.random.randint(0,cls.n_row),np.random.randint(0,cls.n_col))])\n else:\n self.targets = State.to_token(*np.array(targets).T)\n\n \n def add_action(self, action, cost):\n self.action += [action,]\n self.cost += [cost,]\n self.Q += [0,]\n \n # self.map[action] = cost\n \n def change_cost(self, action, cost):\n self.cost[self.action == action] = cost\n # self.map[action] = cost\n \n \n def update_Q(self):\n for i in range(len(self.action)):\n self.Q[i] = self.action[i].value + self.cost[i]\n\n def update_V(self, targets=None, values=None):\n '''\n targets: self-defined targets, iterable, in terms of token\n values: dict, key=target token, value=value of target\n '''\n if targets is None:\n targets = self.targets\n if self.token in targets:\n # print(type(self.token), self.token)\n self.value = values[int(self.token)] if values is not None else 0\n return self.value\n old_value = self.value\n prob = np.exp(np.array(self.Q) * State.beta)\n prob /= np.sum(prob)\n self.value = np.matmul(prob, np.array(self.Q))\n return abs(self.value - old_value)\n\n\n\ndef set_board(n=10, m=10, blocks=[],targets=None, agents=None,beta=1.0):\n \n \n State.set_beta(beta)\n State.set_params(n_row=n, n_col=m, agents=agents)\n\n seq = [None] * ((m+2)*(n+2))\n\n seq = np.array(seq, dtype=State)\n board = seq.reshape(n+2,m+2)\n\n for i in range(m*n):\n board[i//m+1, i%m+1] = State(i//m, i%m)\n board[i//m+1, i%m+1].set_targets(targets=targets)\n\n for block in blocks:\n # assert isinstance(block[0],int)\n board[int(block[0]), int(block[1])] = None\n \n \n directions = [np.array([-1,0]),\n np.array([1,0]),\n np.array([0,-1]),\n np.array([0,1])]\n for i in range(1,n+1):\n for j in range(1, m+1):\n if board[i,j] is None:\n continue\n for d in directions:\n if board[i+d[0], j+d[1]] is not None:\n board[i,j].add_action(board[i+d[0], j+d[1]], 0 if State.to_token(i+d[0], j+d[1]) in board[i,j].targets else -1)\n\n return seq, board\n\n\ndef update(board, seq=None, targets=None, values=None):\n '''\n could be more flexible, but less efficient\n '''\n diff = np.zeros_like(seq, dtype=float)\n for element in seq:\n if element is not None:\n element.update_Q()\n for i, element in enumerate(seq):\n if element is not None:\n diff[i] = element.update_V(targets, values)\n return diff","sub_path":"grid2.py","file_name":"grid2.py","file_ext":"py","file_size_in_byte":4201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"626709647","text":"\nfrom __future__ import print_function\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os, time, sys, copy\nfrom time import gmtime, strftime\nfrom tqdm import tqdm\n\nfrom sklearn.cross_validation import KFold\nfrom sklearn.metrics import fbeta_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\nimport cv2\nfrom PIL import Image, ImageEnhance\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nimport torchvision.models as models\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\n\n## Import self-defined modules ###\nimport PyTorch_models as my_models\nimport Image_transformation as IT\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n#####################################################\ntrain_img_path = '../input/train-jpg/'\ntest_img_path = '../input/test-jpg/'\nimg_ext = '.jpg'\n\nmodel_weight_file = './PyTorch_densenet_v1.hdf5'\npretrained_weight_file = './densenet121_weights_tf.h5'\n\nnum_classes = 17\npatience = 10\n\nimg_dim_1 = 224 # 224 standard input size for densenet, resnet, VGG\nimg_dim_2 = 299 # 299 input size for inception_v3\n\nnum_epochs = 40 #25\nbatch_size = 20\n\nlr = 1e-4 #1e-3 for SGD; 1e-4 for Adam\nlr_decay_epoch = 12\n\nwarm_start = True\n\nrandomTTA = False\nTTA_num_train = 7 # If randomTTA False, automatically set to 7\nTTA_num_test = 7 # If randomTTA False, automatically set to 7\n\nsharperness_factor = 1.6\ncontrast_factor = 1.05\n\nrun_training = True\ngenerate_predictions = True\nthreshold_optimisation = True\nmake_submission = True\n\n#####################################################\nstart_time = time.time()\nprint()\nprint('Start Time: {}'.format(strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())))\n\ndf_train_all = pd.read_csv('../input/train_v2.csv')\ndf_test = pd.read_csv('../input/sample_submission_v2.csv')\n\nmlb = MultiLabelBinarizer()\nmlb.fit_transform( df_train_all['tags'].str.split()).astype(np.float32)\n\nprint('-' * 10), print('Labels:'), print('-' * 10)\nfor label in list(mlb.classes_):\n print(label)\nprint('-' * 50)\n\n\n######################################################\ndef get_train_valid_df(df_train_all, val_size=0.2):\n train_size = 1 - val_size\n K = int(len(df_train_all) * train_size)\n\n df_train_all = df_train_all.sample(frac=1).reset_index(drop=True)\n df_train = df_train_all[:K].reset_index(drop=True)\n df_valid = df_train_all[K:].reset_index(drop=True)\n\n return df_train, df_valid\n\n\n######################################################\nrepeat_splitting = True\nsplit_count = 0\n\nwhile repeat_splitting:\n\n df_train, df_valid = get_train_valid_df(df_train_all, val_size=0.2)\n\n # Code below make sure the valid set has enough samples for rare labels\n mlb_valid = MultiLabelBinarizer()\n Y = mlb_valid.fit_transform( df_valid['tags'].str.split()).astype(np.float32)\n labels = list(mlb.classes_)\n split_count += 1\n\n idx1 = labels.index('blow_down') #Only 98 images in Train set\n idx2 = labels.index('conventional_mine') #Only 100 images in Train set\n\n a1 = np.sum(Y[:,idx1])\n a2 = np.sum(Y[:,idx2])\n\n if (len(mlb_valid.classes_) == num_classes) and a1 >= 25 and a2 >= 25:\n print('Train valid split count = {}'.format(split_count))\n print('Valid data: blow_down count = {}; conventional_mine count = {}'.format(a1, a2))\n repeat_splitting = False\n\n######################################################\n\nclass KaggleAmazonDataset(Dataset):\n ## From: https://www.kaggle.com/mratsim/starting-kit-for-pytorch-deep-learning\n \"\"\"Dataset wrapping images and target labels for Kaggle - Planet Amazon from Space competition.\n\n Arguments:\n A CSV file path\n Path to image folder\n Extension of images\n PIL transforms\n \"\"\"\n\n def __init__(self, df, img_path, img_ext='.jpg', transform=None):\n\n assert df['image_name'].apply(lambda x: os.path.isfile(img_path + x + img_ext)).all()\n\n self.mlb = MultiLabelBinarizer()\n self.img_path = img_path\n self.img_ext = img_ext\n self.transform = transform\n\n self.X_train = df['image_name']\n self.y_train = self.mlb.fit_transform(df['tags'].str.split()).astype(np.float32)\n self.tags = df['tags']\n\n def __getitem__(self, index):\n img = Image.open(self.img_path + self.X_train[index] + self.img_ext)\n\n img = ImageEnhance.Sharpness(img).enhance( sharperness_factor)\n img = ImageEnhance.Contrast(img).enhance( contrast_factor)\n\n img = img.convert('RGB')\n if self.transform is not None:\n img = self.transform(img)\n\n label = torch.from_numpy(self.y_train[index])\n return img, label, self.tags[index]\n\n def __len__(self):\n return len(self.X_train.index)\n\n\n######################################################\ndef get_y_train(df=df_train):\n mlb = MultiLabelBinarizer()\n Y = mlb.fit_transform( df['tags'].str.split()).astype(np.float32)\n #print('Labels: {}'.format(list(mlb.classes_)))\n return Y\n\n#######################################################\ndef exp_lr_scheduler(optimizer, epoch, init_lr=lr, lr_decay_epoch=lr_decay_epoch):\n \"\"\"Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.\"\"\"\n lr = init_lr * (0.1**(epoch // lr_decay_epoch))\n\n if epoch % lr_decay_epoch == 0:\n print('LR is set to {}'.format(lr))\n\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n return optimizer\n\n#######################################################\ndef fixed_lr_scheduler(optimizer, epoch, init_lr=lr): #lr=0.01\n lr = init_lr\n if epoch >= 6: lr = init_lr * 0.1\n if epoch >= 12: lr = init_lr * 0.01\n if epoch >= 18: lr = init_lr * 0.001\n\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n print('LR is set to {}'.format(lr))\n return optimizer\n\n#######################################################\ndef f2_score(y_true, y_pred):\n # fbeta_score throws a confusing error if inputs are not numpy arrays\n y_true, y_pred, = np.array(y_true), np.array(y_pred)\n # We need to use average='samples' here, any other average method will generate bogus results\n return fbeta_score(y_true, y_pred, beta=2, average='samples')\n\n######################################################\ndef train_model(model, optimizer, lr_scheduler, num_epochs=30):\n\n best_model = model\n best_loss = 1.0\n best_epoch = 0\n patience_count = 0\n\n for epoch in range(num_epochs):\n since = time.time()\n\n\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 50)\n\n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n if phase == 'train':\n optimizer = lr_scheduler(optimizer, epoch)\n model.train(mode=True) # Set model to training mode\n else:\n model.train(mode=False) # Set model to evaluate mode\n\n running_loss = 0.0\n data_count = 0\n predictions = []\n y_true = []\n\n #Used in inter-epoch print out\n num_print_per_epoch = 10\n num_batches = int(dset_sizes[phase] // batch_size + 1)\n A = int(num_batches // num_print_per_epoch + 1)\n\n # Iterate over data in batches\n for batch_idx, data in enumerate(dset_loaders[phase]):\n inputs, labels, _ = data\n inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())\n\n data_count += len(inputs)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n outputs = model(inputs)\n\n loss = F.binary_cross_entropy(outputs, labels)\n running_loss += batch_size * loss.data[0]\n\n if (phase == 'train'):\n # backward + optimize only if in training phase\n loss.backward()\n optimizer.step()\n\n # Print inter-epoch output\n if (batch_idx % A == 0):\n # print('{} Epoch: {} [{}/{} ({:.0f}%)] \\tLoss: {:.6f}'.format(\n # phase, epoch, batch_idx * len(inputs), dset_sizes[phase],\n # 100. * batch_idx / num_batches, loss.data[0]))\n\n num_processed = batch_idx * len(inputs)\n print('{} Epoch: {} [{}/{} ({:.0f}%)] \\tLoss: {:.6f}'.format(\n phase, epoch, num_processed, dset_sizes[phase],\n 100. * num_processed / dset_sizes[phase], loss.data[0]))\n\n\n if phase == 'val':\n output_numpy = outputs.cpu().data.numpy().reshape(-1, num_classes)\n predictions = np.vstack((predictions, output_numpy)) if batch_idx > 0 else output_numpy\n\n labels_numpy = labels.cpu().data.numpy().reshape(-1, num_classes)\n y_true = np.vstack((y_true, labels_numpy)) if batch_idx > 0 else labels_numpy\n\n\n epoch_loss = running_loss / dset_sizes[phase]\n print('{} Loss: {:.4f}'.format( phase, epoch_loss))\n\n # deep copy the model\n if phase == 'val':\n if epoch_loss < best_loss:\n best_loss = epoch_loss\n best_epoch = epoch\n best_model = copy.deepcopy(model)\n torch.save(best_model, '../modelsnapshot/best_current_model.torch')\n patience_count = 0\n else:\n patience_count += 1\n print('Patience count: {}'.format(patience_count))\n\n assert (data_count == dset_sizes[phase])\n\n f_score = fbeta_score(y_true, predictions > 0.2, beta=2, average='samples')\n print('Validation Fbeta_score: {:.6f}'.format(f_score))\n\n time_elapsed = time.time() - since\n print('Epoch complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n print('')\n\n if patience_count >= patience:\n break\n\n print('Best result in epoch: {}'.format(best_epoch))\n torch.save(best_model, '../modelsnapshot/best_final_model.torch')\n\n time_elapsed = time.time() - start_time\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n print('')\n\n return best_model, predictions\n\n#####################################################\ndef predict(model, dataset_loader, to_evaluate=True):\n\n since = time.time()\n\n N = len(dataset_loader.dataset)\n model.train(mode=False) # Set model to evaluate mode\n\n # Used in inter-epoch print out\n # num_print_per_epoch = 4\n # num_batches = int(N // batch_size + 1)\n # A = int(num_batches // num_print_per_epoch + 1)\n\n running_loss = 0.0\n data_count = 0\n predictions = []\n y_true = []\n\n # Iterate over data in batches\n for batch_idx, data in enumerate(dataset_loader):\n inputs, labels, tags = data\n inputs, labels = Variable(inputs.cuda(), volatile=True), Variable(labels.cuda(), volatile=True)\n\n data_count += len(inputs)\n\n # forward\n outputs = model(inputs)\n\n output_numpy = outputs.cpu().data.numpy().reshape(-1, num_classes)\n predictions = np.vstack((predictions, output_numpy)) if batch_idx > 0 else output_numpy\n\n # Print inter-epoch output\n # if (batch_idx % A == 0):\n # num_processed = batch_idx * len(inputs)\n # print('[{}/{} ({:.0f}%)]'.format(num_processed, N, 100. * num_processed / N))\n\n if to_evaluate:\n loss = F.binary_cross_entropy(outputs, labels)\n running_loss += batch_size * loss.data[0]\n\n labels_numpy = labels.cpu().data.numpy().reshape(-1, num_classes)\n y_true = np.vstack((y_true, labels_numpy)) if batch_idx > 0 else labels_numpy\n\n assert (data_count == N)\n #print(( np.shape(predictions), np.shape(y_true)))\n\n if to_evaluate:\n epoch_loss = running_loss / N\n print('Evaluation Loss: {:.4f}'.format(epoch_loss))\n\n f_score = fbeta_score(y_true, predictions > 0.2, beta=2, average='samples')\n print('Fbeta_score: {:.6f}'.format(f_score))\n\n time_elapsed = time.time() - since\n print('Evaluation/Prediction complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n print()\n\n return predictions\n\n\n############## Initialising the model ##############\n#use_gpu = torch.cuda.is_available()\n\n# my_Model, model_name = my_models.inception_v3(num_classes = 17, pretrained=True)\n# my_Model, model_name = my_models.resnet34(num_classes = 17, pretrained=True)\n# my_Model, model_name = my_models.resnet18(num_classes = 17, pretrained=True)\nmy_Model, model_name = my_models.densenet121(num_classes = 17, pretrained=True)\n# my_Model, model_name = my_models.vgg19(num_classes = 17, pretrained=True)\n\n#ignored_params = list(map(id, param_list))\nignored_params = list(map(id, my_Model.sigmoid.parameters()))\nbase_params = filter(lambda p: id(p) not in ignored_params, my_Model.parameters())\n\n# optimizer = optim.Adam(my_Model.parameters(), lr=lr)\n\n# optimizer = optim.SGD([\n# {'params': base_params, 'lr': lr*0.1},\n# {'params': my_Model.sigmoid.parameters()}\n# ], lr=lr, momentum=0.9)\n\noptimizer = optim.Adam([\n {'params': base_params, 'lr': lr*0.1},\n {'params': my_Model.sigmoid.parameters()}\n ], lr=lr)\n\nmy_Model = my_Model.cuda()\n\n\n############## Setting Data Loaders ##############\nimg_dim = img_dim_2 if model_name == 'Inception_v3' else img_dim_1\n\n#Normalise with Image net Mean and Std when using pre-trained models\nnormMean = [0.485, 0.456, 0.406]\nnormStd = [0.229, 0.224, 0.225]\n\ntrain_transform = [ transforms.Lambda(lambda x: IT.RandomResize(x)),\n transforms.RandomCrop(img_dim),\n transforms.Lambda(lambda x: IT.transformations(x, np.random.randint(7))),\n transforms.ToTensor(),\n transforms.Normalize(normMean, normStd)\n ]\n\nval_transform = [ transforms.CenterCrop(img_dim),\n transforms.Lambda(lambda x: IT.transformations(x, np.random.randint(7))),\n transforms.ToTensor(),\n transforms.Normalize(normMean, normStd)\n ]\n\nif model_name == 'Inception_v3':\n train_transform.insert(0, transforms.Scale(340))\n val_transform.insert(0, transforms.Scale(340))\n\ndata_transforms = {\n 'train': transforms.Compose(train_transform),\n 'val': transforms.Compose(val_transform),\n}\n\ndsets = {\n 'train': KaggleAmazonDataset(df_train, train_img_path, img_ext, data_transforms['train']),\n 'val': KaggleAmazonDataset(df_valid, train_img_path, img_ext, data_transforms['val']),\n}\n\ndset_loaders = {\n x: DataLoader(\n dsets[x],\n batch_size=batch_size,\n shuffle=True,\n num_workers=1, # 1 for CUDA\n pin_memory=True # CUDA only\n )\n for x in ['train', 'val']\n}\n\ndset_sizes = {x: len(dsets[x]) for x in ['train', 'val']}\nprint('dset sizes: {}'.format(dset_sizes))\nprint('-' * 50)\n\n\n######## Training models ########################\nif run_training:\n print('###### {} model to run for {} epochs ######'.format(model_name, num_epochs))\n print('-' * 50)\n\n if warm_start:\n my_Model = torch.load('../modelsnapshot/best_current_model.torch')\n print('Continuing from best_current_model')\n\n best_model, _ = train_model(my_Model, optimizer, exp_lr_scheduler, num_epochs=num_epochs)\n #best_model, _ = train_model(my_Model, optimizer, fixed_lr_scheduler, num_epochs=num_epochs)\n print('-' * 50)\n\n######## Getting predictions ######################\nif generate_predictions:\n best_model = torch.load('../modelsnapshot/best_final_model.torch')\n # best_model = torch.load('../modelsnapshot/best_{}.torch'.format())\n\n for phase in ['train', 'test']:\n pred_list = []\n\n if not randomTTA:\n TTA_num_train = 7\n TTA_num_test = 7\n\n print('TTA_num_train: {}; TTA_num_test: {}'.format(TTA_num_train, TTA_num_test))\n\n for i in range(TTA_num_test):\n print('Running {} TTA prediction, iter {}'.format(phase, i))\n\n data_transforms['augmentation'] = transforms.Compose([\n #transforms.CenterCrop(img_dim),\n transforms.Scale(img_dim),\n transforms.Lambda(lambda x: IT.transformations(x, choice=i)),\n transforms.ToTensor(),\n transforms.Normalize(normMean, normStd)\n ])\n\n if phase == 'train':\n dsets[phase] = KaggleAmazonDataset(df_train_all, train_img_path, img_ext, data_transforms['augmentation'])\n #dsets[phase] = KaggleAmazonDataset(df_valid, train_img_path, img_ext, data_transforms['augmentation'])\n eval_flag = True\n else:\n dsets[phase] = KaggleAmazonDataset(df_test, test_img_path, img_ext, data_transforms['augmentation'])\n eval_flag = False\n\n dset_loaders[phase] = DataLoader(\n dsets[phase], batch_size=batch_size*4, shuffle=False, num_workers=1, pin_memory=True)\n\n pred = predict(best_model, dset_loaders[phase], to_evaluate=eval_flag)\n pred_list.append(pred)\n\n # if phase == 'valid' and i >= TTA_num_train-1:\n # break\n\n TTA_predictions = np.mean(pred_list, axis=0)\n\n prediction_file = '../submission/TTA_{}_pred_{}.npy'.format(phase, model_name)\n np.save(prediction_file, TTA_predictions)\n\n print('-' * 50)\n\n####### Threshold optimisation ################\nif threshold_optimisation:\n print('Optimise Threshold...')\n\n p_test = np.load('../submission/TTA_test_pred_{}.npy'.format(model_name))\n p_train = np.load('../submission/TTA_train_pred_{}.npy'.format(model_name))\n y_train = get_y_train( df_train_all)\n # p_train = np.load('../submission/TTA_valid_pred_{}.npy'.format(model_name))\n # y_train = get_y_train(df_valid)\n\n M = len(p_train)\n C = num_classes\n\n def get_f2_score(y_true, x_pred, x):\n y_pred = np.zeros((M, C))\n\n for i in range(C):\n y_pred[:, i] = (x_pred[:, i] > x[i]).astype(np.int)\n score = fbeta_score(y_true, y_pred, beta=2, average='samples')\n return score\n\n base_threshold = [0.2] * num_classes\n base_line_score = get_f2_score(y_train, p_train, base_threshold)\n print('Base line Train data F2 score: {:.6f}'.format(base_line_score))\n\n #########################\n def optimise_f2_thresholds(y_true, x_pred, resolution, verbose=True):\n # From: https://www.kaggle.com/c/planet-understanding-the-amazon-from-space/discussion/32475\n label_count = 0\n\n x = [0.2] * num_classes\n for c in range(C):\n best_threshold = 0\n best_score = 0\n for i in range(resolution):\n i /= float(resolution)\n x[c] = i\n score = get_f2_score(y_true, x_pred, x)\n if score > best_score:\n best_threshold = i\n best_score = score\n x[c] = best_threshold\n if verbose:\n print('{}, best threshold {}, f2-score {:.6f}'.format(c, best_threshold, best_score))\n return x\n\n optimised_threshold = optimise_f2_thresholds(y_train, p_train, 100)\n optimised_score = get_f2_score(y_train, p_train, optimised_threshold)\n print('Best Train data F2 score: {:.6f}'.format(optimised_score))\n print()\n\n###### Prepare submission ######\nif make_submission:\n print('Making submission......')\n p_train = np.load('../submission/TTA_train_pred_{}.npy'.format(model_name))\n #p_train = np.load('../submission/TTA_valid_pred_{}.npy'.format(model_name))\n p_test = np.load('../submission/TTA_test_pred_{}.npy'.format(model_name))\n y_train = get_y_train(df_train_all)\n\n labels = list(mlb.classes_)\n pred_tags = []\n\n for i in tqdm(range(len(p_test)), miniters=1000):\n a = p_test[i]\n row_labels = []\n\n for j in range(num_classes):\n if a[j] >= optimised_threshold[j]:\n row_labels = np.append(row_labels, labels[j])\n pred_tags = np.append(pred_tags, [' '.join(row_labels)])\n\n df_test = pd.read_csv('../input/sample_submission_v2.csv')\n df_test['tags'] = pred_tags\n submission_file = '../submission/submission_{:.4f}.csv'.format(optimised_score)\n df_test.to_csv(submission_file, index=False)\n print('{} saved'.format(submission_file))\n\n df_test.head()\n\n print('Process done. Duration: {:.1f} minutes'.format((time.time() - start_time)/60))\n\n#######################################################\n\n# if __name__ == \"__main__\":\n #train_model()\n\n","sub_path":"PyTorch Amazon.py","file_name":"PyTorch Amazon.py","file_ext":"py","file_size_in_byte":21034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"562863632","text":"# encoding='utf-8'\r\nimport os\r\nimport re\r\n\r\n# 去除空行\r\ndef delblankline(infile, outfile):\r\n \"\"\" Delete blanklines of infile \"\"\"\r\n infp = open(infile+\".txt\", \"r\", encoding='utf-8')\r\n outfp = open(infile+outfile, \"w\", encoding='utf-8')\r\n lines = infp.readlines()\r\n for li in lines:\r\n if li.split():\r\n outfp.writelines(li)\r\n infp.close()\r\n outfp.close()\r\n\r\n# 添加中文逗号\r\ndef addPunctuation(infile, outfile):\r\n infp = open(infile+\".txt\", \"r\", encoding='utf-8')\r\n outfp = open(infile+outfile, \"w\", encoding='utf-8')\r\n lines = infp.readlines()\r\n i = 0\r\n j = 0\r\n for li in lines:\r\n # if j == 4*i+2:\r\n if j == 4*i+2:\r\n # +\",\"\r\n outfp.writelines(li+\",\")\r\n i = i + 1\r\n j = j+1\r\n infp.close()\r\n outfp.close()\r\n\r\n\r\n# 添加英文文逗号\r\ndef addengPunctuation(infile, outfile):\r\n infp = open(infile+\".txt\", \"r\", encoding='utf-8')\r\n outfp = open(infile+outfile, \"w\", encoding='utf-8')\r\n lines = infp.readlines()\r\n i = 0\r\n j = 0\r\n for li in lines:\r\n # if j == 4*i+3:\r\n if j == 3*i:\r\n # +\",\"\r\n outfp.writelines(li)\r\n i = i + 1\r\n j = j+1\r\n infp.close()\r\n outfp.close()\r\n\r\n# 去除换行\r\ndef deleteln(infile, outfile):\r\n \"\"\" Delete blanklines of infile \"\"\"\r\n infp = open(infile+\".txt\", \"r\", encoding='utf-8')\r\n outfp = open(infile+outfile, \"w\", encoding='utf-8')\r\n lines = infp.readlines()\r\n for li in lines:\r\n li = li.strip('\\n')\r\n outfp.writelines(li)\r\n infp.close()\r\n outfp.close()\r\n\r\n\r\n# 调用示例\r\nif __name__ == \"__main__\":\r\n\tfilename = \"1_8\"\r\n\tdelblankline(filename, \"no.txt\")\r\n\t# addPunctuation(filename +\"no\", \"ch.txt\")\r\n\t# deleteln(filename+\"noch\",\"ch.txt\")\r\n\t# filename = \"1_13\"\r\n\t# delblankline(filename, \"no.txt\")\r\n\taddengPunctuation(filename+\"no\", \"e.txt\")\r\n\tdeleteln(filename+\"noe\",\"en.txt\")\r\n","sub_path":"tool/deal_en.py","file_name":"deal_en.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"66532169","text":"\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nfrom compas_blender.artists import Artist\r\nfrom compas_blender.artists.mixins import VertexArtist\r\nfrom compas_blender.artists.mixins import EdgeArtist\r\n\r\n\r\n__all__ = [\r\n 'NetworkArtist',\r\n]\r\n\r\n\r\nclass NetworkArtist(EdgeArtist, VertexArtist, Artist):\r\n\r\n __module__ = \"compas_blender.artists\"\r\n\r\n\r\n def __init__(self, network, layer=None):\r\n super(NetworkArtist, self).__init__(layer=layer)\r\n\r\n self.network = network\r\n self.defaults.update({\r\n 'color.vertex': [255, 255, 255],\r\n 'color.edge': [0, 0, 0],\r\n })\r\n\r\n\r\n @property\r\n def network(self):\r\n\r\n return self.datastructure\r\n\r\n\r\n @network.setter\r\n def network(self, network):\r\n\r\n self.datastructure = network\r\n\r\n\r\n def draw(self):\r\n\r\n raise NotImplementedError\r\n\r\n\r\n def clear(self):\r\n\r\n self.clear_vertices()\r\n self.clear_edges()\r\n\r\n\r\n# ==============================================================================\r\n# Main\r\n# ==============================================================================\r\n\r\nif __name__ == \"__main__\":\r\n\r\n import compas\r\n\r\n from compas.datastructures import Network\r\n\r\n\r\n network = Network.from_obj(compas.get('grid_irregular.obj'))\r\n\r\n artist = NetworkArtist(network=network)\r\n\r\n # artist.clear_layer()\r\n\r\n artist.draw_vertices(radius=0.1)\r\n artist.draw_vertexlabels()\r\n # artist.clear_vertexlabels()\r\n\r\n artist.draw_edges(width=0.01)\r\n artist.draw_edgelabels()\r\n # artist.clear_edgelabels()\r\n","sub_path":"src/compas_blender/artists/networkartist.py","file_name":"networkartist.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"3894867","text":"import os\nimport os.path as osp\nfrom collections import abc as container_abcs\n\nimport numpy as np\n\nimport torch\nimport torch.distributed as dist\nfrom torch.utils.data import Dataset\n\nimport mmcv\nfrom mmcv.runner import Hook, obj_from_dict\nfrom mmcv.runner import LogBuffer\nfrom mmcv.parallel import scatter, collate\n\nfrom dmb.visualization.stereo import ShowConf\n\nfrom .eval import remove_padding, do_evaluation\n\n\ndef to_cpu(tensor):\n error_msg = \"Tensor must contain tensors, dicts or lists; found {}\"\n if isinstance(tensor, torch.Tensor):\n return tensor.detach().cpu()\n elif isinstance(tensor, container_abcs.Mapping):\n return {key: to_cpu(tensor[key]) for key in tensor}\n elif isinstance(tensor, container_abcs.Sequence):\n return [to_cpu(samples) for samples in tensor]\n\n raise TypeError((error_msg.format(type(tensor))))\n\n\nclass DistEvalHook(Hook):\n\n def __init__(self, cfg, dataset, interval=1):\n self.cfg = cfg.copy()\n assert isinstance(dataset, Dataset), \\\n \"dataset must be a Dataset object, not {}\".format(type(dataset))\n self.dataset = dataset\n self.interval = interval\n\n def after_train_epoch(self, runner):\n if not self.every_n_epochs(runner, self.interval):\n return\n\n runner.logger.info(\n \"Start evaluation on {} dataset({} images).\".format(self.dataset.name, len(self.dataset))\n )\n runner.model.eval()\n\n # get prog bar\n if runner.rank == 0:\n prog_bar = mmcv.ProgressBar(len(self.dataset))\n else:\n prog_bar = None\n\n results = [None for _ in range(len(self.dataset))]\n for idx in range(runner.rank, len(self.dataset), runner.world_size):\n data = self.dataset[idx]\n data_gpu = scatter(\n collate([data], samples_per_gpu=1), [torch.cuda.current_device()]\n )[0]\n\n # compute output\n with torch.no_grad():\n result, _ = runner.model(data_gpu)\n disps = result['disps']\n costs = result['costs']\n\n ori_size = data_gpu['original_size']\n disps = remove_padding(disps, ori_size)\n target = data_gpu['leftDisp'] if 'leftDisp' in data_gpu else None\n target = remove_padding(target, ori_size)\n error_dict = do_evaluation(\n disps[0], target, self.cfg.model.eval.lower_bound, self.cfg.model.eval.upper_bound)\n\n if self.cfg.model.eval.eval_occlusion and 'leftDisp' in data_gpu and 'rightDisp' in data_gpu:\n data_gpu['leftDisp'] = remove_padding(data_gpu['leftDisp'], ori_size)\n data_gpu['rightDisp'] = remove_padding(data_gpu['rightDisp'], ori_size)\n\n occ_error_dict = do_occlusion_evaluation(\n disps[0], data_gpu['leftDisp'], data_gpu['rightDisp'],\n self.cfg.model.eval.lower_bound, self.cfg.model.eval.upper_bound)\n error_dict.update(occ_error_dict)\n\n result = {\n 'Disparity': disps,\n 'GroundTruth': target,\n 'Error': error_dict,\n }\n\n if self.cfg.model.eval.is_cost_return:\n if self.cfg.model.eval.is_cost_to_cpu:\n costs = [cost.cpu() for cost in costs]\n result['Cost'] = costs\n\n # if result contains image, as the process advanced, the cuda cache explodes soon.\n result = to_cpu(result)\n\n filter_result = dict()\n filter_result['Error'] = result['Error']\n if 'Confidence' in result:\n filter_result['Confidence'] = self.process_conf(result, bins_number=100)\n\n results[idx] = filter_result\n\n batch_size = runner.world_size\n\n if runner.rank == 0:\n for _ in range(batch_size):\n prog_bar.update()\n\n if runner.rank == 0:\n print('\\n')\n dist.barrier()\n for i in range(1, min(runner.world_size, len(self.dataset))):\n tmp_file = osp.join(runner.work_dir, \"temp_{}.pkl\".format(i))\n tmp_results = mmcv.load(tmp_file)\n for idx in range(i, len(results), runner.world_size):\n results[idx] = tmp_results[idx]\n os.remove(tmp_file)\n self.evaluate(runner, results)\n else:\n tmp_file = osp.join(runner.work_dir, \"temp_{}.pkl\".format(runner.rank))\n mmcv.dump(results, tmp_file)\n dist.barrier()\n dist.barrier()\n torch.cuda.empty_cache()\n\n def evaluate(self, *args, **kwargs):\n raise NotImplementedError\n\n\nclass DistStereoEvalHook(DistEvalHook):\n\n def __init__(self, cfg, dataset, interval=1):\n super(DistStereoEvalHook, self).__init__(cfg, dataset, interval)\n self.conf_tool = ShowConf()\n\n def evaluate(self, runner, results):\n self.eval_conf(runner, results, bins_number=100)\n\n error_log_buffer = LogBuffer()\n for result in results:\n error_log_buffer.update(result['Error'])\n error_log_buffer.average()\n log_items = []\n for key in error_log_buffer.output.keys():\n runner.log_buffer.output[key] = error_log_buffer.output[key]\n\n val = error_log_buffer.output[key]\n if isinstance(val, float):\n val = \"{:.4f}\".format(val)\n log_items.append(\"{}: {}\".format(key, val))\n\n # runner.epoch start at 0\n log_str = \"Epoch [{}] Evaluation Result: \\t\".format(runner.epoch + 1)\n log_str += \", \".join(log_items)\n runner.logger.info(log_str)\n runner.log_buffer.ready = True\n error_log_buffer.clear()\n\n # confidence distribution statistics\n def process_conf(self, result, bins_number=100):\n if 'Confidence' not in result:\n return\n\n counts = []\n bin_edges = []\n # for each confidence map, statistic its confidence distribution, and stored in a list\n for i, conf in enumerate(result['Confidence']):\n # hist and bin_edges\n count, bin_edge = self.conf_tool.conf2hist(conf, bins=bins_number)\n counts.append(count)\n bin_edges.append(bin_edge)\n\n return {\n 'counts': counts,\n 'bin_edges': bin_edges\n }\n\n def eval_conf(self, runner, results, bins_number=100):\n # results is a list, corresponds to each test sample,\n # for each sample, the result are saved as dict\n # if the first sample contains the keyword 'Confidence'\n if 'Confidence' not in results[0]:\n return\n\n # each sample has several confidence map, i.e. bin_edges is a list,\n # with length = confidence map number\n conf_number = len(results[0]['Confidence']['bin_edges'])\n\n # for each confidence map, statistic its confidence distribution among all samples\n total_counts = np.zeros((conf_number, bins_number))\n total_bin_edges = np.zeros((conf_number, bins_number + 1))\n for result in results:\n # enumerate each sample's every confidence map, and i is the index of confidence map\n for i, conf in enumerate(result['Confidence']['bin_edges']):\n counts, bin_edges = result['Confidence']['counts'][i], result['Confidence']['bin_edges'][i]\n # accumulate each confidence map's counts for all samples\n total_counts[i] = total_counts[i] + counts\n # each confidence map's bin_edges are same\n total_bin_edges[i] = bin_edges\n\n for i in range(conf_number):\n total_counts[i] = total_counts[i] / sum(total_counts[i])\n name = \"figure/confidence_histogram/{}\".format(i)\n conf_hist = self.conf_tool.hist2vis(total_counts[i], total_bin_edges[i])\n runner.log_buffer.output[name] = conf_hist\n\n runner.logger.info(\"Epoch [{}] Confidence evaluation done!\".format(runner.epoch + 1))\n runner.log_buffer.ready = True\n","sub_path":"dmb/data/datasets/evaluation/stereo/eval_hooks.py","file_name":"eval_hooks.py","file_ext":"py","file_size_in_byte":8183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"541577139","text":"# single responsibility\nclass Journal:\n def __init__(self):\n self.entries = []\n self.count = 0\n\n def add_entry(self, text):\n self.count += 1\n self.entries.append(f\"{self.count}: {text}\")\n\n def remove_entry(self, pos):\n del self.entries[pos]\n self.count -= 1\n\n def __str__(self):\n return \"\\n\".join(self.entries)\n\n\n# single responsibility\nclass PersistenceManager:\n @staticmethod\n def save_to_file(journal, filename):\n with open(filename, \"w\") as f:\n f.write(str(journal))\n f.close()\n\n\nj = Journal()\nj.add_entry(\"drank water\")\nj.add_entry(\"learnt something\")\nprint(f\"journal entries from object:\\n{j}\")\n\nfp = \"C://SMITA PERSONAL REPOSITORY//GITHUB CODE//.temp/dummy.txt\"\n\np = PersistenceManager()\np.save_to_file(j, fp)\n\nwith open(fp, \"r\") as f:\n print(f\"journal entries from file:\\n{f.read()}\")\n","sub_path":"PYTHON/PYTHON_DESIGN_PATTERNS/p002_single_responsibility_principle.py","file_name":"p002_single_responsibility_principle.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"211090013","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 19 16:45:15 2015\n\n@author: tsz\n\"\"\"\n\nfrom __future__ import division\n\nimport numpy as np\n\nimport pycity_base.classes.supply.HeatingDevice as HeatingDevice\nimport pycity_base.functions.handleData as handleData\n\n\nclass Heatpump(HeatingDevice.HeatingDevice):\n \"\"\"\n Implementation of the heat pump.\n \"\"\"\n \n def __init__(self, environment, \n tAmbient, tFlow, \n heat, power, cop,\n tMax, \n lowerActivationLimit=1):\n \"\"\"\n Parameters\n ----------\n environment : Environment object\n Common to all other objects. Includes time and weather instances\n tAmbient : Array_like\n DESCRIPTION\n tFlow : Array_like\n DESCRIPTION\n heat : Array_like (2 dimensional)\n DESCRIPTION\n power : Array_like (2 dimensional)\n DESCRIPTION\n cop : Array_like (2 dimensional)\n DESCRIPTION\n tMax : Float\n DESCRIPTION\n lowerActivationLimit : float (0 <= lowerActivationLimit <= 1)\n Define the lower activation limit. For example, heat pumps are \n typically able to operate between 50 % part load and rated load. \n In this case, lowerActivationLimit would be 0.5\n Two special cases: \n Linear behavior: lowerActivationLimit = 0\n Two-point controlled: lowerActivationLimit = 1 \n \"\"\"\n \n qNominal=np.zeros(environment.timer.timestepsHorizon)\n super(Heatpump, self).__init__(environment, \n qNominal,\n tMax,\n lowerActivationLimit)\n self._kind = \"heatpump\"\n \n self.tAmbient = tAmbient\n self.tFlow = tFlow\n self.heat = heat\n self.power = power\n \n timestepsTotal = environment.timer.timestepsTotal\n timestepsUsedHorizon = environment.timer.timestepsUsedHorizon\n self.totalPConsumption = np.zeros(timestepsTotal)\n self.currentPConsumption = np.zeros(timestepsUsedHorizon)\n \n def getNominalValues(self, tFlow):\n \"\"\"\n Return the nominal electricity consumption, heat output and lower \n activation limit.\n \n The electricity consumption and heat output are computed by two \n dimensional interpolation with the ambient temperature and required\n flow temperature as well as the heat pump's characteristics.\n \n Parameters\n ----------\n tFlow : Array_like\n Required flow temperature\n \n Returns\n -------\n pNominal : Array_like\n Nominal electricity consumption at the given flow temperatures and\n the forecast of the current ambient temperature\n qNominal : Array_like\n Nominal heat output at the given flow temperatures and the \n forecast of the current ambient temperature\n tMax : float\n Maximum flow temperature that can be provided by the heat pump\n lowerActivationLimit : float (0 <= lowerActivationLimit <= 1)\n Define the lower activation limit. For example, heat pumps are \n typically able to operate between 50 % part load and rated load. \n In this case, lowerActivationLimit would be 0.5\n Two special cases: \n Linear behavior: lowerActivationLimit = 0\n Two-point controlled: lowerActivationLimit = 1\n \n Example\n -------\n >>> tFlow = building.getFlowTemperature()\n >>> (pNominal, qNominal, lowerActivationLimit) = hp.getNominals(tFlow)\n \"\"\"\n # Get weather forecast\n weatherForecast = self.environment.weather.getWeatherForecast\n (tAmbient,) = weatherForecast(getTAmbient=True)\n \n # Two dimensional interpolation is required.\n # Initialize temporary results of the first interpolation\n timestepsHorizon = self.environment.timer.timestepsHorizon\n heat = np.zeros((timestepsHorizon, len(self.tFlow)))\n power = np.zeros((timestepsHorizon, len(self.tFlow)))\n \n # Compute first interpolation\n for i in range(len(self.tFlow)):\n heat[:,i] = np.interp(tAmbient, self.tAmbient, self.heat[:,i])\n power[:,i] = np.interp(tAmbient, self.tAmbient, self.power[:,i])\n \n # Initialize final results\n heatNominal = np.zeros(timestepsHorizon)\n powerNominal = np.zeros(timestepsHorizon)\n for j in range(timestepsHorizon):\n heatNominal[j] = np.interp(tFlow[j], self.tFlow, heat[j,:])\n powerNominal[j] = np.interp(tFlow[j], self.tFlow, power[j,:])\n \n # Return results\n return (powerNominal, heatNominal, \n self.tMax, self.lowerActivationLimit)\n \n def getResults(self, currentValues=True):\n \"\"\"\n Return results.\n \n Parameter\n ---------\n currentValues : boolean, optional\n - True : Return only values for this scheduling period\n - False : Return values for all scheduling periods\n \n Order\n -----\n pConsumption : array_like\n Electricity consumption of the heat pump\n qOutput : array_like\n Heat production of the heat pump\n schedule : array_like\n Operational schedule\n \"\"\"\n pConsumption = handleData.getValues(currentValues,\n self.currentPConsumption,\n self.totalPConsumption)\n \n return (pConsumption,\n self._getQOutput(currentValues), \n self._getSchedule(currentValues))\n\n def setResults(self, pConsumption, qOutput, schedule):\n \"\"\"\n Save resulting electricty consumption, heat output and \n operational schedule.\n \"\"\"\n self._setSchedule(schedule)\n self._setQOutput(qOutput)\n result = handleData.saveResult(self.environment.timer,\n self.currentPConsumption,\n self.totalPConsumption,\n pConsumption)\n (self.currentPConsumption, self.totalPConsumption) = result","sub_path":"pycity_base/classes/supply/HeatPump.py","file_name":"HeatPump.py","file_ext":"py","file_size_in_byte":6453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"273496063","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.utils.safestring import mark_safe\nfrom rest_framework import serializers\nfrom shop.search.serializers import ProductSearchSerializer as BaseProductSearchSerializer\nfrom shop.models.cart import CartModel\nfrom shop.serializers.defaults.catalog import AddToCartSerializer\nfrom storefront.search_indexes import myshop_search_index_classes\n\n\nclass ProductSearchSerializer(BaseProductSearchSerializer):\n \"\"\"\n Serializer to search over all products in this shop\n \"\"\"\n media = serializers.SerializerMethodField()\n\n class Meta(BaseProductSearchSerializer.Meta):\n fields = BaseProductSearchSerializer.Meta.fields + ['media', 'caption']\n field_aliases = {'q': 'text'}\n search_fields = ['text']\n index_classes = myshop_search_index_classes\n\n def get_media(self, search_result):\n return mark_safe(search_result.search_media)\n\n\nclass CatalogSearchSerializer(BaseProductSearchSerializer):\n \"\"\"\n Serializer to restrict products in the catalog\n \"\"\"\n media = serializers.SerializerMethodField()\n\n class Meta(BaseProductSearchSerializer.Meta):\n fields = BaseProductSearchSerializer.Meta.fields + ['media', 'caption']\n field_aliases = {'q': 'autocomplete'}\n search_fields = ['autocomplete']\n index_classes = myshop_search_index_classes\n\n def get_media(self, search_result):\n return mark_safe(search_result.catalog_media)\n\n\nclass AddSmartPhoneToCartSerializer(AddToCartSerializer):\n \"\"\"\n Modified AddToCartSerializer which handles SmartPhones\n \"\"\"\n\n def get_instance(self, context, data, extra_args):\n product = context['product']\n request = context['request']\n try:\n cart = CartModel.objects.get_from_request(request)\n except CartModel.DoesNotExist:\n cart = None\n try:\n variant = product.get_product_variant(\n product_code=data['product_code'])\n except (TypeError, KeyError, product.DoesNotExist):\n variant = product.variants.first()\n instance = {\n 'product': product.id,\n 'product_code': variant.product_code,\n 'unit_price': variant.unit_price,\n 'is_in_cart': bool(product.is_in_cart(cart, product_code=variant.product_code)),\n 'extra': {'storage': variant.storage},\n 'availability': variant.get_availability(request),\n }\n return instance\n","sub_path":"storefront/storefront/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"208814073","text":"#coding=utf-8\n'''\nCreated on 2015-1-3\n\n@author: Shawn\n'''\n\n# import orm\n\nclass PM(object):\n \"\"\"\n 权限管理\n \"\"\"\n ''' 用户权限枚举=> '''\n\n PM_MAP = {}\n ''' 用户权限枚举=> '''\n\n ''' 登录权限比较特殊 '''\n PERMISSION_BAN_LOGIN = set(['PERMISSION_BAN_LOGIN'])\n PM_MAP['PERMISSION_BAN_LOGIN'] = PERMISSION_BAN_LOGIN\n\n ''' 其他权限 '''\n\n ''' 创建用户组 '''\n PERMISSION_CREATE_USER_GROUP = set(['PERMISSION_CREATE_USER_GROUP'])\n PM_MAP['PERMISSION_CREATE_USER_GROUP'] = PERMISSION_CREATE_USER_GROUP\n\n ''' 创建用户 '''\n PERMISSION_CREATE_USER = set(['PERMISSION_CREATE_USER'])\n PM_MAP['PERMISSION_CREATE_USER'] = PERMISSION_CREATE_USER\n\n ''' 查看用户列表 '''\n PERMISSION_USER_LIST = set(['PERMISSION_USER_LIST'])\n PM_MAP['PERMISSION_USER_LIST'] = PERMISSION_USER_LIST\n\n ''' 创建用户组 '''\n PERMISSION_USER_GROUP_LIST = set(['PERMISSION_USER_GROUP_LIST'])\n PM_MAP['PERMISSION_USER_GROUP_LIST'] = PERMISSION_USER_GROUP_LIST\n\n ''' 修改用户信息 '''\n PERMISSION_MODIF_USER = set(['PERMISSION_MODIF_USER'])\n PM_MAP['PERMISSION_MODIF_USER'] = PERMISSION_MODIF_USER\n\n ''' 修改 用户组 信息 '''\n PERMISSION_MODIF_USER_GROUP = set(['PERMISSION_MODIF_USER_GROUP'])\n PM_MAP['PERMISSION_MODIF_USER_GROUP'] = PERMISSION_MODIF_USER_GROUP\n\n ''' 管理用户信息页面 '''\n PERMISSION_MANAGER_USER = set(['PERMISSION_MANAGER_USER'])\n PM_MAP['PERMISSION_MANAGER_USER'] = PERMISSION_MANAGER_USER\n\n ''' 本地服务的伪终端 '''\n PERMISSION_SIM_TERM_LOCAL_SERVER = set(['PERMISSION_SIM_TERM_LOCAL_SERVER'])\n PM_MAP['PERMISSION_SIM_TERM_LOCAL_SERVER'] = PERMISSION_SIM_TERM_LOCAL_SERVER\n\n ''' 本地服务执行 python 代码 '''\n PERMISSION_LOCAL_EXEC_PYTHON_CODE = set(['PERMISSION_LOCAL_EXEC_PYTHON_CODE'])\n PM_MAP['PERMISSION_LOCAL_EXEC_PYTHON_CODE'] = PERMISSION_LOCAL_EXEC_PYTHON_CODE\n\n ''' 以 PERMISSION_* 的形式来命名变量 '''\n\n ''' <=用户权限枚举 '''\n ''' 以 PERMISSION_* 的形式来命名变量 '''\n\n\n\n @classmethod\n def getPermissionDic(cls):\n '''\n 获得权限的字典{属性名: 权限}\n :return:\n '''\n return cls.PM_MAP.copy()\n\n\n @classmethod\n def defaultPms(cls):\n \"\"\"\n 默认权限\n :return:\n \"\"\"\n return set()\n","sub_path":"src/www/app/models/pm.py","file_name":"pm.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"131695539","text":"class ModelData:\n def __init__(self):\n self.dataset=None\n\n def Load(self):\n # 모드 별로 설명하고 원하는 모드 번호를 입력받는 코드 \n choice=int(input('\\nWhich of the two modes do you want?\\nEnter the number of the mode you want.\\n1. Exercise mode\\n2. Practice mode\\n'))\n if choice == 1 : # 연습모드를 선택했을 때, 예제데이터 불러오는 함수 실행\n print('You have selected Exercise mode.')\n self._LoadExampleData()\n elif choice == 2: # 실습모드를 선택했을 때, 파일 불러오기\n print('You have selected Practice mode.\\n')\n self._LoadPracticeData()\n\n def _LoadExampleData(self): # 예제데이터를 불러오는 함수\n url = 'https://raw.githubusercontent.com/Seo-Junh0/first-git/master/NiFeCr_Total_Hardness.csv' # 예제데이터 위치(깃허브)\n self.dataset = pd.read_csv(url, index_col=0) # csv 형식의 예제데이터를 데이터프레임 형태로 불러오기 \n\n def _LoadPracticeData(self):\n # 실습모드에서 파일불러오는 방법은 1. 로컬드라이브에서 불러오기 2. 구글드라이브에서 불러오기 두가지로 구성\n location=int(input('\\nNow where do you want to load your file from?\\n1. Local drive\\n2. Google drive\\n'))\n if location == 1:\n self._LocalData()\n elif location == 2:\n self._DriveData()\n\n def _LocalData(self):\n # 2. 구글드라이브에서 불러오기\n import pathlib\n from google.colab import files\n uploaded = files.upload()\n for fn in uploaded.keys():\n print('User uploaded file \"{name}\" with length {length} bytes'.format(name=fn, length=len(uploaded[fn])))\n import io\n self.dataset= pd.read_csv(io.BytesIO(uploaded[fn]), index_col=0)\n\n def _DriveData(self):\n # 1. 로컬드라이브에서 불러오기\n filepath=input(\"\\nInput your file path(in your google drive)\\n\")\n filename = filepath\n self.dataset= pd.read_csv(filename)\n\n def ScanData(self): # 불러온 데이터가 전부 유효하거나 숫자인지 확인하는 함수\n check_for_nan1 = self.dataset.isnull().values.any()\n df=self.dataset.apply(pd.to_numeric, errors = 'coerce')\n check_for_nan2 = df.isnull().values.any()\n if check_for_nan1==True:\n print('Warning! Some of your data is abnormal.')\n elif check_for_nan2==True:\n print('Caution! Your data contains a non-numeric format.')\n else :\n print(\"Your data is all numeric. So it's available.\")\n\nclass DataSelect:\n\n def __init__(self,dataset):\n self.dataset=dataset\n self.target_name=None\n self.feature_names= None\n self.selected_feature_names = None\n self.data_to_use=None\n\n def TargetSelect(self):\n index=int(input(\"Column number of the target variable : \"))-1\n self.target_name=self.dataset.columns[index] # target_index를 ��해 타겟 변수의 이름 구하기\n self.feature_data=self.dataset.drop(self.target_name, axis=1) # 데이터에서 타겟 변수 열을 제외하기\n self.feature_names=list(self.feature_data.columns) # 타겟 변수를 제외한 특징들의 이름 리스트\n print(\"You chose '%s' as the target variable.\\n\"%self.target_name)\n\n def FeatureSelect(self):\n selected_feature_indexs=input('Enter the index of features you want to use among the above features (Use \",\" to separate each index number) : \\n').split(',')\n self.selected_feature_names = [self.feature_names[((int (i))-1)] for i in selected_feature_indexs] # 구한 인덱스 값으로 해당 선택된 특징의 이름 구하여 리스트 만들기\n print(\"You chose %s as the input feature.\\n\"%self.selected_feature_names)\n \n def PearsonHeatmap(self):\n pearson = self.dataset.corr(method = 'pearson') # 데이터의 각 특징 간의 피어슨 상관계수 구하기\n plt.figure(figsize = (8,8)) # 상관계수 그림 크기 설\n sns_plot_pearson = sns.heatmap(pearson.apply(lambda x: x ** 2), square=True, cmap='Reds') # 상관계수 값의 제곱한 값을 기준으로 히트맵이미지 그리기\n sns_plot_pearson.set_title('The Table for Correlation')\n\n def ScatterPlot(self):\n # 이름 앞에 인덱스 변호 추가 하기\n total_range=[]\n feature_data=self.dataset.drop(self.target_name, axis=1) # 데이터에서 타겟 변수 열을 제외하기\n for i in range(1,self.dataset.shape[1]):\n total_range.append(str(i)+\". \"+self.feature_names[i-1])\n feature_data.columns=total_range\n # 타겟 변수와 특징 사이의 산점도 나타내기\n feature_data[self.target_name]=self.dataset[self.target_name].values\n column=5\n part=(len(total_range)-1)//column\n for i in range(0,part):\n sns_scatterplot=sns.pairplot(data=feature_data, diag_kind=\"kde\", x_vars=total_range[i*column:(i+1)*column], y_vars=[self.target_name])\n if i==0:\n sns_scatterplot.fig.subplots_adjust(top=0.9)\n sns_scatterplot.fig.suptitle(\"The Graph for Linearity (between '%s' and remaining features)\"%self.target_name)\n sns_scatterplot=sns.pairplot(data=feature_data, diag_kind=\"kde\", x_vars=total_range[part*column:], y_vars=[self.target_name])\n\n def ExtractDataToUse(self):\n self.data_to_use=self.dataset.loc[:,self.selected_feature_names+[self.target_name]] # 선택된 특징과 타겟 변수로 구성된 데이터 만들기\n return self.data_to_use # 선택된 특징와 타겟 변수로만 이루어진 데이터 확인하기\n\nclass PrintDot(keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs):\n if epoch % 100 == 0: print('')\n print('.', end='')\n\nclass ANN:\n\n activfunc_list=['softmax','sigmoid', 'tanh', 'relu', 'elu'] # 지원하는 활성화 함수 리스트\n optimizerfunc_list=[keras.optimizers.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False),\n keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=None, decay=0.0),\n keras.optimizers.SGD(lr=0.01, momentum=0.9, decay=0.0, nesterov=True),\n keras.optimizers.Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004)] # 지원하는 최적화 함수 리스트\n\n lossfunc=['mse','categorical_crossentropy']\n outlayer_activfunc_list=['linear','softmax']\n metrics=[['mae','mse'],['accuracy', tf.keras.metrics.Recall(), tf.keras.metrics.Precision()]]\n\n def __init__(self, data_to_use, target_name):\n self.purpose=int(input(\"Which model do you want to create, classification or regression?\\n1.Regression 2.Classification\\n\"))-1\n\n fraction=float(input('Proportion of Train Data you want(e.g. 0.8) : '))\n # 훈련용과 평가용 데이터를 나눌 비율을 입력받고, 해당 비율로 나누기\n Train_set=data_to_use.sample(frac=fraction,random_state=0).sample(frac=1)\n Test_set=data_to_use.drop(Train_set.index).sample(frac=1)\n # 나눠진 두 데이터셋에서 타겟 변수 분리하기\n Train_labels = pd.DataFrame(Train_set.pop(target_name))\n Test_labels = pd.DataFrame(Test_set.pop(target_name))\n # 타겟 변수(레이블) 인코딩, 타겟변수가 분리된 두 데이터셋 정규화,\n \n self.number_of_hidden=None\n self.setup_data=[]\n\n self.model=None\n self.history=None\n self.optimizer=None\n\n self.train_data=Train_set\n self.train_labels=pd.get_dummies(Train_labels) if self.purpose else Train_labels\n self.test_data=Test_set\n self.test_labels=pd.get_dummies(Test_labels) if self.purpose else Test_labels\n \n def SetUp(self):\n self.number_of_hidden=int(input('\\nThe number of hidden layers you want to add to the model : ')) # 원하는 은닉층 수 입력\n # 입력층에 쓰일 활성화 함수 입력\n print('\\nThe Input Layer')\n temp=[self._WhichActivfunc(),len(self.train_data.keys())]\n self.setup_data.append(temp)\n # 은닉층에 쓰일 활성화 함수와 노드 수 입력\n for i in range(self.number_of_hidden):\n print('\\nThe Hidden Layer %i'%(i+1)) # 입력받은 은닉층 수만큼 프린트\n temp=[self._WhichActivfunc(),int(input('Number of nodes : '))]\n self.setup_data.append(temp)\n print('\\nThe Outer Layer\\n')\n\n def _WhichActivfunc(self):\n hiddenlayer_activfunc=int(input('Activation function (1.Softmax 2.Sigmoid 3.tanh 4.ReLU 5.ELU) : '))-1 # 각각의 활성화 함수 번호 입력\n return ANN.activfunc_list[hiddenlayer_activfunc]\n\n def DesignLayer(self):\n self.model=keras.Sequential()\n for i in range(self.number_of_hidden+1): # 층 수만큼 반복\n self.model.add(layers.Dense(self.setup_data[i][1], activation=self.setup_data[i][0])) # 입력받은 노드의 개수와 활성화 함수를 바탕으로 층 추가\n self.model.add(layers.Dense(len(self.train_labels.keys()),activation=ANN.outlayer_activfunc_list[self.purpose])) # 출력층 구성\n optimizer_num=int(input(\"Which optimization function will you use?\\n1.Gradient descent\\n2.RMSprop\\n3.NAG\\n4.NAdam\\n\"))-1\n self.model.compile(loss=ANN.lossfunc[self.purpose], optimizer=ANN.optimizerfunc_list[optimizer_num], metrics=ANN.metrics[self.purpose]) # 오차를 측정하는 방법으로 mae와 mse를 사용\n\n def _Norm(self,x): # 열 별로 정규화해주는 함수\n train_stats=x.describe() # 데이터 x의 기본적인 통계값 계산하여 train_stats에 저장\n train_stats = train_stats.transpose()\n return (x - train_stats['mean']) / train_stats['std'] # 그중 평균과 분산을 이용하여 정규화\n\n def Train(self):\n # 원하는 반복 횟수 입력\n EPOCHS = int(input('\\nNumber of times to repeat model training (Epoch) : '))\n # 입력받은 반복 횟수만큼 학습\n self.history = self.model.fit(\n self._Norm(self.train_data), self.train_labels,\n epochs=EPOCHS, validation_split = 0.2, verbose=0, validation_data=(self._Norm(self.train_data), self.train_labels),\n callbacks=[PrintDot()]) # 무작위로 검증데이터를 20% 선택하여 학습 진행\n\n def PlotByEpoch(self):\n hist = pd.DataFrame(self.history.history) # 반복 횟수별로 검증정확도를 데이터프레임 형태로 바꾸기\n hist['epoch'] = self.history.epoch # epoch 값 나타내는 열 추가\n\n plt.figure(figsize=(6,4)) # 그래프 크기 설정\n\n plt.xlabel('Epoch') # x축 이름 붙이기\n plt.ylabel('Loss') # y축 이름 붙이기\n plt.plot(hist['epoch'], hist['loss'],\n label='Train Error') # 학습데이터를 기준으로 정확도 채점했을 때 그래프\n plt.plot(hist['epoch'], hist['val_loss'],\n label = 'Val Error') # 검증데이터를 기준으로 정확도 채점했을 때 그래프\n plt.legend()\n \n def Evaluate(self):\n loss, *arg=self.model.evaluate(self._Norm(self.test_data), self.test_labels, verbose=2)\n if self.purpose:\n precision=arg[2]\n recall=arg[1]\n f1_score=2*(precision*recall)/(precision+recall)\n print('\\nLoss : {0}\\nAccuracy : {1}\\nF1-score : {2}'.format(loss, arg[0], f1_score))\n else:\n print('\\nMean Squared Error : {0}\\nMean Absolute Error : {1}'.format(loss, arg[0]))\n\n def ResultPlot(self):\n test_predictions = self.model.predict(self._Norm(self.test_data)).flatten() # 평가용 데이터를 이용해 예측값을 직접 구하기\n # 평가용 데이터를 이용해 구한 예측값을 평가용 레이블의 실측값과 비교하는 그래프 그리기\n plt.scatter(self.test_labels, test_predictions)\n plt.xlabel('True Values')\n plt.ylabel('Predictions')\n plt.axis('equal')\n plt.axis('square')\n plt.xlim([0,plt.xlim()[1]])\n plt.ylim([0,plt.ylim()[1]])\n _ = plt.plot([-100, 100], [-100, 100])\n\n def Save(self):\n ModelName=input(\"Name your model to save to 'ANN_Model' folder : \") # 모델 이름 입력\n keras_model_path = \"/content/drive/MyDrive/ANN_Model/%s\"%ModelName # 각자의 드라이브에 ANN_Model 폴더를 만들어 그 안에 저장\n self.model.save(keras_model_path) # 케라스 API 모델 저장\n","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":11899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"410032888","text":"from datetime import datetime\n# datetime object containing current date and time\nimport time\nimport os\nimport numpy as np\nimport cv2\nfrom bmp280 import BMP280\nimport sys\n\nprint(cv2.__version__)\n\ntry:\n from smbus2 import SMBus\nexcept ImportError:\n from smbus import SMBus\n\nbus = SMBus(1)\nbmp280 = BMP280(i2c_dev=bus)\n\nclasses = ['negative','positive']\ndef predict(model2,resizeVar=None):\n model = cv2.dnn.readNet(model2)\n while(True):\n now = datetime.now()\n dt_string = now.strftime(\"%Y%m%d%H%M%S\")\n string = \"curl -XPOST -H 'Content-Type: application/json' -d '{\\\"type\\\":\\\"request\\\", \\\"action\\\": \\\"camera.ir.mlx90640.capture\\\", \\\"args\\\": {\\\"output_file\\\":\\\"~/img/%s.jpg\\\", \\\n \\\"scale_factor\\\":20, \\\"grayscale\\\": true}}' http://localhost:8008/execute\" % (dt_string)\n os.system(string)\n \n img = '/home/pi/img/%s.jpg' % (dt_string)\n img = cv2.imread(os.path.abspath(os.path.expanduser(img)))\n\n string = \"curl -XPOST -H 'Content-Type: application/json' -d '{\\\"type\\\":\\\"request\\\", \\\"action\\\": \\\"camera.ir.mlx90640.capture\\\", \\\"args\\\": {\\\"output_file\\\":\\\"~/colorimg/%s.jpg\\\", \\\n \\\"scale_factor\\\":20}}' http://localhost:8008/execute\" % (dt_string)\n os.system(string)\n color = '/home/pi/colorimg/%s.jpg' % (dt_string)\n color = cv2.imread(os.path.abspath(os.path.expanduser(color)))\n \n img = cv2.dnn.blobFromImage(img, size=tuple(resizeVar), mean=0.5)\n model.setInput(img)\n output = model.forward()\n prediction = int(np.argmax(output))\n \n if classes:\n prediction = classes[prediction]\n \n #temperature = bmp280.get_temperature()\n #pressure = bmp280.get_pressure()\n #altitude = bmp280.get_altitude()\n \n imgPath = '/home/pi/img/%s.jpg' % (dt_string)\n img = cv2.imread(os.path.abspath(os.path.expanduser(imgPath)))\n colorPath = '/home/pi/colorimg/%s.jpg' % (dt_string)\n color = cv2.imread(os.path.abspath(os.path.expanduser(colorPath)))\n \n font = cv2.FONT_HERSHEY_SIMPLEX\n bottomLeftCornerOfText = (0,50)\n fontScale = 0.5\n fontColor = (0,0,0)\n lineType = 2\n \n #listVal = [prediction, str(round(temperature,2)), str(round(pressure,2)), str(round(altitude,2))]\n cv2.putText(color,prediction, \n bottomLeftCornerOfText, \n font, \n fontScale,\n fontColor,\n lineType)\n \n numpy_horizontal = np.hstack((color, img))\n #cv2.namedWindow(\"Numpy Horizontal\", cv2.WINDOW_NORMAL)\n #cv2.setWindowProperty(\"Numpy Horizontal\",cv2.WND_PROP_AUTOSIZE,cv2.WINDOW_NORMAL)\n \n cv2.imshow('Numpy Horizontal', numpy_horizontal)\n cv2.waitKey(10)\n \n os.remove(imgPath)\n os.remove(colorPath)\n \n print(prediction)\n\n\n\npb_file = '/home/pi/Desktop/CEG-Capstone/drone/InfraredCamModel.pb'\npb_file = os.path.abspath(os.path.expanduser(pb_file))\n\n# Read the graph.\npredict(pb_file, [24,32])\n\n# allow the camera to warmup\n\n","sub_path":"drone/ThermalCamFeed.py","file_name":"ThermalCamFeed.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"485370714","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n#from rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom .models import RentalCarInfo\nfrom .serializers import RentalCarSerializer\n\n\n@csrf_exempt\ndef RentalCar_list(request):\n if request.method == 'GET':\n RentalCars = RentalCarInfo.objects.all()\n serializer = RentalCarSerializer(RentalCars, many=True)\n print(\"RentalCar_list---GET\")\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = RentalCarSerializer(data=data)\n print(\"RentalCar_list---POST\")\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n@csrf_exempt\ndef RentalCar_detail(request, pk):\n try:\n RentalCar = RentalCarInfo.objects.get(pk=pk)\n except RentalCarInfo.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = RentalCarSerializer(RentalCar)\n return JsonResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = RentalCarSerializer(RentalCar, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n RentalCar.delete()\n return HttpResponse(status=204)\n\n","sub_path":"django_rest_framework/EastcarServer/eastcar/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"448962653","text":"import nltk\r\nfrom nltk.tokenize import word_tokenize # works like string.split()\r\nimport numpy as np\r\nimport random\r\nimport pickle\r\nfrom collections import Counter\r\nfrom nltk.stem import WordNetLemmatizer\r\n\r\nlemmatizer = WordNetLemmatizer() # takes similar words like run ran running and converts them to a single element\r\nhm_lines = 100000\r\n\r\ndef create_lexicon(pos,neg):\r\n\r\n\tlexicon = []\r\n\twith open(pos,'r') as f:\r\n\t\tcontents = f.readlines()\r\n\t\tfor l in contents[:hm_lines]:\r\n\t\t\tall_words = word_tokenize(l)\r\n\t\t\tlexicon += list(all_words) # make a list of all words ( tokenize) and then add them to the lexicon\r\n\r\n\twith open(neg,'r') as f:\r\n\t\tcontents = f.readlines()\r\n\t\tfor l in contents[:hm_lines]:\r\n\t\t\tall_words = word_tokenize(l)\r\n\t\t\tlexicon += list(all_words)\r\n\r\n\tlexicon = [lemmatizer.lemmatize(i) for i in lexicon]\r\n\tw_counts = Counter(lexicon)\r\n\tl2 = []\r\n\tfor w in w_counts:\r\n\t\t#print(w_counts[w])\r\n\t\tif 1000 > w_counts[w] > 50: # only take the words which mean something to us. taking words like 'the' 'and' etc wont be useful \r\n\t\t\tl2.append(w)\r\n\tprint(len(l2))\r\n\treturn l2\r\n\r\n\r\n\r\n\r\n\r\ndef sample_handling(sample,lexicon,classification):\r\n\r\n\tfeatureset = []\r\n\r\n\twith open(sample,'r') as f:\r\n\t\tcontents = f.readlines()\r\n\t\tfor l in contents[:hm_lines]:\r\n\t\t\tcurrent_words = word_tokenize(l.lower())\r\n\t\t\tcurrent_words = [lemmatizer.lemmatize(i) for i in current_words]\r\n\t\t\tfeatures = np.zeros(len(lexicon)) # makes a 0 array [ 0 0 0 0 0 .......]\r\n\t\t\tfor word in current_words:\r\n\t\t\t\tif word.lower() in lexicon:\r\n\t\t\t\t\tindex_value = lexicon.index(word.lower())\r\n\t\t\t\t\tfeatures[index_value] += 1\r\n\r\n\t\t\tfeatures = list(features)\r\n\t\t\tfeatureset.append([features,classification])\r\n\r\n\treturn featureset\r\n\r\n\r\n\r\ndef create_feature_sets_and_labels(pos,neg,test_size = 0.1):\r\n\tlexicon = create_lexicon(pos,neg)\r\n\tfeatures = []\r\n\tfeatures += sample_handling('pos.txt',lexicon,[1,0])\r\n\tfeatures += sample_handling('neg.txt',lexicon,[0,1])\r\n\trandom.shuffle(features)\r\n\tfeatures = np.array(features)\r\n\r\n\ttesting_size = int(test_size*len(features))\r\n\r\n\ttrain_x = list(features[:,0][:-testing_size]) #last 10% #### the features are = [[ [ 0 1 1 0 0 1] [ 1 0] ]]\r\n\ttrain_y = list(features[:,1][:-testing_size]) # ^ feature ^ label\r\n\ttest_x = list(features[:,0][-testing_size:]) #first 90% or till the last 10% #### so here the [0:, 1] extracts all the features from the featuresets\r\n\ttest_y = list(features[:,1][-testing_size:])\r\n\r\n\treturn train_x,train_y,test_x,test_y\r\n\r\n\r\nif __name__ == '__main__':\r\n\ttrain_x,train_y,test_x,test_y = create_feature_sets_and_labels('pos.txt','neg.txt')\r\n\t# if you want to pickle this data:\r\n\twith open('sentiment_set.pickle','wb') as f:\r\n\t\tpickle.dump([train_x,train_y,test_x,test_y],f)\r\n","sub_path":"sentiment_neuralnet.py","file_name":"sentiment_neuralnet.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"5322349","text":"from setuptools import setup, find_packages\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\n\nsetup(\n name='holey',\n\n version='2018.11',\n\n description='Geometry predicates written in python, optimised with numba',\n\n long_description=long_description,\n long_description_content_type='text/markdown',\n\n url='https://github.io/pelson/holey',\n\n author='Phil Elson',\n\n author_email='pelson.pub@gmail.com',\n\n # For a list of valid classifiers, see https://pypi.org/classifiers/\n classifiers=[\n 'Development Status :: 3 - Alpha',\n\n 'Intended Audience :: Science/Research',\n 'Topic :: Scientific/Engineering :: GIS',\n\n 'License :: OSI Approved :: BSD License',\n\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n ],\n\n keywords='geometry polygon shapely triangulation rasterization',\n\n packages=find_packages(exclude=['examples']),\n install_requires=[\n 'numba',\n 'numpy'],\n\n extras_require={\n 'test': ['coverage', 'pytest'],\n },\n project_urls={\n 'Source': 'https://github.com/pelson/holey/',\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"507497109","text":"import numpy as np\nimport scipy.sparse as sparse\nfrom numba import njit, prange\nimport scipy.special as sc\nimport matplotlib.pyplot as plt\nimport time\n\n\ndef train(doc_word_mat, n_topics, alpha, beta, n_iter, plot_likelihood=False, plot_file=''):\n \"\"\"\n trains a Latent Dirichlet Allocation (LDA) model.\n Args:\n doc_word_mat: document word matrix of a corpus\n n_topics: number of topics for the model\n alpha: hyperparameter of the model\n beta: hyperparameter of the model\n plot_likelihood: whether to plot likelihood function against number of iterations\n Returns:\n likelihood function value when the training stops\n word_given_topic matrix\n topic_given_doc matrix\n \"\"\"\n N = np.sum(doc_word_mat.data)\n n_docs = doc_word_mat.shape[0]\n vocab_size = doc_word_mat.shape[1]\n n_topics = n_topics\n\n doc = np.repeat(doc_word_mat.row, doc_word_mat.data)\n word = np.repeat(doc_word_mat.col, doc_word_mat.data)\n topic = np.random.randint(0, n_topics, N)\n prob = np.zeros((n_topics))\n\n topic_doc = np.zeros((n_topics, n_docs))\n word_topic = np.zeros((vocab_size, n_topics))\n topic_count = np.zeros((n_topics))\n initialize(N, topic_doc, word_topic, topic_count, doc, word, topic)\n\n # for plotting the likelihood for monitoring\n if plot_likelihood:\n n_points = 400\n step = n_iter // n_points\n iterations = [step * (i + 1) for i in range(n_points)]\n likelihoods = []\n for _ in range(n_points):\n gibbs_sampling(N, vocab_size, n_topics, doc, word, topic, prob,\n topic_doc, word_topic, topic_count, alpha/n_topics, beta, step)\n likelihoods.append(-np.mean(sc.gammaln(word_topic + beta).sum(axis=0)\n - sc.gammaln(topic_count + vocab_size * beta)))\n plt.figure()\n plt.xlabel('Iterations')\n plt.ylabel('Negative Log Likelihood')\n plt.plot(iterations, likelihoods)\n plt.savefig(plot_file)\n else:\n gibbs_sampling(N, vocab_size, n_topics, doc, word, topic, prob,\n topic_doc, word_topic, topic_count, alpha/n_topics, beta, n_iter)\n\n likelihood = np.mean(sc.gammaln(word_topic + beta).sum(axis=0) - sc.gammaln(topic_count + vocab_size * beta))\n word_given_topic = (word_topic + beta) / (topic_count + vocab_size * beta)\n topic_given_doc = (topic_doc + alpha) / (topic_doc.sum(axis=0) + n_topics * alpha)\n\n return likelihood, word_given_topic, topic_given_doc\n\n@njit\ndef initialize(N, topic_doc, word_topic, topic_count, doc, word, topic):\n for i in range(N):\n topic_doc[topic[i], doc[i]] += 1\n word_topic[word[i], topic[i]] += 1\n topic_count[topic[i]] += 1\n\n\n@njit\ndef gibbs_sampling(N, vocab_size, n_topics, doc, word, topic, prob,\n topic_doc, word_topic, topic_count, alpha, beta, n_iter):\n # Perform n_iter Gibbs sampling iterations\n for _ in range(n_iter):\n for i in range(N):\n # Compute counts with word i removed from dataset\n topic_doc[topic[i], doc[i]] -= 1\n word_topic[word[i], topic[i]] -= 1\n topic_count[topic[i]] -= 1\n\n # Compute probability of each topic for word i\n for k in range(n_topics):\n prob[k] = (topic_doc[k, doc[i]] + alpha) * (word_topic[word[i], k] + beta)\n prob[k] /= topic_count[k] + vocab_size * beta\n for k in range(1, n_topics):\n prob[k] += prob[k-1]\n\n # Sampling\n u = np.random.rand()\n\n k_low, k_up = -1, n_topics\n while k_up - k_low > 1:\n k_mid = (k_up + k_low) // 2\n if u < prob[k_mid] / prob[n_topics - 1]:\n k_up = k_mid\n else:\n k_low = k_mid\n topic[i] = k_up\n\n # Compute counts with word i included in dataset\n topic_doc[topic[i], doc[i]] += 1\n word_topic[word[i], topic[i]] += 1\n topic_count[topic[i]] += 1\n","sub_path":"lda.py","file_name":"lda.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"231624475","text":"import requests\nimport argparse\n\n\npayloads = {\n \"etc/passwd\": \"root\",\n \"boot.ini\": \"[boot loader]\"\n}\n\nup_dir = \"../\"\n\n\ndef traversal(url, n):\n try:\n for payload, string in payloads.items():\n for x in range(n):\n res = requests.post(url=url+(up_dir*x)+payload)\n\n if string in res.text:\n print(\"[*] Found Vulnerable\\r\\n\")\n print(f\"[*] Attack string {(i*up_dir)+payload}\")\n print(res.text)\n break\n except Exception as e:\n print(f\"[!] exception {e}\")\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--count\", action=\"store\", dest=\"count\", type=int)\n parser.add_argument(\"--url\", action=\"store\", dest=\"url\", type=str)\n\n options = parser.parse_args()\n\n if options.url is None and options.count is None:\n parser.print_usage()\n parser.print_help()\n else:\n traversal(options.url, options.count)\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"dir.py","file_name":"dir.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"405382652","text":"import torch\nimport torch.nn as nn\nimport torchgan.layers as tgl\n\nimport config as c\nfrom minibatchdiscr import MiniBatchDiscrimination\n\n\n# custom weights initialization called on netG and netD\ndef weights_init(m):\n classname = m.__class__.__name__ \n if classname.find('Conv') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.05)\n elif classname.find('BatchNorm') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.05)\n nn.init.constant_(m.bias.data, 0)\n \n \n# Generator Code\nclass Generator(nn.Module):\n def __init__(self):\n super(Generator, self).__init__()\n self.convtrans1 = nn.Sequential(\n # input is Z, going into a convolution\n nn.ConvTranspose2d(c.nz, c.ngf * 16, c.kg, 1, 1, bias=False),\n nn.BatchNorm2d(c.ngf * 16),\n nn.ReLU(True))\n #nn.LeakyReLU(0.2, inplace=True))\n # state size. (ngf*16) x 3 x 3\n self.convtrans2 = nn.Sequential(\n nn.ConvTranspose2d(c.ngf * 16, c.ngf * 8, c.kg, 2, 2, 1, bias=False),\n nn.BatchNorm2d(c.ngf * 8),\n nn.ReLU(True))\n #nn.LeakyReLU(0.2, inplace=True))\n # state size. (ngf*8) x 6 x 6\n self.convtrans3 = nn.Sequential(\n nn.ConvTranspose2d(c.ngf * 8, c.ngf * 4, c.kg, 2, 2, 1, bias=False),\n nn.BatchNorm2d(c.ngf * 4),\n nn.ReLU(True))\n #nn.LeakyReLU(0.2, inplace=True))\n # state size. (ngf*4) x 12 x 12\n self.convtrans4 = nn.Sequential(\n nn.ConvTranspose2d(c.ngf * 4, c.ngf * 2, c.kg, 2, 2, 1, bias=False),\n nn.BatchNorm2d(c.ngf * 2),\n nn.ReLU(True))\n #nn.LeakyReLU(0.2, inplace=True))\n # state size. (ngf) x 24 x 24\n self.convtrans5 = nn.Sequential(\n nn.ConvTranspose2d(c.ngf * 2, c.ngf, c.kg, 2, 2, 1, bias=False),\n nn.BatchNorm2d(c.ngf),\n nn.ReLU(True))\n #nn.LeakyReLU(0.2, inplace=True))\n # state size. (ngf) x 48 x 48\n self.convtrans6 = nn.Sequential(\n nn.ConvTranspose2d(c.ngf, c.nc, c.kg, 2, 2, 1, bias=False))\n self.activationG = nn.Tanh()\n \n # state size. (nc) x 96 x 96)\n \n \n def forward(self, inp):\n x = self.convtrans1(inp)\n x = self.convtrans2(x)\n x = self.convtrans3(x)\n x = self.convtrans4(x)\n x = self.convtrans5(x)\n last_conv_out = self.convtrans6(x)\n tanh_out = self.activationG(last_conv_out)\n return tanh_out\n\n\n# Discriminator Code\n# kernel_size = 5\nclass Discriminator(nn.Module):\n def __init__(self):\n super(Discriminator, self).__init__()\n self.conv1 = nn.Sequential(\n # input is (nc) x 96 x 96\n nn.Conv2d(c.nc, c.ndf, c.kd, 2, 2, bias=False),\n nn.BatchNorm2d(c. ndf),\n nn.LeakyReLU(0.2, inplace=True))\n # state size. (ndf) x 48 x 48\n self.conv2 = nn.Sequential(\n nn.Conv2d(c.ndf, c.ndf * 2, c.kd, 2, 2, bias=False),\n nn.BatchNorm2d(c.ndf * 2),\n nn.LeakyReLU(0.2, inplace=True))\n # state size. (ndf*2) x 24 x 24\n self.conv3 = nn.Sequential(\n nn.Conv2d(c.ndf * 2, c.ndf * 4, c.kd, 2, 2, bias=False),\n nn.BatchNorm2d(c.ndf * 4),\n nn.LeakyReLU(0.2, inplace=True))\n # state size. (ndf*4) x 12 x 12\n self.conv4 = nn.Sequential(\n nn.Conv2d(c.ndf * 4, c.ndf * 8, c.kd, 2, 2, bias=False),\n nn.BatchNorm2d(c.ndf * 8),\n nn.LeakyReLU(0.2, inplace=True))\n # state size. (ndf*8) x 6 x 6\n #self.conv5 = nn.Sequential(\n # nn.Conv2d(c.ndf * 8, c.ndf * 16, c.kd, 2, 2, bias=False),\n # nn.BatchNorm2d(c.ndf * 16),\n # nn.LeakyReLU(0.2, inplace=True))\n # state size. (ndf*16) x 3 x 3\n #self.conv6 = nn.Conv2d(c.ndf * 16, 1, c.kd, 2, 1, bias=False)\n if c.mbdiscr: \n self.conv5 = nn.Sequential(\n nn.Conv2d(c.ndf * 8, 50, c.kd, 2, 1, bias=False))\n #self.conv6 = nn.Conv2d(c.ndf * 16, 1, c.kd, 2, 1, bias=False)\n self.lin1 = nn.Linear(200, 200)#nn.Linear(200, 100) \n self.mbd = tgl.MinibatchDiscrimination1d(200, 100)#tgl.MinibatchDiscrimination1d(100,50) \n self.lin2 = nn.Linear(300, 1)#nn.Linear(150, 1) \n else:\n self.conv5 = nn.Sequential(\n nn.Conv2d(c.ndf * 8, c.ndf * 16, c.kd, 2, 2, bias=False),\n nn.BatchNorm2d(c.ndf * 16),\n nn.LeakyReLU(0.2, inplace=True))\n self.conv6 = nn.Conv2d(c.ndf * 16, 1, c.kd, 2, 1, bias=False)\n self.activationD = nn.Sigmoid()\n\n \n def forward(self, inp): \n x = self.conv1(inp)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.conv4(x)\n if c.mbdiscr:\n last_conv_output = self.conv5(x)\n x = last_conv_output.view(-1, self.num_flat_features(last_conv_output))\n x = self.lin1(x)\n mbd_layer = self.mbd(x)\n mbd_layer = self.lin2(mbd_layer)\n sig_out = self.activationD(mbd_layer)\n else:\n x = self.conv5(x)\n last_conv_output = self.conv6(x)\n sig_out = self.activationD(last_conv_output)\n return last_conv_output, sig_out\n\n\n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\n","sub_path":"DCGAN/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"528403109","text":"# -*- coding: utf-8 -*-\n\n'''\n 链表\n'''\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n def getData(self):\n return self.data\n\n def setData(self, data):\n self.data = data\n\n def getNext(self):\n return self.next\n\n def getPrev(self):\n return self.prev\n\nclass TwoWayList:\n def __init__(self):\n self.head = None\n self.tail = None\n self.length = 0\n\n def isEmpty(self):\n return self.head == None\n \n def append(self, item):\n if self.length == 0:\n node = Node(item)\n self.head = node\n self.tail = node\n self.length = 1\n return\n node = Node(item)\n tail = self.tail\n tail.next = node\n node.prev = tail\n self.tail = node\n self.length += 1\n \n def insert(self, index, item):\n length = self.length\n if (index<0 and abs(index)>length) or (index>0 and index>=length):\n return False\n if index < 0:\n index = index + length\n if index == 0:\n node = Node(item)\n if self.head != None:\n self.head.prev = node\n else:\n self.tail = node\n node.next = self.head\n self.head = node\n self.length += 1\n return True\n if index == length - 1:\n return self.append(item)\n\n\n node1 = self.head\n for i in range(0, index):\n node1 = node1.next\n node2 = node1.next\n\n node = Node(item)\n node.prex = node1\n node.next = node2\n node1.next = node\n node2.prev = node\n\n self.length += 1\n return True\n\n def get(self, data):\n node = self.head\n for i in range(self.length):\n if node.data == data:\n return node\n else:\n node = node.next\n else:\n return False\n\n def getByIndex(self, index):\n if index >= self.length:\n return False\n if index == 0:\n return self.head\n\n now = self.head\n for i in range(self.length):\n if i == index:\n return now\n now = now.next\n\n def setData(self, index, data):\n if index >= self.length:\n return False\n if index == 0:\n self.head.data = data\n\n now = self.head\n for i in range(self.length):\n if i == index:\n now.data = data\n return True\n now = now.next\n \n def remove(self, index):\n if index >= self.length:\n return False\n if index == 0:\n self.head = self.head.next\n if self.length != 1:\n self.head.prev = None\n self.length -= 1\n return True\n if index == self.length-1:\n self.tail = self.tail.prev\n self.tail.next = None\n self.length -= 1\n return True\n\n now = self.head\n for i in range(self.length):\n if i == index:\n now.next.prev = now.prev\n now.prev.next = now.next\n self.length -= 1\n return True\n now = now.next\n\n def reverse(self):\n now = self.head\n last = None\n for i in range(self.length):\n last = now\n now = now.next\n tmp = last.prev\n last.prev = last.next\n last.next = tmp\n tmp = self.head\n self.head = self.tail\n self.tail = tmp\n return True\n \n def clear(self):\n self.head = None\n self.tail = None\n self.length = 0\n\n def __str__(self):\n string = ''\n node = self.head\n for i in range(self.length):\n string += str(node.data) + '/'\n node = node.next\n return string\n\nli = TwoWayList()\nli.isEmpty()\nli.insert(0, 1)\nli.getByIndex(0)\nli.remove(0)\n\nprint(li)\nli.append(1)\n\nprint(li)\nli.append(2)\nprint(li)\nli.append(4)\nprint(li)\nli.insert(2,3)\nprint(li)\nli.insert(3,4)\n\nprint(li)\nli.remove(2)\nprint(li)\nli.setData(2,10)\nprint(li)\nli.reverse()\nprint(li)\nprint(li.get(2).data)\nprint(li.getByIndex(1).data)","sub_path":"link/twowaylist.py","file_name":"twowaylist.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"297323725","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n#Import packages\nimport pandas as pd\nimport numpy as np\nimport sklearn\n\n\n# In[2]:\n\n\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity='all' # this is magic command which will execute all the lines in code instead of last one.\n\n\n# In[3]:\n\n\n#Import dataset and create a dataframe\nfrom sklearn import datasets\nboston=datasets.load_boston()\n\n\n# In[4]:\n\n\n#Find out more about this dataset\nprint(boston.DESCR)\n\n\n# In[5]:\n\n\n#create dataframe\ndf=pd.DataFrame(boston.data,columns=boston.feature_names)\ndf['House_Price']=boston.target\n\n\n# In[6]:\n\n\ndf.head()\n\n\n# In[7]:\n\n\ndf.describe()\n\n\n# In[8]:\n\n\n#scale all values between 0 & 1\nfrom sklearn.preprocessing import MinMaxScaler\nscld=MinMaxScaler(feature_range=(0,1))\narr_scld=scld.fit_transform(df)\ndf_scld=pd.DataFrame(arr_scld,columns=df.columns)\ndf.head()\ndf.describe()\ndf_scld.head()\ndf_scld.describe()\n\n\n# In[9]:\n\n\n#Inverse scaling to revert back to same scale\ndf_scld.head()\ndf1=pd.DataFrame(scld.inverse_transform(df_scld),columns=df.columns)\ndf1.head()\n\n\n# In[10]:\n\n\ndf.count()\n\n\n# In[11]:\n\n\n#Add dependent variabels\ndf['House_Price']=boston.target\ndf.head()\ndf.describe()\n\n\n# In[12]:\n\n\n#correlation matrix\nx=df.corr()\nx\n\n\n# In[15]:\n\n\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nget_ipython().magic('matplotlib inline')\nimport seaborn as sns\nplt.subplots(figsize=(20,20))\nsns.heatmap(x,cmap='RdYlGn',annot=True)\nplt.show()\n\n\n# In[16]:\n\n\n#Create features and labels on the data\nx=df.drop('House_Price', axis=1)\ny=df['House_Price']\nx.head()\ny.head()\n\n\n# In[17]:\n\n\nimport sklearn\nfrom sklearn.cross_validation import train_test_split\n\n\n# In[18]:\n\n\n#Create train and test data with 75% and 25% split\ntrain_x, test_x,train_y,test_y=train_test_split(x,y,test_size=0.3,random_state=1)\ntrain_x.shape\ntest_x.shape\ntrain_y.shape\ntest_y.shape\n\n\n# In[19]:\n\n\n#lets import the regression object and define model\nfrom sklearn.linear_model import LinearRegression\nlm=LinearRegression()\nlm\n\n\n# In[20]:\n\n\n#Fit a model on the train data\nlm.fit(train_x,train_y)\n\n\n# In[21]:\n\n\n#Evaluate the model\npredict_test=lm.predict(test_x)\n\n\n# In[22]:\n\n\n#R2 Value\nprint(\"Rsquare value for TEST data is-\")\nnp.round(lm.score(test_x, test_y)*100,0)\nprint(\"Rsquare value for TRAIN data is-\")\nnp.round(lm.score(train_x,train_y)*100,0)\n\n\n# In[23]:\n\n\n#Predict on test and training data\npredict_test=lm.predict(test_x)\n\n\n# In[24]:\n\n\n#Print the Loss Function - MSE\nimport numpy as np\nfrom sklearn import metrics\nprint (\"Mean Square Error (MSE) for TEST data is-\")\nnp.round(metrics.mean_squared_error(test_y,predict_test),0)\n\n\n# In[25]:\n\n\nfrom sklearn.metrics import mean_absolute_error\nprint (\"Mean Absolute Error (MAE) for TEST data is-\")\nnp.round(mean_absolute_error(test_y,predict_test),0)\n\n\n# In[26]:\n\n\n#Liner regression model fitting and model Evaluation\n#Append data\nfdf=pd.concat([test_x,test_y],1)\nfdf['Predicted']=np.round(predict_test,1)\nfdf['Prediction_error']=fdf['House_Price']-fdf['Predicted']\nfdf\n\n\n# In[27]:\n\n\nplt.subplots(figsize=(20,20))\nplt.scatter(fdf.House_Price,fdf.Prediction_error,color='red')\nplt.xlabel ('House Price')\nplt.ylabel ('Error')\nplt.show();\n\n\n# In[28]:\n\n\nimport seaborn as sns\n\n\n# In[29]:\n\n\n#magic command which will show graphs in the same notebook rather than saving some where.\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nplt.show()\n\n\n# In[30]:\n\n\niris=sns.load_dataset('iris')\n\n\n# In[31]:\n\n\niris.head()\n\n\n# In[32]:\n\n\nnp.round(iris.mean(),2)\n\n\n# In[33]:\n\n\nnp.round(iris.median(),2)\n\n\n# In[34]:\n\n\niris.count()\n\n\n# In[35]:\n\n\n#Counting frequency for categorical values\npd.crosstab(index=iris[\"species\"],columns=\"Frequency\")\n\n\n# In[36]:\n\n\ncorrelation=iris.corr()\ncorrelation\n\n\n# In[37]:\n\n\nsns.heatmap(correlation,cmap=\"RdYlGn\",annot=True)\nplt.show();\nsns.heatmap(correlation,cmap=\"Blues\",annot=True)\nplt.show();\n\n","sub_path":"Boston_Raghavendra Reddy_linerregression.py","file_name":"Boston_Raghavendra Reddy_linerregression.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"2673663","text":"# Load libraries\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom sklearn.metrics import confusion_matrix\r\nimport matplotlib.pyplot as plt\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n# Unpickle data\r\ndata = pd.read_pickle('data')\r\n\r\n# Separate target and features\r\ntarget = 'diagnosis'\r\ny = data[target]\r\nX = data.drop(columns=[target])\r\nfeatures_DT_list = ['texture_mean', 'area_worst', 'smoothness_worst', 'area_mean', 'concavity_mean']\r\nX = X[features_DT_list]\r\n\r\n# Split the dataset into train and test\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=100)\r\n\r\nclfs = {'dt': DecisionTreeClassifier(random_state=0)}\r\n\r\npipe_clfs = {}\r\n\r\nfor name, clf in clfs.items():\r\n pipe_clfs[name] = Pipeline([('StandardScaler', StandardScaler()),\r\n ('clf', clf)])\r\n\r\nparam_grids = {}\r\n\r\n# Parameter grid for Decision Tree\r\nparam_grid = [{'clf__min_samples_split': [2],\r\n 'clf__min_samples_leaf': [3]}]\r\n\r\nparam_grids['dt'] = param_grid\r\n\r\ngs = GridSearchCV(estimator=pipe_clfs['dt'],\r\n param_grid=param_grids['dt'],\r\n scoring='accuracy',\r\n n_jobs=1,\r\n iid=False,\r\n cv=StratifiedKFold(n_splits=10,\r\n shuffle=True,\r\n random_state=0))\r\n\r\n# Fit the pipeline\r\ngs = gs.fit(X_train, y_train)\r\n\r\n# Get prediction\r\ny_pred = gs.predict(X_test)\r\n\r\nprint('Accuracy:', accuracy_score(y_test, y_pred))\r\nprint('Classification Report:')\r\nprint(classification_report(y_test, y_pred))\r\n\r\nle = LabelEncoder()\r\ny_test = le.fit_transform(y_test)\r\ny_pred = le.fit_transform(y_pred)\r\n\r\nprint('ROC_AUC Score', roc_auc_score(y_test, y_pred))\r\n\r\n# CONFUSION MATRIX\r\n# Plot non-normalized confusion matrix\r\nfrom sklearn.metrics import ConfusionMatrixDisplay\r\ncm = confusion_matrix(y_test, y_pred)\r\ncmd = ConfusionMatrixDisplay(cm, display_labels=['B','M'])\r\ncmd.plot(cmap='Blues')\r\ncmd.ax_.set(xlabel='Predicted', ylabel='True')\r\nplt.figure(figsize=(5,5))\r\nplt.show()\r\n\r\ntn, fp, fn, tp = cm.ravel()\r\nprint('Coefficients Confusion DT - best parameters')\r\nprint('tn', tn, 'fp', fp, 'fn', fn, 'tp', tp)\r\n\r\n# OUTPUT TO INPUT CAPSTONE PROJECT\r\n# OUTPUT THE MODEL\r\nimport pickle\r\nwith open('clf.DT', 'wb') as f:\r\n pickle.dump(gs, f)\r\n\r\n# OUTPUT THE PREDICTIONS\r\nfrom numpy import savetxt\r\nsavetxt('DT_y_pred.csv', y_pred, delimiter=',')\r\n\r\n# OUTPUT THE WRONG PREDICTIONS AND CORRESPONDING SAMPLE NUMBER\r\nDT_x_wrong = []\r\nDT_y_wrong = []\r\n\r\nfor i in range(len(y_pred)):\r\n y_t = y_test[i]\r\n y_p = y_pred[i]\r\n if y_t != y_p:\r\n DT_x_wrong.append(i)\r\n DT_y_wrong.append(y_p)\r\n print(i, 'predicted:', y_p, 'true:', y_t)\r\n\r\n# save to csv file\r\nsavetxt('DT_x_wrong.csv', DT_x_wrong, delimiter=',')\r\nsavetxt('DT_y_wrong.csv', DT_y_wrong, delimiter=',')\r\n","sub_path":"DM Final Project_6_DT.py","file_name":"DM Final Project_6_DT.py","file_ext":"py","file_size_in_byte":3349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"619940089","text":"import unittest\n\nfrom selenium.webdriver.android import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n\nclass TestSelenium(unittest.TestCase):\n @unittest.skip(\"Nie pyknie na serwerze github, bo nie sciagamy sterownika\")\n def test_selenium(self):\n driver = webdriver.Chrome(executable_path='/Users/jacja/Downloads/chromedriver')\n driver.get(\"http://www.python.org\")\n self.assertIn(\"Python\", driver.title)\n elem = driver.find_element_by_name(\"q\")\n elem.clear()\n elem.send_keys(\"pycon\")\n elem.send_keys(Keys.RETURN)\n self.assertNotIn(\"No results found.\", driver.page_source)\n driver.close()","sub_path":"tests/selenium/test_selenium.py","file_name":"test_selenium.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"573245506","text":"\n\nfrom xai.brain.wordbase.nouns._syrian import _SYRIAN\n\n#calss header\nclass _SYRIANS(_SYRIAN, ):\n\tdef __init__(self,): \n\t\t_SYRIAN.__init__(self)\n\t\tself.name = \"SYRIANS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"syrian\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_syrians.py","file_name":"_syrians.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"418889002","text":"#!/usr/bin/env python3\nimport asyncio\nimport json\nfrom pathlib import Path\nimport random\n\nasync def get_message(loop, name, persistent):\n reader, writer = await asyncio.open_connection(\n '127.0.0.1', 14141, loop=loop\n )\n writer.write(json.dumps({\n 'type': 'command',\n 'command': 'read',\n 'destination': name.rstrip(),\n 'persistent_queue': persistent\n }).encode('utf-8'))\n writer.write_eof()\n await writer.drain()\n response = await reader.read()\n writer.close()\n return response\n\nasync def get_destination_name():\n path = Path(\"free_users.txt\")\n if path.is_file():\n with open(\"free_users.txt\", 'r+') as f:\n all_names = f.readlines()\n length = len(all_names)\n f.seek(0)\n for i, val in enumerate(all_names):\n if i == 0:\n name = val\n else:\n f.write(val)\n f.truncate()\n f.close()\n with open(\"connected_users.txt\", \"a\") as f:\n f.write(name)\n return name\n\nasync def run_receiver(loop):\n name = await get_destination_name()\n int_number = random.randint(1, 2)\n persistent = False\n if int_number == 1:\n persistent = True\n print(persistent)\n while True:\n try:\n response = await get_message(loop, name, persistent)\n print('Received %s', response)\n await asyncio.sleep(2)\n except KeyboardInterrupt:\n break\n\n\ndef main():\n loop = asyncio.get_event_loop()\n loop.run_until_complete(run_receiver(loop))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"155511429","text":"# Modules\nimport os\nimport csv\n\n# Set path for file\ncsvpath = os.path.join(\"election_data.csv\")\n\n# Open the CSV\nwith open(csvpath, newline=\"\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n\n # Assign list to a variable\n my_list = list(csvreader)\n\n # Removing header row from my list\n my_list.remove(my_list[0])\n\n # Create Election Results summary list\n results = []\n\n # Add title to Election Results\n results.append(\"Election Results\")\n\n # Add separation lines to Election Results\n results.append(\"-------------------------\")\n\n # Count how many total votes there are\n votes = len(my_list)\n\n # Add Total Votes to Election Results\n results.append(\"Total Votes: \" + str(votes))\n\n # Add separation lines to Election Results\n results.append(\"-------------------------\")\n\n # Start vote counter for each candidate\n Khan = 0\n Correy = 0\n Li = 0\n OTooley = 0\n\n # Read each row and add 1 to counter for each candidate\n for row in my_list:\n if row[2] == 'Khan':\n Khan += 1\n if row[2] == 'Correy':\n Correy += 1\n if row[2] == 'Li':\n Li += 1\n if row[2] == 'O\\'Tooley':\n OTooley += 1\n\n # Convert decimal to percentage\n kper = (Khan/votes)*100\n cper = (Correy/votes)*100\n lper = (Li/votes)*100\n oper = (OTooley/votes)*100\n\n # Round percentages to third decimal\n from decimal import Decimal\n kper = Decimal(kper).quantize(Decimal('1e-3'))\n cper = Decimal(cper).quantize(Decimal('1e-3'))\n lper = Decimal(lper).quantize(Decimal('1e-3'))\n oper = Decimal(oper).quantize(Decimal('1e-3'))\n\n # Add individual candidate results to Election Results\n results.append(\"Khan: \" + str(kper) + \"% (\" + str(Khan) + \")\")\n results.append(\"Correy: \" + str(cper) + \"% (\" + str(Correy) + \")\")\n results.append(\"Li: \" + str(lper) + \"% (\" + str(Li) + \")\")\n results.append(\"O'Tooley: \" + str(oper) + \"% (\" + str(OTooley) + \")\")\n\n # Add separation lines to Election Results\n results.append(\"-------------------------\")\n\n # Determine winner\n comparison = [Khan, Correy, Li, OTooley]\n highest = max(comparison)\n if highest == Khan:\n winner = 'Khan'\n elif highest == Correy:\n winner = 'Correy'\n elif highest == Li:\n winner = 'Li'\n elif highest == OTooley:\n winner = 'O\\'Tooley' \n\n # Add winner to Election Results\n results.append(\"Winner: \" + winner)\n\n # Add separation lines to Election Results\n results.append(\"-------------------------\")\n\n # Add Election Results to text file\n with open('electionresults.txt', 'w') as filehandle: \n for listitem in results:\n filehandle.write('%s\\n' % listitem)\n\n # Print Election Results \n print(*results, sep = \"\\n\")","sub_path":"03-PythonChallenge/PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"278223253","text":"from tkinter import *\nimport time, random\n\ntk = Tk()\ncanvas = Canvas(tk, width = 1000, height = 1000)\ncanvas.pack()\n\ndef move(event):\n if event.keysym == 'Up':\n global y\n global y1\n y-=10\n y1-=10\n print(1)\n elif event.keysym == 'Down':\n y+=10\n y1+=10\n print(2)\n elif event.keysym == 'Right':\n global x\n global x1\n x+=10\n x1+=10\n print(3)\n elif event.keysym == 'Left':\n x-=10\n x1-=10\n print(4)\n \nbackground = canvas.create_rectangle(0, 0, 1000, 1000, fill = 'white') #draws background\nranNum=random.random()*960 #Creates a random number\nranNum1=random.random()*960 #Creates a random number\n#food = canvas.create_rectangle(ranNum, ranNum1, ranNum + 15, ranNum1 + 15, fill='green') #creates food\nr1 = None\no = 0\nlength = 4\nx = 500\ny = 500\nx1 = 515\ny1 = 515\nwhile o < length:\n if canvas.find_overlapping(ranNum, ranNum, ranNum + 15, ranNum1 + 15) == True:\n x+=5\n y+=5\n x1+=5\n y1+=5\n #canvas.delete(food)\n r=canvas.create_rectangle(x, y, x1, y1, fill = 'blue')\n tk.bind('', move )\n tk.bind('', move)\n tk.bind('', move)\n tk.bind('', move)\n time.sleep(.0)\n canvas.delete(r1)\n r1 = r\n tk.update()\n\ntk.mainloop()\n","sub_path":"car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"215876511","text":"import numpy as np\r\nfrom emoji_translator import just_emojis\r\nimport zipfile\r\nimport os\r\nimport re\r\nimport gensim\r\nfrom pathlib import Path\r\nfrom pathlib import PurePath\r\nfrom rusvectores_script.rus_preprocessing_udpipe import ultimate_process\r\nemb_dim = 300\r\nbase_path = os.path.abspath('')\r\ntrained_models_directiory = PurePath(base_path, 'borrowed_model')\r\npath_to_current_model = os.path.join(trained_models_directiory,\r\n \"rusvectores_180.zip\")\r\npath_to_current_emoji_model = os.path.join(trained_models_directiory,\r\n \"emoji2vec.bin\")\r\nwith zipfile.ZipFile(path_to_current_model, 'r') as archive:\r\n stream = archive.open('model.bin')\r\n model = gensim.models.KeyedVectors.load_word2vec_format(stream, binary=True)\r\nemoji_model = gensim.models.KeyedVectors.load_word2vec_format(path_to_current_emoji_model, binary=True)\r\nvse_ne_bukvy = re.compile('[^а-я ]')\r\ndef from_tweet_to_text_vector(x):\r\n temp = x.lower() #понижает регистр\r\n #temp = re.sub('ё', 'е', temp) #заменяет Ё на Е \r\n temp = vse_ne_bukvy.sub('', temp) #убирает всё кроме букв и пробелов\r\n return [model[word] for word in ultimate_process(temp) if word in model]\r\n\r\nvse_ne_emoji = re.compile('[^\\U0001f600-\\U0001f650]') \r\ndef from_tweet_to_emoji_vector(x):\r\n unicode_emoji_lst = list(vse_ne_emoji.sub('', x)) #оставит только эмоджи\r\n ascii_emoji_lst = just_emojis(x) #оставит только ascii эмоджи\r\n emoji_lst = unicode_emoji_lst + ascii_emoji_lst\r\n return [emoji_model[emoji] for emoji in emoji_lst if emoji in emoji_model]\r\n\r\ndef to_connect_and_size(text, emoji, text_maxlen, emoji_maxlen):\r\n return np.append(to_size(text, text_maxlen),\r\n to_size(emoji, emoji_maxlen),\r\n axis=1)\r\n\r\ndef to_size(data, maxlen):\r\n output = []\r\n for smp in data:\r\n if smp.size >0:\r\n output.append(np.append(smp[:maxlen],\r\n np.zeros((max(0, maxlen - len(smp)),\r\n emb_dim)),\r\n axis = 0))\r\n else: output.append(np.zeros((maxlen - len(smp), emb_dim)))\r\n return np.array(output)\r\n","sub_path":"main_library.py","file_name":"main_library.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"407850356","text":"b=[]\r\nfor i in range(int(input())):\r\n name = input()\r\n score = float(input())\r\n a=[]\r\n a.append(name)\r\n a.append(score)\r\n b.append(a)\r\nmarks=[]\r\nfor j in range(len(b)):\r\n marks.append(b[j][1])\r\nmarks.sort()\r\nfor k in range(len(marks)-1):\r\n if marks[k]!=marks[k+1]:\r\n sec_small=marks[k+1]\r\n break\r\n else:\r\n k=k+1\r\nname=[]\r\nfor p in range(len(b)):\r\n for q in range(2):\r\n if b[p][q]==sec_small:\r\n name.append(b[p][q-1])\r\nname.sort()\r\nfor z in range(len(name)):\r\n print(name[z]) \r\n","sub_path":"Python/Nested Lists.py","file_name":"Nested Lists.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"285616206","text":"import math\n\n\n# Implementing Binary Min Heap using an array\nclass MinHeap:\n def __init__(self):\n self.heap = [None]\n\n def insert(self, value):\n self.heap.append(value)\n\n if len(self.heap) > 2:\n self._heapify_up(len(self.heap) - 1)\n\n # Returns the min value in the heap\n def peek(self):\n return self.heap[0]\n\n # Removes and returns the min value in the heap\n def extract_min(self):\n min_val = self.heap[0]\n\n # swap root with last element in the heap\n # then bubble down this value\n self.heap[0] = self.heap[len(self.heap) - 1]\n self.heap = self.heap[:-1]\n self._heapify_down(0)\n\n return min_val\n\n def _heapify_up(self, index):\n # get the parent index\n if index % 2 != 0:\n parent_index = int(math.floor((index - 1)/2))\n else:\n parent_index = int(index/2)\n\n # swap the two values if the child is smaller than its parent\n if parent_index > 0 and self.heap[parent_index] > self.heap[index]:\n self.heap[parent_index], self.heap[index] = self.heap[index], self.heap[parent_index]\n\n # recursively \"bubble up\" this value until it has reached its appropriate position in the heap\n self._heapify_up(parent_index)\n\n def _heapify_down(self, index):\n # get the child indices\n l_child = index * 2\n r_child = 2 * index + 1\n\n # swap the values if the child is smaller than its parent\n # recursively \"bubble down\" this value until reach leaf node\n if l_child < len(self.heap) - 1:\n if self.heap[index] > self.heap[l_child]:\n self.heap[index], self.heap[l_child] = self.heap[l_child], self.heap[index]\n self._heapify_down(l_child)\n\n if r_child < len(self.heap) - 1:\n if self.heap[index] > self.heap[r_child]:\n self.heap[index], self.heap[r_child] = self.heap[r_child], self.heap[index]\n self._heapify_down(r_child)\n\n def __str__(self):\n if len(self.heap) == 1:\n return str([])\n else:\n return str(self.heap[1:])\n\n\nif __name__ == \"__main__\":\n heap = MinHeap()\n heap.insert(40)\n heap.insert(60)\n heap.insert(10)\n heap.insert(20)\n heap.insert(50)\n heap.insert(30)\n print(heap)\n\n heap.extract_min()\n print(heap)\n","sub_path":"binary-min-heap/binary_min_heap.py","file_name":"binary_min_heap.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"643810001","text":"import logging\nimport logging.config\nimport os\nimport sys\n\nimport pandas as pd\n\nfrom api_calls import API_KEY, get_api_call, get_api_sig\nfrom api_keys import HOST\nfrom config import config\nfrom constants import (\n LIB_COMMON_DIR,\n PLAYERS_IN_TEAM_URL,\n PLAYERS_STATS_COLS,\n PLAYERS_STATS_URL,\n PROJECT_DIR,\n)\nfrom db_handle import insert_values\n\nfor d in [PROJECT_DIR, LIB_COMMON_DIR]:\n sys.path.append(d)\n\n\nlogger = logging.getLogger('main_logger')\n\nLOGS_DIR = os.path.join(PROJECT_DIR, 'logs')\nos.makedirs(LOGS_DIR, exist_ok=True)\nos.chdir(LOGS_DIR)\n\n\ndef get_players_in_team(team_id, league):\n\n API_SIG = get_api_sig()\n json_data = get_api_call(\n PLAYERS_IN_TEAM_URL.format(HOST, league, team_id, API_KEY, API_SIG)\n )\n\n if 'apiResults' not in json_data.keys():\n logger.info(\"There are no players in team {}\".format(team_id))\n return None\n\n res_raw = json_data['apiResults']\n res = res_raw[0]['league']['players']\n player_ids = [p['playerId'] for p in res]\n\n return player_ids\n\n\ndef get_players_stats_from_events(game_events_df):\n\n game_stats = [\n 'aerial_won',\n 'is_recovery_location_last_third',\n 'pass_in_last_third',\n 'pass_into_last_third',\n 'is_recovery',\n 'is_turnover',\n ]\n\n game_stats_df = (\n game_events_df[game_stats + ['offensivePlayer_playerId']]\n .groupby('offensivePlayer_playerId')\n .sum()\n .reset_index()\n )\n\n # Add aerial duels lost\n lost_duels = (\n game_events_df[['lost_duel_playerId', 'aerial_won']]\n .groupby('lost_duel_playerId')\n .sum()\n .reset_index()\n )\n lost_duels.columns = ['offensivePlayer_playerId', 'aerial_lost']\n\n stats_from_events_df = pd.merge(game_stats_df, lost_duels, how='left')\n stats_from_events_df['aerial_lost'].fillna(0, inplace=True)\n\n # Add fouls suffered in last third\n foul_in_last_third = (\n game_events_df[['defensivePlayer_playerId', 'foul_in_last_third']]\n .groupby('defensivePlayer_playerId')\n .sum()\n .reset_index()\n )\n\n foul_in_last_third.columns = [\n 'offensivePlayer_playerId',\n 'fouls_suffered_in_last_third',\n ]\n\n final_df = pd.merge(stats_from_events_df, foul_in_last_third, how='left')\n final_df['fouls_suffered_in_last_third'].fillna(0, inplace=True)\n\n final_df.rename(columns={'offensivePlayer_playerId': 'player_id'}, inplace=True)\n\n return final_df\n\n\ndef get_api_results(league, p, g, try_number=0):\n if try_number > 4:\n logger.info(\"There is no data for player {} in game {}\".format(p, g))\n return None\n else:\n API_SIG = get_api_sig()\n json_data = get_api_call(\n PLAYERS_STATS_URL.format(HOST, league, p, g, API_KEY, API_SIG)\n )\n\n if 'apiResults' not in json_data.keys():\n try_number += 1\n return get_api_results(league, p, g, try_number)\n else:\n return json_data\n\n\ndef insert_players_stats(g, league, game_events_df):\n\n stats_from_events_df = get_players_stats_from_events(game_events_df)\n\n game_stats = []\n\n for grp, grp_df in game_events_df.groupby(['teamId', 'offensivePlayer_playerId']):\n t, p = grp\n p = int(p)\n\n json_data = get_api_results(league, p, g)\n\n res = json_data['apiResults'][0]['league']['players'][0]['seasons'][0][\n 'eventType'\n ][0]['splits'][0]['events'][0]\n\n pl_stats = res['playerStats']\n\n player_dict = {}\n for key, val in pl_stats.items():\n if isinstance(val, dict):\n for k, v in val.items():\n key_name = '{}_{}'.format(key, k)\n player_dict[key_name] = [v]\n else:\n player_dict[key] = [val]\n\n gk_dit = {}\n if 'goaltenderStats' in res.keys():\n for key, val in res['goaltenderStats'].items():\n if isinstance(val, dict):\n for k, v in val.items():\n key_name = '{}_{}'.format(key, k)\n player_dict[key_name] = [v]\n gk_dit[key_name] = [v]\n else:\n player_dict[key] = [val]\n gk_dit[key] = [val]\n\n player_df = pd.DataFrame(player_dict)\n\n player_df['game_id'] = g\n player_df['team_id'] = t\n player_df['player_id'] = p\n\n game_stats.append(player_df)\n\n if not len(game_stats):\n return pd.DataFrame()\n\n game_stats_df = pd.concat(game_stats, sort=True)\n\n players_game_stats_df = pd.merge(game_stats_df, stats_from_events_df)\n\n insert_values(players_game_stats_df, 'players_stats', PLAYERS_STATS_COLS)\n\n return game_stats_df\n\n\nif __name__ == '__main__':\n logging.config.dictConfig(config['logger'])\n","sub_path":"get_data/python/get_players_stats.py","file_name":"get_players_stats.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"13283822","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'Wang Chao'\n__date__ = '14-7-14'\n\nfrom core.signals import vip_changed_signal\nfrom core.prison import Prison\nfrom core.mail import Mail\nfrom core.plunder import Plunder\nfrom preset.settings import MAIL_VIP_CHANGED_CONTENT, MAIL_VIP_CHANGED_TITLE\nfrom preset.data import VIP_FUNCTION\n\n\ndef _vip_change(char_id, old_vip, new_vip, **kwargs):\n Prison(char_id).vip_changed(new_vip)\n m = Mail(char_id)\n m.add(name=MAIL_VIP_CHANGED_TITLE, content=MAIL_VIP_CHANGED_CONTENT.format(new_vip))\n\n # 增加掠夺次数\n plunder_times_change_value = VIP_FUNCTION[new_vip].plunder - VIP_FUNCTION[old_vip].plunder\n if plunder_times_change_value:\n plunder = Plunder(char_id)\n plunder.change_current_plunder_times(plunder_times_change_value, allow_overflow=True)\n\n\nvip_changed_signal.connect(\n _vip_change,\n dispatch_uid='callbacks.signals.vip._vip_up'\n)\n\n","sub_path":"sanguo/callbacks/signals/vip.py","file_name":"vip.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"534001974","text":"#!/usr/bin/python2\n# coding: utf-8\nfrom __future__ import unicode_literals\n\n# Tweets import script\n\nfrom tweepy_import import FilteredStream\n\nSIZE = 1000 # Number of tweets saved in a file\n\nclass MyFilteredStream(FilteredStream):\n\n def __init__(self):\n\n\t\t# Search criterias\n self.criterias = {\n \"track\": [\"Paris\", \"Bordeaux\"],\n \"locations\": [-0.6389644,44.8111222,-0.5334955,44.9163535],\n \"lang\": [\"fr\"]\n }\n FilteredStream.__init__(self, self.criterias, SIZE, \"../config.json\")\n self.tweets = []\n self.num_export = 0\n\n def action(self, tweets_list):\n self.tweets += tweets_list\n # print(\"Missing : \" + str(SIZE - len(self.tweets)))\n\n if len(self.tweets) >= SIZE:\n exp = []\n for i in range(0, SIZE):\n exp += [self.tweets.pop(0)]\n\n self.export('tweets-' + str(self.num_export) + '.json', exp)\n self.num_export += 1\n\nstream = MyFilteredStream()\nstream.stream()\n","sub_path":"vectorize_clustering/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"218038341","text":"import os\r\nimport time\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport numpy as np\r\nimport argparse\r\n\r\nfrom modeling.classification.MobileNetV2 import mobilenet_v2\r\nfrom torch.utils.data import DataLoader\r\nfrom torchvision import transforms, datasets\r\n\r\nfrom utils.relation import create_relation\r\nfrom dfq import cross_layer_equalization, bias_absorption, bias_correction, _quantize_error, clip_weight\r\nfrom utils.layer_transform import switch_layers, replace_op, restore_op, set_quant_minmax, merge_batchnorm, quantize_targ_layer#, LayerTransform\r\nfrom PyTransformer.transformers.torchTransformer import TorchTransformer\r\n\r\nfrom utils.quantize import QuantConv2d, QuantLinear, QuantNConv2d, QuantNLinear, QuantMeasure\r\n\r\ndef get_argument():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--quantize\", action='store_true')\r\n parser.add_argument(\"--equalize\", action='store_true')\r\n parser.add_argument(\"--correction\", action='store_true')\r\n parser.add_argument(\"--absorption\", action='store_true')\r\n parser.add_argument(\"--relu\", action='store_true')\r\n parser.add_argument(\"--clip_weight\", action='store_true')\r\n parser.add_argument(\"--trainable\", action='store_true')\r\n return parser.parse_args()\r\n\r\n\r\ndef inference_all(model):\r\n print(\"Start inference\")\r\n imagenet_dataset = datasets.ImageFolder('/home/jakc4103/Windows/Dec19/workspace/dataset/ILSVRC/Data/CLS-LOC/val', transforms.Compose([\r\n transforms.Resize(256),\r\n transforms.CenterCrop(224),\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\r\n std=[0.229, 0.224, 0.225]),\r\n ]))\r\n\r\n dataloader = DataLoader(imagenet_dataset, batch_size=256, shuffle=False, num_workers=4, pin_memory=True)\r\n\r\n num_correct = 0\r\n num_total = 0\r\n with torch.no_grad():\r\n for ii, sample in enumerate(dataloader):\r\n image, label = sample[0].cuda(), sample[1].numpy()\r\n logits = model(image)\r\n\r\n pred = torch.max(logits, 1)[1].cpu().numpy()\r\n \r\n num_correct += np.sum(pred == label)\r\n num_total += image.shape[0]\r\n # print(num_correct, num_total, num_correct/num_total)\r\n acc = num_correct / num_total\r\n return acc\r\n\r\n\r\ndef main():\r\n args = get_argument()\r\n assert args.relu or args.relu == args.equalize, 'must replace relu6 to relu while equalization'\r\n assert args.equalize or args.absorption == args.equalize, 'must use absorption with equalize'\r\n data = torch.ones((4, 3, 224, 224))#.cuda()\r\n\r\n model = mobilenet_v2('modeling/classification/mobilenetv2_1.0-f2a8633.pth.tar')\r\n model.eval()\r\n \r\n transformer = TorchTransformer()\r\n module_dict = {}\r\n if args.quantize:\r\n if args.trainable:\r\n module_dict[1] = [(nn.Conv2d, QuantConv2d), (nn.Linear, QuantLinear)]\r\n else:\r\n module_dict[1] = [(nn.Conv2d, QuantNConv2d), (nn.Linear, QuantNLinear)]\r\n \r\n if args.relu:\r\n module_dict[0] = [(torch.nn.ReLU6, torch.nn.ReLU)]\r\n\r\n # transformer.summary(model, data)\r\n # transformer.visualize(model, data, 'graph_cls', graph_size=120)\r\n\r\n model, transformer = switch_layers(model, transformer, data, module_dict, ignore_layer=[QuantMeasure], quant_op=args.quantize)\r\n\r\n graph = transformer.log.getGraph()\r\n bottoms = transformer.log.getBottoms()\r\n output_shape = transformer.log.getOutShapes()\r\n if args.quantize:\r\n if args.trainable:\r\n targ_layer = [QuantConv2d, QuantLinear]\r\n else:\r\n targ_layer = [QuantNConv2d, QuantNLinear]\r\n else:\r\n targ_layer = [nn.Conv2d, nn.Linear]\r\n\r\n model = merge_batchnorm(model, graph, bottoms, targ_layer)\r\n\r\n #create relations\r\n if args.equalize:\r\n res = create_relation(graph, bottoms, targ_layer)\r\n cross_layer_equalization(graph, res, targ_layer, visualize_state=False, converge_thres=2e-7)\r\n \r\n if args.absorption:\r\n bias_absorption(graph, res, bottoms, 3)\r\n \r\n if args.clip_weight:\r\n clip_weight(graph, range_clip=[-15, 15], targ_type=targ_layer)\r\n\r\n if args.correction:\r\n bias_correction(graph, bottoms, targ_layer)\r\n\r\n if args.quantize:\r\n if not args.trainable:\r\n graph = quantize_targ_layer(graph, targ_layer)\r\n set_quant_minmax(graph, bottoms, output_shape)\r\n \r\n model = model.cuda()\r\n model.eval()\r\n\r\n if args.quantize:\r\n replace_op()\r\n acc = inference_all(model)\r\n print(\"Acc: {}\".format(acc))\r\n if args.quantize:\r\n restore_op()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"main_cls.py","file_name":"main_cls.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"77878950","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport tensorflow as tf\nimport numpy as np\nfrom skimage.io import imread\nfrom skimage.transform import resize\nimport cv2\nimport numpy as np\nimport os\nfrom violencemodel import *\nfrom flask import Flask , request , jsonify , Response\nfrom PIL import Image\nfrom io import BytesIO\nimport time\nfrom skimage.transform import resize\nfrom tensorflow.keras.models import Sequential, Model, load_model\nfrom tensorflow.keras.layers import Dropout, Dense, Flatten, Input\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.metrics import categorical_crossentropy\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import backend\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.datastructures import FileStorage\nfrom collections import deque\nimport numpy as np\nimport argparse\nimport pickle\nimport cv2\nfrom twilio.rest import Client\n\nmodel1 = souhaiel_model(tf)\n# construct the argument parser and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--input\", required=True,\n\thelp=\"path to our input video\")\nap.add_argument(\"-o\", \"--output\", required=True,\n\thelp=\"path to our output video\")\nap.add_argument(\"-s\", \"--size\", type=int, default=128,\n\thelp=\"size of queue for averaging\")\nargs = vars(ap.parse_args())\n\n# load the trained model and label binarizer from disk\nprint(\"[INFO] loading model and label binarizer...\")\nmodel = model1\n# initialize the image mean for mean subtraction along with the\n# predictions queue\n#mean = np.array([123.68, 116.779, 103.939][::1], dtype=\"float32\")\nQ = deque(maxlen=args[\"size\"])\n\n# initialize the video stream, pointer to output video file, and\n# frame dimensions\nvs = cv2.VideoCapture(args[\"input\"])\nvc=cv2.VideoCapture('weeknd1.mp4')\nfps = vs.get(cv2.CAP_PROP_FPS)\nwriter = None\n(W, H) = (None, None)\n#client = Client(\"ACea4cecca40ebb1bf4594098d5cef4541\", \"32789639585561088d5937514694e115\") #update from twilio\nprelabel = ''\nok = 'Normal'\nokk='violence'\ni=0\nframes = np.zeros((30, 160, 160, 3), dtype=np.float)\ndatav = np.zeros((1, 30, 160, 160, 3), dtype=np.float)\nframe_counter=0\n\n# loop over frames from the video file stream\nwhile True:\n # read the next frame from the file\n (grabbed, frm) = vc.read()\n \n # if the frame was not grabbed, then we have reached the end\n # of the stream\n if not grabbed:\n break\n # if the frame dimensions are empty, grab them\n if W is None or H is None:\n (H, W) = frm.shape[:2]\n #framecount = framecount+1\n # clone the output frame, then convert it from BGR to RGB\n # ordering, resize the frame to a fixed 224x224, and then\n # perform mean subtraction\n output = frm.copy()\n while i < 30:\n rval, frame = vs.read()\n frame_counter +=1\n if frame_counter == vs.get(cv2.CAP_PROP_FRAME_COUNT):\n frame_counter = 0 #Or whatever as long as it is the same as next line\n vs.set(cv2.CAP_PROP_POS_FRAMES, 0)\n frame = resize(frame,(160,160,3))\n frame = np.expand_dims(frame,axis=0)\n if(np.max(frame)>1):\n frame = frame/255.0\n frames[i][:] = frame\n i +=1\n \n datav[0][:][:] =frames\n frames -= mean\n \n\n\t# make predictions on the frame and then update the predictions\n\t# queue\n #preds = model1.predict(datav)\n#\tprint('Preds = :', preds)\n\t\n#\ttotal = (preds[0]+ preds[1]+preds[2] + preds[3]+ preds[4]+preds[5])\n#\tmaximum = max(preds)\n#\trest = total - maximum\n \n#\tdiff = (.8*maximum) - (.1*rest)\n#\tprint('Difference of prob ', diff)\n#\tth = 100\n#\tif diff > .60:\n#\t\tth = diff\n#\tprint('Old threshold = ', th)\n \n \n prediction = preds.argmax(axis=0)\n Q.append(preds)\n\n\t# perform prediction averaging over the current history of\n\t# previous predictions\n results = np.array(Q).mean(axis=0)\n print('Results = ', results)\n maxprob = np.max(results)\n print('Maximun Probability = ', maxprob)\n i = np.argmax(results)\n rest = 1 - maxprob\n \n diff = (maxprob) - (rest)\n print('Difference of prob ', diff)\n th = 100\n if diff > .80:\n th = diff\n \n \n \n \n if (preds[0][1]) < th:\n text = \"Alert : {} - {:.2f}%\".format((ok), 100 - (maxprob * 100))\n cv2.putText(output, text, (35, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.25, (0, 255, 0), 5)\n else:\n\t\t\n text = \"Alert : {} - {:.2f}%\".format((okk), maxprob * 100)\n cv2.putText(output, text, (35, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.25, (0, 0, 255), 5) \n#\t\tif label != prelabel:\n#\t\t\tclient.messages.create(to=\"<+country code>< receiver mobile number>\", #for example +918255555555\n# from_=\"+180840084XX\", #sender number can be coped from twilo\n# body='\\n'+ str(text) +'\\n Satellite: ' + str(camid) + '\\n Orbit: ' + location)\n \n\n\n\t# check if the video writer is None\n if writer is None:\n\t # initialize our video writer\n fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n writer = cv2.VideoWriter(args[\"output\"], fourcc, 27.0,\n\t\t\t(W, H), True)\n\n\t# write the output frame to disk\n writer.write(output)\n\n\t# show the output image\n cv2.imshow(\"Output\", output)\n key = cv2.waitKey(1) & 0xFF\n\n\t# if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break\n#print('Frame count', framecount)\n# release the file pointers\nprint(\"[INFO] cleaning up...\")\nwriter.release()\nvs.release()\nvc.release()\n","sub_path":"predict_video1.py","file_name":"predict_video1.py","file_ext":"py","file_size_in_byte":5507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"252546368","text":"# -*- coding: utf-8 -*-\n\"\"\"\nLUT Processing\n==============\n\nDefines the classes and definitions handling *LUT* processing:\n\n- :class:`colour.LUT1D`\n- :class:`colour.LUT3x1D`\n- :class:`colour.LUT3D`\n- :class:`colour.LUTSequence`\n- :class:`colour.io.LUT_to_LUT`\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\nimport re\nfrom abc import ABCMeta, abstractmethod\nfrom collections import MutableSequence\nfrom copy import deepcopy\n# pylint: disable=W0622\nfrom operator import add, mul, pow, sub, iadd, imul, ipow, isub\n\n# Python 3 compatibility.\ntry:\n from operator import div, idiv\nexcept ImportError:\n from operator import truediv, itruediv\n\n div = truediv\n idiv = itruediv\nfrom six import add_metaclass\n\nfrom colour.algebra import LinearInterpolator, table_interpolation_trilinear\nfrom colour.constants import DEFAULT_INT_DTYPE\nfrom colour.utilities import (as_float_array, is_numeric, is_iterable,\n is_string, linear_conversion, runtime_warning,\n tsplit, tstack, usage_warning)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2019 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = [\n 'AbstractLUT', 'LUT1D', 'LUT3x1D', 'LUT3D', 'LUT_to_LUT',\n 'AbstractLUTSequenceOperator', 'LUTSequence'\n]\n\n\n@add_metaclass(ABCMeta)\nclass AbstractLUT:\n \"\"\"\n Defines the base class for *LUT*.\n\n This is an :class:`ABCMeta` abstract class that must be inherited by\n sub-classes.\n\n Parameters\n ----------\n table : array_like, optional\n Underlying *LUT* table.\n name : unicode, optional\n *LUT* name.\n dimensions : int, optional\n *LUT* dimensions, typically, 1 for a 1D *LUT*, 2 for a 3x1D *LUT* and 3\n for a 3D *LUT*.\n domain : unicode, optional\n *LUT* domain, also used to define the instantiation time default table\n domain.\n size : int, optional\n *LUT* size, also used to define the instantiation time default table\n size.\n comments : array_like, optional\n Comments to add to the *LUT*.\n\n Attributes\n ----------\n table\n name\n dimensions\n domain\n size\n comments\n\n Methods\n -------\n __str__\n __repr__\n __eq__\n __ne__\n __add__\n __iadd__\n __sub__\n __isub__\n __mul__\n __imul__\n __div__\n __idiv__\n __pow__\n __ipow__\n arithmetical_operation\n is_domain_explicit\n linear_table\n apply\n copy\n as_LUT\n \"\"\"\n\n def __init__(self,\n table=None,\n name=None,\n dimensions=None,\n domain=None,\n size=None,\n comments=None):\n default_name = ('Unity {0}'.format(size)\n if table is None else '{0}'.format(id(self)))\n self._name = default_name\n self.name = name\n\n self._dimensions = dimensions\n\n # TODO: Re-enable when dropping Python 2.7.\n # pylint: disable=E1121\n self._table = self.linear_table(size, domain)\n self.table = table\n self._domain = None\n self.domain = domain\n self._comments = []\n self.comments = comments\n\n @property\n def table(self):\n \"\"\"\n Getter and setter property for the underlying *LUT* table.\n\n Parameters\n ----------\n value : unicode\n Value to set the the underlying *LUT* table with.\n\n Returns\n -------\n unicode\n Underlying *LUT* table.\n \"\"\"\n\n return self._table\n\n @table.setter\n def table(self, value):\n \"\"\"\n Setter for **self.table** property.\n \"\"\"\n\n if value is not None:\n # pylint: disable=E1121\n self._table = self._validate_table(value)\n\n @property\n def name(self):\n \"\"\"\n Getter and setter property for the *LUT* name.\n\n Parameters\n ----------\n value : unicode\n Value to set the *LUT* name with.\n\n Returns\n -------\n unicode\n *LUT* name.\n \"\"\"\n\n return self._name\n\n @name.setter\n def name(self, value):\n \"\"\"\n Setter for **self.name** property.\n \"\"\"\n\n if value is not None:\n assert is_string(value), (\n ('\"{0}\" attribute: \"{1}\" type is not \"str\" or \"unicode\"!'\n ).format('name', value))\n\n self._name = value\n\n @property\n def domain(self):\n \"\"\"\n Getter and setter property for the *LUT* domain.\n\n Parameters\n ----------\n value : unicode\n Value to set the *LUT* domain with.\n\n Returns\n -------\n unicode\n *LUT* domain.\n \"\"\"\n\n return self._domain\n\n @domain.setter\n def domain(self, value):\n \"\"\"\n Setter for **self.domain** property.\n \"\"\"\n\n if value is not None:\n # pylint: disable=E1121\n self._domain = self._validate_domain(value)\n\n @property\n def dimensions(self):\n \"\"\"\n Getter and setter property for the *LUT* dimensions.\n\n Returns\n -------\n unicode\n *LUT* dimensions.\n \"\"\"\n\n return self._dimensions\n\n @property\n def size(self):\n \"\"\"\n Getter property for the *LUT* size.\n\n Returns\n -------\n unicode\n *LUT* size.\n \"\"\"\n\n return self._table.shape[0]\n\n @property\n def comments(self):\n \"\"\"\n Getter and setter property for the *LUT* comments.\n\n Parameters\n ----------\n value : unicode\n Value to set the *LUT* comments with.\n\n Returns\n -------\n unicode\n *LUT* comments.\n \"\"\"\n\n return self._comments\n\n @comments.setter\n def comments(self, value):\n \"\"\"\n Setter for **self.comments** property.\n \"\"\"\n\n if value is not None:\n assert is_iterable(value), ((\n '\"{0}\" attribute: \"{1}\" must be an array like!').format(\n 'comments', value))\n self._comments = value\n\n def __str__(self):\n \"\"\"\n Returns a formatted string representation of the *LUT*.\n\n Returns\n -------\n unicode\n Formatted string representation.\n \"\"\"\n\n def _indent_array(a):\n \"\"\"\n Indents given array string representation.\n \"\"\"\n\n return str(a).replace(' [', ' ' * 14 + '[')\n\n comments = [\n 'Comment {0} : {1}'.format(str(i + 1).zfill(2), comment)\n for i, comment in enumerate(self.comments)\n ]\n\n return ('{0} - {1}\\n'\n '{2}\\n\\n'\n 'Dimensions : {3}\\n'\n 'Domain : {4}\\n'\n 'Size : {5!s}{6}').format(\n self.__class__.__name__, self.name,\n '-' * (len(self.__class__.__name__) + 3 + len(self.name)),\n self.dimensions, _indent_array(self.domain),\n str(self.table.shape).replace(\"L\", \"\"), '\\n{0}'.format(\n '\\n'.join(comments)) if comments else '')\n\n def __repr__(self):\n \"\"\"\n Returns an evaluable string representation of the *LUT*.\n\n Returns\n -------\n unicode\n Evaluable string representation.\n \"\"\"\n\n representation = repr(self.table)\n representation = representation.replace('array',\n self.__class__.__name__)\n representation = representation.replace(\n ' [',\n '{0}['.format(' ' * (len(self.__class__.__name__) + 2)))\n\n domain = repr(self.domain).replace('array(', '').replace(')', '')\n domain = domain.replace(\n ' [',\n '{0}['.format(' ' * (len(self.__class__.__name__) + 9)))\n\n indentation = ' ' * (len(self.__class__.__name__) + 1)\n representation = ('{0},\\n'\n '{1}name=\\'{2}\\',\\n'\n '{1}domain={3}{4})').format(\n representation[:-1], indentation, self.name,\n domain, ',\\n{0}comments={1}'.format(\n indentation, repr(self.comments))\n if self.comments else '')\n\n return representation\n\n def __eq__(self, other):\n \"\"\"\n Returns whether the *LUT* is equal to given other object.\n\n Parameters\n ----------\n other : object\n Object to test whether it is equal to the *LUT*.\n\n Returns\n -------\n bool\n Is given object equal to the *LUT*.\n \"\"\"\n\n if isinstance(other, AbstractLUT):\n if all([\n np.array_equal(self.table, other.table),\n np.array_equal(self.domain, other.domain)\n ]):\n return True\n\n return False\n\n def __ne__(self, other):\n \"\"\"\n Returns whether the *LUT* is not equal to given other object.\n\n Parameters\n ----------\n other : object\n Object to test whether it is not equal to the *LUT*.\n\n Returns\n -------\n bool\n Is given object not equal to the *LUT*.\n \"\"\"\n\n return not (self == other)\n\n def __add__(self, a):\n \"\"\"\n Implements support for addition.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to add.\n\n Returns\n -------\n AbstractLUT\n Variable added *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '+')\n\n def __iadd__(self, a):\n \"\"\"\n Implements support for in-place addition.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to add in-place.\n\n Returns\n -------\n AbstractLUT\n In-place variable added *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '+', True)\n\n def __sub__(self, a):\n \"\"\"\n Implements support for subtraction.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to subtract.\n\n Returns\n -------\n AbstractLUT\n Variable subtracted *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '-')\n\n def __isub__(self, a):\n \"\"\"\n Implements support for in-place subtraction.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to subtract in-place.\n\n Returns\n -------\n AbstractLUT\n In-place variable subtracted *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '-', True)\n\n def __mul__(self, a):\n \"\"\"\n Implements support for multiplication.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to multiply by.\n\n Returns\n -------\n AbstractLUT\n Variable multiplied *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '*')\n\n def __imul__(self, a):\n \"\"\"\n Implements support for in-place multiplication.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to multiply by in-place.\n\n Returns\n -------\n AbstractLUT\n In-place variable multiplied *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '*', True)\n\n def __div__(self, a):\n \"\"\"\n Implements support for division.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to divide by.\n\n Returns\n -------\n AbstractLUT\n Variable divided *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '/')\n\n def __idiv__(self, a):\n \"\"\"\n Implements support for in-place division.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to divide by in-place.\n\n Returns\n -------\n AbstractLUT\n In-place variable divided *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '/', True)\n\n __itruediv__ = __idiv__\n __truediv__ = __div__\n\n def __pow__(self, a):\n \"\"\"\n Implements support for exponentiation.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to exponentiate by.\n\n Returns\n -------\n AbstractLUT\n Variable exponentiated *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '**')\n\n def __ipow__(self, a):\n \"\"\"\n Implements support for in-place exponentiation.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to exponentiate by in-place.\n\n Returns\n -------\n AbstractLUT\n In-place variable exponentiated *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '**', True)\n\n def arithmetical_operation(self, a, operation, in_place=False):\n \"\"\"\n Performs given arithmetical operation with :math:`a` operand, the\n operation can be either performed on a copy or in-place, must be\n reimplemented by sub-classes.\n\n Parameters\n ----------\n a : numeric or ndarray or AbstractLUT\n Operand.\n operation : object\n Operation to perform.\n in_place : bool, optional\n Operation happens in place.\n\n Returns\n -------\n AbstractLUT\n *LUT*.\n \"\"\"\n\n operation, ioperator = {\n '+': (add, iadd),\n '-': (sub, isub),\n '*': (mul, imul),\n '/': (div, idiv),\n '**': (pow, ipow)\n }[operation]\n\n if in_place:\n if isinstance(a, AbstractLUT):\n operand = a.table\n else:\n operand = as_float_array(a)\n\n self.table = ioperator(self.table, operand)\n\n return self\n else:\n copy = ioperator(self.copy(), a)\n\n return copy\n\n @abstractmethod\n def _validate_table(self, table):\n \"\"\"\n Validates given table according to *LUT* dimensions.\n\n Parameters\n ----------\n table : array_like\n Table to validate.\n\n Returns\n -------\n ndarray\n Validated table as a :class:`ndarray` instance.\n \"\"\"\n\n pass\n\n @abstractmethod\n def _validate_domain(self, domain):\n \"\"\"\n Validates given domain according to *LUT* dimensions.\n\n Parameters\n ----------\n domain : array_like\n Domain to validate.\n\n Returns\n -------\n ndarray\n Validated domain as a :class:`ndarray` instance.\n \"\"\"\n\n pass\n\n @abstractmethod\n def is_domain_explicit(self):\n \"\"\"\n Returns whether the *LUT* domain is explicit (or implicit).\n\n An implicit domain is defined by its shape only::\n\n [[0 1]\n [0 1]\n [0 1]]\n\n While an explicit domain defines every single discrete samples::\n\n [[0.0 0.0 0.0]\n [0.1 0.1 0.1]\n [0.2 0.2 0.2]\n [0.3 0.3 0.3]\n [0.4 0.4 0.4]\n [0.8 0.8 0.8]\n [1.0 1.0 1.0]]\n\n Returns\n -------\n bool\n Is *LUT* domain explicit.\n \"\"\"\n\n pass\n\n @abstractmethod\n def linear_table(size=None, domain=None):\n \"\"\"\n Returns a linear table of given size according to *LUT* dimensions.\n\n Parameters\n ----------\n size : int or array_like, optional\n Expected table size, for a 1D *LUT*, the number of output samples\n :math:`n` is equal to ``size``, for a 3x1D *LUT* :math:`n` is equal\n to ``size * 3`` or ``size[0] + size[1] + size[2]``, for a 3D *LUT*\n :math:`n` is equal to ``size**3 * 3`` or\n ``size[0] * size[1] * size[2] * 3``.\n domain : array_like, optional\n Domain of the table.\n\n Returns\n -------\n ndarray\n Linear table.\n \"\"\"\n\n pass\n\n @abstractmethod\n def apply(self, RGB, interpolator, interpolator_args):\n \"\"\"\n Applies the *LUT* to given *RGB* colourspace array using given method.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* onto.\n interpolator : object, optional\n Interpolator class type or object to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating or calling the interpolating\n function.\n\n Returns\n -------\n ndarray\n Interpolated *RGB* colourspace array.\n \"\"\"\n\n pass\n\n def copy(self):\n \"\"\"\n Returns a copy of the sub-class instance.\n\n Returns\n -------\n AbstractLUT\n *LUT* copy.\n \"\"\"\n\n return deepcopy(self)\n\n @abstractmethod\n def as_LUT(self, cls, force_conversion, **kwargs):\n \"\"\"\n Converts the *LUT* to given ``cls`` class instance.\n\n Parameters\n ----------\n cls : LUT1D or LUT3x1D or LUT3D\n *LUT* class instance.\n force_conversion : bool, optional\n Whether to force the conversion as it might be destructive.\n\n Other Parameters\n ----------------\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n size : int, optional\n Expected table size in case of an upcast to or a downcast from a\n :class:`LUT3D` class instance.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D\n Converted *LUT* class instance.\n\n Warning\n -------\n Some conversions are destructive and raise a :class:`ValueError`\n exception by default.\n\n Raises\n ------\n ValueError\n If the conversion is destructive.\n \"\"\"\n\n pass\n\n\nclass LUT1D(AbstractLUT):\n \"\"\"\n Defines the base class for a 1D *LUT*.\n\n Parameters\n ----------\n table : array_like, optional\n Underlying *LUT* table.\n name : unicode, optional\n *LUT* name.\n domain : unicode, optional\n *LUT* domain, also used to define the instantiation time default table\n domain.\n size : int, optional\n Size of the instantiation time default table.\n comments : array_like, optional\n Comments to add to the *LUT*.\n\n Methods\n -------\n is_domain_explicit\n linear_table\n apply\n as_LUT\n\n Examples\n --------\n Instantiating a unity LUT with a table with 16 elements:\n\n >>> print(LUT1D(size=16))\n LUT1D - Unity 16\n ----------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (16,)\n\n Instantiating a LUT using a custom table with 16 elements:\n\n >>> print(LUT1D(LUT1D.linear_table(16) ** (1 / 2.2))) # doctest: +ELLIPSIS\n LUT1D - ...\n --------...\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (16,)\n\n Instantiating a LUT using a custom table with 16 elements, custom name,\n custom domain and comments:\n\n >>> from colour.algebra import spow\n >>> domain = np.array([-0.1, 1.5])\n >>> print(LUT1D(\n ... spow(LUT1D.linear_table(16, domain), 1 / 2.2),\n ... 'My LUT',\n ... domain,\n ... comments=['A first comment.', 'A second comment.']))\n LUT1D - My LUT\n --------------\n \n Dimensions : 1\n Domain : [-0.1 1.5]\n Size : (16,)\n Comment 01 : A first comment.\n Comment 02 : A second comment.\n \"\"\"\n\n def __init__(self,\n table=None,\n name=None,\n domain=None,\n size=10,\n comments=None):\n if domain is None:\n domain = np.array([0, 1])\n\n super(LUT1D, self).__init__(table, name, 1, domain, size, comments)\n\n def _validate_table(self, table):\n \"\"\"\n Validates given table is a 1D array.\n\n Parameters\n ----------\n table : array_like\n Table to validate.\n\n Returns\n -------\n ndarray\n Validated table as a :class:`ndarray` instance.\n \"\"\"\n\n table = as_float_array(table)\n\n assert len(table.shape) == 1, 'The table must be a 1D array!'\n\n return table\n\n def _validate_domain(self, domain):\n \"\"\"\n Validates given domain.\n\n Parameters\n ----------\n domain : array_like\n Domain to validate.\n\n Returns\n -------\n ndarray\n Validated domain as a :class:`ndarray` instance.\n \"\"\"\n\n domain = as_float_array(domain)\n\n assert len(domain.shape) == 1, 'The domain must be a 1D array!'\n\n assert domain.shape[0] >= 2, (\n 'The domain column count must be equal or greater than 2!')\n\n return domain\n\n def is_domain_explicit(self):\n \"\"\"\n Returns whether the *LUT* domain is explicit (or implicit).\n\n An implicit domain is defined by its shape only::\n\n [0 1]\n\n While an explicit domain defines every single discrete samples::\n\n [0.0 0.1 0.2 0.4 0.8 1.0]\n\n Returns\n -------\n bool\n Is *LUT* domain explicit.\n\n Examples\n --------\n >>> LUT1D().is_domain_explicit()\n False\n >>> table = domain = np.linspace(0, 1, 10)\n >>> LUT1D(table, domain=domain).is_domain_explicit()\n True\n \"\"\"\n\n return len(self.domain) != 2\n\n # pylint: disable=W0221\n @staticmethod\n def linear_table(size=10, domain=np.array([0, 1])):\n \"\"\"\n Returns a linear table, the number of output samples :math:`n` is equal\n to ``size``.\n\n Parameters\n ----------\n size : int, optional\n Expected table size.\n domain : array_like, optional\n Domain of the table.\n\n Returns\n -------\n ndarray\n Linear table with ``size`` samples.\n\n Examples\n --------\n >>> LUT1D.linear_table(5, np.array([-0.1, 1.5]))\n array([-0.1, 0.3, 0.7, 1.1, 1.5])\n >>> LUT1D.linear_table(domain=np.linspace(-0.1, 1.5, 5))\n array([-0.1, 0.3, 0.7, 1.1, 1.5])\n \"\"\"\n\n domain = as_float_array(domain)\n\n if len(domain) != 2:\n return domain\n else:\n assert is_numeric(size), 'Linear table size must be a numeric!'\n\n return np.linspace(domain[0], domain[1], size)\n\n def apply(self,\n RGB,\n interpolator=LinearInterpolator,\n interpolator_args=None):\n \"\"\"\n Applies the *LUT* to given *RGB* colourspace array using given method.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* onto.\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n\n Returns\n -------\n ndarray\n Interpolated *RGB* colourspace array.\n\n Examples\n --------\n >>> LUT = LUT1D(LUT1D.linear_table() ** (1 / 2.2))\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.4529220..., 0.4529220..., 0.4529220...])\n \"\"\"\n\n if interpolator_args is None:\n interpolator_args = {}\n\n if self.is_domain_explicit():\n samples = self.domain\n else:\n domain_min, domain_max = self.domain\n\n samples = np.linspace(domain_min, domain_max, self._table.size)\n\n RGB_interpolator = interpolator(samples, self._table,\n **interpolator_args)\n\n return RGB_interpolator(RGB)\n\n def as_LUT(self, cls, force_conversion=False, **kwargs):\n \"\"\"\n Converts the *LUT* to given ``cls`` class instance.\n\n Parameters\n ----------\n cls : LUT1D or LUT3x1D or LUT3D\n *LUT* class instance.\n force_conversion : bool, optional\n Whether to force the conversion as it might be destructive.\n\n Other Parameters\n ----------------\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n size : int, optional\n Expected table size in case of an upcast to a :class:`LUT3D` class\n instance.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D\n Converted *LUT* class instance.\n\n Warning\n -------\n Some conversions are destructive and raise a :class:`ValueError`\n exception by default.\n\n Raises\n ------\n ValueError\n If the conversion is destructive.\n\n Examples\n --------\n >>> LUT = LUT1D()\n >>> print(LUT.as_LUT(LUT1D))\n LUT1D - Unity 10 - Converted 1D to 1D\n -------------------------------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n >>> print(LUT.as_LUT(LUT3x1D))\n LUT3x1D - Unity 10 - Converted 1D to 3x1D\n -----------------------------------------\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (10, 3)\n >>> print(LUT.as_LUT(LUT3D, force_conversion=True))\n LUT3D - Unity 10 - Converted 1D to 3D\n -------------------------------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (33, 33, 33, 3)\n \"\"\"\n\n return LUT_to_LUT(self, cls, force_conversion, **kwargs)\n\n\nclass LUT3x1D(AbstractLUT):\n \"\"\"\n Defines the base class for a 3x1D *LUT*.\n\n Parameters\n ----------\n table : array_like, optional\n Underlying *LUT* table.\n name : unicode, optional\n *LUT* name.\n domain : unicode, optional\n *LUT* domain, also used to define the instantiation time default table\n domain.\n size : int, optional\n Size of the instantiation time default table.\n comments : array_like, optional\n Comments to add to the *LUT*.\n\n Methods\n -------\n is_domain_explicit\n linear_table\n apply\n as_LUT\n\n Examples\n --------\n Instantiating a unity LUT with a table with 16x3 elements:\n\n >>> print(LUT3x1D(size=16))\n LUT3x1D - Unity 16\n ------------------\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (16, 3)\n\n Instantiating a LUT using a custom table with 16x3 elements:\n\n >>> print(LUT3x1D(LUT3x1D.linear_table(16) ** (1 / 2.2)))\n ... # doctest: +ELLIPSIS\n LUT3x1D - ...\n ----------...\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (16, 3)\n\n Instantiating a LUT using a custom table with 16x3 elements, custom name,\n custom domain and comments:\n\n >>> from colour.algebra import spow\n >>> domain = np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]])\n >>> print(LUT3x1D(\n ... spow(LUT3x1D.linear_table(16), 1 / 2.2),\n ... 'My LUT',\n ... domain,\n ... comments=['A first comment.', 'A second comment.']))\n LUT3x1D - My LUT\n ----------------\n \n Dimensions : 2\n Domain : [[-0.1 -0.2 -0.4]\n [ 1.5 3. 6. ]]\n Size : (16, 3)\n Comment 01 : A first comment.\n Comment 02 : A second comment.\n \"\"\"\n\n def __init__(self,\n table=None,\n name=None,\n domain=None,\n size=10,\n comments=None):\n if domain is None:\n domain = np.array([[0, 0, 0], [1, 1, 1]])\n\n super(LUT3x1D, self).__init__(table, name, 2, domain, size, comments)\n\n def _validate_table(self, table):\n \"\"\"\n Validates given table is a 3x1D array.\n\n Parameters\n ----------\n table : array_like\n Table to validate.\n\n Returns\n -------\n ndarray\n Validated table as a :class:`ndarray` instance.\n \"\"\"\n\n table = as_float_array(table)\n\n assert len(table.shape) == 2, 'The table must be a 2D array!'\n\n return table\n\n def _validate_domain(self, domain):\n \"\"\"\n Validates given domain.\n\n Parameters\n ----------\n domain : array_like\n Domain to validate.\n\n Returns\n -------\n ndarray\n Validated domain as a :class:`ndarray` instance.\n \"\"\"\n\n domain = as_float_array(domain)\n\n assert len(domain.shape) == 2, 'The domain must be a 2D array!'\n\n assert domain.shape[0] >= 2, (\n 'The domain row count must be equal or greater than 2!')\n\n assert domain.shape[1] == 3, (\n 'The domain column count must be equal to 3!')\n\n return domain\n\n def is_domain_explicit(self):\n \"\"\"\n Returns whether the *LUT* domain is explicit (or implicit).\n\n An implicit domain is defined by its shape only::\n\n [[0 1]\n [0 1]\n [0 1]]\n\n While an explicit domain defines every single discrete samples::\n\n [[0.0 0.0 0.0]\n [0.1 0.1 0.1]\n [0.2 0.2 0.2]\n [0.3 0.3 0.3]\n [0.4 0.4 0.4]\n [0.8 0.8 0.8]\n [1.0 1.0 1.0]]\n\n Returns\n -------\n bool\n Is *LUT* domain explicit.\n\n Examples\n --------\n >>> LUT3x1D().is_domain_explicit()\n False\n >>> samples = np.linspace(0, 1, 10)\n >>> table = domain = tstack([samples, samples, samples])\n >>> LUT3x1D(table, domain=domain).is_domain_explicit()\n True\n \"\"\"\n\n return self.domain.shape != (2, 3)\n\n # pylint: disable=W0221\n @staticmethod\n def linear_table(size=10, domain=np.array([[0, 0, 0], [1, 1, 1]])):\n \"\"\"\n Returns a linear table, the number of output samples :math:`n` is equal\n to ``size * 3`` or ``size[0] + size[1] + size[2]``.\n\n Parameters\n ----------\n size : int or array_like, optional\n Expected table size.\n domain : array_like, optional\n Domain of the table.\n\n Returns\n -------\n ndarray\n Linear table with ``size * 3`` or ``size[0] + size[1] + size[2]``\n samples.\n\n Warnings\n --------\n If ``size`` is non uniform, the linear table will be padded\n accordingly.\n\n Examples\n --------\n >>> LUT3x1D.linear_table(\n ... 5, np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]]))\n array([[-0.1, -0.2, -0.4],\n [ 0.3, 0.6, 1.2],\n [ 0.7, 1.4, 2.8],\n [ 1.1, 2.2, 4.4],\n [ 1.5, 3. , 6. ]])\n >>> LUT3x1D.linear_table(\n ... np.array([5, 3, 2]),\n ... np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]]))\n array([[-0.1, -0.2, -0.4],\n [ 0.3, 1.4, 6. ],\n [ 0.7, 3. , nan],\n [ 1.1, nan, nan],\n [ 1.5, nan, nan]])\n >>> domain = np.array([[-0.1, -0.2, -0.4],\n ... [0.3, 1.4, 6.0],\n ... [0.7, 3.0, np.nan],\n ... [1.1, np.nan, np.nan],\n ... [1.5, np.nan, np.nan]])\n >>> LUT3x1D.linear_table(domain=domain)\n array([[-0.1, -0.2, -0.4],\n [ 0.3, 1.4, 6. ],\n [ 0.7, 3. , nan],\n [ 1.1, nan, nan],\n [ 1.5, nan, nan]])\n \"\"\"\n\n domain = as_float_array(domain)\n\n if domain.shape != (2, 3):\n return domain\n else:\n if is_numeric(size):\n size = np.tile(size, 3)\n\n R, G, B = tsplit(domain)\n\n samples = [\n np.linspace(a[0], a[1], size[i])\n for i, a in enumerate([R, G, B])\n ]\n\n if not len(np.unique(size)) == 1:\n runtime_warning('Table is non uniform, axis will be '\n 'padded with \"NaNs\" accordingly!')\n\n samples = [\n np.pad(\n axis, (0, np.max(size) - len(axis)),\n mode='constant',\n constant_values=np.nan) for axis in samples\n ]\n\n return tstack(samples)\n\n def apply(self,\n RGB,\n interpolator=LinearInterpolator,\n interpolator_args=None):\n \"\"\"\n Applies the *LUT* to given *RGB* colourspace array using given method.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* onto.\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n\n Returns\n -------\n ndarray\n Interpolated *RGB* colourspace array.\n\n Examples\n --------\n >>> LUT = LUT3x1D(LUT3x1D.linear_table() ** (1 / 2.2))\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.4529220..., 0.4529220..., 0.4529220...])\n >>> from colour.algebra import spow\n >>> domain = np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]])\n >>> table = spow(LUT3x1D.linear_table(domain=domain), 1 / 2.2)\n >>> LUT = LUT3x1D(table, domain=domain)\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.4423903..., 0.4503801..., 0.3581625...])\n >>> domain = np.array([[-0.1, -0.2, -0.4],\n ... [0.3, 1.4, 6.0],\n ... [0.7, 3.0, np.nan],\n ... [1.1, np.nan, np.nan],\n ... [1.5, np.nan, np.nan]])\n >>> table = spow(LUT3x1D.linear_table(domain=domain), 1 / 2.2)\n >>> LUT = LUT3x1D(table, domain=domain)\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.2996370..., -0.0901332..., -0.3949770...])\n \"\"\"\n\n if interpolator_args is None:\n interpolator_args = {}\n\n R, G, B = tsplit(RGB)\n\n if self.is_domain_explicit():\n samples = [\n axes[:(~np.isnan(axes)).cumsum().argmax() + 1]\n for axes in np.transpose(self.domain)\n ]\n R_t, G_t, B_t = [\n axes[:len(samples[i])]\n for i, axes in enumerate(np.transpose(self._table))\n ]\n else:\n domain_min, domain_max = self.domain\n size = DEFAULT_INT_DTYPE(self._table.size / 3)\n samples = [\n np.linspace(domain_min[i], domain_max[i], size)\n for i in range(3)\n ]\n\n R_t, G_t, B_t = tsplit(self._table)\n\n s_R, s_G, s_B = samples\n\n RGB_i = [\n interpolator(a[0], a[1], **interpolator_args)(a[2])\n for a in zip((s_R, s_G, s_B), (R_t, G_t, B_t), (R, G, B))\n ]\n\n return tstack(RGB_i)\n\n def as_LUT(self, cls, force_conversion=False, **kwargs):\n \"\"\"\n Converts the *LUT* to given ``cls`` class instance.\n\n Parameters\n ----------\n cls : LUT1D or LUT3x1D or LUT3D\n *LUT* class instance.\n force_conversion : bool, optional\n Whether to force the conversion as it might be destructive.\n\n Other Parameters\n ----------------\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n size : int, optional\n Expected table size in case of an upcast to a :class:`LUT3D` class\n instance.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D\n Converted *LUT* class instance.\n\n Warning\n -------\n Some conversions are destructive and raise a :class:`ValueError`\n exception by default.\n\n Raises\n ------\n ValueError\n If the conversion is destructive.\n\n Examples\n --------\n >>> LUT = LUT3x1D()\n >>> print(LUT.as_LUT(LUT1D, force_conversion=True))\n LUT1D - Unity 10 - Converted 3x1D to 1D\n ---------------------------------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n >>> print(LUT.as_LUT(LUT3x1D))\n LUT3x1D - Unity 10 - Converted 3x1D to 3x1D\n -------------------------------------------\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (10, 3)\n >>> print(LUT.as_LUT(LUT3D, force_conversion=True))\n LUT3D - Unity 10 - Converted 3x1D to 3D\n ---------------------------------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (33, 33, 33, 3)\n \"\"\"\n\n return LUT_to_LUT(self, cls, force_conversion, **kwargs)\n\n\nclass LUT3D(AbstractLUT):\n \"\"\"\n Defines the base class for a 3D *LUT*.\n\n Parameters\n ----------\n table : array_like, optional\n Underlying *LUT* table.\n name : unicode, optional\n *LUT* name.\n domain : unicode, optional\n *LUT* domain, also used to define the instantiation time default table\n domain.\n size : int, optional\n Size of the instantiation time default table.\n comments : array_like, optional\n Comments to add to the *LUT*.\n\n Methods\n -------\n is_domain_explicit\n linear_table\n apply\n as_LUT\n\n Examples\n --------\n Instantiating a unity LUT with a table with 16x16x16x3 elements:\n\n >>> print(LUT3D(size=16))\n LUT3D - Unity 16\n ----------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (16, 16, 16, 3)\n\n Instantiating a LUT using a custom table with 16x16x16x3 elements:\n\n >>> print(LUT3D(LUT3D.linear_table(16) ** (1 / 2.2))) # doctest: +ELLIPSIS\n LUT3D - ...\n --------...\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (16, 16, 16, 3)\n\n Instantiating a LUT using a custom table with 16x16x16x3 elements, custom\n name, custom domain and comments:\n\n >>> from colour.algebra import spow\n >>> domain = np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]])\n >>> print(LUT3D(\n ... spow(LUT3D.linear_table(16), 1 / 2.2),\n ... 'My LUT',\n ... domain,\n ... comments=['A first comment.', 'A second comment.']))\n LUT3D - My LUT\n --------------\n \n Dimensions : 3\n Domain : [[-0.1 -0.2 -0.4]\n [ 1.5 3. 6. ]]\n Size : (16, 16, 16, 3)\n Comment 01 : A first comment.\n Comment 02 : A second comment.\n \"\"\"\n\n def __init__(self,\n table=None,\n name=None,\n domain=None,\n size=33,\n comments=None):\n if domain is None:\n domain = np.array([[0, 0, 0], [1, 1, 1]])\n\n super(LUT3D, self).__init__(table, name, 3, domain, size, comments)\n\n def _validate_table(self, table):\n \"\"\"\n Validates given table is a 4D array and that its dimensions are equal.\n\n Parameters\n ----------\n table : array_like\n Table to validate.\n\n Returns\n -------\n ndarray\n Validated table as a :class:`ndarray` instance.\n \"\"\"\n\n table = as_float_array(table)\n\n assert len(table.shape) == 4, 'The table must be a 4D array!'\n\n return table\n\n def _validate_domain(self, domain):\n \"\"\"\n Validates given domain.\n\n Parameters\n ----------\n domain : array_like\n Domain to validate.\n\n Returns\n -------\n ndarray\n Validated domain as a :class:`ndarray` instance.\n\n Notes\n -----\n - A :class:`LUT3D` class instance must use an implicit domain.\n \"\"\"\n\n domain = as_float_array(domain)\n\n assert len(domain.shape) == 2, 'The domain must be a 2D array!'\n\n assert domain.shape[0] >= 2, (\n 'The domain row count must be equal or greater than 2!')\n\n assert domain.shape[1] == 3, (\n 'The domain column count must be equal to 3!')\n\n return domain\n\n def is_domain_explicit(self):\n \"\"\"\n Returns whether the *LUT* domain is explicit (or implicit).\n\n An implicit domain is defined by its shape only::\n\n [[0 0 0]\n [1 1 1]]\n\n While an explicit domain defines every single discrete samples::\n\n [[0.0 0.0 0.0]\n [0.1 0.1 0.1]\n [0.2 0.2 0.2]\n [0.3 0.3 0.3]\n [0.4 0.4 0.4]\n [0.8 0.8 0.8]\n [1.0 1.0 1.0]]\n\n Returns\n -------\n bool\n Is *LUT* domain explicit.\n\n Examples\n --------\n >>> LUT3D().is_domain_explicit()\n False\n >>> domain = np.array([[-0.1, -0.2, -0.4],\n ... [0.7, 1.4, 6.0],\n ... [1.5, 3.0, np.nan]])\n >>> LUT3D(domain=domain).is_domain_explicit()\n True\n \"\"\"\n\n return self.domain.shape != (2, 3)\n\n # pylint: disable=W0221\n @staticmethod\n def linear_table(size=33, domain=np.array([[0, 0, 0], [1, 1, 1]])):\n \"\"\"\n Returns a linear table, the number of output samples :math:`n` is equal\n to ``size**3 * 3`` or ``size[0] * size[1] * size[2] * 3``.\n\n Parameters\n ----------\n size : int or array_like, optional\n Expected table size.\n domain : array_like, optional\n Domain of the table.\n\n Returns\n -------\n ndarray\n Linear table with ``size**3 * 3`` or\n ``size[0] * size[1] * size[2] * 3`` samples.\n\n Examples\n --------\n >>> LUT3D.linear_table(\n ... 3, np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]]))\n array([[[[-0.1, -0.2, -0.4],\n [-0.1, -0.2, 2.8],\n [-0.1, -0.2, 6. ]],\n \n [[-0.1, 1.4, -0.4],\n [-0.1, 1.4, 2.8],\n [-0.1, 1.4, 6. ]],\n \n [[-0.1, 3. , -0.4],\n [-0.1, 3. , 2.8],\n [-0.1, 3. , 6. ]]],\n \n \n [[[ 0.7, -0.2, -0.4],\n [ 0.7, -0.2, 2.8],\n [ 0.7, -0.2, 6. ]],\n \n [[ 0.7, 1.4, -0.4],\n [ 0.7, 1.4, 2.8],\n [ 0.7, 1.4, 6. ]],\n \n [[ 0.7, 3. , -0.4],\n [ 0.7, 3. , 2.8],\n [ 0.7, 3. , 6. ]]],\n \n \n [[[ 1.5, -0.2, -0.4],\n [ 1.5, -0.2, 2.8],\n [ 1.5, -0.2, 6. ]],\n \n [[ 1.5, 1.4, -0.4],\n [ 1.5, 1.4, 2.8],\n [ 1.5, 1.4, 6. ]],\n \n [[ 1.5, 3. , -0.4],\n [ 1.5, 3. , 2.8],\n [ 1.5, 3. , 6. ]]]])\n >>> LUT3D.linear_table(\n ... np.array([3, 3, 2]),\n ... np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]]))\n array([[[[-0.1, -0.2, -0.4],\n [-0.1, -0.2, 6. ]],\n \n [[-0.1, 1.4, -0.4],\n [-0.1, 1.4, 6. ]],\n \n [[-0.1, 3. , -0.4],\n [-0.1, 3. , 6. ]]],\n \n \n [[[ 0.7, -0.2, -0.4],\n [ 0.7, -0.2, 6. ]],\n \n [[ 0.7, 1.4, -0.4],\n [ 0.7, 1.4, 6. ]],\n \n [[ 0.7, 3. , -0.4],\n [ 0.7, 3. , 6. ]]],\n \n \n [[[ 1.5, -0.2, -0.4],\n [ 1.5, -0.2, 6. ]],\n \n [[ 1.5, 1.4, -0.4],\n [ 1.5, 1.4, 6. ]],\n \n [[ 1.5, 3. , -0.4],\n [ 1.5, 3. , 6. ]]]])\n >>> domain = np.array([[-0.1, -0.2, -0.4],\n ... [0.7, 1.4, 6.0],\n ... [1.5, 3.0, np.nan]])\n >>> LUT3D.linear_table(domain=domain)\n array([[[[-0.1, -0.2, -0.4],\n [-0.1, -0.2, 6. ]],\n \n [[-0.1, 1.4, -0.4],\n [-0.1, 1.4, 6. ]],\n \n [[-0.1, 3. , -0.4],\n [-0.1, 3. , 6. ]]],\n \n \n [[[ 0.7, -0.2, -0.4],\n [ 0.7, -0.2, 6. ]],\n \n [[ 0.7, 1.4, -0.4],\n [ 0.7, 1.4, 6. ]],\n \n [[ 0.7, 3. , -0.4],\n [ 0.7, 3. , 6. ]]],\n \n \n [[[ 1.5, -0.2, -0.4],\n [ 1.5, -0.2, 6. ]],\n \n [[ 1.5, 1.4, -0.4],\n [ 1.5, 1.4, 6. ]],\n \n [[ 1.5, 3. , -0.4],\n [ 1.5, 3. , 6. ]]]])\n \"\"\"\n\n domain = as_float_array(domain)\n\n if domain.shape != (2, 3):\n samples = np.flip([\n axes[:(~np.isnan(axes)).cumsum().argmax() + 1]\n for axes in np.transpose(domain)\n ], -1)\n size = [len(axes) for axes in samples]\n else:\n if is_numeric(size):\n size = np.tile(size, 3)\n\n R, G, B = tsplit(domain)\n\n size = np.flip(size, -1)\n samples = [\n np.linspace(a[0], a[1], size[i])\n for i, a in enumerate([B, G, R])\n ]\n\n table = np.meshgrid(*samples, indexing='ij')\n table = np.flip(\n np.transpose(table).reshape(np.hstack([np.flip(size, -1), 3])), -1)\n\n return table\n\n def apply(self,\n RGB,\n interpolator=table_interpolation_trilinear,\n interpolator_args=None):\n \"\"\"\n Applies the *LUT* to given *RGB* colourspace array using given method.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* onto.\n interpolator : object, optional\n Interpolator object to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when calling the interpolating function.\n\n Returns\n -------\n ndarray\n Interpolated *RGB* colourspace array.\n\n Examples\n --------\n >>> LUT = LUT3D(LUT3D.linear_table() ** (1 / 2.2))\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.4583277..., 0.4583277..., 0.4583277...])\n >>> from colour.algebra import spow\n >>> domain = np.array([[-0.1, -0.2, -0.4],\n ... [0.3, 1.4, 6.0],\n ... [0.7, 3.0, np.nan],\n ... [1.1, np.nan, np.nan],\n ... [1.5, np.nan, np.nan]])\n >>> table = spow(LUT3D.linear_table(domain=domain), 1 / 2.2)\n >>> LUT = LUT3D(table, domain=domain)\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.2996370..., -0.0901332..., -0.3949770...])\n \"\"\"\n\n if interpolator_args is None:\n interpolator_args = {}\n\n R, G, B = tsplit(RGB)\n\n if self.is_domain_explicit():\n domain_min = self.domain[0, ...]\n domain_max = [\n axes[:(~np.isnan(axes)).cumsum().argmax() + 1][-1]\n for axes in np.transpose(self.domain)\n ]\n usage_warning(\n '\"LUT\" was defined with an explicit domain but requires '\n 'an implicit domain to be applied. The following domain '\n 'will be used: {0}'.format(\n np.vstack([domain_min, domain_max])))\n else:\n domain_min, domain_max = self.domain\n\n RGB_l = [\n linear_conversion(j, (domain_min[i], domain_max[i]), (0, 1))\n for i, j in enumerate((R, G, B))\n ]\n\n return interpolator(tstack(RGB_l), self._table, **interpolator_args)\n\n def as_LUT(self, cls, force_conversion=False, **kwargs):\n \"\"\"\n Converts the *LUT* to given ``cls`` class instance.\n\n Parameters\n ----------\n cls : LUT1D or LUT3x1D or LUT3D\n *LUT* class instance.\n force_conversion : bool, optional\n Whether to force the conversion as it might be destructive.\n\n Other Parameters\n ----------------\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n size : int, optional\n Expected table size in case of a downcast from a :class:`LUT3D`\n class instance.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D\n Converted *LUT* class instance.\n\n Warning\n -------\n Some conversions are destructive and raise a :class:`ValueError`\n exception by default.\n\n Raises\n ------\n ValueError\n If the conversion is destructive.\n\n Examples\n --------\n >>> LUT = LUT3D()\n >>> print(LUT.as_LUT(LUT1D, force_conversion=True))\n LUT1D - Unity 33 - Converted 3D to 1D\n -------------------------------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n >>> print(LUT.as_LUT(LUT3x1D, force_conversion=True))\n LUT3x1D - Unity 33 - Converted 3D to 3x1D\n -----------------------------------------\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (10, 3)\n >>> print(LUT.as_LUT(LUT3D))\n LUT3D - Unity 33 - Converted 3D to 3D\n -------------------------------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (33, 33, 33, 3)\n \"\"\"\n\n return LUT_to_LUT(self, cls, force_conversion, **kwargs)\n\n\ndef LUT_to_LUT(LUT, cls, force_conversion=False, **kwargs):\n \"\"\"\n Converts given *LUT* to given ``cls`` class instance.\n\n Parameters\n ----------\n cls : LUT1D or LUT3x1D or LUT3D\n *LUT* class instance.\n force_conversion : bool, optional\n Whether to force the conversion as it might be destructive.\n\n Other Parameters\n ----------------\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n size : int, optional\n Expected table size in case of an upcast to or a downcast from a\n :class:`LUT3D` class instance.\n channel_weights : array_like, optional\n Channel weights in case of a downcast from a :class:`LUT3x1D` or\n :class:`LUT3D` class instance.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D\n Converted *LUT* class instance.\n\n Warning\n -------\n Some conversions are destructive and raise a :class:`ValueError` exception\n by default.\n\n Raises\n ------\n ValueError\n If the conversion is destructive.\n\n Examples\n --------\n >>> print(LUT_to_LUT(LUT1D(), LUT3D, force_conversion=True))\n LUT3D - Unity 10 - Converted 1D to 3D\n -------------------------------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (33, 33, 33, 3)\n >>> print(LUT_to_LUT(LUT3x1D(), LUT1D, force_conversion=True))\n LUT1D - Unity 10 - Converted 3x1D to 1D\n ---------------------------------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n >>> print(LUT_to_LUT(LUT3D(), LUT1D, force_conversion=True))\n LUT1D - Unity 33 - Converted 3D to 1D\n -------------------------------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n \"\"\"\n\n ranks = {LUT1D: 1, LUT3x1D: 2, LUT3D: 3}\n path = (ranks[LUT.__class__], ranks[cls])\n path_verbose = [\n '{0}D'.format(element) if element != 2 else '3x1D' for element in path\n ]\n if path in ((1, 3), (2, 1), (2, 3), (3, 1), (3, 2)):\n if not force_conversion:\n raise ValueError(\n 'Conversion of a \"LUT\" {0} to a \"LUT\" {1} is destructive, '\n 'please use the \"force_conversion\" argument to proceed.'.\n format(*path_verbose))\n\n suffix = ' - Converted {0} to {1}'.format(*path_verbose)\n name = '{0}{1}'.format(LUT.name, suffix)\n\n # Same dimension conversion, returning a copy.\n if len(set(path)) == 1:\n LUT = LUT.copy()\n LUT.name = name\n else:\n size = kwargs.get('size', 33 if cls is LUT3D else 10)\n if 'size' in kwargs:\n del kwargs['size']\n\n channel_weights = as_float_array(\n kwargs.get('channel_weights', np.full(3, 1 / 3)))\n if 'channel_weights' in kwargs:\n del kwargs['channel_weights']\n\n # TODO: Implement support for non-uniform domain, e.g. \"cinespace\"\n # LUTs.\n if isinstance(LUT, LUT1D):\n if cls is LUT3x1D:\n domain = tstack([LUT.domain, LUT.domain, LUT.domain])\n table = tstack([LUT.table, LUT.table, LUT.table])\n elif cls is LUT3D:\n domain = tstack([LUT.domain, LUT.domain, LUT.domain])\n table = LUT3D.linear_table(size, domain)\n table = LUT.apply(table, **kwargs)\n elif isinstance(LUT, LUT3x1D):\n if cls is LUT1D:\n domain = np.array([\n np.sum(LUT.domain[0, ...] * channel_weights),\n np.sum(LUT.domain[-1, ...] * channel_weights)\n ])\n table = np.sum(LUT.table * channel_weights, axis=-1)\n elif cls is LUT3D:\n domain = LUT.domain\n table = LUT3D.linear_table(size, domain)\n table = LUT.apply(table, **kwargs)\n elif isinstance(LUT, LUT3D):\n if cls is LUT1D:\n domain = np.array([\n np.sum(LUT.domain[0, ...] * channel_weights),\n np.sum(LUT.domain[-1, ...] * channel_weights)\n ])\n table = LUT1D.linear_table(size, domain)\n table = LUT.apply(tstack([table, table, table]), **kwargs)\n table = np.sum(table * channel_weights, axis=-1)\n elif cls is LUT3x1D:\n domain = LUT.domain\n table = LUT3x1D.linear_table(size, domain)\n table = LUT.apply(table, **kwargs)\n\n LUT = cls(table, name, domain, table.shape[0], LUT.comments)\n\n return LUT\n\n\n@add_metaclass(ABCMeta)\nclass AbstractLUTSequenceOperator:\n \"\"\"\n Defines the base class for *LUT* sequence operators.\n\n This is an :class:`ABCMeta` abstract class that must be inherited by\n sub-classes.\n\n Methods\n -------\n apply\n \"\"\"\n\n @abstractmethod\n def apply(self, RGB, *args):\n \"\"\"\n Applies the *LUT* sequence operator to given *RGB* colourspace array.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* sequence operator onto.\n\n Returns\n -------\n ndarray\n Processed *RGB* colourspace array.\n \"\"\"\n\n pass\n\n\nclass LUTSequence(MutableSequence):\n \"\"\"\n Defines the base class for a *LUT* sequence, i.e. a series of *LUTs*.\n\n The `colour.LUTSequence` class can be used to model series of *LUTs* such\n as when a shaper *LUT* is combined with a 3D *LUT*.\n\n Other Parameters\n ----------------\n \\\\*args : list, optional\n Sequence of `colour.LUT1D`, `colour.LUT3x1D`, `colour.LUT3D` or\n `colour.io.lut.l.AbstractLUTSequenceOperator` class instances.\n\n Attributes\n ----------\n sequence\n\n Methods\n -------\n __getitem__\n __setitem__\n __delitem__\n __len__\n __str__\n __repr__\n __eq__\n __ne__\n insert\n apply\n copy\n\n Examples\n --------\n >>> LUT_1 = LUT1D()\n >>> LUT_2 = LUT3D(size=3)\n >>> LUT_3 = LUT3x1D()\n >>> print(LUTSequence(LUT_1, LUT_2, LUT_3))\n LUT Sequence\n ------------\n \n Overview\n \n LUT1D ---> LUT3D ---> LUT3x1D\n \n Operations\n \n LUT1D - Unity 10\n ----------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n \n LUT3D - Unity 3\n ---------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (3, 3, 3, 3)\n \n LUT3x1D - Unity 10\n ------------------\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (10, 3)\n \"\"\"\n\n def __init__(self, *args):\n for arg in args:\n assert isinstance(\n arg, (LUT1D, LUT3x1D, LUT3D, AbstractLUTSequenceOperator)), (\n '\"args\" elements must be instances of \"LUT1D\", '\n '\"LUT3x1D\", \"LUT3D\" or \"AbstractLUTSequenceOperator\"!')\n\n self._sequence = list(args)\n\n @property\n def sequence(self):\n \"\"\"\n Getter and setter property for the underlying *LUT* sequence.\n\n Parameters\n ----------\n value : list\n Value to set the the underlying *LUT* sequence with.\n\n Returns\n -------\n list\n Underlying *LUT* sequence.\n \"\"\"\n\n return self._sequence\n\n @sequence.setter\n def sequence(self, value):\n \"\"\"\n Setter for **self.sequence** property.\n \"\"\"\n\n if value is not None:\n self._sequence = list(value)\n\n def __getitem__(self, index):\n \"\"\"\n Returns the *LUT* sequence item at given index.\n\n Parameters\n ----------\n index : int\n *LUT* sequence item index.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D or AbstractLUTSequenceOperator\n *LUT* sequence item at given index.\n \"\"\"\n\n return self._sequence[index]\n\n def __setitem__(self, index, value):\n \"\"\"\n Sets given the *LUT* sequence item at given index with given value.\n\n Parameters\n ----------\n index : int\n *LUT* sequence item index.\n value : LUT1D or LUT3x1D or LUT3D or AbstractLUTSequenceOperator\n Value.\n \"\"\"\n\n self._sequence[index] = value\n\n def __delitem__(self, index):\n \"\"\"\n Deletes the *LUT* sequence item at given index.\n\n Parameters\n ----------\n index : int\n *LUT* sequence item index.\n \"\"\"\n\n del self._sequence[index]\n\n def __len__(self):\n \"\"\"\n Returns the *LUT* sequence items count.\n\n Returns\n -------\n int\n *LUT* sequence items count.\n \"\"\"\n\n return len(self._sequence)\n\n def __str__(self):\n \"\"\"\n Returns a formatted string representation of the *LUT* sequence.\n\n Returns\n -------\n unicode\n Formatted string representation.\n \"\"\"\n\n operations = re.sub(\n '^',\n ' ' * 4,\n '\\n\\n'.join([str(a) for a in self._sequence]),\n flags=re.MULTILINE)\n operations = re.sub('^\\\\s+$', '', operations, flags=re.MULTILINE)\n\n return ('LUT Sequence\\n'\n '------------\\n\\n'\n 'Overview\\n\\n'\n ' {0}\\n\\n'\n 'Operations\\n\\n'\n '{1}').format(\n ' ---> '.join(\n [a.__class__.__name__ for a in self._sequence]),\n operations)\n\n def __repr__(self):\n \"\"\"\n Returns an evaluable string representation of the *LUT* sequence.\n\n Returns\n -------\n unicode\n Evaluable string representation.\n \"\"\"\n\n operations = re.sub(\n '^',\n ' ' * 4,\n ',\\n'.join([repr(a) for a in self._sequence]),\n flags=re.MULTILINE)\n operations = re.sub('^\\\\s+$', '', operations, flags=re.MULTILINE)\n\n return '{0}(\\n{1}\\n)'.format(self.__class__.__name__, operations)\n\n def __eq__(self, other):\n \"\"\"\n Returns whether the *LUT* sequence is equal to given other object.\n\n Parameters\n ----------\n other : object\n Object to test whether it is equal to the *LUT* sequence.\n\n Returns\n -------\n bool\n Is given object equal to the *LUT* sequence.\n \"\"\"\n\n if not isinstance(other, LUTSequence):\n return False\n\n if len(self) != len(other):\n return False\n\n # pylint: disable=C0200\n for i in range(len(self)):\n if self[i] != other[i]:\n return False\n\n return True\n\n def __ne__(self, other):\n \"\"\"\n Returns whether the *LUT* sequence is not equal to given other object.\n\n Parameters\n ----------\n other : object\n Object to test whether it is not equal to the *LUT* sequence.\n\n Returns\n -------\n bool\n Is given object not equal to the *LUT* sequence.\n \"\"\"\n\n return not (self == other)\n\n # pylint: disable=W0221\n def insert(self, index, LUT):\n \"\"\"\n Inserts given *LUT* at given index into the *LUT* sequence.\n\n Parameters\n ----------\n index : index\n Index to insert the *LUT* at into the *LUT* sequence.\n LUT : LUT1D or LUT3x1D or LUT3D or AbstractLUTSequenceOperator\n *LUT* to insert into the *LUT* sequence.\n \"\"\"\n\n assert isinstance(\n LUT, (LUT1D, LUT3x1D, LUT3D, AbstractLUTSequenceOperator)), (\n '\"LUT\" must be an instance of \"LUT1D\", \"LUT3x1D\", \"LUT3D\" or '\n '\"AbstractLUTSequenceOperator\"!')\n\n self._sequence.insert(index, LUT)\n\n def apply(self,\n RGB,\n interpolator_1D=LinearInterpolator,\n interpolator_1D_args=None,\n interpolator_3D=table_interpolation_trilinear,\n interpolator_3D_args=None):\n \"\"\"\n Applies the *LUT* sequence sequentially to given *RGB* colourspace\n array.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* sequence sequentially\n onto.\n interpolator_1D : object, optional\n Interpolator object to use as interpolating function for\n :class:`colour.LUT1D` (and :class:`colour.LUT3x1D`) class\n instances.\n interpolator_1D_args : dict_like, optional\n Arguments to use when calling the interpolating function for\n :class:`colour.LUT1D` (and :class:`colour.LUT3x1D`) class\n instances.\n interpolator_3D : object, optional\n Interpolator object to use as interpolating function for\n :class:`colour.LUT3D` class instances.\n interpolator_3D_args : dict_like, optional\n Arguments to use when calling the interpolating function for\n :class:`colour.LUT3D` class instances.\n\n Returns\n -------\n ndarray\n Processed *RGB* colourspace array.\n\n Examples\n --------\n >>> LUT_1 = LUT1D(LUT1D.linear_table(16) + 0.125)\n >>> LUT_2 = LUT3D(LUT3D.linear_table(16) ** (1 / 2.2))\n >>> LUT_3 = LUT3x1D(LUT3x1D.linear_table(16) * 0.750)\n >>> LUT_sequence = LUTSequence(LUT_1, LUT_2, LUT_3)\n >>> samples = np.linspace(0, 1, 5)\n >>> RGB = tstack([samples, samples, samples])\n >>> LUT_sequence.apply(RGB) # doctest: +ELLIPSIS\n array([[ 0.2899886..., 0.2899886..., 0.2899886...],\n [ 0.4797662..., 0.4797662..., 0.4797662...],\n [ 0.6055328..., 0.6055328..., 0.6055328...],\n [ 0.7057779..., 0.7057779..., 0.7057779...],\n [ 0.75 ..., 0.75 ..., 0.75 ...]])\n \"\"\"\n\n for operation in self:\n if isinstance(operation, (LUT1D, LUT3x1D)):\n RGB = operation.apply(RGB, interpolator_1D,\n interpolator_1D_args)\n elif isinstance(operation, LUT3D):\n RGB = operation.apply(RGB, interpolator_3D,\n interpolator_3D_args)\n else:\n RGB = operation.apply(RGB)\n\n return RGB\n\n def copy(self):\n \"\"\"\n Returns a copy of the *LUT* sequence.\n\n Returns\n -------\n LUTSequence\n *LUT* sequence copy.\n \"\"\"\n\n return deepcopy(self)\n","sub_path":"colour/io/luts/lut.py","file_name":"lut.py","file_ext":"py","file_size_in_byte":67475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"102691742","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-)\n\nimport pickle \n\n#i = 1\n#while(1 == 1):\n# file = open('%s.csv' % i, 'w')\n# file.close()\n# i=i+1\n\nf = open('conv.txt', 'r')\nfText = f.read()\n#bin(int.from_bytes('hello'.encode(), 'big'))\nfBin = bin(int.from_bytes(fText.encode(), 'big'))\nf.close()\nf = open('conv.txt', 'w+')\n#fEn = fBin.decode('ascii')\nf.write(fBin )\n#pickle.dump(fBin, f)\n\n#print(fText)\n#print('Binario')\n#print(fBin)\n\n#n = int('0b110100001100101011011000110110001101111', 2)\n#n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()\n\nf.close()\n","sub_path":"convert/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"536919318","text":"import os\r\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\r\nimport sys\r\nimport csv\r\nimport cv2\r\nimport argparse\r\nimport numpy as np\r\nimport torch\r\nfrom autoencoders import myColorizationAE\r\nfrom data_io import load_single_image\r\nfrom utils import show_image\r\nfrom func import predict_once\r\n\r\n\r\n### データセットに応じてこの部分を書き換える必要あり ###\r\n\r\n# 入力画像の縦幅・横幅・チャンネル数の設定(別データセットを使う場合,下の二つを書き換える)\r\nWIDTH = 128 # VGGFace2顔画像の場合,横幅は 128 pixels\r\nHEIGHT = 128 # VGGFace2顔画像の場合,縦幅も 128 pixels\r\n\r\n### ここまで ###\r\n\r\n\r\n# エントリポイント\r\nif __name__ == '__main__':\r\n\r\n # コマンドライン引数のパース\r\n parser = argparse.ArgumentParser(description = 'CNN Model for Image Colorization (Execution)')\r\n parser.add_argument('--gpu', '-g', default=-1, type=int, help='GPU ID (negative value indicates CPU)')\r\n parser.add_argument('--in_filepath', '-i', default='', type=str, help='input file path')\r\n parser.add_argument('--out_filepath', '-o', default='', type=str, help='output file path')\r\n parser.add_argument('--model', '-m', default='colorize_model.pth', type=str, help='file path of trained model')\r\n args = parser.parse_args()\r\n\r\n # コマンドライン引数のチェック\r\n if args.in_filepath is None or args.in_filepath == '':\r\n print('error: no input file path is specified.', file=sys.stderr)\r\n exit()\r\n if args.out_filepath is None or args.out_filepath == '':\r\n print('error: no output file path is specified.', file=sys.stderr)\r\n exit()\r\n\r\n # デバイスの設定\r\n dev_str = 'cuda:{0}'.format(args.gpu) if torch.cuda.is_available() and args.gpu >= 0 else 'cpu'\r\n dev = torch.device(dev_str)\r\n\r\n # オプション情報の設定・表示\r\n in_filepath = args.in_filepath # 入力ファイルパス\r\n out_filepath = args.out_filepath # 出力ファイルパス\r\n model_filepath = args.model # 学習済みモデルのファイルパス\r\n print('device: {0}'.format(dev_str), file=sys.stderr)\r\n print('input file: {0}'.format(in_filepath), file=sys.stderr)\r\n print('output file: {0}'.format(out_filepath), file=sys.stderr)\r\n print('model file: {0}'.format(model_filepath), file=sys.stderr)\r\n print('', file=sys.stderr)\r\n\r\n # 学習済みのオートエンコーダをロード\r\n cnn = myColorizationAE(WIDTH, HEIGHT)\r\n cnn.load_state_dict(torch.load(model_filepath))\r\n\r\n # mode=0: 入力ファイルをグレースケール画像として読み込む\r\n img = load_single_image(in_filepath, mode=0)\r\n\r\n # 入力画像を表示\r\n show_image(img, title='input image', mode=0)\r\n\r\n # 入力画像をモデルに入力してカラー化\r\n y = predict_once(device=dev, model=cnn, in_data=img)\r\n\r\n # カラー化結果を表示\r\n show_image(y, title='output image', mode=1)\r\n\r\n # カラー化結果をファイルに保存\r\n y = np.asarray(y.transpose(1, 2, 0) * 255, dtype=np.uint8)\r\n cv2.imwrite(out_filepath, y)\r\n\r\n print('', file=sys.stderr)\r\n","sub_path":"colorize_exec.py","file_name":"colorize_exec.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"7947987","text":"def bleTrcpsEnable(symbol, event):\n symbol.setEnabled(event[\"value\"])\n\n#def bleTrcpcEnable(symbol, event):\n# symbol.setEnabled(event[\"value\"])\n \n \ndef instantiateComponent(profileBLE_TRCP_Component):\n print('profileBLE_TRCP_Component')\n configName = Variables.get('__CONFIGURATION_NAME')\n processor = Variables.get(\"__PROCESSOR\")\n\n print('Config Name: {} processor: {}'.format(configName, processor))\n\n #################################################################\n ################## Client Role Settings ###############\n #################################################################\n menuClient = profileBLE_TRCP_Component.createBooleanSymbol('TRCP_BOOL_CLIENT', None)\n menuClient.setLabel('Enable Client Role')\n menuClient.setDefaultValue(False)\n menuClient.setVisible(False)\n \n \n #################################################################\n ################## Server Role Settings ###############\n #################################################################\n menuSERVER = profileBLE_TRCP_Component.createBooleanSymbol('TRCP_BOOL_SERVER', None)\n menuSERVER.setLabel('Enable Server Role')\n menuSERVER.setDefaultValue(False)\n\n\n #################################################################\n ################## Add Source File ###############\n #################################################################\n\n # Add ble_trcbps.c file\n bleTrcbpsSourceFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n bleTrcbpsSourceFile.setSourcePath('driver/ble/src/ble_src/profile_ble/ble_trcbps/ble_trcbps.c')\n bleTrcbpsSourceFile.setOutputName('ble_trcbps.c')\n bleTrcbpsSourceFile.setOverwrite(True)\n bleTrcbpsSourceFile.setDestPath('ble/profile_ble/ble_trcbps/')\n bleTrcbpsSourceFile.setProjectPath('config/' + configName + '/ble/profile_ble/ble_trcbps/')\n bleTrcbpsSourceFile.setType('SOURCE')\n bleTrcbpsSourceFile.setEnabled(False)\n bleTrcbpsSourceFile.setMarkup(True)\n bleTrcbpsSourceFile.setDependencies(bleTrcpsEnable, [\"TRCP_BOOL_SERVER\"])\n\n # Add ble_trcbps.h file\n bleTrcbpsHeaderFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n bleTrcbpsHeaderFile.setSourcePath('driver/ble/src/ble_src/profile_ble/ble_trcbps/ble_trcbps.h')\n bleTrcbpsHeaderFile.setOutputName('ble_trcbps.h')\n bleTrcbpsHeaderFile.setOverwrite(True)\n bleTrcbpsHeaderFile.setDestPath('ble/profile_ble/ble_trcbps/')\n bleTrcbpsHeaderFile.setProjectPath('config/' + configName + '/ble/profile_ble/ble_trcbps/')\n bleTrcbpsHeaderFile.setType('HEADER')\n bleTrcbpsHeaderFile.setEnabled(False)\n bleTrcbpsHeaderFile.setMarkup(True)\n bleTrcbpsHeaderFile.setDependencies(bleTrcpsEnable, [\"TRCP_BOOL_SERVER\"])\n\n # Add app_trcbps.c file - static file\n bleTrcbpsAppSourceFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n bleTrcbpsAppSourceFile.setSourcePath('driver/ble/src/app_trcbps_handler.c')\n bleTrcbpsAppSourceFile.setOutputName('app_trcbps_handler.c')\n bleTrcbpsAppSourceFile.setOverwrite(True)\n bleTrcbpsAppSourceFile.setDestPath('../../app_ble')\n bleTrcbpsAppSourceFile.setProjectPath('app_ble')\n bleTrcbpsAppSourceFile.setType('Source')\n bleTrcbpsAppSourceFile.setEnabled(False)\n bleTrcbpsAppSourceFile.setDependencies(bleTrcpsEnable, [\"TRCP_BOOL_SERVER\"])\n \n # Add app_trcbps.h file - static file\n bleTrcbpsAppHeaderFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n bleTrcbpsAppHeaderFile.setSourcePath('driver/ble/src/app_trcbps_handler.h')\n bleTrcbpsAppHeaderFile.setOutputName('app_trcbps_handler.h')\n bleTrcbpsAppHeaderFile.setOverwrite(True)\n bleTrcbpsAppHeaderFile.setDestPath('../../app_ble')\n bleTrcbpsAppHeaderFile.setProjectPath('app_ble')\n bleTrcbpsAppHeaderFile.setType('HEADER')\n bleTrcbpsAppHeaderFile.setEnabled(False)\n bleTrcbpsAppHeaderFile.setDependencies(bleTrcpsEnable, [\"TRCP_BOOL_SERVER\"])\n \n # Add ble_trcbpc.c file\n #bleTrcbpsSourceFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n #bleTrcbpsSourceFile.setSourcePath('driver/ble/src/ble_src/profile_ble/ble_trcbpc/ble_trcbpc.c')\n #bleTrcbpsSourceFile.setOutputName('ble_trcbpc.c')\n #bleTrcbpsSourceFile.setOverwrite(True)\n #bleTrcbpsSourceFile.setDestPath('ble/profile_ble/ble_trcbpc/')\n #bleTrcbpsSourceFile.setProjectPath('config/' + configName + '/ble/profile_ble/ble_trcbpc/')\n #bleTrcbpsSourceFile.setType('SOURCE')\n #bleTrcbpsSourceFile.setEnabled(False)\n #bleTrcbpsSourceFile.setMarkup(True)\n #bleTrcbpsSourceFile.setDependencies(bleTrcpcEnable, [\"TRCP_BOOL_CLIENT\"])\n\n # Add ble_trcbpc.h file\n #bleTrcbpsHeaderFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n #bleTrcbpsHeaderFile.setSourcePath('driver/ble/src/ble_src/profile_ble/ble_trcbpc/ble_trcbpc.h')\n #bleTrcbpsHeaderFile.setOutputName('ble_trcbpc.h')\n #bleTrcbpsHeaderFile.setOverwrite(True)\n #bleTrcbpsHeaderFile.setDestPath('ble/profile_ble/ble_trcbpc/')\n #bleTrcbpsHeaderFile.setProjectPath('config/' + configName + '/ble/profile_ble/ble_trcbpc/')\n #bleTrcbpsHeaderFile.setType('HEADER')\n #bleTrcbpsHeaderFile.setEnabled(False)\n #bleTrcbpsHeaderFile.setMarkup(True)\n #bleTrcbpsHeaderFile.setDependencies(bleTrcpcEnable, [\"TRCP_BOOL_CLIENT\"]) \n\n # Add app_trcbpC.c file - static file\n #bleTrcbpcAppSourceFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n #bleTrcbpcAppSourceFile.setSourcePath('driver/ble/src/app_trcbpc_handler.c')\n #bleTrcbpcAppSourceFile.setOutputName('app_trcbpc_handler.c')\n #bleTrcbpcAppSourceFile.setOverwrite(True)\n #bleTrcbpcAppSourceFile.setDestPath('../../')\n #bleTrcbpcAppSourceFile.setProjectPath('')\n #bleTrcbpcAppSourceFile.setType('Source')\n #bleTrcbpcAppSourceFile.setEnabled(True)\n #bleTrcbpcAppSourceFile.setDependencies(bleTrcpcEnable, [\"TRCP_BOOL_CLIENT\"])\n \n # Add app_trcbpC.h file - static file\n #bleTrcbpcAppHeaderFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n #bleTrcbpcAppHeaderFile.setSourcePath('driver/ble/src/app_trcbpc_handler.h')\n #bleTrcbpcAppHeaderFile.setOutputName('app_trcbpc_handler.h')\n #bleTrcbpcAppHeaderFile.setOverwrite(True)\n #bleTrcbpcAppHeaderFile.setDestPath('../../')\n #bleTrcbpcAppHeaderFile.setProjectPath('')\n #bleTrcbpcAppHeaderFile.setType('HEADER')\n #bleTrcbpcAppHeaderFile.setEnabled(True)\n #bleTrcbpcAppHeaderFile.setDependencies(bleTrcpcEnable, [\"TRCP_BOOL_SERVER\"]) \n\n\ndef finalizeComponent(BLEStackComponent):\n Log.writeInfoMessage('Finalizing: {}'.format(BLEStackComponent.getID()))\n activeComponents = Database.getActiveComponentIDs()\n requiredComponents = ['svcBLE_TRCS']\n for r in requiredComponents:\n if r not in activeComponents:\n res = Database.activateComponents([r])\n","sub_path":"H3/wireless/driver/ble/config/trcp.py","file_name":"trcp.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"405262576","text":"import itertools\nfrom cellular_functions import *\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n'''x=int(input(\"Enter elements of rule vector \"))\nst=input(\"Enter the rule vector :\")\nrule=list(map(int, st.split(' ')[:x]))\nn=int(input(\"Enter elements of rule vector \"))\ncomb=list(itertools.product(rule,repeat=n))'''\n\n\n#problem 1 solution\ndef print_pattern_defined(n,rule):\n output=[]\n for i in range(0,2**n):\n s=bin(i)[2:]\n string='0'*n\n string=string[:-len(s)]+s\n output.append(apply(string,rule))\n return output\nx=int(input(\"Enter the size of rule vector \"))\nst=input(\"Enter the rule vector :\")\nrule=list(map(int, st.split(' ')[:x]))\nans=print_pattern_defined(x,rule)\nans=[int('0b'+i,2) for i in ans]\nprint(ans)\ng = nx.DiGraph()\ng.add_nodes_from([i for i in range(len(ans))])\nfor i in range(0,len(ans)):\n g.add_edge(i,ans[i])\n#pos=nx.fruchterman_reingold_layout(g)\n#pos=nx.spring_layout(g)\npos=nx.shell_layout(g)\nnx.draw(g,pos,with_labels=True)\n#plt.savefig(\"weighted_graph.png\")\nplt.draw()\nplt.show()\n\n","sub_path":"Cellular Null Boundary/draw_std.py","file_name":"draw_std.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"613335497","text":"\"\"\"\n WualaCleaner: tool to clean up \"fotos-familie\" archive\n WualaCleaner.py is copyright 2013,2014 Jeroen Doggen.\n\"\"\"\n\nimport os\nimport sys\nimport shutil\n\n\nSCRIPTPATH = os.getcwd()\nINPUTFOLDER = SCRIPTPATH + \"/input\"\nOUTPUTFOLDER = SCRIPTPATH + \"/output\"\n\n\ndef run():\n \"\"\"Run the main program\"\"\"\n print(\"Moving files to output folder & creating lowres versions...\")\n for directory, subdirectories, files in os.walk(INPUTFOLDER):\n print(directory)\n for thefile in files:\n os.chdir(directory)\n if not \"_lowres\" in thefile:\n outputfile = thefile + \"_lowres.jpg\"\n os.system(\"convert -gaussian-blur 0.03 -quality 75% -resize 1280\"\n + \" \" + thefile\n + \" \" + outputfile)\n dirs = os.path.split(directory)\n dirs = dirs[1]\n target = os.path.join(OUTPUTFOLDER, dirs)\n print(\"Creating: \" + dirs + \"/\" + outputfile)\n if not os.path.exists(target):\n os.mkdir(target)\n if os.path.exists(outputfile):\n shutil.move(outputfile, target + \"/\" + outputfile)\n os.chdir(INPUTFOLDER)\n\n\ndef get_size(start_path='.'):\n \"\"\" Calculate folder size \"\"\"\n total_size = 0\n for dirpath, dirnames, filenames in os.walk(start_path):\n for inputfile in filenames:\n filepointer = os.path.join(dirpath, inputfile)\n total_size += os.path.getsize(filepointer)\n return float(total_size)\n\n\nif __name__ == \"__main__\":\n sys.exit(run())\n","sub_path":"wualaCleaner/WualaCleaner.py","file_name":"WualaCleaner.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"126123812","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 17 18:09:58 2019\n\n@author: harshal\n\"\"\"\n\nmainStr = 'pqrsxytprqmjklqprsxypqrsd'\n\ntar = 'pqr'\n\n'''find the start index of all permutations of target string'''\n\nL = len(mainStr)\nX=[]\nfor i in range(len(mainStr)):\n temp = list(tar)\n if mainStr[i] in tar:\n while temp and i 1.2.5.\n# exchange-calendars is a fork that retained the same functionalities,\n# but dropped support for zipline 1 minute delay in open and changed some default settings in calendars.\n#\n# We resort here to monkey patching the `_fabricate` function of the ExchangeCalendarDispatcher\n# and importing `ExchangeCalendar as TradingCalendar` to get as close as possible to the\n# behavior expected by zipline, while also maintaining the possibility to revert back\n# to pandas==1.2.5 and trading-calendars in case something breaks heavily.\n#\n# In order to avoid problems, especially when using the exchange-calendars,\n# all imports should be done via `calendar_utils`, e.g:\n# `from zipline.utils.calendar_utils import get_calendar, register_calendar, ...`\n#\n# Some calendars like for instance the Korean exchange have been extensively updated and might no longer\n# work as expected\n\ntry:\n from exchange_calendars import ExchangeCalendar as TradingCalendar\n from exchange_calendars.calendar_utils import (\n ExchangeCalendarDispatcher,\n _default_calendar_factories,\n _default_calendar_aliases,\n )\n from exchange_calendars.errors import InvalidCalendarName\n from exchange_calendars.utils.memoize import lazyval\n from exchange_calendars.utils.pandas_utils import days_at_time # noqa: reexport\n\n def _fabricate(self, name: str, **kwargs):\n \"\"\"Fabricate calendar with `name` and `**kwargs`.\"\"\"\n try:\n factory = self._calendar_factories[name]\n except KeyError as e:\n raise InvalidCalendarName(calendar_name=name) from e\n if name in [\"us_futures\", \"CMES\", \"XNYS\"]:\n # exchange_calendars has a different default start data\n # that we need to overwrite in order to pass the legacy tests\n setattr(factory, \"default_start\", pd.Timestamp(\"1990-01-01\", tz=UTC))\n # kwargs[\"start\"] = pd.Timestamp(\"1990-01-01\", tz=\"UTC\")\n if name not in [\"us_futures\", \"24/7\", \"24/5\", \"CMES\"]:\n # Zipline had default open time of t+1min\n factory.open_times = [\n (d, t.replace(minute=t.minute + 1)) for d, t in factory.open_times\n ]\n calendar = factory(**kwargs)\n self._factory_output_cache[name] = (calendar, kwargs)\n return calendar\n\n # Yay! Monkey patching\n ExchangeCalendarDispatcher._fabricate = _fabricate\n\n global_calendar_dispatcher = ExchangeCalendarDispatcher(\n calendars={},\n calendar_factories=_default_calendar_factories,\n aliases=_default_calendar_aliases,\n )\n get_calendar = global_calendar_dispatcher.get_calendar\n\n get_calendar_names = global_calendar_dispatcher.get_calendar_names\n clear_calendars = global_calendar_dispatcher.clear_calendars\n deregister_calendar = global_calendar_dispatcher.deregister_calendar\n register_calendar = global_calendar_dispatcher.register_calendar\n register_calendar_type = global_calendar_dispatcher.register_calendar_type\n register_calendar_alias = global_calendar_dispatcher.register_calendar_alias\n resolve_alias = global_calendar_dispatcher.resolve_alias\n aliases_to_names = global_calendar_dispatcher.aliases_to_names\n names_to_aliases = global_calendar_dispatcher.names_to_aliases\n\nexcept ImportError:\n if PANDAS_VERSION > \"1.2.5\":\n raise ImportError(\"For pandas >= 1.3 YOU MUST INSTALL exchange-calendars\")\n else:\n from trading_calendars import (\n register_calendar,\n TradingCalendar,\n get_calendar,\n register_calendar_alias,\n )\n from trading_calendars.calendar_utils import global_calendar_dispatcher\n from trading_calendars.utils.memoize import lazyval\n from trading_calendars.utils.pandas_utils import days_at_time # noqa: reexport\n","sub_path":"src/zipline/utils/calendar_utils.py","file_name":"calendar_utils.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"570354112","text":"import logging\n\nimport arrow\nimport gspread\nfrom django.conf import settings\nfrom django.contrib.auth.models import Group\nfrom django.core.exceptions import ValidationError\nfrom django.core.management.base import BaseCommand\nfrom epfl.sti.helpers.ldap import get_users\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom web.models import Person\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n \"\"\"Loads all supervisions from GSheet and update the DB accordingly.\"\"\"\n\n def handle(self, **options):\n logger.info(\"loading supervisions\")\n client = get_client()\n supervisions = get_supervisions(\n client, settings.GOOGLE_SUPERVISORS_WORKSHEET_NAME\n )\n supervisions = process_supervisions(supervisions)\n update_supervisions(\n supervisions, client, settings.GOOGLE_SUPERVISORS_WORKSHEET_NAME\n )\n\n\ndef get_client():\n \"\"\"Get a Google API client instance\n\n Returns:\n client: the instance of the Google API client\n \"\"\"\n logger.info(\"getting client\")\n scope = [\"https://www.googleapis.com/auth/drive\"]\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n settings.GOOGLE_CLIENT_SECRET_PATH, scope\n )\n client = gspread.authorize(credentials)\n return client\n\n\ndef get_supervisions(client, worksheetName):\n \"\"\"Returns the list of supervisions contained in the worksheet.\n Args:\n client (client_class): The client object currently authenticated\n worksheetName (str): The name of the worksheet as it appears on Google Drive\n Returns:\n List of lists: The list of supervisions\n \"\"\"\n logger.info(\"getting supervisions\")\n sheet = client.open(worksheetName).sheet1\n records = sheet.get_all_values()\n return records\n\n\ndef process_supervisions(supervisions):\n \"\"\"Process all the supervisions\n Args:\n supervisions ([]): the list of supervision list you want to process\n Returns:\n []: the processed list of supervision lists\n \"\"\"\n logger.info(\"processing supervisions\")\n fields = supervisions[0]\n values = supervisions[1:]\n\n actionColIndex = fields.index(\"Action\")\n studentIdColIndex = fields.index(\"PhD sciper\")\n supervisorIdColIndex = fields.index(\"Supervisor sciper\")\n statusColIndex = fields.index(\"Synchronization status\")\n timestampeColIndex = fields.index(\"Synchronized at\")\n\n for value in values:\n\n # only perform a change for values that did not change already\n if value[timestampeColIndex] == \"\":\n value[statusColIndex] = \"\"\n\n result = process_supervision(\n action=value[actionColIndex],\n studentSciper=value[studentIdColIndex],\n supervisorSciper=value[supervisorIdColIndex],\n )\n\n value[statusColIndex] = result\n value[timestampeColIndex] = arrow.now(\"Europe/Zurich\").format(\n \"YYYY-MM-DD HH:mm:ss\"\n )\n\n returnValue = [fields] + values\n\n return returnValue\n\n\ndef process_supervision(studentSciper, supervisorSciper, action=\"add\"):\n \"\"\"process the supervision\n\n Args:\n studentSciper (str): the sciper id of the student\n supervisorSciper (str): the sciper id of the teacher\n action (str, optional): the action to be performed ([add|remove]). Defaults to \"add\".\n\n Returns:\n str: the status message of the operation\n \"\"\"\n logger.info(\n \"processing supervision ({} {} supervises {})\".format(\n action, supervisorSciper, studentSciper\n )\n )\n if action == \"add\":\n return add_supervision(studentSciper, supervisorSciper)\n elif action == \"remove\":\n return remove_supervision(studentSciper, supervisorSciper)\n else:\n logger.error(\"unknown action\")\n return \"unknown action. It should be 'add' or 'remove'\"\n\n\ndef add_supervision(studentSciper, supervisorSciper):\n \"\"\"add the supervision in the DB\n\n Args:\n studentSciper (str): the sciper id of the student\n supervisorSciper (str): the sciper id of the supervisor\n\n Returns:\n str: the status message of the operation\n \"\"\"\n has_error = False\n error_messages = []\n\n try:\n teacher = Person.objects.filter(sciper=supervisorSciper).first()\n if teacher is None:\n teacher = add_supervisor(supervisorSciper)\n add_to_group(teacher, \"teachers\")\n\n except Exception as ex:\n has_error = True\n error_messages.append(\"unable to get teacher - \" + str(ex))\n\n try:\n phd = Person.objects.filter(sciper=studentSciper).first()\n if phd is None:\n phd = add_phd(studentSciper)\n add_to_group(phd, \"phds\")\n except Exception as ex:\n has_error = True\n error_messages.append(\"unable to get phd - \" + str(ex))\n\n if has_error:\n logger.error(\"\\n\".join(error_messages))\n return \"\\n\".join(error_messages)\n\n try:\n if phd not in teacher.students.all():\n logger.info(\"adding student to teacher\")\n teacher.students.add(phd)\n return \"OK\"\n else:\n logger.warn(\"student already supervised by teacher\")\n return \"Already added\"\n except ValidationError as ex:\n logger.error(ex.message)\n return ex.message\n except Exception as ex:\n logger.exception(ex)\n return str(ex)\n\n\ndef remove_supervision(studentSciper, supervisorSciper):\n \"\"\"Remove the supervision from the DB\n\n Args:\n studentSciper (str): the sciper id of the student\n supervisorSciper (str): the sciper of the supervisor\n\n Returns:\n str: the status message of the operation\n \"\"\"\n logger.info(\"removing supervision\")\n logger.debug(\"student: \" + studentSciper)\n logger.debug(\"supervisor: \" + supervisorSciper)\n\n try:\n teacher = Person.objects.filter(sciper=supervisorSciper).first()\n phd = Person.objects.filter(sciper=studentSciper).first()\n\n if phd not in teacher.students.all():\n logger.warn(\"the student was not supervised by this person\")\n return \"Already removed\"\n else:\n teacher.students.remove(phd)\n logger.info(\"supervision removed\")\n return \"OK\"\n except Exception as ex:\n logger.exception(ex)\n return str(ex)\n\n\ndef add_supervisor(sciper):\n \"\"\"Add the person as teacher\n\n Args:\n sciper (str): the sciper of the person to add\n\n Returns:\n Person: The person object in DB that belongs to the Teachers group\n \"\"\"\n logger.info(\"adding supervisor with sciper #\" + sciper)\n supervisor = add_person(sciper)\n add_to_group(supervisor, \"teachers\")\n return supervisor\n\n\ndef add_phd(sciper):\n \"\"\"Add a person as PhD\n\n Args:\n sciper (str): the sciper of the PhD to add\n\n Returns:\n Person: The person object in DB that belongs to the PhDs group\n \"\"\"\n logger.info(\"adding phd with sciper #\" + sciper)\n phd = add_person(sciper)\n add_to_group(phd, \"phds\")\n return phd\n\n\ndef add_person(sciper):\n \"\"\"Add the person to the database\n\n Args:\n sciper (str): the sciper of the person to be added\n\n Returns:\n Person: The created entry in DB\n \"\"\"\n logger.info(\"adding person with sciper #\" + sciper)\n ldapData = get_users(settings, [sciper])[0]\n person = Person()\n person.sciper = sciper\n person.username = ldapData[\"username\"]\n person.email = ldapData[\"email\"]\n person.first_name = ldapData[\"first_name\"]\n person.last_name = ldapData[\"last_name\"]\n person.save()\n return person\n\n\ndef add_to_group(person, groupName):\n \"\"\"Add the person into group\n\n Args:\n person (Person): the person to be added to the group\n groupName (str): The name of the group the person should belong to\n \"\"\"\n logger.info(\"Adding {} to {} group\".format(person, groupName))\n if person.groups.filter(name=groupName).exists() == False:\n group = Group.objects.get(name=groupName)\n group.user_set.add(person)\n\n\ndef update_supervisions(supervisions, client, worksheetName):\n \"\"\"saves the list of supervisions to GSheet\n Args:\n supervisions (List): The list of supervisions\n client (client_class): The Google authenticated client object\n worksheetName (str): The name of GSheet\n \"\"\"\n logger.info(\"updating GSheet with results\")\n sheet = client.open(worksheetName).sheet1\n\n sheet.update(supervisions, value_input_option=\"USER_ENTERED\")\n","sub_path":"teaching_pool_project/web/management/commands/load_supervisors.py","file_name":"load_supervisors.py","file_ext":"py","file_size_in_byte":8563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"573924281","text":"import tensorflow as tf\nfrom keras import backend as K\nfrom keras import layers\nfrom keras.activations import relu\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom keras.layers import (Activation, Add, BatchNormalization, Concatenate,\n Conv2D, DepthwiseConv2D, Dropout,\n GlobalAveragePooling2D, Input, Lambda, Reshape,\n Softmax, ZeroPadding2D)\nfrom keras.models import Model\nfrom keras.utils.data_utils import get_file\n\nfrom nets.mobilenetV2 import mobilenetV2\n\n\ndef SepConv_BN(x, filters, prefix, stride=1, kernel_size=3, rate=1, depth_activation=False, epsilon=1e-3):\n if stride == 1:\n depth_padding = 'same'\n else:\n kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)\n pad_total = kernel_size_effective - 1\n pad_beg = pad_total // 2\n pad_end = pad_total - pad_beg\n x = ZeroPadding2D((pad_beg, pad_end))(x)\n depth_padding = 'valid'\n \n if not depth_activation:\n x = Activation('relu')(x)\n\n # 首先使用3x3的深度可分离卷��\n x = DepthwiseConv2D((kernel_size, kernel_size), strides=(stride, stride), dilation_rate=(rate, rate),\n padding=depth_padding, use_bias=False, name=prefix + '_depthwise')(x)\n x = BatchNormalization(name=prefix + '_depthwise_BN', epsilon=epsilon)(x)\n if depth_activation:\n x = Activation('relu')(x)\n\n # 利用1x1卷积进行通道数调整\n x = Conv2D(filters, (1, 1), padding='same', use_bias=False, name=prefix + '_pointwise')(x)\n x = BatchNormalization(name=prefix + '_pointwise_BN', epsilon=epsilon)(x)\n if depth_activation:\n x = Activation('relu')(x)\n\n return x\n\ndef Deeplabv3(input_shape=(416, 416, 3), classes=21, alpha=1.):\n img_input = Input(shape=input_shape)\n\n # x 52, 52, 320\n # skip1 104, 104, 24\n x, skip1 = mobilenetV2(img_input, alpha)\n size_before = tf.keras.backend.int_shape(x)\n\n #---------------------------------------------------------------#\n # 全部求平均后,再利用expand_dims扩充维度\n # 52,52,320 -> 1,1,320 -> 1,1,320\n #---------------------------------------------------------------#\n b4 = GlobalAveragePooling2D()(x)\n b4 = Lambda(lambda x: K.expand_dims(x, 1))(b4)\n b4 = Lambda(lambda x: K.expand_dims(x, 1))(b4)\n b4 = Conv2D(256, (1, 1), padding='same', use_bias=False, name='image_pooling')(b4)\n b4 = BatchNormalization(name='image_pooling_BN', epsilon=1e-5)(b4)\n b4 = Activation('relu')(b4)\n # 1,1,256 -> 52,52,256\n b4 = Lambda(lambda x: tf.image.resize_images(x, size_before[1:3]))(b4)\n\n #---------------------------------------------------------------#\n # 调整通道\n #---------------------------------------------------------------#\n b0 = Conv2D(256, (1, 1), padding='same', use_bias=False, name='aspp0')(x)\n b0 = BatchNormalization(name='aspp0_BN', epsilon=1e-5)(b0)\n b0 = Activation('relu', name='aspp0_activation')(b0)\n\n # 52, 52, 256 + 52, 52, 256 -> 52, 52, 512\n x = Concatenate()([b4, b0])\n\n # 利用1x1卷积调整通道数\n # 52, 52, 1280 -> 52,52,256\n x = Conv2D(256, (1, 1), padding='same', use_bias=False, name='concat_projection')(x)\n x = BatchNormalization(name='concat_projection_BN', epsilon=1e-5)(x)\n x = Activation('relu')(x)\n x = Dropout(0.1)(x)\n\n # 52,52,256 -> 104,104,2 -> 416,416,2\n size_before3 = tf.keras.backend.int_shape(img_input)\n x = Conv2D(classes, (1, 1), padding='same')(x)\n x = Lambda(lambda xx:tf.image.resize_images(xx, size_before3[1:3]))(x)\n\n x = Reshape((-1,classes))(x)\n x = Softmax()(x)\n\n model = Model(img_input, x, name='deeplabv3plus')\n return model\n\n","sub_path":"Muiti_Class_deeplab_Mobile/nets/deeplab.py","file_name":"deeplab.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"105051350","text":"import sys\r\n\r\ninput = sys.stdin.readline\r\n\r\n\r\ndef update(i, diff):\r\n while i < size:\r\n bit[i] += diff\r\n i |= i + 1\r\n\r\n\r\ndef get(x): # size = 4\r\n left, right = 0, size\r\n for i in range(exp + 1):\r\n mid = (left + right) >> 1\r\n val = bit[mid - 1]\r\n if val >= x:\r\n right = mid\r\n else:\r\n left = mid\r\n x -= val\r\n return left\r\n\r\n\r\nn, k = map(int, input().split())\r\n\r\nexp, size = 0, 1\r\nwhile size < n:\r\n exp += 1\r\n size *= 2\r\nbit = [0] * size\r\nfor i in range(n):\r\n update(i, 1)\r\n\r\n\r\n\r\nans = []\r\nx = 0\r\nfor j in range(n, 0, -1):\r\n x = (x + k - 1) % j\r\n\r\n val = get(x + 1)\r\n update(val, -1)\r\n ans.append(val + 1)\r\n\r\nsys.stdout.write(f'<{\", \".join(map(str, ans))}>')","sub_path":"1168_pypy.py","file_name":"1168_pypy.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"365907203","text":"import nltk\nimport numpy\nimport re\nfrom nltk.util import ngrams\nimport operator\nimport gensim\nfrom collections import defaultdict\nfrom math import sqrt\nimport json\nimport requests\nimport hashlib\nimport time\nfrom operator import itemgetter\nimport pickle\nimport os\n\n# extract configured set of features from list of text instances\n# global variables to pass around data\nsource_texts = []\ntokenized_texts_case = []\nword_counts = []\ntokenized_texts = []\ntagged_texts = []\ncropped_texts = []\nstemmed_texts = []\nstemmed_cropped_texts = []\nw2v_model = None\npfolder = 0\n\n\ndef preprocess():\n \"\"\" prepares source_texts for feature extraction; called by extract_features\n\n puts words in lower case, tokenizes and stems them, and removes rare words\n no args and no return because of use of global variables\n \"\"\"\n\n global source_texts, tokenized_texts_case, word_counts, tokenized_texts, \\\n tagged_texts, cropped_texts, stemmed_texts, stemmed_cropped_texts, pfolder\n\n # load the processed texts from pickle dumps if those exist (check for one)\n if os.path.exists(pfolder+'/tokenized_texts_case.p'):\n with open(pfolder+'/tokenized_texts_case.p', 'rb') as p_file:\n tokenized_texts_case = pickle.load(p_file)\n with open(pfolder+'/word_counts.p', 'rb') as p_file:\n word_counts = pickle.load(p_file)\n with open(pfolder+'/tokenized_texts.p', 'rb') as p_file:\n tokenized_texts = pickle.load(p_file)\n with open(pfolder+'/tagged_texts.p', 'rb') as p_file:\n tagged_texts = pickle.load(p_file)\n with open(pfolder+'/cropped_texts.p', 'rb') as p_file:\n cropped_texts = pickle.load(p_file)\n with open(pfolder+'/stemmed_texts.p', 'rb') as p_file:\n stemmed_texts = pickle.load(p_file)\n with open(pfolder+'/stemmed_cropped_texts.p', 'rb') as p_file:\n stemmed_cropped_texts = pickle.load(p_file)\n return\n else:\n # lower case, count words, tokenize, and tag\n tokenized_texts_case = [nltk.word_tokenize(text) for text in source_texts]\n source_texts = [text.lower() for text in source_texts]\n word_counts = [len(text.split()) for text in source_texts]\n tokenized_texts = [nltk.word_tokenize(text) for text in source_texts]\n tagged_texts = [[tag[1] for tag in nltk.pos_tag(text)]\n for text in tokenized_texts]\n\n stop_list = nltk.corpus.stopwords.words('english')\n stop_list.extend(['.', ',', ':', ';', '(', ')', '!', '?', '\"', \"'\", \"''\",\n '``', '-', \"'s\", 'would', '[', ']', '{', '}', '...',\n 'p.'])\n cropped_texts = [[word for word in text if word not in stop_list]\n for text in tokenized_texts]\n\n # stem using standard nltk porter stemmer\n porter = nltk.PorterStemmer()\n # stemmed_texts = [[porter.stem(t) for t in tokens]\n # for tokens in tokenized_texts]\n # iterating instead of list comprehension to allow exception handling\n stemmed_texts = []\n for tokens in tokenized_texts:\n stemmed_text = []\n for t in tokens:\n try:\n stemmed_text.extend([porter.stem(t)])\n except IndexError:\n stemmed_text.extend('')\n stemmed_texts.append(stemmed_text)\n stemmed_cropped_texts = []\n for tokens in cropped_texts:\n stemmed_cropped_text = []\n for t in tokens:\n try:\n stemmed_cropped_text.extend([porter.stem(t)])\n except IndexError:\n stemmed_cropped_text.extend('')\n stemmed_cropped_texts.append(stemmed_cropped_text)\n\n # remove rare words\n # vocab = nltk.FreqDist(w for w in line for line in stemmed_texts)\n vocab = nltk.FreqDist(w for text in stemmed_texts for w in text)\n rare_words_list = [re.escape(word) for word in vocab.hapaxes()]\n rare_words_regex = re.compile(r'\\b(%s)\\b' % '|'.join(rare_words_list))\n stemmed_texts = [[rare_words_regex.sub('', w) for w in text]\n for text in stemmed_texts]\n # note: source_texts will be lower case, but only stemmed_texts will have\n # rare words removed\n\n # dump the processed texts to pickle files for next time they are needed\n with open(pfolder+'/tokenized_texts_case.p', 'wb') as p_file:\n pickle.dump(tokenized_texts_case, p_file)\n with open(pfolder+'/word_counts.p', 'wb') as p_file:\n pickle.dump(word_counts, p_file)\n with open(pfolder+'/tokenized_texts.p', 'wb') as p_file:\n pickle.dump(tokenized_texts, p_file)\n with open(pfolder+'/tagged_texts.p', 'wb') as p_file:\n pickle.dump(tagged_texts, p_file)\n with open(pfolder+'/cropped_texts.p', 'wb') as p_file:\n pickle.dump(cropped_texts, p_file)\n with open(pfolder+'/stemmed_texts.p', 'wb') as p_file:\n pickle.dump(stemmed_texts, p_file)\n with open(pfolder+'/stemmed_cropped_texts.p', 'wb') as p_file:\n pickle.dump(stemmed_cropped_texts, p_file)\n\n\ndef bag_of_function_words():\n \"\"\" returns, for each nltk stop word, count per text in source_texts \"\"\"\n bow = []\n for sw in nltk.corpus.stopwords.words('english'):\n counts = [sum(1 for _ in re.finditer(r'\\b%s\\b' % sw, text))\n for text in source_texts]\n counts = [counts[i] / word_counts[i] for i in range(0, len(counts))]\n bow.append(counts)\n return bow\n\n\ndef bag_of_ngrams(texts, n=1, m=None):\n \"\"\" returns counts of up to m overall most common ngrams for each given text\n\n determines the counts of all ngrams, orders them by sum of counts across\n texts and returns counts for up to m most common ones\n\n args:\n texts: list of texts as list of list of words (or tags etc)\n n: 1 for unigram (default), 2 for bigram, 3 for trigram etc.\n m: upper limit for number of features; if none, all are returned\n\n returns:\n list of list of most common ngram counts, m x len(texts)\n \"\"\"\n # generate list of lists of ngrams for all texts\n ngrammed_texts = [list(ngrams(text, n)) for text in texts]\n\n # count ngrams in dictionaries, one for each text, plus one for sums\n cnts = []\n cnt_sum = defaultdict(int)\n for text in ngrammed_texts:\n cnts.append(defaultdict(int))\n i = len(cnts) - 1\n for ngram in text:\n cnts[i][ngram] += 1\n cnt_sum[ngram] += 1\n\n # create list of lists of counts for each text for the most common ngrams\n # first, sort the ngrams by total counts\n cnt_sorted = sorted(cnt_sum.items(), key=operator.itemgetter(1),\n reverse=True)\n # then, create the bag of ngrams (up to m), normalized by word count\n bon = []\n for ngram, total in cnt_sorted:\n counts = [cnt[ngram] for cnt in cnts]\n counts = [counts[i] / word_counts[i] for i in range(0, len(counts))]\n bon.append(counts)\n if m and len(bon) >= m:\n break\n return bon\n\n\n# def bag_of_char_ngrams(texts, n=1, m=None):\n# \"\"\" returns counts of up to m overall most common character ngrams for\n# each given text\"\"\"\n\n\ndef unique_words_ratio():\n \"\"\" returns #unique words / #words for each text\n\n uses stemmed words so 'eat' and 'eating' etc. are not treated as distinct\n (assuming they are stemmed correctly; 'eat' and 'ate' are still 'distinct');\n note that punctuation characters, parentheses etc. are treated as words\n \"\"\"\n return [[len(set(text)) / len(text) for text in stemmed_texts]]\n\n\ndef words_per_sentence():\n \"\"\" returns average number of words per sentence for each text\n\n uses the '.' POS tag to detect number of sentences to avoid treating '.' in\n abbreviations as sentence ends\n \"\"\"\n return [[word_counts[i] /\n (tagged_texts[i].count('.') if tagged_texts[i].count('.') > 0\n else 1)\n for i in range(0, len(word_counts))]]\n\n\ndef characters_per_words():\n \"\"\" returns average number of characters per word for each text\n\n note that character count includes punctuation, parentheses etc.\n \"\"\"\n return [[(len(source_texts[i]) - word_counts[i] + 1) / word_counts[i]\n for i in range(0, len(word_counts))]]\n\n\ndef topic_model_scores(num_topics):\n \"\"\" returns, for the top num_topics topics (lsi), the score for each text\n\n args:\n num_topics: number of topics (features) to consider\n \"\"\"\n dictionary = gensim.corpora.Dictionary(cropped_texts)\n corpus = [dictionary.doc2bow(text) for text in cropped_texts]\n tfidf = gensim.models.TfidfModel(corpus)\n corpus_tfidf = tfidf[corpus]\n lsi = gensim.models.lsimodel.LsiModel(corpus=corpus, id2word=dictionary,\n num_topics=num_topics)\n corpus_lsi = lsi[corpus_tfidf]\n\n return [[scores[i][1] if len(scores) > i else 0 for scores in corpus_lsi]\n for i in range(0, num_topics)]\n\n\ndef word2vec_avg():\n \"\"\" returns avg vector for words in each text \"\"\"\n global w2v_model\n w2v_model = gensim.models.KeyedVectors.load_word2vec_format(\n 'data/GoogleNews-vectors-negative300.bin.gz', binary=True)\n\n return [[sum(w2v_model[token][i] for token in text if token in w2v_model) /\n len(text)\n # use texts in original case (google word2vec is case sensitive)\n for text in tokenized_texts_case]\n for i in range(0, 50)]\n\n\ndef word2vec_max_val():\n \"\"\" returns vector of max value for each dim for all words in each text \"\"\"\n return [[max(w2v_model[token][i] for token in text if token in w2v_model)\n # use texts in original case (google word2vec is case sensitive)\n for text in tokenized_texts_case]\n for i in range(0, 50)]\n\n\ndef word2vec_avg_max_abs(n=5):\n \"\"\" returns avg of n vectors with max abs value for words in each text \"\"\"\n # compute absolute values for word vectors for words in each text\n abs_vals = [[[w2v_model[token],\n sqrt(sum(val * val for val in w2v_model[token]))]\n for token in text if token in w2v_model]\n for text in tokenized_texts_case]\n # sort vectors within texts by absolute values\n abs_vals_sorted = [sorted(vec_lst, key=operator.itemgetter(1), reverse=True)\n for vec_lst in abs_vals]\n # return average of top n vectors for each text\n return [[sum(vec_lst[j][0][i] for j in range(0, min(n, len(vec_lst)))) /\n min(n, len(vec_lst))\n for vec_lst in abs_vals_sorted]\n for i in range(0, 50)]\n\n\ndef liwc_scores():\n \"\"\" returns 93 liwc scores for each text\"\"\"\n def get_liwc_scores(text):\n \"\"\" aux function to handle the api call to liwc for a single text\"\"\"\n\n api_key = '58d00611e53b0b05af5239d6'\n api_secret = 'isYCnugw39h025UjvQe5ZCdCKhj1EgaAHjZjsIbPips'\n\n # hash + timestamp as identifer for each text\n # must be unique and texts apparently cannot be deleted after upload\n text_index = '%s_%s' % (\n hashlib.sha1(text.encode()).hexdigest(),\n time.time())\n\n headers = {\n 'X-API-KEY': api_key,\n 'X-API-SECRET-KEY': api_secret,\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n }\n\n data = {\n 'name': text_index,\n 'person_handle': text_index,\n 'gender': 0,\n 'content': {\n 'language_content': text\n }\n }\n\n response = requests.post('https://app.receptiviti.com/v2/api/person',\n headers=headers, data=json.dumps(data))\n if response.status_code != 200:\n if response.status_code == 429:\n raise Exception('LIWC API call failed, too many requests!')\n else:\n print(text)\n return numpy.zeros(93)\n # raise Exception('API call for LIWC scores failed!')\n\n liwc_raw = response.json()['contents'][0]['liwc_scores']\n # 7 keys directly contain a score, 1 key contains dict; flatten this\n liwc_tuples = [(key, val) for (key, val) in liwc_raw.items()\n if key != 'categories']\n liwc_tuples.extend([(key, val) for (key, val)\n in liwc_raw['categories'].items()])\n # return just the scores, sorted by their keys\n return [val for (key, val) in sorted(liwc_tuples, key=itemgetter(0))]\n\n text_scores = [get_liwc_scores(text) for text in source_texts]\n return [[scores[i] for scores in text_scores]\n for i in range(0, len(text_scores[0]))]\n\n\ndef extract_features(texts, conf, folder):\n \"\"\" extracts features in given conf from each text in given list of texts\n\n args:\n texts: list of texts from which to extract features\n conf: set of identifiers of features to be extracted; from conf file\n folder: which pickle folder\n\n returns:\n list of lists, #instances x #features = len(texts) x len(conf)\n \"\"\"\n\n global pfolder\n if folder == 0:\n pfolder = \"pickle_concat\"\n else:\n pfolder = \"pickle_ind\"\n\n global source_texts\n source_texts = texts\n preprocess()\n\n def load_or_compute(feature):\n global pfolder\n feat_data = []\n if os.path.exists('%s/%s.p' % (pfolder, feature)):\n with open('%s/%s.p' % (pfolder, feature), 'rb') as p_file:\n feat_data = pickle.load(p_file)\n else:\n if feature == 'bag_of_function_words':\n feat_data = bag_of_function_words()\n if feature == 'bag_of_pos_trigrams':\n feat_data = bag_of_ngrams(tagged_texts, 3, 500)\n if feature == 'bag_of_pos_bigrams':\n feat_data = bag_of_ngrams(tagged_texts, 2, 100)\n if feature == 'bag_of_pos_unigrams':\n feat_data = bag_of_ngrams(tagged_texts, 1, None)\n if feature == 'bag_of_trigrams':\n feat_data = bag_of_ngrams(stemmed_texts, 3, 500)\n if feature == 'bag_of_bigrams':\n feat_data = bag_of_ngrams(stemmed_texts, 2, 100)\n if feature == 'bag_of_unigrams':\n feat_data = bag_of_ngrams(stemmed_cropped_texts, 1, 100)\n if feature == 'characters_per_word':\n feat_data = characters_per_words()\n if feature == 'unique_words_ratio':\n feat_data = unique_words_ratio()\n if feature == 'words_per_sentence':\n feat_data = words_per_sentence()\n if feature == 'topic_model_scores':\n feat_data = topic_model_scores(20)\n if feature == 'word2vec_avg':\n feat_data = word2vec_avg()\n if feature == 'word2vec_max_val':\n feat_data = word2vec_max_val()\n if feature == 'word2vec_avg_max_abs':\n feat_data = word2vec_avg_max_abs()\n if feature == 'liwc_scores':\n feat_data = liwc_scores()\n if feature == 'char_unigram':\n feat_data = bag_of_ngrams(source_texts, 1, 100)\n if feature == 'char_bigram':\n feat_data = bag_of_ngrams(source_texts, 2, 100)\n if feature == 'char_trigram':\n feat_data = bag_of_ngrams(source_texts, 3, 500)\n with open('%s/%s.p' % (pfolder, feature), 'wb') as p_file:\n pickle.dump(feat_data, p_file)\n return feat_data\n\n all_features = conf is None or len(conf) == 0\n\n # names of all supported features\n supported_feats = ['bag_of_function_words', 'bag_of_pos_trigrams',\n 'bag_of_pos_bigrams', 'bag_of_pos_unigrams',\n 'bag_of_trigrams', 'bag_of_bigrams',\n 'bag_of_unigrams', 'topic_model_scores',\n 'characters_per_word', 'unique_words_ratio',\n 'words_per_sentence', 'word2vec_avg',\n 'word2vec_avg_max_abs', 'word2vec_max_val',\n 'liwc_scores', 'char_unigram',\n 'char_bigram', 'char_trigram']\n\n # features will be list of lists\n # each component list will have the same length as the list of input text\n features = []\n\n # for each feature, load pickle or compute values if there is no dump\n for feat in supported_feats:\n if all_features or feat in conf:\n features.extend(load_or_compute(feat))\n\n # transpose list of lists so its dimensions are #instances x #features\n return numpy.asarray(features).T.tolist()\n","sub_path":"feature_extractor.py","file_name":"feature_extractor.py","file_ext":"py","file_size_in_byte":16813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"537599380","text":"import torch\nfrom torch.autograd import Variable\n\nx_data=Variable(torch.Tensor([[1.0],[2.0],[3.0]]))\ny_data=Variable(torch.Tensor([[2.0],[4.0],[6.0]])) #3x1 matrix\n\nclass LinearModel(torch.nn.Module):\n def __index__(self):\n super(LinearModel, self).__init__()\n self.linear=torch.nn.Linear(1,1) #w,no need to know batch size\n def forward(self, x):\n y_pred=self.linear(x)\n return y_pred\n\nLmodel=LinearModel()\ncriterion=torch.nn.MSELoss(size_average=False)\noptimizer=torch.optim.SGD(Lmodel.parameters(),lr=0.01)\n\n\nfor epoch in range(500):\n y_pred=Lmodel(x_data)\n loss=criterion(y_pred,y_data)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n\n\nhour_var = Variable(torch.Tensor([[4.0]]))\ny_pred = Lmodel(hour_var)\nprint(\"predict (after training)\", 4, Lmodel(hour_var).data[0][0])","sub_path":"linearreg.py","file_name":"linearreg.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"536263259","text":"from django.conf.urls import patterns, url\n\nfrom charts import views\n\n__author__ = 'Samuel FLORES'\n\nurlpatterns = patterns('',\n # root of charts/\n url(r'^$', views.index, name='index'),\n #\n url(r'^(?P\\d+)/', views.hw_resources, name='host_url')\n )\n","sub_path":"web_interface/charts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"124605008","text":"import numpy as np\r\nimport pandas as pd\r\nimport pandas_datareader.data as web \r\nimport datetime\r\nimport matplotlib.pyplot as plt\r\n\r\nclass plot(object):\r\n\r\n def __init__(self, ticker, y1, m1, d1, y2, m2, d2):#choosing stock and period of backtesting, y1 - year of start date\r\n self.ticker=ticker\r\n self.y1=y1\r\n self.m1=m1\r\n self.d1=d1\r\n self.y2=y2\r\n self.m2=m2\r\n self.d2=d2\r\n\r\n def ma(self,s,l):\r\n\r\n start = datetime.datetime(self.y1,self.m1,self.d1)\r\n \r\n end = datetime.datetime(self.y2,self.m2,self.d2)\r\n\r\n dates=pd.date_range(start,end)\r\n df1=pd.DataFrame(index=dates)\r\n \r\n \r\n\r\n stock = web.DataReader(self.ticker, \"yahoo\", start, end)\r\n \r\n \r\n \r\n stock['short']=np.round(stock['Adj Close'].rolling(window=s).mean(),2)\r\n stock['long']=np.round(stock['Adj Close'].rolling(window=l).mean(),2)\r\n \r\n stock[['Adj Close','short','long']].plot(grid=True,figsize=(13,8))#employing plot function\r\n plt.ylabel('MA Crossover') \r\n return plt.show()\r\n\r\n def stochastic(self):#check\r\n \r\n start = datetime.datetime(self.y1,self.m1,self.d1)\r\n \r\n end = datetime.datetime(self.y2,self.m2,self.d2)\r\n\r\n dates=pd.date_range(start,end)\r\n df1=pd.DataFrame(index=dates)\r\n \r\n \r\n\r\n stock = web.DataReader(self.ticker, \"yahoo\", start, end)\r\n \r\n df1=df1.join(stock)\r\n\r\n \r\n\r\n stock['LL']=np.round(stock['Low'].rolling(window=14).min(),2) #Min of last 14 values of Low\r\n stock['HH']=np.round(stock['High'].rolling(window=14).max(),2)#Max of last 14 of High\r\n \r\n \r\n stock['K']=100*(stock['Adj Close'][13:]-stock['LL'][13:])/(stock['HH'][13:]-stock['LL'][13:]) #calculating K\r\n\r\n df2=stock['K'].dropna() # drop missing data\r\n\r\n\r\n D=np.round(df2.rolling(window=3).mean(),2).dropna()# calcualtio of D by given formula; dropping mising data\r\n\r\n #stock['Adj Close'].plot(grid=True,figsize=(10,6))\r\n D.plot(grid=True,figsize=(13,8))\r\n \r\n plt.ylabel('Stochastic Oscillator') \r\n return plt.show() \r\n","sub_path":"codes/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"394420280","text":"'''\n边框 最小矩形区域和最小闭圆的轮廓\n'''\n\nimport cv2\nimport numpy as np\n\n#处理借鉴 https://www.cnblogs.com/zyly/p/9327425.html\n\nimg = cv2.pyrDown(cv2.imread('E:/pic1.jpg', cv2.IMREAD_UNCHANGED))\n\n# 转换为灰色gray_img\ngray_img = cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY)\n\n# 对图像二值化处理 输入图像必须为单通道8位或32位浮点型\nret, thresh = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)\n\n# 寻找最外面的图像轮廓 返回修改后的图像 图像的轮廓 以及它们的层次\n#要想返回三个参数:把OpenCV 降级成3.4.3.18 就可以了,在终端输入pip install opencv-python==3.4.3.18\n# image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\ncontours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\nprint(type(contours))\nprint(type(contours[0]))\nprint(len(contours))\n\n# 遍历每一个轮廓\nfor c in contours:\n # 找到边界框的坐标\n x, y, w, h = cv2.boundingRect(c)\n # 在img图像上 绘制矩形 线条颜色为green 线宽为2\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n # 找到最小区域\n rect = cv2.minAreaRect(c)\n\n # 计算最小矩形的坐标\n box = cv2.boxPoints(rect)\n\n # 坐标转换为整数\n box = np.int0(box)\n\n # 绘制轮廓 最小矩形 blue\n cv2.drawContours(img, [box], 0, (255, 0, 0), 3)\n\n # 计算闭圆中心店和和半径\n (x, y), radius = cv2.minEnclosingCircle(c)\n\n # 转换为整型\n center = (int(x), int(y))\n radius = int(radius)\n\n # 绘制闭圆\n img = cv2.circle(img, center, radius, (0, 255, 0), 2)\n\ncv2.drawContours(img, contours, -1, (0, 0, 255), 2)\ncv2.imshow('contours', img)","sub_path":"ImageSolve/测试收纳/fc2.py","file_name":"fc2.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"87993715","text":"import pytest\nfrom django.contrib.auth import get_user_model\nfrom django.views.generic import ListView, DetailView\n\nfrom vprad.views.generic.mixin import ModelDataMixin\n\n\ndef test_model_data_mixin_get_model_or_object():\n class AListView(ModelDataMixin, ListView):\n model = get_user_model()\n\n class ADetailView(ModelDataMixin, DetailView):\n model = get_user_model()\n\n list = AListView()\n assert list._get_model_or_object() == get_user_model()\n detail = ADetailView()\n with pytest.raises(AttributeError):\n # .get_object() has not been called,\n # so .object should raise an AttributeError\n detail._get_model_or_object()\n\n\ndef test_get_headline_object(db):\n class ADetailView(ModelDataMixin, DetailView):\n model = get_user_model()\n\n object = get_user_model()()\n object.a_headline = 'a_headline'\n object.a_headline_callable = lambda: 'a_callable'\n view = ADetailView()\n\n view.object = object\n assert view.get_headline() == ''\n view.headline = 'a_headline'\n assert view.get_headline() == 'a_headline'\n view.headline = 'a_headline_callable'\n assert view.get_headline() == 'a_callable'\n\n\ndef test_get_headline_model(db):\n class AListView(ModelDataMixin, ListView):\n model = get_user_model()\n\n model = get_user_model()\n model.b_headline = 'b_headline'\n model.b_headline_callable = lambda: 'b_callable'\n view = AListView()\n\n assert view.get_headline() == 'user list'\n view.headline = 'b_headline'\n assert view.get_headline() == 'b_headline'\n view.headline = 'b_headline_callable'\n assert view.get_headline() == 'b_callable'\n del model.b_headline\n del model.b_headline_callable\n\n\ndef test_get_headline_subtitle(db):\n class ADetailView(ModelDataMixin, DetailView):\n model = get_user_model()\n\n object = get_user_model()()\n object.a_subtitle = 'a_subtitle'\n object.a_subtitle_callable = lambda: 'a_callable'\n view = ADetailView()\n\n view.object = object\n assert view.get_headline_subtitle() == '-'\n view.headline_subtitle = 'a_subtitle'\n assert view.get_headline_subtitle() == 'a_subtitle'\n view.headline_subtitle = 'a_subtitle_callable'\n assert view.get_headline_subtitle() == 'a_callable'\n\n","sub_path":"tests/views/test_mixin_modeldata.py","file_name":"test_mixin_modeldata.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"143233186","text":"\"\"\"\n.. module: security_monkey.views.poam\n :platform: Unix\n\n.. version:: $$VERSION$$\n.. moduleauthor:: Pritam D. Gautam @nuagedm\n\n\"\"\"\nfrom sqlalchemy.orm import joinedload, aliased, load_only, defer\n\nfrom security_monkey import db, rbac\nfrom security_monkey.views import AuthenticatedService\nfrom security_monkey.datastore import Item, ItemAudit, Account, Technology, ItemRevision\nfrom sqlalchemy import func, text, null as sqlnull, false, between\n\n\ndef sev2score(score):\n if score < 5:\n return \"Low\"\n elif score > 10:\n return \"High\"\n else:\n return \"Medium\"\n\n\n# Get a List of POA&M Items\nclass POAMItemList(AuthenticatedService):\n decorators = [rbac.allow(['View'], [\"GET\"])]\n\n\n def get(self):\n \"\"\"\n .. http:get:: /api/1/poamitems\n\n Get a List of POA&M Items by account.\n\n **Example Request**:\n\n .. sourcecode:: http\n\n GET /api/1/poamitems HTTP/1.1\n Host: example.com\n Accept: application/json\n\n **Example Response**:\n\n .. sourcecode:: http\n\n HTTP/1.1 200 OK\n Vary: Accept\n Content-Type: application/json\n\n {\n \"items\": [\n {\n \"control\": \"policy\",\n \"create_date\": \"2017-11-01 19:29:52.329638\",\n \"poam_comments\": null,\n \"poam_id\": \"sa_poam-12868\",\n \"item_id\": \"\",\n \"account\": \"DEV\",\n \"score\": 10,\n \"weakness_description\": \"Service [iam] Category: [Permissions] Resources: [\\\"*\\\"], universal, ServiceCatalogAdmin-SupplementalPermissions\",\n \"weakness_name\": \"Sensitive Permissions\"\n }\n ],\n \"total\": 1,\n \"page\": 1,\n \"count\" 1,\n \"auth\": {\n \"authenticated\": true,\n \"user\": \"user@example.com\"\n }\n }\n\n :statuscode 200: no error\n :statuscode 401: Authentication Error. Please Login.\n \"\"\"\n\n # SQL Query base for implementation\n # select\n # distinct concat('sa_poam-', ia.id) as \"poam_id\",\n # i.id as \"item_id\",\n # acc.name as \"account\",\n # t.name as \"control\",\n # ia.issue as \"weakness_name\",\n # concat(\n # ia.notes, ', ', i.region, ', ', i.name\n # ) as \"weakness_description\",\n # ia.score,\n # ir.create_date,\n # ia.action_instructions as \"poam_comments\"\n # from\n # item i\n # inner join itemaudit ia ON i.id = ia.item_id\n # and (\n # (i.account_id in (select a.id from account a where a.\"name\" in (p_account_id)) )\n # or (p_account_id is null)\n # )\n # inner join technology t ON i.tech_id = t.id\n # inner join (\n # select\n # item_id,\n # min(date_created) as \"create_date\"\n # from\n # itemrevision\n # group by\n # item_id\n # ) ir on i.id = ir.item_id\n # inner join account acc ON i.account_id = acc.id\n # where\n # ia.justified = FALSE\n # and ia.fixed = FALSE\n # and i.arn is not null\n # and ia.score > 1\n # order by\n # ir.create_date asc,\n # ia.score desc\n\n self.reqparse.add_argument('accounts', type=str, default=None, location='args')\n self.reqparse.add_argument('count', type=int, default=10, location='args')\n self.reqparse.add_argument('page', type=int, default=1, location='args')\n self.reqparse.add_argument('sev', type=str, default=None, location='args')\n self.reqparse.add_argument('tech', type=str, default=None, location='args')\n\n args = self.reqparse.parse_args()\n page = args.pop('page', None)\n count = args.pop('count', None)\n for k, v in args.items():\n if not v:\n del args[k]\n\n # Read more about filtering:\n # https://docs.sqlalchemy.org/en/latest/orm/query.html\n query = Item.query.join((ItemAudit, Item.id == ItemAudit.item_id)) \\\n .options(load_only(Item.id)) \\\n .distinct()\n query = query.join((Technology, Technology.id == Item.tech_id))\n\n # Subquery on ItemRevision Table\n itemrevision_subquery = db.session \\\n .query(ItemRevision, func.min(ItemRevision.date_created).label('create_date')) \\\n .options(load_only(\"item_id\")) \\\n .group_by(ItemRevision.item_id) \\\n .subquery()\n\n query = query.join(itemrevision_subquery, Item.id == itemrevision_subquery.c.item_id)\n query = query.join((Account, Account.id == Item.account_id))\n\n # Add Select Columns\n query = query \\\n .add_column(func.concat('sa_poam-', ItemAudit.id).label('poam_id')) \\\n .add_column(Account.name.label('account')) \\\n .add_column(Technology.name.label('control')) \\\n .add_column(ItemAudit.issue.label('weakness_name')) \\\n .add_column(func.concat(ItemAudit.notes, ',', Item.region, ',', Item.name).label('weakness_description')) \\\n .add_column(ItemAudit.score.label('score')) \\\n .add_column(itemrevision_subquery.c.create_date.label('create_date')) \\\n .add_column(ItemAudit.action_instructions.label('poam_comments'))\n\n # Filters\n query = query.filter(ItemAudit.justified == false())\n query = query.filter(ItemAudit.fixed == false())\n query = query.filter(ItemAudit.score > 1)\n query = query.filter(Item.arn != sqlnull())\n\n if 'accounts' in args:\n accounts = args['accounts'].split(',')\n query = query.filter(Account.name.in_(accounts))\n\n if 'sev' in args:\n sev = args['sev'].lower()\n if sev == 'low':\n query = query.filter(ItemAudit.score < 5)\n elif sev == 'medium':\n query = query.filter(between(ItemAudit.score, 5, 10))\n elif sev == 'high':\n query = query.filter(ItemAudit.score > 10)\n\n if 'tech' in args:\n tech = args['tech'].split(',')\n query = query.join((Technology, Technology.id == Item.tech_id))\n query = query.filter(Technology.name.in_(tech))\n\n\n\n # Order By\n query = query.order_by(itemrevision_subquery.c.create_date)\n query = query.order_by(ItemAudit.score.desc())\n\n # Eager load the joins\n query = query.options(joinedload('account'))\n query = query.options(joinedload('technology'))\n\n # Paginate\n items = query.paginate(page, count)\n\n marshaled_dict = {\n 'page': items.page,\n 'total': items.total,\n 'auth': self.auth_dict\n }\n\n marshaled_items = []\n for row in items.items:\n row_dict = dict(row.__dict__)\n marshaled_items.append({\n 'poam_id': row_dict['poam_id'],\n 'item_id': row_dict['Item'].id,\n 'account': row_dict['account'],\n 'control': row_dict['control'],\n 'weakness_name': row_dict['weakness_name'],\n 'weakness_description': row_dict['weakness_description'],\n 'score': row_dict['score'],\n 'sev': sev2score(row_dict['score']),\n 'create_date': str(row_dict['create_date']),\n 'poam_comments': row_dict['poam_comments']\n })\n\n marshaled_dict['items'] = marshaled_items\n marshaled_dict['count'] = len(marshaled_items)\n\n return marshaled_dict, 200\n","sub_path":"security_monkey/views/poam.py","file_name":"poam.py","file_ext":"py","file_size_in_byte":8283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"598156005","text":"# Authored by Jaison, minor edits by Lizzie\nfrom django.db import models\nimport datetime\nfrom users.models import UserProfile, FriendRequest\nfrom sport.models import Sport\n\nSUCCESS = 1\nINVALID_CREATOR = -1\nINVALID_NEW_PLAYER = -2\nGAME_DNE = -3\nINVALID_INVITER = -4\nINVALID_INVITEE = -5\nINVALID_PLAYER = -6\nINVALID_NEW_TIME = -7\nINVALID_LOCATION = -8\n\nclass Game(models.Model):\n\tMAX_NAME_LENGTH = 100\n\tMAX_LOCATION_LENGTH = 2000\n\n\tname = models.CharField(max_length=MAX_NAME_LENGTH)\n\thost = models.ForeignKey(UserProfile, related_name='gameHost', default=None)\n\tsport = models.ForeignKey(Sport, related_name='gamelist', default=None)\n\ttime = models.DateTimeField(default=datetime.datetime.now)\n\tplayers = models.ManyToManyField(UserProfile, related_name = 'gamePlayers', default=None)\n\tlocation = models.CharField(max_length = MAX_LOCATION_LENGTH)\n\n\t#players_request = models.ManyToManyField(UserProfile, related_name = 'gameInvites', default=None)\n\t\n\n\tdef createGame(self, name, host, sport, time, location):\n\t\ttry:\n\t\t\thostObject = UserProfile.objects.get(username = host)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn (INVALID_CREATOR, None)\n\t\ttry:\n\t\t\tsport_obj = Sport.objects.get(name = sport)\n\t\texcept Sport.DoesNotExist:\n\t\t\tsport_obj = Sport.objects.create(name = sport)\n\t\ttime_obj = datetime.datetime.strptime(time, \"%m/%d/%Y %I:%M %p\")\n\t\tnew_game = Game(name=name, host=hostObject, sport=sport_obj, time = time_obj, location=location)\n\t\tnew_game.save()\n\t\tnew_game.players.add(hostObject)\n\t\tUserProfile().addActivity(host, \"creat\", new_game) #took off \"e\" in \"create\" so it says \"created\" instead of \"createed\" on newsfeed\n\t\treturn (SUCCESS, new_game.id)\n\n\n\tdef addPlayer(self, game, newPlayer):\n\t\ttry:\n\t\t\tnp = UserProfile.objects.get(username = newPlayer)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn INVALID_NEW_PLAYER\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn GAME_DNE\n\t\tgame_obj.players.add(np)\n\t\treturn SUCCESS\n\n\tdef invitePlayer(self, game, inviter, invitee):\n\t\ttry:\n\t\t\tinviter_obj = UserProfile.objects.get(username = inviter)\n\t\texcept UserProfile.DoesNotExist as e:\n\t\t\treturn INVALID_INVITER\n\n\t\ttry:\n\t\t\tinvitee_obj = UserProfile.objects.get(username = invitee)\n\t\texcept UserProfile.DoesNotExist as e:\n\t\t\treturn INVALID_INVITEE\n\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn GAME_DNE\n\n\t\ttry:\n\t\t\tgame_obj.players.get(username = inviter)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn INVALID_INVITER\n\n\t\texist=game_obj.players.filter(username=invitee)\n\n\t\tc=GameRequest.objects.filter(inviter= inviter, invitee=invitee, gameID=game)\n\t\tif c.count()==0 and exist.count()==0:\n\t\t\tnewreq=GameRequest.objects.create(inviter=inviter, invitee=invitee, gameID=game, game_obj=game_obj)\n\t\t\tnewreq.save()\n\t\t\treturn SUCCESS\n\t\telse:\n\t\t\treturn SUCCESS\n\n\tdef acceptinvite(self, game, inviter, invitee):\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn (GAME_DNE, game, inviter)\n\n\t\tif GameRequest.objects.filter(inviter = inviter, invitee=invitee, gameID=game)!=0:\n\t\t\t#game_obj.join(invitee, game)\n\t\t\treq = GameRequest.objects.get(inviter = inviter, invitee=invitee, gameID=game)\n\t\t\treq.delete()\n\t\t\treturn (SUCCESS, game, inviter)\n\t\telse:\n\t\t\treturn (INVALID_INVITEE, game, inviter)\n\n\tdef rejectinvite(self, game, inviter, invitee):\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn (GAME_DNE, game, inviter)\n\n\t\tif GameRequest.objects.filter(inviter = inviter, invitee=invitee, gameID=game).count()!=0:\n\t\t\treq = GameRequest.objects.get(inviter = inviter, invitee=invitee, gameID=game)\n\t\t\treq.delete()\n\t\t\treturn (SUCCESS, game, inviter)\n\t\telse:\n\t\t\treturn (INVALID_INVITEE, game, inviter)\n\t\t\t#return (INVALID_INVITEE, game, inviter)\n\n\tdef removePlayer(self, game, player):\n\t\ttry:\n\t\t\tp = UserProfile.objects.get(username = player)\n\t\texcept UserProfile.DoesNotExist as e:\n\t\t\treturn INVALID_PLAYER\n\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn GAME_DNE\n\n\t\ttry:\n\t\t\tgame_obj.players.get(username = player)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn INVALID_PLAYER\n\n\t\tgame_obj.players.remove(p)\n\t\treturn SUCCESS\n\n\tdef gameTimeChange(self, game, newTime):\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn GAME_DNE\n\t\ttime_obj = datetime.datetime.strptime(newTime, \"%m/%d/%Y %I:%M %p\")\n\n\t\tgame_obj.time = time_obj\n\n\t\tgame_obj.save()\n\t\treturn SUCCESS\n\n\tdef gameLocationChange(self, gameID, newLocation):\n\n\t\tif newLocation == \"\":\n\t\t\treturn INVALID_LOCATION\n\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = gameID)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn GAME_DNE\n\t\tgame_obj.location = newLocation\n\t\tgame_obj.save()\n\n\t\treturn SUCCESS\n\n\tdef joinGame(self, username, gameID):\n\t\ttry:\n\t\t\tgame_obj=Game.objects.get(id=gameID)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn (UserProfile.GAME_DNE, None)\n\n\t\trev = game_obj.addPlayer(gameID, username)\n\t\tif rev < 0:\n\t\t\treturn (UserProfile.INVALID_USERNAME, None)\n\t\tUserProfile().addActivity(username, \"join\", game_obj)\n\t\treturn (UserProfile.SUCCESS, game_obj.id)\n\n\tdef unjoinGame(self, username, game):\n\t\ttry:\n\t\t\tgame_obj=Game.objects.get(id=game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn UserProfile.GAME_DNE\n\n\t\trev = game_obj.removePlayer(game, username)\n\n\t\tif rev < 0:\n\t\t\treturn UserProfile.INVALID_USERNAME\n\t\treturn UserProfile.SUCCESS\n\n\tdef changeHost(self, username, newhost, gameID):\n\t\ttry:\n\t\t\tgame_obj=Game.objects.get(id=gameID)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn UserProfile.GAME_DNE\n\n\t\ttry:\n\t\t\thost_obj=UserProfile.objects.get(username = newhost)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn INVALID_PLAYER\n\n\t\ttry:\n\t\t\tuser_obj=UserProfile.objects.get(username = username)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn INVALID_PLAYER\n\n\n\t\tif user_obj==game_obj.host and user_obj!=host_obj:\n\t\t\tgame_obj.host = host_obj\n\t\t\tgame_obj.save()\n\t\t\treturn SUCCESS\n\t\telse:\n\t\t\treturn INVALID_PLAYER\n\n\tdef TESTAPI_reset(self):\n\t\t\"\"\"\n\t\tReset all user tables.\n\t\t\"\"\"\n\t\t#UserProfile.objects.all().delete()\n\t\t#Game.objects.all().delete()\n\t\tGameRequest.objects.all().delete()\n\t\t#Sport.objects.all().delete()\n\t\treturn SUCCESS\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\nclass GameRequest(models.Model):\n\tinviter= models.CharField(max_length=UserProfile.MAX_USERNAME_LENGTH)\n\tinvitee= models.CharField(max_length=UserProfile.MAX_USERNAME_LENGTH)\n\tgameID= models.IntegerField()\n\tgame_obj= models.ForeignKey(Game, related_name='gamereq', default=None)\n\n\t#objects=models.Manager()\n\tdef invitesToUser(self, username):\n\t\ttry:\n\t\t\treq = GameRequest.objects.filter(invitee=username)\n\t\texcept GameRequest.DoesNotExist as e:\n\t\t\treq = None\n\t\treturn req","sub_path":"game/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"406275049","text":"# -*- coding: utf-8 -*-\n# 3.0\n\n# \n\n# Generation 2 CSV file builder library for CEPALStat\n\n# \n\n# This script creates csv files out of CEPALStat data, in a format suitable for subsequent loading to the Statmart database. Each country with an available time series will have two csv files representing their data. The first contains the time series data, and the second will contain metadata about the time series. Additionally, the file \"\\_PREFIX.csv\" will be created to list all the created files.\n\n# \n\n# A full set of stats for an indicator is stored in a file called XXX_all.csv, where XXX is the ID of the indicator, as found in CEPALStat\n\n# \n\nimport os, imp, sys, traceback\nimport pandas as pd\n\nfrom settings_statmart import *\nimport utils_statmart as us\nimport gen1_cepalstat\n\n# \n\n\n# \n\ndef parse_meta_file(metafile):\n metamap = {}\n \n mf = pd.read_csv(metafile, encoding=\"utf-8\")\n source = mf.ix[mf[\"Key\"] == \"source\"][\"Value\"]\n if len(source) > 0:\n metamap[\"source\"] = clip_period(source[source.index[0]].strip())\n \n indicator = mf.loc[mf[\"Key\"] == \"indicator\"][\"Value\"]\n metamap[\"indicator\"] = clip_period(indicator[indicator.index[0]].strip())\n \n definition = mf.loc[mf[\"Key\"] == \"definition\"][\"Value\"]\n if len(\"definition\") > 0:\n metamap[\"definition\"] = clip_period(definition[definition.index[0]].strip())\n \n nf = mf.loc[mf[\"Key\"] == \"note\"][[\"ID\",\"Value\"]]\n nf = nf.set_index([\"ID\"])\n\n for index in us.get_index_set(nf):\n note = nf.ix[index][\"Value\"].strip()\n note = clip_period(note)\n metamap[str(index)] = note\n return metamap\n\ndef get_notes(notes, mmap):\n if notes == \"nan\":\n return \"\"\n notes = notes.split(\",\")\n mynotes = []\n for note in notes:\n if note in mmap:\n mynotes.append(note)\n return \"|\".join(map(lambda x : mmap[str(x)], mynotes))\n\ndef clip_period(str):\n if str[-1] == \".\":\n str = str[0:-1] \n return str\n\n# \n\ndef build_files(df, config):\n filelist = []\n countrylist = []\n for iso3 in us.get_index_set(df):\n try:\n idf = df.ix[iso3]\n if type(idf) == pd.Series: #idf a Series if there is only one element in it, but we want a DataFrame always\n idf = pd.DataFrame([idf])\n idf = idf[[\"Year\",\"Value\",\"Source\",\"Notes\"]]\n idf.columns = [\"year\",\"value\",\"source\",\"note\"]\n mult = config[\"multiplier\"]\n if mult:\n if (mult <= 1 and mult >= -1) or not type(mult) is int:\n idf[\"value\"] = idf[\"value\"].apply(lambda x : x * mult)\n else:\n idf[\"value\"] = idf[\"value\"].apply(lambda x : int(x * mult)).astype(object)\n idf[\"source\"] = idf[\"source\"].apply(lambda x : config[\"source\"])\n idf[\"note\"] = idf[\"note\"].apply(lambda x : get_notes(str(x), config))\n filestem = config[\"prefix\"] + \"_\" + iso3.lower() + \"_\" + config[\"suffix\"]\n filename = filestem + \".csv\"\n filepath = config[\"gen_2_dir\"] + filename\n us.log(filepath)\n idf.to_csv(filepath, encoding=\"utf8\", index=False)\n \n country = us.get_country_by_iso3(iso3) \n meta = [(\"name\", \"%s - %s [CEPALStat]\" % (country, config[\"indicator\"])),\n (\"originalsource\", config[\"source\"]),\n (\"proximatesource\", \"CEPALStat\"),\n (\"dataset\", config[\"indicator\"] + \" [\" + config[\"indicator_id\"] + \"]\"),\n (\"description\", config[\"definition\"]),\n (\"category\", config[\"indicator_category\"]),\n (\"type\", config[\"indicator_type\"]),\n (\"file\", filename),\n (\"filehash\", us.githash(filepath)),\n (\"columns\", \"year,value,source,notes\")\n ]\n \n metafile = config[\"gen_2_dir\"] + filestem + \"_meta.csv\" \n pd.DataFrame(meta,columns = [\"key\",\"value\"]).to_csv(metafile, encoding=\"utf8\", float_format='%.3f',index=False)\n filelist.append([filestem])\n countrylist.append(country)\n except Exception as strerror:\n us.log(\"ERROR: Failed to build data for %s\" % iso3)\n us.log(sys.exc_info())\n traceback.print_tb(sys.exc_info()[2])\n \n fldf = pd.DataFrame(filelist, index=countrylist).sort_index()\n fldf.to_csv(config[\"gen_2_dir\"] + \"_\" + config[\"prefix\"] + \".csv\", encoding=\"utf8\", float_format='%.1f', index=False, header=False)\n return fldf\n\n# \n\n# This is what gets called by build scripts. The config object should contain all required variables; it can be generated using utils_statmart.build_config().\n\n# \n\ndef build(config):\n statfile = config[\"gen_1_dir\"] + config[\"indicator_id\"] + \"_all.csv\"\n df = pd.read_csv(statfile, encoding=\"utf-8\", index_col=[\"ISO3\"], dtype={'Notes':'object'} )\n metafile = config[\"gen_1_dir\"] + config[\"indicator_id\"] + \"_meta.csv\"\n metamap = parse_meta_file(metafile)\n metamap.update(config) # this enables customizations in config to override entries in the meta file\n report = build_files(df, metamap)\n us.log(\"%i series saved to %s\" % (len(report), config[\"gen_2_dir\"]))\n return report\n \n\n","sub_path":"scripts/gen2_cepalstat.py","file_name":"gen2_cepalstat.py","file_ext":"py","file_size_in_byte":5381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"69956076","text":"# 중위표기식 -> 후위표기식\ndef ISP(char): # in-stack priority\n lst = ['(', '+-', '*/', 'blank']\n for i in lst:\n if char in i:\n return lst.index(i)\n\ndef ICP(char): # in-coming priority\n lst = ['blank', '+-', '*/', '(']\n for i in lst:\n if char in i:\n return lst.index(i)\n\ndef Postfix(expression):\n operands = '0123456789'\n result = ''\n stack = []\n\n for i in expression:\n if i in operands: # 피연산자\n result += i\n else: # 연산자와 괄호\n if i == ')': # 연산자와 괄호 중 ')'\n if not stack:\n return 'Error'\n else:\n top = stack.pop()\n while top != '(':\n result += top\n if stack: top = stack.pop()\n if top != '(' and not stack:\n return 'Error'\n else: # 연산자와 괄호 중 ')'을 제외한 것들\n if not stack:\n stack.append(i)\n elif ISP(stack[-1]) <= ICP(i):\n if ISP(stack[-1]) == ICP(i):\n result += stack.pop()\n stack.append(i)\n else:\n result += i\n\n if stack: return 'Error'\n return result\n\ndef add(a, b):\n return a + b\ndef subtract(a, b):\n return a - b\ndef multiply(a, b):\n return a * b\ndef divide(a, b):\n if b: return a // b\n\ndef Cal_Postfix(expression):\n stack = []\n operands = '0123456789'\n\n if expression == 'Error': return '잘못된 입력입니다.'\n else:\n for i in expression:\n if i in operands:\n stack.append(int(i))\n else:\n right = stack.pop()\n left = stack.pop()\n temp = 0\n if i == '+': temp = add(left, right)\n elif i == '-': temp = subtract(left, right)\n elif i == '*': temp = multiply(left, right)\n else: temp = divide(left, right)\n stack.append(temp)\n return stack.pop()\n\nexpression = '(6+5*(2-8)/2)'\nexpression2 = '(6+5*(2-8))/2)'\nexpression3 = ')(6+5*(2-8)/2)'\nexpression4 = '((6+5*(2-8)/2)'\n\nprint(Postfix(expression))\nprint(Postfix(expression2))\nprint(Postfix(expression3))\nprint(Postfix(expression4))\nprint()\nprint(Cal_Postfix(Postfix(expression)))\nprint(Cal_Postfix(Postfix(expression2)))","sub_path":"python/swea/intermediate/Stack2_Calculator.py","file_name":"Stack2_Calculator.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"32453833","text":"import requests\nimport errorhandling as err\n\ndef search_place(key,query):\n \n url_search =\"https://maps.googleapis.com/maps/api/place/textsearch/json\"\n search = {\"key\":key,\"query\":query}\n search_req = requests.get(url_search,params=search)\n print(\"status code search:\",search_req.status_code)\n\n search_json = search_req.json()\n \n err.error_handling(search_json[\"status\"])\n place_id = search_json[\"results\"][0][\"place_id\"]\n return place_id\n\n\ndef search_details(key,place_id):\n \n url_detail = \"https://maps.googleapis.com/maps/api/place/details/json\"\n details = {\"key\":key,\"place_id\":place_id}\n detail_req = requests.get(url_detail,params=details)\n\n print(\"status code details:\",detail_req.status_code)\n detail_json = detail_req.json()\n err.error_handling(detail_json[\"status\"])\n\n return detail_json\n \n\ndef searchapi(key,query,param='search'):\n try: \n place_id= search_place(key,query)\n details= search_details(key,place_id)\n if param=='search':\n return details\n \n elif param=='url':\n return details[\"result\"][\"url\"]\n \n elif param=='address':\n return details[\"result\"][\"adr_address\"]\n\n elif param=='geometry':\n return details[\"result\"][\"geometry\"]\n\n \n except err.ZeroResultError as e:\n message = {\n 'status_code':404,\n 'message':e.msg,\n 'status':e.status, 'html_attributions':[]\n }\n return message\n\n except err.OverQueryError as e:\n message = {\n 'status_code':429, \n 'message':e.msg,\n 'status':e.status, 'html_attributions':[]\n }\n return message\n\n except err.RequestDeniedError as e:\n message = {\n 'status_code':401, \n 'message':e.msg,\n 'status':e.status,'html_attributions':[]\n }\n return message\n\n except err.InvalidRequestError as e:\n message = {\n 'status_code':400, \n 'message':e.msg,\n 'status':e.status, 'html_attributions':[]\n }\n return message\n \n except err.UnknownError as e:\n message = {\n 'status_code':400, \n 'message':e.msg,\n 'status':e.status, 'html_attributions':[]\n }\n return message\n\n except err.NotFoundError as e:\n message = {\n 'status_code':404, \n 'message':e.msg,\n 'status':e.status, 'html_attributions':[]\n }\n return message\n","sub_path":"SearchPlaceDetails/searchAPI.py","file_name":"searchAPI.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"351254620","text":"from django.shortcuts import render, render_to_response, redirect\nfrom django.http import HttpResponse\nfrom problem.models import Problem, ParamResource, TypeParam, ResourceScript, Logical, Resource, LogicalClass, Process, ConnectShape, ClassResource, Script, ProcessScript, ClassProcess, Product, ProductScript, Event, EventScript, User\nfrom problem.forms import addProblem\nfrom django.core.context_processors import csrf\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.contrib.auth.models import User\nimport simplejson\n\n# Create your views here.\ndef all(request):\n arg = Problem.objects.all()\n return render_to_response('all.html', {'arg': arg})\n\n\ndef add(request):\n args = {}\n args.update(csrf(request))\n args['form'] = addProblem()\n if request.POST:\n form = addProblem(request.POST)\n args['form'] = form\n if form.is_valid():\n form.save()\n return HttpResponse('vse OK!')\n else:\n return render_to_response('add.html', args)\n return render_to_response('add.html', args)\n\ndef monitoring(request):\n problems = Problem.objects.all()\n return render_to_response('monitoring.html',{'problems': problems})\n\ndef getprobleminfo(request,problem_id=1):\n try:\n arg = Problem.objects.get(id=problem_id)\n except:\n arg = {}\n return render_to_response('problem.html',{'arg': arg})\n\ndef getproblem(request,problem_id=1):\n if request.is_ajax():\n script = Script.objects.get(problem_id=problem_id)\n functions = ProcessScript.objects.filter(script=script)\n return HttpResponse(simplejson.dumps( [{'process': op.process.name} for op in functions] ),\n content_type=\"application/json\")\n args = []\n return render_to_response('get.html',{'args': args})\n\ndef getproblema(request, problem_id=1):\n problem = Problem.objects.get(id=problem_id)\n script = Script.objects.get(problem=problem)\n data = ProcessScript.objects.filter(script=script)\n data2 = ConnectShape.objects.filter(script=script)\n data3 = ProductScript.objects.filter(script=script)\n data4 = EventScript.objects.filter(script=script)\n data5 = Logical.objects.filter(script=script)\n data6 = ResourceScript.objects.filter(script=script)\n return HttpResponse(simplejson.dumps( {\"functions\":[{'xUser': op.xUser,\n 'idProcess': op.idScriptProcess,\n 'idUser': op.idScriptMan,\n 'yUser': op.yUser,\n 'xProcess': op.xProcess,\n 'yProcess': op.yProcess,\n 'user': op.user.username,\n 'datefinish': op.finish,\n 'datestart': op.start,\n 'url': op.url,\n 'name': op.process.name,\n 'class': op.process.classProcess.name,\n 'status': op.status} for op in data],\n \"connect\":[{'from': op.idFrom,\n 'to': op.idTo} for op in data2],\n \"products\":[{'id': op.idProduct,\n 'name': op.product.name,\n 'x': op.x,\n 'y': op.y,\n 'class': op.product.classProduct.name} for op in data3],\n \"resource\":[{'id': op.idResource,\n 'name': op.resource.name,\n 'x': op.x,\n 'y': op.y,\n 'class': op.resource.classResource.name} for op in data6],\n \"events\":[{'id': op.idEvent,\n 'name': op.event.name,\n 'x': op.x,\n 'y': op.y} for op in data4],\n \"logicals\":[{'id': op.idLogical,\n 'name': op.classLogical.name,\n 'x': op.x,\n 'y': op.y} for op in data5]} ),\n content_type=\"application/json\")\n\ndef adminproblem(request,problem_id=1):\n if request.is_ajax():\n return HttpResponse('lol')\n else:\n try:\n arg = Problem.objects.get(id=problem_id)\n except:\n arg = {}\n return render_to_response('admin.html', {'arg': arg})\n\ndef getFunctionList(request): #получить список классов функций\n if request.is_ajax():\n classProduct = request.GET.get('classProduct')\n data = ClassProcess.objects.all()\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getProcessList(request):\n if request.is_ajax():\n if request.GET.get('class'):\n cls = ClassProcess.objects.get(name=request.GET.get('class'))\n data = Process.objects.filter(classProcess=cls)\n else:\n cls = ClassProcess.objects.all()\n data = Process.objects.filter(classProcess=cls[0])\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getEventList(request):\n if request.is_ajax():\n data = Event.objects.all()\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getParamResource(request):\n if request.is_ajax():\n type = TypeParam.objects.get(name=request.GET.get('class'))\n resource = Resource.objects.get(name=request.GET.get('name'))\n data = ParamResource.objects.filter(resource=resource, type=type)\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getResource(request):\n if request.is_ajax():\n if request.GET.get('class'):\n cls = ClassResource.objects.get(name=request.GET.get('class'))\n data = Resource.objects.filter(classResource=cls)\n else:\n cls = ClassResource.objects.all()\n data = Resource.objects.filter(classResource=cls[0])\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getResourceList(request): #получить список классов ресурсов\\продуктов\n if request.is_ajax():\n data = ClassResource.objects.all()\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getUserList(request): #получить список исполнителей\n if request.is_ajax():\n data = User.objects.all()\n return HttpResponse(simplejson.dumps( [{'name': op.username} for op in data] ),\n content_type=\"application/json\")\n\ndef addNewScript(request, problem_id=1):\n if request.is_ajax():\n data = request.GET.get('json')\n data = simplejson.loads(data)\n key = 0\n try: #удаляем предыдущий сценарий для проблемы и создаем новый\n script = Script.objects.get(problem_id=problem_id)\n script.delete()\n script = Script(problem_id=problem_id)\n except: #создаем новый сценарий\n script = Script(problem_id=problem_id)\n script.save()\n while key < len(data[\"functions\"]): #записываем множество функций\n try:\n process = Process.objects.get(name=data[\"functions\"][key][\"name\"])\n except:\n classProcess = ClassProcess.objects.get(id=6)\n #classProcess = ClassProcess.objects.get(name=data[\"functions\"][key][\"class\"])\n process = Process(name=data[\"functions\"][key][\"name\"],\n classProcess=classProcess)\n process.save()\n user = User.objects.get(username=data[\"functions\"][key][\"user\"])\n connect = ProcessScript(\n user=user,\n script=script,\n process=process,\n url=data[\"functions\"][key][\"url\"],\n start=data[\"functions\"][key][\"start\"],\n finish=data[\"functions\"][key][\"finish\"],\n xProcess=data[\"functions\"][key][\"position\"][\"x\"],\n yProcess=data[\"functions\"][key][\"position\"][\"y\"],\n xUser=data[\"functions\"][key][\"positionUser\"][\"x\"],\n yUser=data[\"functions\"][key][\"positionUser\"][\"y\"],\n idScriptProcess=data[\"functions\"][key][\"idProcess\"],\n status=data[\"functions\"][key][\"status\"],\n idScriptMan=data[\"functions\"][key][\"idUser\"]);\n connect.save()\n key = key + 1\n key = 0\n while key < len(data[\"products\"]): #создаем множество продуктов\n try:\n product = Process.objects.get(name=data[\"products\"][key][\"name\"])\n except:\n classProduct = ClassResource.objects.get(name=data[\"products\"][key][\"class\"])\n product = Product(name=data[\"products\"][key][\"name\"],\n classProduct=classProduct)\n product.save()\n connect = ProductScript(product=product, script=script,\n x=data[\"products\"][key][\"position\"][\"x\"],\n y=data[\"products\"][key][\"position\"][\"y\"],\n idProduct=data[\"products\"][key][\"idProduct\"])\n connect.save()\n key = key + 1\n key = 0\n while key < len(data[\"resource\"]): #создаем множество ресурсов\n try:\n resource = Resource.objects.get(name=data[\"resource\"][key][\"name\"])\n except:\n classResource = ClassResource.objects.get(name=data[\"resource\"][key][\"class\"])\n resource = Resource(name=data[\"resource\"][key][\"name\"],\n classResource=classResource)\n resource.save()\n connect = ResourceScript(resource=resource, script=script,\n x=data[\"resource\"][key][\"position\"][\"x\"],\n y=data[\"resource\"][key][\"position\"][\"y\"],\n idResource=data[\"resource\"][key][\"idResource\"])\n connect.save()\n key = key + 1\n key = 0\n while key < len(data[\"events\"]): #создаем множество событий\n try:\n event = Event.objects.get(name=data[\"events\"][key][\"name\"])\n except:\n event = Event(name=data[\"events\"][key][\"name\"])\n event.save()\n eventScript = EventScript(event=event,\n script=script,\n x=data[\"events\"][key][\"position\"][\"x\"],\n y=data[\"events\"][key][\"position\"][\"y\"],\n idEvent=data[\"events\"][key][\"id\"])\n eventScript.save()\n key = key + 1\n key = 0\n while key < len(data[\"logicals\"]): #создаем множество логических перекрестков\n classLogical = LogicalClass.objects.get(name=data[\"logicals\"][key][\"class\"])\n logical = Logical(classLogical=classLogical,\n script=script,\n idLogical=data[\"logicals\"][key][\"id\"],\n x=data[\"logicals\"][key][\"position\"][\"x\"],\n y=data[\"logicals\"][key][\"position\"][\"y\"])\n logical.save()\n key = key + 1\n key = 0\n while key < len(data[\"connect\"]): #создаем множество связей\n connect = ConnectShape(script=script, idFrom=data[\"connect\"][key][\"from\"], idTo=data[\"connect\"][key][\"to\"])\n connect.save();\n key = key + 1;\n return HttpResponse()\n","sub_path":"problem/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"385473433","text":"import dash\nfrom dash.dependencies import Input, Output\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_table\nimport pandas\nimport plotly.graph_objs as go\n\n\ndef load_df_as_json():\n idx = pandas.IndexSlice\n\n rs_raw = pandas.read_hdf('./data/runscanner_illumina_cache.hd5')\n inst_raw = pandas.read_hdf('./data/pinery_instruments_cache.hd5')\n\n rs_flow = rs_raw.loc[idx[:, 'flow_cell', :, :], 'value'].unstack('key')\n rs_flow = rs_flow[['sequencerName', 'startDate', 'healthType']]\n rs_flow = rs_flow.reset_index()\n\n inst_model = inst_raw[['name_instrument', 'name_model']]\n\n rs_flow = rs_flow.merge(\n inst_model, 'left', left_on='sequencerName', right_on='name_instrument'\n )\n\n rs_lane = rs_raw.loc[\n idx[:, ['Read', 'Index'], :, :], 'value'\n ].unstack('key')\n rs_lane_yield = rs_lane.groupby('run_alias')[['Yield']].sum()\n rs_lane_yield = rs_lane_yield.rename(columns={'Yield': 'Total Yield (GB)'})\n\n final = rs_flow.merge(rs_lane_yield, on='run_alias', right_index=True)\n final = final[final['healthType'] == 'COMPLETED']\n final = final.astype({'startDate': 'datetime64[ns]'})\n\n return final\n\n\nraw_df = load_df_as_json()\nraw_df_table_col_names = [\n {'name': i, 'id': i} for i in raw_df.columns\n]\n\nlayout = html.Div([\n dcc.Dropdown(\n id='freq_dropdown',\n options=[\n {'label': 'Daily', 'value': 'D'},\n {'label': 'Weekly', 'value': 'W'},\n {'label': 'Monthly', 'value': 'M'},\n {'label': 'Quarterly', 'value': 'BQ-MAR'},\n {'label': 'Yearly', 'value': 'Y'},\n ],\n value='M',\n clearable=False,\n ),\n\n dcc.Dropdown(\n id='colour_by_dropdown',\n options=[\n {'label': 'Machine ID', 'value': 'sequencerName'},\n {'label': 'Machine Model', 'value': 'name_model'},\n ],\n value=None,\n placeholder='Colour By'\n ),\n\n dcc.Graph(\n id='bar_sum',\n ),\n\n dcc.Tabs(id=\"table_tabs\", value='grouped', children=[\n dcc.Tab(label='Grouped Data', value='grouped'),\n dcc.Tab(label='All Data', value='all'),\n ]),\n\n html.Div(\n id='table_tabs_content'\n ),\n\n html.Div(\n id='raw_df_json',\n style={'display': 'none'},\n children=raw_df.to_json(\n date_format='iso', orient='records'\n ),\n ),\n\n html.Div(\n id='df_group_sum',\n style={'display': 'none'},\n ),\n])\n\ntry:\n from app import app\n app.layout = layout\nexcept ModuleNotFoundError:\n import dash\n app = dash.Dash(__name__)\n app.layout = layout\n\n\n@app.callback(\n Output('bar_sum', 'figure'),\n [Input('df_group_sum', 'children'),\n Input('colour_by_dropdown', 'value')]\n)\ndef create_bar_sum_fig(df_group_sum, colour_by):\n df = pandas.read_json(df_group_sum, orient='split')\n\n layout = {\n 'yaxis': {'title': 'PF Yield (GB)'},\n 'legend': {'orientation': 'h'},\n }\n\n if colour_by is None:\n return {\n 'data': [go.Bar(\n x=df['startDate'],\n y=df['Total Yield (GB)']\n )],\n 'layout': layout,\n }\n else:\n traces = []\n for name, data in df.groupby(colour_by):\n t = go.Bar(\n x=list(data['startDate']),\n y=list(data['Total Yield (GB)']),\n name=name\n )\n traces.append(t)\n\n return {\n 'data': traces,\n 'layout': layout\n }\n\n\n@app.callback(\n Output('table_tabs_content', 'children'),\n [Input('table_tabs', 'value'),\n Input('raw_df_json', 'children'),\n Input('df_group_sum', 'children')]\n)\ndef update_table_tab(selected_tab, raw_df_json, group_df_json):\n if selected_tab == 'grouped':\n df = pandas.read_json(group_df_json, orient='split')\n if selected_tab == 'all':\n df = pandas.read_json(raw_df_json, orient='records')\n\n col_names = [{'name': i, 'id': i} for i in df.columns]\n\n return dash_table.DataTable(\n id='test',\n columns=col_names,\n data=df.to_dict('rows')\n )\n\n\n@app.callback(\n Output('df_group_sum', 'children'),\n [Input('raw_df_json', 'children'),\n Input('freq_dropdown', 'value'),\n Input('colour_by_dropdown', 'value')]\n)\ndef update_grouped_df(raw_df_json, frequency, colour_grouper):\n raw = pandas.read_json(\n raw_df_json, orient='records', convert_dates=['startDate']\n )\n\n if colour_grouper is None:\n grouper = [\n pandas.Grouper(key='startDate', freq=frequency)\n ]\n else:\n grouper = [\n pandas.Grouper(key='startDate', freq=frequency),\n colour_grouper\n ]\n\n return raw.groupby(\n grouper\n ).sum().reset_index().to_json(\n date_format='iso', orient='split',\n )\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"runscanner/yield_over_time.py","file_name":"yield_over_time.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"589917199","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom progress import StatusBar\nimport re\n\ndef find_ids(nodes, *args):\n\tif not args:\n\t\treturn [-1]\n\tbar = StatusBar(len(nodes))\n\tregex = re.compile(r'^.*?\\tartist\\t(%s)\\n' % '|'.join(args), re.IGNORECASE)\n\tids = []\n\tfor index, row in enumerate(nodes):\n\t\tif regex.match(row):\n\t\t\tids.append(index)\n\t\tif index % 10000 == 0: bar.update(index)\n\tbar.close()\n\treturn ids\n\ndef delete(nodes, edges, *deletion_indices):\n\tfrom datetime import datetime\n\tfor index in deletion_indices:\n\t\tnodes[index] = None\n\tbar = StatusBar(len(edges))\n\tdeletion_indices = set(deletion_indices) # set for constant time 'in' check\n\tfor i, row in enumerate(edges):\n\t\tdata = row.split(\"\\t\", 2)\n\t\tleft = int(data[0])\n\t\tright = int(data[1])\n\t\tif left in deletion_indices or right in deletion_indices:\n\t\t\tedges[i] = None\n\t\tif i % 10000 == 0: bar.update(i)\n\tbar.close()","sub_path":"processing/various_artists.py","file_name":"various_artists.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"49882122","text":"#######################################################################\n# Script to train the segmentation model, one model for multi labels #\n#######################################################################\n\nimport logging\nimport os\nimport sys\nfrom glob import glob\nimport pathlib\nimport argparse\nimport shutil\nimport random\nimport numpy as np\nimport copy\n\nfrom PIL import Image\n\nimport monai\nfrom monai.data import PersistentDataset\nfrom monai import transforms as mt\nfrom monai.utils import set_determinism\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms, datasets, models\n\nfrom model.unet import ResNetUNet\nfrom model.TernausNet import UNet11, LinkNet34, UNet, UNet16, AlbuNet\nfrom model.UNet_3Plus import UNet_3Plus\nfrom model.network import R2U_Net, AttU_Net, R2AttU_Net\n\nfrom collections import defaultdict\nfrom loss import dice_loss\n\nimport matplotlib.pyplot as plt\n\nimport wandb\nwandb.init(project='Medical-CT', entity='zhoushanglin100')\n\n\n######################################################\n\nmoddel_list = {'UNet11': UNet11,\n 'UNet16': UNet16,\n 'UNet': UNet,\n 'AlbuNet': AlbuNet,\n 'LinkNet34': LinkNet34}\n\npjoin = os.path.join\n\ndef reverse_transform(inp):\n inp = inp.numpy().transpose((1, 2, 0))\n inp = np.clip(inp, 0, 1)\n inp = (inp * 255).astype(np.uint8)\n return inp\n\ndef calc_loss(pred, target, metrics, bce_weight=0.5):\n bce = F.binary_cross_entropy_with_logits(pred, target)\n pred = F.sigmoid(pred)\n iou, dice = dice_loss(pred, target)\n loss = bce * bce_weight + dice * (1 - bce_weight)\n\n metrics['iou'] += iou * target.size(0)\n metrics['bce'] += bce * target.size(0)\n metrics['dice'] += dice * target.size(0)\n metrics['loss'] += loss * target.size(0)\n\n return loss, iou\n\n\ndef print_metrics(metrics, epoch_samples, phase):\n outputs = []\n for k in metrics.keys():\n outputs.append(\"{}: {:4f}\".format(k, metrics[k] / epoch_samples))\n if k == \"iou\":\n wandb.log({\"IOU/\"+phase+\"_\"+k: metrics[k]/epoch_samples})\n else:\n wandb.log({\"Loss/\"+phase+\"_\"+k: metrics[k]/epoch_samples})\n\n print(\"{}: {}\".format(phase, \", \".join(outputs)))\n\n\ndef get_transforms(args):\n train_trans = mt.Compose(\n [\n mt.LoadImageD(keys=['img', 'seg']),\n mt.ScaleIntensityD(keys=['img']),\n mt.AddChannelD(keys=['seg']),\n mt.RandGaussianNoiseD(keys=['img']),\n # mt.RandSpatialCropSamplesD(keys=['img', 'seg'], num_samples=5),\n # mt.CropForegroundD(keys=[\"img\", \"seg\"], source_key=\"img\"),\n # mt.RandGaussianSharpenD(keys=['img']),\n mt.RandShiftIntensityD(keys=['img'], offsets = 5),\n # mt.RandAdjustContrastD(keys=['img']),\n mt.ResizeD(keys=['img', 'seg'], spatial_size=(args.dims, args.dims)),\n # mt.ResizeD(keys=['seg'], spatial_size=(args.dims, args.dims)),\n\n # mt.RandCropByPosNegLabeld(keys=[\"img\", \"seg\"], label_key=\"seg\", \n # spatial_size=[224, 224], pos=1, neg=1, num_samples=4),\n # mt.RandRotate90d(keys=[\"img\", \"seg\"], prob=0.3, spatial_axes=[0, 1]),\n # mt.RandHistogramShiftd(keys=[\"img\", \"seg\"]),\n mt.ToTensorD(keys=['img', 'seg']),\n mt.AsDiscreteD(keys=['seg'], threshold_values=True),\n ]\n )\n val_trans = mt.Compose(\n [\n mt.LoadImageD(keys=['img', 'seg']),\n mt.ScaleIntensityD(keys=['img']),\n mt.AddChannelD(keys=['seg']),\n\n mt.ResizeD(keys=['img', 'seg'], spatial_size=(args.dims, args.dims)),\n # mt.ResizeD(keys=['seg'], spatial_size=(1, args.dims, args.dims)),\n\n # mt.CropForegroundd(keys=[\"img\", \"seg\"], source_key=\"img\"),\n mt.ToTensorD(keys=['img', 'seg']),\n mt.AsDiscreteD(keys=['seg'], threshold_values=True),\n ]\n )\n \n return train_trans, val_trans\n\n\n\n######################################################\n\ndef train(args, model, device, train_loader, optimizer, epoch):#, scheduler):\n model.train()\n\n metrics = defaultdict(float)\n epoch_samples = 0\n\n # for batch_data in train_loader:\n for batch_idx, batch_data in enumerate(train_loader):\n inputs, labels = batch_data['img'].to(device), batch_data['seg'].to(device)\n \n # print(\"!!!!!!!!!!!!!!!\")\n # print(inputs.shape, labels.shape)\n # print(\"!!!!!!!!!!!!!!!\")\n\n optimizer.zero_grad()\n\n outputs = model(inputs)\n loss, iou = calc_loss(outputs, labels, metrics)\n loss.backward()\n optimizer.step()\n\n epoch_samples += inputs.size(0)\n \n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}, iou: {:.6f}'.format(\n epoch+1, batch_idx * len(inputs), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss, iou))\n\n print_metrics(metrics, epoch_samples, 'train')\n epoch_loss = metrics['loss'] / epoch_samples\n epoch_iou = metrics['iou'] / epoch_samples\n \n # scheduler.step()\n wandb.log({\"learning_rate\": optimizer.param_groups[0]['lr']})\n\n\n\n\ndef validation(args, model, device, val_loader):\n metrics = defaultdict(float)\n epoch_samples = 0\n\n model.eval()\n \n with torch.no_grad():\n metric_count = 0\n metric_sum = 0.0\n # for val_data in val_loader:\n for batch_idx, val_data in enumerate(val_loader):\n val_images, val_labels = val_data['img'].to(device), val_data['seg'].to(device)\n \n val_outputs = model(val_images)\n\n loss, iou = calc_loss(val_outputs, val_labels, metrics)\n epoch_samples += val_images.size(0)\n\n # # -------------\n # ## Plot\n # if batch_idx % args.plot_interval == 0:\n # val_outputs[0] = F.sigmoid(val_outputs[0])\n\n # wandb.log({\"masks/Image\": [wandb.Image(val_images[0], caption=\"Images\")]})\n # wandb.log({\"masks/true\": [wandb.Image(val_labels[0].squeeze_().cpu(), caption=\"Mask/True\")]})\n # wandb.log({\"masks/pred\": [wandb.Image(val_outputs[0].squeeze_().cpu(), caption=\"Mask/Pred\")]})\n # # wandb.log({\"masks/true\": [wandb.Image(reverse_transform(val_labels.squeeze_().cpu()), caption=\"Mask/True\")]})\n # # wandb.log({\"masks/pred\": [wandb.Image(reverse_transform(val_outputs.squeeze_().cpu()), caption=\"Mask/Pred\")]})\n # # ---------------------------------\n\n print_metrics(metrics, epoch_samples, 'val')\n epoch_loss = metrics['loss'] / epoch_samples\n epoch_iou = metrics['iou'] / epoch_samples\n\n return epoch_loss, epoch_iou, model.state_dict()\n\n##########################################################################################################\ndef main(args):\n\n ###################################\n # Path\n ###################################\n\n config = wandb.config\n \n logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n data_folder = './data/3d'\n image_folder = 'img_'+args.data_view\n mask_folder = 'mask_'+args.data_view\n tmp_path = './tmp'\n\n shutil.rmtree(tmp_path, ignore_errors=True)\n persistent_cache = pathlib.Path(tmp_path, \"persistent_cache\")\n persistent_cache.mkdir(parents=True, exist_ok=True)\n set_determinism(seed=0)\n\n ###################################\n # Dataset\n ###################################\n\n # images = sorted(glob(pjoin(data_folder, 'train_polar', 'images_polar_2', '*.npz')))\n # segs = sorted(glob(pjoin(data_folder, 'train_polar', 'masks_polar_2', '*.npz')))\n\n images = sorted(glob(pjoin(data_folder, image_folder, '*.npz')))\n segs = sorted(glob(pjoin(data_folder, mask_folder, '*.npz')))\n\n # aa = sorted(glob(pjoin('../Medical/data', 'train', 'images', '*.npz')))\n\n data_dicts = [\n {\"img\": image_name, \"seg\": label_name}\n for image_name, label_name in zip(images, segs)\n ]\n\n random.shuffle(data_dicts)\n\n val_idx = int(0.2*len(images))\n\n train_files, val_files = data_dicts[:-val_idx], data_dicts[-val_idx:]\n train_trans, val_trans = get_transforms(args)\n\n train_ds = PersistentDataset(data=train_files, transform=train_trans, cache_dir=persistent_cache)\n val_ds = PersistentDataset(data=val_files, transform=val_trans, cache_dir=persistent_cache)\n\n train_loader = DataLoader(train_ds, batch_size=args.batch_size, shuffle=True, num_workers=16, pin_memory=torch.cuda.is_available())\n val_loader = DataLoader(val_ds, batch_size=args.test_batch_size, num_workers=16)#, pin_memory=torch.cuda.is_available())\n\n ###################################\n # Model\n ###################################\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n # model = ResNetUNet(n_class=4).to(device)\n\n if args.model == 'ResNetUNet':\n model = ResNetUNet(n_class=args.num_classes)\n\n elif args.model == 'UNet3+':\n model = UNet_3Plus(n_classes=args.num_classes)\n elif args.model =='R2U_Net':\n model = R2U_Net(img_ch=3, output_ch=args.num_classes, t=3)\n elif args.model =='AttU_Net':\n model = AttU_Net(img_ch=3, output_ch=args.num_classes)\n elif args.model == 'R2AttU_Net':\n model = R2AttU_Net(img_ch=3, output_ch=args.num_classes, t=3)\n elif args.model == 'UNet':\n model = UNet(num_classes=args.num_classes)\n else:\n model_name = moddel_list[args.model]\n model = model_name(num_classes=args.num_classes, pretrained=False)\n\n model = model.to(device) \n\n # # ----------------------------\n # from torchsummary import summary\n # from prettytable import PrettyTable\n\n # summary(model, input_size=(3, 480, 640))\n\n # def count_parameters(model):\n # table = PrettyTable([\"Modules\", \"Parameters\"])\n # total_params = 0\n # for name, parameter in model.named_parameters():\n # param = parameter.numel()\n # table.add_row([name, param])\n # total_params+=param\n # print(table)\n # print(f\"Total Trainable Params: {total_params}\")\n # return total_params\n \n # count_parameters(model)\n # # --------------------------------\n\n optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr)\n # optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr, momentum=0.5)\n # scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1)\n\n best_model_wts = copy.deepcopy(model.state_dict())\n\n # best_loss = 1e10\n best_iou = 0\n\n for epoch in range(args.epochs):\n print('Epoch {}/{}'.format(epoch+1, args.epochs))\n print('-' * 50)\n\n train(args, model, device, train_loader, optimizer, epoch)#, scheduler)\n\n if (epoch + 1) % args.val_inter == 0:\n\n epoch_loss, epoch_iou, best_state = validation(args, model, device, val_loader)\n\n if epoch_iou > best_iou:\n print(\"Get a new best test iou:{:.2f}\\n\".format(epoch_iou))\n best_iou = epoch_iou\n best_metric_epoch = epoch + 1\n best_model_wts = copy.deepcopy(model.state_dict())\n\n model_name = \"ckpt/\"+args.data_view+\"_\"+args.model+\"_\"+str(epoch)+\".pt\"\n torch.save(best_model_wts, model_name)\n\n print(\"current epoch: {}; current test iou: {:.4f}; best test iou: {:.4f} at epoch {}\\n\".format(\n epoch+1, epoch_iou, best_iou, best_metric_epoch))\n \n \n# ---------------------------------------------------------\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--dims\", default=256, type=list, \n help=\"Original shape: [(512, 512) -> (512, 512), (221, 512) -> (224, 512)]\")\n parser.add_argument(\"--model\", default='ResNetUNet', type=str,\n help='Choose from [ResNetUNet, UNet, UNet11, UNet16, AlbuNet, LinkNet34]')\n parser.add_argument(\"--num_classes\", default=1, type=int)\n parser.add_argument('--data_view', type=str, default=\"updown\", metavar='N',\n help=\"Choose from ['updown', 'leftright', 'frontback']\")\n parser.add_argument(\"--val_inter\", default=1, type=int)\n parser.add_argument(\"--batch_size\", default=64, type=int)\n parser.add_argument(\"--test_batch_size\", default=64, type=int)\n parser.add_argument(\"--epochs\", default=150, type=int)\n parser.add_argument(\"--lr\", default=1e-3, type=float)\n parser.add_argument('--log_interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n parser.add_argument('--plot_interval', type=int, default=10000, metavar='N',\n help='how many batches to wait before logging training status')\n\n args = parser.parse_args()\n print(args)\n \n ###################################\n\n args, unknown = parser.parse_known_args()\n wandb.init(config=args)\n wandb.config.update(args)\n \n main(args)\n","sub_path":"train_try.py","file_name":"train_try.py","file_ext":"py","file_size_in_byte":13285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"116113713","text":"import pandas as pd \nimport numpy as np\nimport argparse\nimport os\nimport time\nimport yfinance as yf \n\n\n'''\nThis file deal with the preprocess of option data\n\n1. read dataset from csv files\n2. select option with suitable features \n3. generating features for future usage\n moneyness S/K, maturity T\n'''\n\n\ndef preprocess_all_stock_price(args):\n # stock price data\n if not args.refresh and os.path.exists(args.data_path+args.stock_price_file_path[:-4]+'.h5'):\n print(args.stock_price_file_path[:-4]+'.h5' + ' already exists')\n return \n print('Reading Stock Price Data')\n start_time = time.time()\n df = pd.read_csv(args.data_path+args.stock_price_file_path, low_memory=False)\n df['Price'] = (df['BID'] + df['ASK'])/2\n df['Spread'] = df['ASK'] - df['BID']\n df = df[['date', 'TICKER', 'Price', 'Spread', 'ASK', 'BID']] \n #df['date'] = pd.to_datetime(df['date'])\n print('Save Stock Price Data into H5 file')\n df.to_hdf(args.data_path+args.stock_price_file_path[:-4]+'.h5', key=args.stock_price_file_path[:-4])\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n\ndef option_selection2(option, para):\n #option = option[option['open_interest']>para[volume_threshold] ] # consider option with some traded volume\n option = option[option['cp_flag']==para['cp_flag']]\n \n # liquidity indicator\n # reference : https://www.investopedia.com/ask/answers/050615/what-difference-between-open-interest-and-volume.asp#:~:text=Volume%20and%20open%20interest%20are,are%20active%2C%20or%20not%20settled.\n option = option[option['volume'] >= para['volume_threshold']]\n option = option[option['open_interest'] >= para['open_interest_threshold']]\n # Open interest is lagged by one-day after November 28th, 2000\n\n return option\n\n\ndef option_feature(option, ticker, TYPE='C'):\n \n price = pd.read_hdf(args.data_path+args.stock_price_file_path[:-4]+'.h5')\n price = price[price['TICKER'] == ticker].set_index('date')\n\n # compute moneyness\n # forward_price may be missing\n option = option.dropna(subset=['date', 'exdate', 'delta', 'vega', \\\n 'strike_price', 'best_bid', 'best_offer']).copy()\n # for robustness\n option = option[option['date'].apply(lambda x: True if x in price.index else False)]\n\n option['stock_price'] = option['date'].apply(lambda x: price.loc[x,'Price'])\n option['moneyness'] = option['stock_price'] / (option['strike_price'] /1000)\n option['log_forward_moneyness'] = option['forward_price'] / (option['strike_price'] /1000)\n option['log_forward_moneyness'] = option['log_forward_moneyness'].apply(np.log)\n\n option['price'] = (option['best_bid'] + option['best_offer'])/2 \n\n option['date'] = pd.to_datetime(option['date'],format = '%Y%m%d')\n option['exdate'] = pd.to_datetime(option['exdate'],format = '%Y%m%d')\n\n option['maturity'] = option['exdate'] - option['date']\n option['maturity'] = option['maturity'].apply(lambda x:x.days)\n option['maturity'] = option.apply(lambda x: x['maturity'] if x['am_settlement']==0 else x['maturity']-1, axis=1)\n option['normalized_T'] = option['maturity'] / 365\n\n option = option.drop(['best_bid', 'best_offer','exdate', 'last_date'], axis=1) #'forward_price'\n \n # options with less than 14 days are removed\n #option = option[option['maturity']<=365]\n option = option[option['maturity']>=14]\n\n # options whose delta less than 0.05 or greater than 0.95 are removed \n if TYPE == 'C':\n option = option[option['delta']>0.05 ] \n option = option[option['delta']<=0.95 ] \n elif TYPE == 'P':\n option = option[option['delta']<-0.05 ] \n option = option[option['delta']>-0.95 ] \n else:\n print('Wrong type')\n\n # sorted to produce observations for the same option on two successive trading days\n option = option.sort_values(by=['optionid','date'])\n return option \n\n\ndef drop_stock_split(df, args):\n t = yf.Ticker(args.ticker)\n t = t.splits \n splits = t[t>0] \n # index is the date of stock plits\n # format : Timestamp\n if len(splits)>0:\n df = df[df['date'].apply(lambda x: x not in list(splits.index))]\n return df \n\n'''\ndef get_stock_price(args): \n df = pd.read_hdf(args.data_path+args.stock_price_file_path[:-4]+'.h5')\n df = df[df['TICKER']==args.ticker]\n\n df['Close'] = df['Price']\n df['dS'] = df['Price'].shift(-1) - df['Price'] \n df['date'] = pd.to_datetime(df['date'].apply(str))\n df['stock_day_diff'] = df['date'].shift(-1) - df['date'] \n df['stock_day_diff'] = df['stock_day_diff'].apply(lambda x: x.days)\n return df.set_index('date').dropna()\n'''\n\ndef get_stock_price(args, SPX=False):\n if SPX:\n df = pd.read_hdf(args.data_path+'SPX_Price.h5')\n df['date'] = pd.to_datetime(df['date'].apply(str))\n return df.set_index('date').dropna()\n \n df = pd.read_hdf(args.data_path+args.stock_price_file_path[:-4]+'.h5')\n df = df[df['TICKER']==args.ticker]\n\n df['Close'] = df['Price']\n df['dS'] = df['Price'].shift(-1) - df['Price'] \n df['date'] = pd.to_datetime(df['date'].apply(str))\n df['stock_day_diff'] = df['date'].shift(-1) - df['date'] \n df['stock_day_diff'] = df['stock_day_diff'].apply(lambda x: x.days)\n return df.set_index('date').dropna()\n\n\ndef cal_dVdS(df, args, start_year=2010):\n ticker = args.ticker\n\n df['month'] = df['date'].apply(lambda x: (x.year-start_year)*12+x.month)\n stockprice = get_stock_price(args) \n df['stock_price'] = df['date'].apply(lambda x: stockprice.loc[x,'Close'])\n\n df['dS'] = df['date'].apply(lambda x: stockprice.loc[x,'dS'])\n df['stock_day_diff'] = df['date'].apply(lambda x: stockprice.loc[x,'stock_day_diff'])\n\n df = df.sort_values(['optionid', 'date'])\n \n df['dV'] = df.groupby('optionid').apply(lambda x:x['price'].shift(-1) - x['price'])\\\n .reset_index().set_index('level_1')['price']\n df['dimp'] = df.groupby('optionid').apply(lambda x:x['impl_volatility'].shift(-1) - x['impl_volatility'])\\\n .reset_index().set_index('level_1')['impl_volatility']\n df['option_day_diff'] = df.groupby('optionid').apply(lambda x:x['date'].shift(-1) - x['date'])\\\n .reset_index().set_index('level_1')['date']\n df['option_day_diff'] = df['option_day_diff'].apply(lambda x: x.days)\n df = df[df['option_day_diff'] == df['stock_day_diff'] ]\n df = df.drop(['option_day_diff', 'stock_day_diff'], axis=1)\n\n # dV, dS is normalized so that the underlying price is 1000\n df['dV'] = df['dV'] / df['stock_price'] * 1000\n df['dS'] = df['dS'] / df['stock_price'] * 1000\n return df \n\n\ndef preprocess_option(args):\n TYPE = args.cp_flag\n ticker = args.ticker + ('' if args.ticker == '' else '_')\n suffix = ('_' if args.suffix != '' else '') + args.suffix\n filename = ticker+'Option_'+ TYPE +'_'+args.exercise_style + suffix\n\n if not args.refresh and os.path.exists(args.data_path+filename+'.h5'):\n print(args.data_path+ticker+filename+'.h5')\n return \n\n start_time = time.time()\n option = read_option_csv(args, saving=False)\n\n print('Selecting Option Data')\n para_dict = {\n 'volume_threshold':args.volume_threshold, \n 'open_interest_threshold': args.open_interest_threshold, \n 'cp_flag':args.cp_flag.upper()\n }\n option = option_selection2(option, para=para_dict)\n\n print('Do feature Engineering on Option Data')\n option = option_feature(option, args.ticker, TYPE)\n\n print('Drop data when stock split happens')\n option = drop_stock_split(option, args)\n\n print('Calculating dV, dS')\n option = cal_dVdS(option, args)\n\n print('Save processed Option Data')\n option.to_hdf(args.data_path+filename+'.h5', key=filename) \n print(\"Option selection and feature engineering--- %s seconds ---\" % (time.time() - start_time))\n\n\ndef preprocess(args):\n preprocess_all_stock_price(args)\n preprocess_option(args)\n\n return \n\n\ndef read_option_csv(args, saving=False):\n ticker = args.ticker + ('' if args.ticker == '' else '_')\n suffix = ('_' if args.suffix != '' else '') + args.suffix\n filename = ticker + 'Option'+ suffix\n\n if not args.refresh and os.path.exists(args.data_path+filename+'.h5'):\n print(args.data_path+filename+'.h5' +' already exists')\n return pd.read_hdf(args.data_path+filename+'.h5')\n\n print('Reading Option Data (CSV)')\n start_time = time.time()\n use_cols = ['optionid', 'ticker','am_settlement', 'date', 'exdate', 'last_date', \\\n 'exercise_style', 'expiry_indicator','ss_flag', 'forward_price',\\\n 'cp_flag', 'strike_price', 'best_bid', 'best_offer', 'volume', 'open_interest',\\\n 'impl_volatility', 'delta', 'gamma', 'vega', 'theta']\n option = pd.read_csv(args.data_path+args.option_file_path, low_memory=False,\\\n usecols=use_cols) \n print('Total number of sample : {}'.format(option.shape[0]))\n print(\"Reading CSV files --- %s seconds ---\" % (time.time() - start_time))\n\n option = option[option['date']>=20100101]\n option = option[option['date']<=20191231]\n\n #option = option[option['am_settlement']==0] # use close price for settlement \n option = option[option['ss_flag']==0] # use standard settlement \n #option = option[option['symbol_flag']==1] # use new OSI data\n option = option[option['exercise_style'] == args.exercise_style] \n \n if args.expiry_indicator == 'regular':\n option = option[option['expiry_indicator'].isna()] \n else:\n option = option[option['expiry_indicator'] == 'w']\n \n option = option.drop(['expiry_indicator','ss_flag'], axis=1)\n\n #'cp_flag', 'symbol_flag','exercise_style', 'forward_price', 'am_settlement'\n #column_to_drop = ['am_set_flag','ss_flag',\n # 'secid','symbol', 'root','suffix','issuer', 'expiry_indicator',\n # 'cusip', 'sic', 'index_flag', 'exchange_d',\n # 'class', 'issue_type', 'industry_group', 'div_convention',\n # 'cfadj', 'contract_size',\t]\n #option = option.drop(column_to_drop, axis=1) \n\n if saving:\n print('Saving Option Data into H5 file')\n option.to_hdf(args.data_path+filename+'.h5', key=filename) \n \n return option \n\n\ndef combine_sentiment(args):\n TYPE = args.cp_flag\n ticker = args.ticker + ('' if args.ticker == '' else '_')\n filename = ticker+'Option_'+ TYPE +'_'+args.exercise_style\n\n if not os.path.exists(args.data_path+filename+'.h5'):\n print(args.data_path+ticker+filename+'.h5 doesn\\'t exist')\n return \n \n start_time = time.time()\n print('Starting reading option and news information')\n print('Option file : '+args.data_path+filename+'.h5')\n option = pd.read_hdf(args.data_path+filename+'.h5')\n\n news_filename = ticker + 'News'\n print('News file : '+args.data_path+news_filename+'.h5')\n news = pd.read_hdf(args.data_path+news_filename+'.h5')\n \n # trade date \n print('Compute the date')\n k = pd.read_hdf(args.data_path+'StockPriceAll.h5')\n first_date = news['RPNA_DATE_UTC'].min()\n last_date = news['RPNA_DATE_UTC'].max()\n k = k[(k['TICKER']==args.ticker) & (k['date'] >= first_date) & (k['date'] <= last_date)]\n print('Number of trading dates : {}'.format(k.shape[0]))\n idx = k['date']\n # to speed up, each date is computed only once and saved in dictionary\n date_map = {}\n for dt in news['RPNA_DATE_UTC'].unique():\n date_map[dt] = idx[idx>=dt].iloc[0] \n print('Number of dates : {}'.format(len(date_map)))\n news['date'] = news['RPNA_DATE_UTC'].map(date_map)\n '''\n r = 0\n for key in date_map:\n if r >= 10:\n break\n print(key, date_map[key])\n r += 1\n '''\n print('Incorporating information of news item into day sentiment')\n sentiment = news.groupby('date')['CSS'].apply(lambda x: (x[x>50].count(), x[x<50].count(), x[x==50].count(), x.count()))\n\n sentiment = pd.DataFrame(sentiment.to_list(), index=sentiment.index, \\\n columns=['pos_count', 'neg_count', 'neu_count', 'count'])\n\n sentiment['max_CSS'] = news.groupby('date')['CSS'].apply(lambda x: (x.max()-50)/50)\n sentiment['min_CSS'] = news.groupby('date')['CSS'].apply(lambda x: (x.max()-50)/50)\n \n sentiment['high_CSS'] = news.groupby('date')['CSS'].apply(lambda x: (x[x>70].mean()-50)/50 if x[x>70].shape[0]>0 else 0)\n sentiment['low_CSS'] = news.groupby('date')['CSS'].apply(lambda x: (x[x<30].mean()-50)/50 if x[x<30].shape[0]>0 else 0)\n \n #sentiment.index = pd.to_datetime(sentiment.index, format='%Y%m%d')\n sentiment['day_CSS'] = (sentiment['pos_count'] - sentiment['neg_count'])/(sentiment['count']-sentiment['neu_count'])\n\n # in some case, there may be no news in a day\n # we fill it with sentiment of previous day\n sentiment = sentiment.reindex(k.set_index('date').index)\n sentiment = sentiment.fillna(method='ffill')\n #print(sentiment.head())\n print('Combine sentiment into option data')\n for name in ['max', 'min', 'day', 'high', 'low']:\n print(name+'_CSS')\n option[name+'_CSS'] = option['date'].apply(lambda x: sentiment.loc[int(x.strftime('%Y%m%d')), name+'_CSS'] ) \n\n print('Save Option Data that combines sentiment')\n option.to_hdf(args.data_path+filename+'.h5', key=filename) \n print(\"Combining sentiment --- %s seconds ---\" % (time.time() - start_time))\n return \n\n\ndef combine_variables(args):\n TYPE = args.cp_flag\n ticker = args.ticker + ('' if args.ticker == '' else '_')\n filename = ticker+'Option_'+ TYPE +'_'+args.exercise_style\n\n if not os.path.exists(args.data_path+filename+'.h5'):\n print(args.data_path+ticker+filename+'.h5 doesn\\'t exist')\n return \n \n start_time = time.time()\n print('Starting reading option information')\n print('Option file : '+args.data_path+filename+'.h5')\n option = pd.read_hdf(args.data_path+filename+'.h5')\n variables = pd.read_hdf(args.data_path+'StockPriceAll.h5')\n #elif args.ticker == 'semiconduct':\n # variables = pd.read_hdf(args.data_path+'stockprice_semiconduct.h5')\n #else:\n # print('Wrong ticker : {}'.format(args.ticker))\n variables = variables[variables['TICKER'] == args.ticker]\n\n variables['Price_adj_backward'] = variables['Price']\n hist = yf.Ticker(args.ticker).history(period=\"max\")\n hist = hist.reset_index()\n hist['date'] = hist['Date'].apply(lambda x: int(x.strftime('%Y%m%d')))\n variables['Price_adj_backward'] = variables['date'].apply(lambda x: hist.set_index('date').loc[x, 'Close'])\n variables = variables.set_index('date')\n variables['log_return'] = variables['Price_adj_backward'] / variables['Price_adj_backward'].shift(1) \n variables['log_return'] = variables['log_return'].apply(np.log)\n variables['log_return_week'] = variables['log_return'].rolling(5).mean()\n variables['log_return_month'] = variables['log_return'].rolling(22).mean()\n\n variables['vol_22'] = variables['log_return'].rolling(22).std()*np.sqrt(22)\n print('Computing log_return, vol_22')\n option['date_int'] = option['date'].apply(lambda x: int(x.strftime('%Y%m%d')) )\n for name in ['log_return', 'log_return_week', 'log_return_month', 'vol_22']: #'vix'\n option[name] = option['date_int'].apply(lambda x: variables.loc[x, name] ) \n\n # get SPX log return \n print('Computing SPX log_return')\n stockprice = get_stock_price(args, SPX=True) \n stockprice['SPX_log_return'] = stockprice['Price'] / stockprice['Price'].shift(1) \n stockprice['SPX_log_return'] = stockprice['SPX_log_return'].apply(np.log)\n # stockprice, date : Timestamp\n for name in ['SPX_log_return']: \n option[name] = option['date'].apply(lambda x: stockprice.loc[x, name] ) \n\n print('Computing vix')\n vix = pd.read_csv(args.data_path+'VIX.csv') \n vix['vix_week'] = vix['vix'].rolling(5).mean()\n vix['vix_month'] = vix['vix'].rolling(22).mean()\n\n vix = vix.set_index('Date')\n for name in ['vix', 'vix_week', 'vix_month']:\n option[name] = option['date_int'].apply(lambda x: vix.loc[x, name])\n option = option.drop(['date_int'], axis=1)\n\n print('Save Option Data that combines variables')\n option.to_hdf(args.data_path+filename+'.h5', key=filename) \n print(\"Combining variables --- %s seconds ---\" % (time.time() - start_time))\n return \n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--ticker', type=str, default='All')\n\n parser.add_argument('--data_path', type=str, default='../data_semiconduct/')\n parser.add_argument('--option_file_path', type=str, default='Option.csv') \n parser.add_argument('--stock_price_file_path', type=str, default='StockPriceAll.csv') \n\n parser.add_argument('--volume_threshold', type=int, default=0)\n parser.add_argument('--open_interest_threshold', type=int, default=0)\n parser.add_argument('--cp_flag', type=str, default='C') # call : 'C' or put : 'P'\n parser.add_argument('--exercise_style', type=str, default='A') # American\n parser.add_argument('--expiry_indicator', type=str, default='regular') # or 'w' weekly option\n\n parser.add_argument('--mode', type=str, default='all')\n parser.add_argument('--suffix', type=str, default='')\n parser.add_argument('--refresh', action='store_true') # default false\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n\n args = parse_args()\n if args.ticker != '':\n args.option_file_path = args.ticker + '_' + args.option_file_path\n\n print('='*9 + 'START' + '='*9)\n print(args)\n if args.mode == 'all': \n if args.ticker == 'All':\n \n print('Starting preprocess option data of all stocks')\n read_option_csv(args, saving=True)\n\n df = pd.read_hdf(args.data_path+'All_Option.h5')\n print('Split All Option Data by Stock')\n for ticker in df['ticker'].unique():\n t = df[df['ticker']==ticker]\n filename = args.data_path+ticker+'_Option.h5'\n if args.refresh or not os.path.exists(filename):\n t.to_hdf(filename, key=ticker)\n print('{} Saved, number of samples : {}'.format(ticker, t.shape[0]))\n else:\n print(filename + ' already exists')\n print('Total {} stocks'.format(len(df['ticker'].unique())))\n \n\n print('Preprocess All Stock Option Data')\n for f in os.listdir(args.data_path):\n idx = f.find(\"_Option.h5\")\n if idx != -1:\n if 'All' in f:\n continue\n print(f)\n args.ticker = f[:idx]\n args.option_file_path = f\n \n preprocess(args)\n combine_variables(args)\n\n print('Concat All Stock Option into One')\n All_Option_A = []\n for f in os.listdir(args.data_path):\n idx = f.find(\"_Option_\"+args.cp_flag+\"_A.h5\")\n if idx != -1:\n if 'All' in f:\n continue\n df = pd.read_hdf(args.data_path+f)\n print(f, df.shape[0])\n All_Option_A.append(df)\n pd.concat(All_Option_A).to_hdf(args.data_path+'All_Option_' +args.cp_flag+'_A.h5', key='all')\n print('All Stock Option Data is Saved')\n \n else:\n preprocess(args)\n combine_variables(args)\n \n elif args.mode == 'read':\n read_option_csv(args, saving=True)\n elif args.mode == 'combine':\n combine_sentiment(args)\n elif args.mode == 'cv':\n combine_variables(args)\n\n\n else:\n print('No such mode')\n\n print('='*10 + 'END' + '='*10)\n \n \n\n\n\n ","sub_path":"option_preprocess_industry.py","file_name":"option_preprocess_industry.py","file_ext":"py","file_size_in_byte":19831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"601030108","text":"\"\"\"\n This library contains the functions that allows the GUI to \n obtain the default and the previous values of the configuration\n\"\"\"\n\n#System Configuration default values\ndef scSetDefultValues():\n defaultValues = {}\n defaultValues[\"std2\"] = \"selected\"\n defaultValues[\"gain\"] = \"selected\"\n defaultValues[\"ledChecked\"] = \"checked\"\n defaultValues[\"agcChecked\"] = \"checked\"\n defaultValues[\"ser2Checked\"] = \"checked\"\n defaultValues[\"stChecked\"] = \"checked\"\n defaultValues[\"tlChecked\"] = \"checked\"\n defaultValues[\"cChecked\"] = \"checked\"\n defaultValues[\"rChecked\"] = \"checked\"\n defaultValues[\"dcChecked\"] = \"checked\"\n defaultValues[\"slfChecked\"] = \"checked\"\n return defaultValues\n\n#System Configuration previous values\ndef scSetPreviousValues(**parameters):\n previousValues={}\n for key,value in parameters.items():\n #========#\n if key == \"selfTrigDelay\":\n if(value==2):\n previousValues[\"std2\"] = \"selected\"\n if(value==4):\n previousValues[\"std4\"] = \"selected\"\n if(value==8):\n previousValues[\"std8\"] = \"selected\"\n if(value==16):\n previousValues[\"std16\"] = \"selected\"\n if(value==32):\n previousValues[\"std32\"] = \"selected\"\n if(value==64):\n previousValues[\"std64\"] = \"selected\"\n if(value==128):\n previousValues[\"std128\"] = \"selected\"\n if(value==256):\n previousValues[\"std256\"] = \"selected\"\n #========#\n if key == \"led\":\n ledChecked = \"\"\n if value:\n ledChecked = \"checked\"\n previousValues[\"ledChecked\"] = ledChecked\n #========#\n if key == \"raw\":\n rawChecked = \"\"\n if value:\n rawChecked = \"checked\"\n previousValues[\"rawChecked\"] = rawChecked\n #========#\n if key == \"agc\":\n agcChecked = \"\"\n if value:\n agcChecked = \"checked\"\n previousValues[\"agcChecked\"] = agcChecked\n if key == \"gain\":\n if(value==8):\n previousValues[\"gain8\"] = \"selected\"\n if(value==21):\n previousValues[\"gain21\"] = \"selected\"\n if(value==43):\n previousValues[\"gain43\"] = \"selected\"\n if(value==56):\n previousValues[\"gain56\"] = \"selected\"\n #========#\n if key == \"ser2\":\n ser2Checked = \"\"\n if value:\n ser2Checked = \"checked\"\n previousValues[\"ser2Checked\"] = ser2Checked\n if key == \"ser1\":\n ser1Checked = \"\"\n if value:\n ser1Checked = \"checked\"\n previousValues[\"ser1Checked\"] = ser1Checked\n if key == \"ext\":\n extChecked = \"\"\n if value:\n extChecked = \"checked\"\n previousValues[\"extChecked\"] = extChecked\n if key == \"st\":\n stChecked = \"\"\n if value:\n stChecked = \"checked\"\n previousValues[\"stChecked\"] = stChecked\n #========#\n if key == \"tl\":\n tlChecked = \"\"\n if value:\n tlChecked = \"checked\"\n previousValues[\"tlChecked\"] = tlChecked\n if key == \"p\":\n pChecked = \"\"\n if value:\n pChecked = \"checked\"\n previousValues[\"pChecked\"] = pChecked\n if key == \"c\":\n cChecked = \"\"\n if value:\n cChecked = \"checked\"\n previousValues[\"cChecked\"] = cChecked\n if key == \"r\":\n rChecked = \"\"\n if value:\n rChecked = \"checked\"\n previousValues[\"rChecked\"] = rChecked\n #========#\n if key == \"dc\":\n dcChecked = \"\"\n if value:\n dcChecked = \"checked\"\n previousValues[\"dcChecked\"] = dcChecked\n if key == \"slf\":\n slfChecked = \"\"\n if value:\n slfChecked = \"checked\"\n previousValues[\"slfChecked\"] = slfChecked\n if key == \"pre\":\n preChecked = \"\"\n if value:\n preChecked = \"checked\"\n previousValues[\"preChecked\"] = preChecked\n #========#\n return previousValues","sub_path":"libraries/guiDefaultValues.py","file_name":"guiDefaultValues.py","file_ext":"py","file_size_in_byte":4375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"240869119","text":"from collections import deque\n\n\ndef main():\n N = int(input())\n cranes = sorted( list(map(int, input().split())), reverse=True)\n\n M = int(input())\n boxes = sorted( list(map(int, input().split())), reverse=True)\n\n\n if cranes[0] < boxes[0]:\n print(-1)\n return\n\n queue = deque(boxes)\n answer = 0\n while True:\n answer += 1\n for c in cranes:\n if queue:\n if c >= queue[0]:\n queue.popleft()\n else: # 더 이상 못해. 다음 사이클에 시도\n break\n else: # 다 옮겼음\n break \n\n if not queue:\n print(answer)\n return\n\nmain()\n\n","sub_path":"bakjoon/배.py","file_name":"배.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"260344427","text":"import os\nimport tornado.web\nimport tornado.ioloop\nimport tornado.httpserver\nimport redis\n\nclass App(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r'/', MainHandler), \n ]\n\n settings = dict(\n template_path = os.path.join(os.path.dirname(\"__file__\"), 'templates')\n )\n\n tornado.web.Application.__init__(self, handlers, **settings)\n\n self.db = redis.StrictRedis()\n\n\nclass BaseHandler(tornado.web.RequestHandler):\n @property\n def db(self):\n return self.application.db\n\n\nclass MainHandler(BaseHandler):\n def get(self):\n name = self.db.get('name')\n self.render('01/index.html', name=name)\n\n def post(self):\n name = self.get_argument('uname')\n self.db.set('name', name)\n self.redirect('/')\n\ndef main():\n http_server = tornado.httpserver.HTTPServer(App())\n http_server.listen(8888)\n tornado.ioloop.IOLoop.instance().start()\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"redis_tornado/f2.py","file_name":"f2.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"492618544","text":"import numpy as np\nfrom automatminer.analytics import Analytics\nfrom matminer.datasets.convenience_loaders import load_expt_gap\nfrom automatminer.featurize import Featurize\nfrom automatminer.preprocess import PreProcess\nfrom matminer import PlotlyFig\nfrom scipy.stats import linregress\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\n# inputs\ntarget = 'gap expt'\nRS = 24\nmode = 'regression'\nMULTIINDEX = True\nif MULTIINDEX:\n target = ('Input Data', target)\n\ndf_init = load_expt_gap()\nfeatzer = Featurize(exclude=['CohesiveEnergy', 'AtomicPackingEfficiency'],\n multiindex=MULTIINDEX)\n\ndf = featzer.featurize_formula(df_init,\n featurizers='all',\n guess_oxidstates=False)\n\nprep = PreProcess(target=target)\ndf = prep.preprocess(df)\n\nprint(df.head())\ndf.to_csv('test.csv')\n\nX_train, X_test, y_train, y_test = train_test_split(\n df.drop(target, axis=1), df[target])\n\nmodel = RandomForestRegressor(n_estimators=100,\n bootstrap=False,\n max_features=0.8,\n min_samples_leaf=1,\n min_samples_split=4,\n random_state=RS)\n\n\nmodel.fit(X_train.values, y_train.values)\nprint('test score:')\nprint(model.score(X_test, y_test))\n\nanalysis = Analytics(model, X_train, y_train, X_test, y_test, mode,\n target=target,\n features=df.drop(target, axis=1).columns,\n test_samples_index=X_test.index,\n random_state=RS)\n\nx = list(analysis.get_feature_importance(sort=False).values())\ny = model.feature_importances_\nlr = linregress(x, y)\nxreg = np.linspace(0.0, round(max(x),2), num=2)\nyreg = lr.intercept + xreg * lr.slope\n\nprint('correlation, r={}'.format(lr.rvalue))\nprint('p-value, p={}'.format(lr.pvalue))\n\npf = PlotlyFig(\n title='Comparison of feature importances in predicting expt. gap',\n x_title='Analytics.feature_importance (Variance Sensitivity Analysis)',\n y_title='RandomForestRegressor.feature_importances_')\npf.xy([(x, y), (xreg, yreg)],\n labels=analysis.features,\n modes=['markers', 'line'],\n showlegends=False)","sub_path":"examples/feature_importance_regression.py","file_name":"feature_importance_regression.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"103991516","text":"#!/usr/bin/python\n\"\"\"\nGiven s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.\n\nFor example,\nGiven:\ns1 = \"aabcc\",\ns2 = \"dbbca\",\n\nWhen s3 = \"aadbbcbcac\", return true.\nWhen s3 = \"aadbbbaccc\", return false.\n\n#97\n\"\"\"\ndef interleaveString(s1, s2, s3):\n w = len(s1)\n h = len(s2)\n if len(s3) != (w+h): return False\n dp = [x[:] for x in [[False]*(w+1)]*(h+1)]\n dp[0][0] = True\n for j in range(1, w+1):\n if s1[j-1] == s3[j-1] and dp[0][j-1] == True: dp[0][j] = True\n\n for i in range(1, h+1):\n if s2[i-1] == s3[i-1] and dp[i-1][0] == True: dp[i][0] = True\n\n for j in range(1, w+1):\n for i in range(1, h+1):\n if (dp[i-1][j] == True and s2[i-1] == s3[i+j-1]) or \\\n (dp[i][j-1] == True and s1[j-1] == s3[i+j-1]):\n dp[i][j] = True\n\n return dp[-1][-1]\n\ndef interleaveStringLessSpace(s1, s2, s3):\n w = len(s1)\n h = len(s2)\n\n if len(s3) != (w+h): return False\n dp = [False]*(w+1)\n for i in range(h+1):\n for j in range(w+1):\n if j == 0 and i == 0: dp[j] = True\n elif i == 0:\n dp[j] = s1[j-1] == s3[j-1] and dp[j-1]\n elif j == 0:\n dp[j] = s2[i-1] == s3[i-1] and dp[j]\n else:\n dp[j] = (dp[j] and s2[i-1] == s3[i+j-1]) or \\\n (dp[j-1] and s1[j-1] == s3[i+j-1])\n\n return dp[-1]\n\ndef test1():\n s1 = 'aabcc'\n s2 = 'dbbca'\n s3 = 'aadbbcbcac'\n print(interleaveString(s1, s2, s3))\n print(interleaveStringLessSpace(s1, s2, s3))\n print('----------------')\n\ndef test2():\n s1 = 'aabcc'\n s2 = 'dbbca'\n s3 = 'aadbbbaccc'\n print(interleaveString(s1, s2, s3))\n print(interleaveStringLessSpace(s1, s2, s3))\n print('----------------')\n\ndef test3():\n s1 = ''\n s2 = ''\n s3 = ''\n print(interleaveString(s1, s2, s3))\n print(interleaveStringLessSpace(s1, s2, s3))\n print('----------------')\n\nif __name__ == '__main__':\n test1()\n test2()\n test3()\n","sub_path":"dynamicProgramming/interleaveString.py","file_name":"interleaveString.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"365958865","text":"#! python/python-anaconda3.2019.7\r\n\r\nimport argparse\r\nimport time\r\nimport glob\r\nimport os\r\n\r\ndef create_pbs_cmd(cmdfile, alias, jnum, gmem, cmds, queue, load_python=True):\r\n\twith open(cmdfile, 'w') as o:\r\n\t\to.write(\"#!/bin/bash\\n#PBS -S /bin/bash\\n#PBS -j oe\\n#PBS -r y\\n\")\r\n\t\to.write(\"#PBS -q %s\\n\" % queue)\r\n\t\to.write(\"#PBS -v PBS_O_SHELL=bash,PBS_ENVIRONMENT=PBS_BATCH \\n\")\r\n\t\to.write(\"#PBS -N \"+ alias+\"\\n\")\r\n\t\to.write(\"#PBS -o %s\\n\" % \"/\".join(cmdfile.split(\"/\")[:-1]))\r\n\t\to.write(\"#PBS -e %s\\n\" % \"/\".join(cmdfile.split(\"/\")[:-1]))\r\n\t\tif gmem:\r\n\t\t\tmem=gmem*1000\r\n\t\t\to.write(\"#PBS -l mem=\"+str(mem)+\"mb\\n\")\r\n\t\tif jnum:\r\n\t\t\tif jnum != 1:\r\n\t\t\t\to.write(\"#PBS -J 1-\"+str(jnum)+\"\\n\\n\")\r\n\t\to.write(\"id\\n\")\r\n\t\to.write(\"date\\n\")\r\n\t\to.write(\"hostname\\n\")\r\n\t\tif load_python:\r\n\t\t\to.write(\"module load python/anaconda_python-3.6.1\\n\") \r\n\t\to.write(\"\\n\")\r\n\t\to.write(cmds)\r\n\t\to.write(\"\\n\")\r\n\t\to.write(\"date\\n\")\r\n\to.close()\r\n\r\ndef submit(cmdfile):\r\n\tcmd = \"/opt/pbs/bin/qsub \" + cmdfile\r\n\tresult = os.popen(cmd).read()\r\n\tif 'power' in result:\r\n\t\treturn result.split(\".\")[0]\r\n\telse:\r\n\t\tprint(\"cmd file was not submitted\")\t\r\n\r\ndef Sleep (alias, job_id, sleep_max = 1200000, sleep_quantum = 10):\r\n\ti = 0 \r\n\tprocess = os.popen(\"qstat -t \" + job_id + \" | wc -l\").read()\r\n\ttry:\r\n\t\tprocess = int(process)\r\n\texcept:\r\n\t\tprocess = 0\r\n\t\r\n\twhile process > 0 and i <= sleep_max: \r\n\t\ttime.sleep(sleep_quantum)\r\n\t\ti += sleep_quantum\r\n\t\tprint (\"Running...\")\r\n\t\tprocess = os.popen(\"qstat -t \" + job_id + \" | wc -l\").read() #check\r\n\t\ttry:\r\n\t\t\tprocess = int(process)\r\n\t\texcept:\r\n\t\t\tprocess = 0\r\n\t\t\r\n\tif process > 0: \r\n\t\traise Exception(alias + \" stage was not completed. Max sleep time reached\\n\")\r\n\r\ndef FindFilesInDir(dir_path, file_type):\r\n\tfile_path = dir_path + \"/*\" + file_type\r\n\tlist_of_files = sorted(glob.glob(file_path))\r\n\tnum_of_files = len(list_of_files)\r\n\tif num_of_files > 0:\r\n\t\tfor file in list_of_files:\r\n\t\t\tsize = os.path.getsize(file)\r\n\t\t\tif size == 0:\r\n\t\t\t\traise Exception(\"Unexpected error, some of the \" + file_type + \" files in \" + dir_path + \" are empty\\n\")\r\n \r\n\treturn list_of_files\r\n\r\ndef run_multi_projects(pipeline_path, cmds_file, queue):\r\n\talias = \"RunMultiProjects\"\r\n\t\r\n\tnum_of_cmd = int(os.popen(\"awk 'END {print NR}' \" + cmds_file).read())\r\n\tif num_of_cmd == 0:\r\n\t\traise Exception (\"Unexpected error, file \" + cmds_file + \" is empty, or number of lines in file does not divide by 2\\n\")\r\n\telif num_of_cmd == 1:\r\n\t\tNR_value = '1'\r\n\t\tgmem = 2\r\n\telse:\r\n\t\tNR_value = '$PBS_ARRAY_INDEX'\r\n\t\tgmem = 7\r\n\t\r\n\tdir_path = os.path.dirname(cmds_file)\r\n\tcmdfile = dir_path + \"/RunMultiProjects.cmd\"\t\r\n\tcmd1 = 'CMD=$(awk \"NR==' + NR_value + '\" ' + cmds_file + ')\\n'\r\n\tcmd2 = \"python \" + pipeline_path + \" $CMD \"\r\n\tcmds = cmd1 + cmd2\r\n\tcreate_pbs_cmd(cmdfile=cmdfile, alias=alias, jnum=num_of_cmd, gmem=gmem, cmds=cmds, queue=queue, load_python=True)\r\n\tjob_id = submit(cmdfile)\r\n\tprint(job_id)\r\n\tSleep(alias, job_id)\r\n\ttime.sleep(10)\r\n\t\r\ndef main(args):\r\n\t\r\n\t#pipeline_path = args.pipeline_runner\r\n\tpipeline_dir = os.path.dirname(os.path.abspath(__file__).strip())\r\n\tpipeline_path = pipeline_dir + \"/Runner.py\"\r\n\r\n\tif not os.path.isfile(pipeline_path):\r\n\t\traise Exception(\"Unexpected error, \" + pipeline_path + \" does not exist, is not a file or or is not a blast file\\n\")\r\n\t\r\n\tcmds_file = args.cmds_file\r\n\tif not os.path.isfile(cmds_file):\r\n\t\traise Exception(\"Unexpected error, \" + cmds_file + \" cmds file does not exist or is not a file\\n\")\r\n\r\n\tqueue = args.queue\r\n\tif queue != None:\r\n\t\tif queue not in [\"inf\", \"hugemem\", \"pup-interactive\", \"parallel\", \"adis\", \"adis-long\"]:\r\n\t\t\traise Exception(\"Unexpected error, queue has to be either 'inf', 'hugemem', 'pup-interactive', 'parallel', 'adis', 'adis-long'\\n\")\r\n\r\n\trun_multi_projects(pipeline_path, cmds_file, queue)\r\n\t\r\n\tprint(\"END OF RUN MULTI PROJECTS\")\r\n\r\nif __name__ == \"__main__\":\r\n\tparser = argparse.ArgumentParser()\r\n\tparser.add_argument(\"-f\", \"--cmds_file\", type=str, help=\"a path to a file containing a list of cmds to run. Different variables for each cmd are excepted\", required=True)\r\n\tparser.add_argument(\"-qu\", \"--queue\", type=str, help=\"queue to run pipeline, default='adis'\", required=False, default=\"adis\")\r\n\targs = parser.parse_args()\r\n\tmain(args)\r\n","sub_path":"Yaara/pipeline/Multi_Projects_Runner.py","file_name":"Multi_Projects_Runner.py","file_ext":"py","file_size_in_byte":4215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"193511665","text":"# version 3.5.1\n# Takes input as density,temp\nimport logging\nfrom math import trunc\n\nlog = logging.getLogger(__name__)\nlog.info('Loaded calc_vcf')\n\n\ndef calc_vol_to_tons(ml, density, temperature):\n log_l = log.getChild('calc_vol_to_tons')\n log_l.info('Started')\n log_l.info('Calling calc_54b')\n corr_vcf = calc_54b(density, temperature)\n log_l.info('calc_54b returned %s' % corr_vcf)\n sl = round(ml * corr_vcf)\n log_l.debug('sl = ml %s, * vcf %s' % (ml, corr_vcf))\n log_l.info('Calling calc_56')\n corr_wcf = calc_56(density)\n log_l.info('calc_56 returned %s' % corr_wcf)\n mt = (round(sl * corr_wcf)) / 1000\n log_l.debug('mt = sl %s, * wcf %s' % (sl, corr_wcf))\n return [ml, sl, mt]\n\n\ndef calc_54b(density, temperature):\n log_l = log.getChild('calc_54b')\n log_l.info('Started.')\n log_l.debug('Density %s, Temp %s' % (density, temperature))\n density = float(density)\n temperature = float(temperature)\n # Call up Individual stepped calculations.\n # return_original_values()\n f = calc_f(temperature)\n # print f, \" 0:\n return 0\n elif a <= 787.5:\n return -0.00336312 + (2680.3206 / (a * a))\n else:\n return 0\n\n\ndef calc_z2(a, z0, z1):\n if z1 > 0 and z0 > 0:\n return 0\n elif a <= 839:\n return 594.5418 / (a * a)\n else:\n return (186.9696 / (a * a)) + (0.4862 / a)\n\n\ndef calc_z54b(z0, z1, z2):\n return z0 + z1 + z2\n\n\ndef calc_x(f):\n return f - 15\n\n\ndef calc_o(z54b, x):\n return 1 + 0.8 * z54b * x\n\n\ndef calc_l(z54b, x, o):\n return -z54b * x * o\n\n\ndef calc_v(l):\n return 2.718281825 ** l\n\n\ndef calc_y(v):\n return round(float(trunc((v + 0.00005) * 10000)) / 10000, 4)\n\n\nif __name__ == '__main__':\n exit()","sub_path":"calcs/calc_vcf.py","file_name":"calc_vcf.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"237555463","text":"# -*- coding: utf-8 -*-\n\"\"\"\n sphinxcontrib.confluencebuilder.test.test_builder\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n :copyright: Copyright 2016-2017 by the contributors (see AUTHORS file).\n :license: BSD, see LICENSE.txt for details.\n\"\"\"\n\nfrom sphinx.application import Sphinx\nfrom sphinxcontrib.confluencebuilder.builder import ConfluenceBuilder\nfrom sphinxcontrib.confluencebuilder.exceptions import ConfluenceConfigurationError\nfrom sphinxcontrib.confluencebuilder.common import ConfluenceDocMap\nimport difflib\nimport os\nimport sys\nimport unittest\n\ndef create_default_test_config():\n config = {}\n config['extensions'] = ['sphinxcontrib.confluencebuilder']\n config['confluence_parent_page'] = 'Documentation'\n config['confluence_publish'] = False\n config['confluence_space_name'] = 'TEST'\n return config\n\nclass TestConfluenceBuilder(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n basedir = os.path.dirname(os.path.realpath(__file__))\n srcdir = os.path.join(basedir, 'testproj')\n self.expected = os.path.join(srcdir, 'expected')\n builddir = os.path.join(srcdir, 'build')\n self.outdir = os.path.join(builddir, 'out')\n doctreedir = os.path.join(builddir, 'doctree')\n\n self.config = create_default_test_config()\n\n self.app = Sphinx(\n srcdir, None, self.outdir, doctreedir, 'confluence', self.config)\n self.app.build(force_all=True)\n\n def _assertExpectedWithOutput(self, name):\n filename = name + '.conf'\n expected_path = os.path.join(self.expected, filename)\n test_path = os.path.join(self.outdir, filename)\n self.assertTrue(os.path.exists(expected_path))\n self.assertTrue(os.path.exists(test_path))\n\n with open(expected_path, 'r') as expected_file:\n with open(test_path, 'r') as test_file:\n expected_data = expected_file.readlines()\n test_data = test_file.readlines()\n diff = difflib.unified_diff(\n expected_data, test_data, lineterm='')\n diff_data = ''.join(list(diff))\n self.assertTrue(diff_data == '', msg=diff_data)\n\n def test_registry(self):\n if hasattr(self.app, 'extensions'):\n self.assertTrue('sphinxcontrib.confluencebuilder' in\n self.app.extensions.keys())\n else:\n self.assertTrue('sphinxcontrib.confluencebuilder' in\n self.app._extensions.keys())\n\n def test_heading(self):\n test_path = os.path.join(self.outdir, 'heading.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n\n self.assertEqual(lines[0], \"h1. HEADING_TEST\\n\")\n self.assertEqual(lines[1], '\\n')\n self.assertEqual(lines[2], 'h2. SUBHEADER_TEST\\n')\n\n def test_list(self):\n test_path = os.path.join(self.outdir, 'list.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(lines[0], 'h1. list test\\n')\n self.assertEqual(lines[1], '\\n')\n self.assertEqual(lines[2], \"* BULLET_1\\n\")\n self.assertEqual(lines[3], '* BULLET_2\\n')\n self.assertEqual(lines[4], '\\n')\n self.assertEqual(lines[5], \"# ENUMERATED_1\\n\")\n self.assertEqual(lines[6], '# ENUMERATED_2\\n')\n\n def test_formatting(self):\n test_path = os.path.join(self.outdir, 'text.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(lines[0], 'h1. this is a text test\\n')\n self.assertEqual(lines[2], '_emphasis_\\n')\n self.assertEqual(lines[4], '*strong emphasis*\\n')\n self.assertEqual(lines[6], '[http://website.com/]\\n')\n self.assertEqual(lines[10], '----\\n')\n self.assertEqual(lines[12], 'End of transition test\\n');\n\n def test_admonitions(self):\n test_path = os.path.join(self.outdir, 'admonitions.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(lines[0], 'h1. Admonition Test\\n')\n self.assertEqual(lines[2], '{note}attention-message{note}\\n')\n self.assertEqual(lines[4], '{warning}caution-message{warning}\\n')\n self.assertEqual(lines[6], '{warning}danger-message{warning}\\n')\n self.assertEqual(lines[8], '{warning}error-message{warning}\\n')\n self.assertEqual(lines[10], '{tip}hint-message{tip}\\n')\n self.assertEqual(lines[12], '{warning}important-message{warning}\\n')\n self.assertEqual(lines[14], '{info}note-message{info}\\n')\n self.assertEqual(lines[16], '{tip}tip-message{tip}\\n')\n self.assertEqual(lines[18], '{warning}warning-message{warning}\\n')\n\n def test_code(self):\n test_path = os.path.join(self.outdir, 'code.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(lines[0], 'h1. Code Test\\n')\n self.assertEqual(lines[2], '{code:linenumbers=false|language=python}\\n')\n self.assertEqual(lines[3], 'import antigravity\\n')\n self.assertEqual(lines[4], 'antigravity.space()\\n')\n self.assertEqual(lines[5], '{code}\\n')\n\n def test_references(self):\n self._assertExpectedWithOutput('ref')\n\n def test_toctree(self):\n test_path = os.path.join(self.outdir, 'toctree.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(lines[0], 'h1. TOCTREE\\n')\n self.assertEqual(lines[2], '* [Code Test]\\n')\n self.assertEqual(lines[3], '* [HEADING_TEST]\\n')\n self.assertEqual(lines[4], '** [SUBHEADER_TEST|HEADING_TEST#SUBHEADER_TEST]\\n')\n\n def test_table(self):\n test_path = os.path.join(self.outdir, 'tables.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(len(lines), 6)\n self.assertEqual(lines[0], 'h1. Table Test\\n')\n self.assertEqual(lines[2], '||A||B||A or B||\\n')\n self.assertEqual(lines[3], '|False|False|False|\\n')\n self.assertEqual(lines[4], '|True|False|True|\\n')\n\n def test_no_parent(self):\n self.assertEqual(ConfluenceDocMap.parent(\"toctree\"), None)\n self.assertEqual(ConfluenceDocMap.parent(\"code\"), None)\n\n def test_publish(self):\n builder = ConfluenceBuilder(self.app)\n builder.config.confluence_publish = True\n with self.assertRaises(ConfluenceConfigurationError):\n builder.init()\n\nclass TestConfluenceBuilderExperimentalParent(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n basedir = os.path.dirname(os.path.realpath(__file__))\n srcdir = os.path.join(basedir, 'testproj')\n self.expected = os.path.join(srcdir, 'expected')\n builddir = os.path.join(srcdir, 'build')\n self.outdir = os.path.join(builddir, 'experimental-parent-out')\n doctreedir = os.path.join(builddir, 'experimental-parent-doctree')\n\n self.config = create_default_test_config()\n self.config['master_doc'] = \"toctree\"\n self.config['confluence_experimental_page_hierarchy'] = True\n\n self.app = Sphinx(\n srcdir, None, self.outdir, doctreedir, 'confluence', self.config)\n self.app.build(force_all=True)\n\n def test_parent(self):\n self.assertEqual(ConfluenceDocMap.parent(\"toctree\"), None)\n self.assertEqual(ConfluenceDocMap.parent(\"code\"), \"toctree\")\n\nclass TestConfluenceBuilderExperimentalDepth(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n basedir = os.path.dirname(os.path.realpath(__file__))\n srcdir = os.path.join(basedir, 'testproj')\n self.expected = os.path.join(srcdir, 'expected')\n builddir = os.path.join(srcdir, 'build')\n self.outdir = os.path.join(builddir, 'experimental-depth-out')\n doctreedir = os.path.join(builddir, 'experimental-depth-doctree')\n\n self.config = create_default_test_config()\n self.config['master_doc'] = \"toctree\"\n self.config['confluence_experimental_max_depth'] = 0\n\n self.app = Sphinx(\n srcdir, None, self.outdir, doctreedir, 'confluence', self.config)\n self.app.build(force_all=True)\n\n def test_parent(self):\n self.assertEqual(ConfluenceDocMap.depth(\"toctree\"), 0)\n self.assertEqual(ConfluenceDocMap.depth(\"code\"), 1)\n\n\nif __name__ == '__main__':\n sys.exit(unittest.main())\n","sub_path":"test/test_builder.py","file_name":"test_builder.py","file_ext":"py","file_size_in_byte":9080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"347328861","text":"import logging\nimport datetime\nimport urlparse\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils import timezone\n\nfrom framework.auth import Auth\nfrom framework.exceptions import PermissionsError\nfrom osf.utils.fields import NonNaiveDateTimeField\nfrom osf.exceptions import NodeStateError\nfrom website.util import api_v2_url\nfrom website import settings\nfrom website.archiver import ARCHIVER_INITIATED\n\nfrom osf.models import (\n OSFUser, RegistrationSchema,\n Retraction, Embargo, DraftRegistrationApproval,\n EmbargoTerminationApproval,\n)\n\nfrom osf.models.archive import ArchiveJob\nfrom osf.models.base import BaseModel, ObjectIDMixin\nfrom osf.models.node import AbstractNode\nfrom osf.models.nodelog import NodeLog\nfrom osf.models.provider import RegistrationProvider\nfrom osf.models.validators import validate_doi\nfrom osf.utils.datetime_aware_jsonfield import DateTimeAwareJSONField\n\nlogger = logging.getLogger(__name__)\n\n\nclass Registration(AbstractNode):\n\n WRITABLE_WHITELIST = [\n 'article_doi',\n 'description',\n 'is_public',\n 'node_license',\n ]\n\n article_doi = models.CharField(max_length=128,\n validators=[validate_doi],\n null=True, blank=True)\n provider = models.ForeignKey('RegistrationProvider', related_name='registrations', null=True)\n registered_date = NonNaiveDateTimeField(db_index=True, null=True, blank=True)\n registered_user = models.ForeignKey(OSFUser,\n related_name='related_to',\n on_delete=models.SET_NULL,\n null=True, blank=True)\n\n registered_schema = models.ManyToManyField(RegistrationSchema)\n\n registered_meta = DateTimeAwareJSONField(default=dict, blank=True)\n registered_from = models.ForeignKey('self',\n related_name='registrations',\n on_delete=models.SET_NULL,\n null=True, blank=True)\n # Sanctions\n registration_approval = models.ForeignKey('RegistrationApproval',\n related_name='registrations',\n null=True, blank=True,\n on_delete=models.SET_NULL)\n retraction = models.ForeignKey('Retraction',\n related_name='registrations',\n null=True, blank=True,\n on_delete=models.SET_NULL)\n embargo = models.ForeignKey('Embargo',\n related_name='registrations',\n null=True, blank=True,\n on_delete=models.SET_NULL)\n embargo_termination_approval = models.ForeignKey('EmbargoTerminationApproval',\n related_name='registrations',\n null=True, blank=True,\n on_delete=models.SET_NULL)\n\n @staticmethod\n def find_failed_registrations():\n expired_if_before = timezone.now() - settings.ARCHIVE_TIMEOUT_TIMEDELTA\n node_id_list = ArchiveJob.objects.filter(sent=False, datetime_initiated__lt=expired_if_before, status=ARCHIVER_INITIATED).values_list('dst_node', flat=True)\n root_nodes_id = AbstractNode.objects.filter(id__in=node_id_list).values_list('root', flat=True).distinct()\n stuck_regs = AbstractNode.objects.filter(id__in=root_nodes_id, is_deleted=False)\n return stuck_regs\n\n @property\n def registered_schema_id(self):\n if self.registered_schema.exists():\n return self.registered_schema.first()._id\n return None\n\n @property\n def is_registration(self):\n \"\"\"For v1 compat.\"\"\"\n return True\n\n @property\n def is_stuck_registration(self):\n return self in self.find_failed_registrations()\n\n @property\n def is_collection(self):\n \"\"\"For v1 compat.\"\"\"\n return False\n\n @property\n def archive_job(self):\n return self.archive_jobs.first() if self.archive_jobs.count() else None\n\n @property\n def sanction(self):\n root = self._dirty_root\n sanction = (\n root.embargo_termination_approval or\n root.retraction or\n root.embargo or\n root.registration_approval\n )\n if sanction:\n return sanction\n else:\n return None\n\n @property\n def is_registration_approved(self):\n root = self._dirty_root\n if root.registration_approval is None:\n return False\n return root.registration_approval.is_approved\n\n @property\n def is_pending_embargo(self):\n root = self._dirty_root\n if root.embargo is None:\n return False\n return root.embargo.is_pending_approval\n\n @property\n def is_pending_embargo_for_existing_registration(self):\n \"\"\" Returns True if Node has an Embargo pending approval for an\n existing registrations. This is used specifically to ensure\n registrations pre-dating the Embargo feature do not get deleted if\n their respective Embargo request is rejected.\n \"\"\"\n root = self._dirty_root\n if root.embargo is None:\n return False\n return root.embargo.pending_registration\n\n @property\n def is_retracted(self):\n root = self._dirty_root\n if root.retraction is None:\n return False\n return root.retraction.is_approved\n\n @property\n def is_pending_registration(self):\n root = self._dirty_root\n if root.registration_approval is None:\n return False\n return root.registration_approval.is_pending_approval\n\n @property\n def is_pending_retraction(self):\n root = self._dirty_root\n if root.retraction is None:\n return False\n return root.retraction.is_pending_approval\n\n @property\n def is_pending_embargo_termination(self):\n root = self._dirty_root\n if root.embargo_termination_approval is None:\n return False\n return root.embargo_termination_approval.is_pending_approval\n\n @property\n def is_embargoed(self):\n \"\"\"A Node is embargoed if:\n - it has an associated Embargo record\n - that record has been approved\n - the node is not public (embargo not yet lifted)\n \"\"\"\n root = self._dirty_root\n if root.is_public or root.embargo is None:\n return False\n return root.embargo.is_approved\n\n @property\n def embargo_end_date(self):\n root = self._dirty_root\n if root.embargo is None:\n return False\n return root.embargo.embargo_end_date\n\n @property\n def archiving(self):\n job = self.archive_job\n return job and not job.done and not job.archive_tree_finished()\n\n @property\n def _dirty_root(self):\n \"\"\"Equivalent to `self.root`, but don't let Django fetch a clean copy\n when `self == self.root`. Use when it's important to reflect unsaved\n state rather than database state.\n \"\"\"\n if self.id == self.root_id:\n return self\n return self.root\n\n def date_withdrawn(self):\n return getattr(self.root.retraction, 'date_retracted', None)\n\n @property\n def withdrawal_justification(self):\n return getattr(self.root.retraction, 'justification', None)\n\n def _initiate_embargo(self, user, end_date, for_existing_registration=False,\n notify_initiator_on_complete=False):\n \"\"\"Initiates the retraction process for a registration\n :param user: User who initiated the retraction\n :param end_date: Date when the registration should be made public\n \"\"\"\n end_date_midnight = datetime.datetime.combine(\n end_date,\n datetime.datetime.min.time()\n ).replace(tzinfo=end_date.tzinfo)\n self.embargo = Embargo.objects.create(\n initiated_by=user,\n end_date=end_date_midnight,\n for_existing_registration=for_existing_registration,\n notify_initiator_on_complete=notify_initiator_on_complete\n )\n self.save() # Set foreign field reference Node.embargo\n admins = self.get_admin_contributors_recursive(unique_users=True)\n for (admin, node) in admins:\n self.embargo.add_authorizer(admin, node)\n self.embargo.save() # Save embargo's approval_state\n return self.embargo\n\n def embargo_registration(self, user, end_date, for_existing_registration=False,\n notify_initiator_on_complete=False):\n \"\"\"Enter registration into an embargo period at end of which, it will\n be made public\n :param user: User initiating the embargo\n :param end_date: Date when the registration should be made public\n :raises: NodeStateError if Node is not a registration\n :raises: PermissionsError if user is not an admin for the Node\n :raises: ValidationError if end_date is not within time constraints\n \"\"\"\n if not self.has_permission(user, 'admin'):\n raise PermissionsError('Only admins may embargo a registration')\n if not self._is_embargo_date_valid(end_date):\n if (end_date - timezone.now()) >= settings.EMBARGO_END_DATE_MIN:\n raise ValidationError('Registrations can only be embargoed for up to four years.')\n raise ValidationError('Embargo end date must be at least three days in the future.')\n\n embargo = self._initiate_embargo(user, end_date,\n for_existing_registration=for_existing_registration,\n notify_initiator_on_complete=notify_initiator_on_complete)\n\n self.registered_from.add_log(\n action=NodeLog.EMBARGO_INITIATED,\n params={\n 'node': self.registered_from._id,\n 'registration': self._id,\n 'embargo_id': embargo._id,\n },\n auth=Auth(user),\n save=True,\n )\n if self.is_public:\n self.set_privacy('private', Auth(user))\n\n def request_embargo_termination(self, auth):\n \"\"\"Initiates an EmbargoTerminationApproval to lift this Embargoed Registration's\n embargo early.\"\"\"\n if not self.is_embargoed:\n raise NodeStateError('This node is not under active embargo')\n if not self.root == self:\n raise NodeStateError('Only the root of an embargoed registration can request termination')\n\n approval = EmbargoTerminationApproval(\n initiated_by=auth.user,\n embargoed_registration=self,\n )\n admins = [admin for admin in self.root.get_admin_contributors_recursive(unique_users=True)]\n for (admin, node) in admins:\n approval.add_authorizer(admin, node=node)\n approval.save()\n approval.ask(admins)\n self.embargo_termination_approval = approval\n self.save()\n return approval\n\n def terminate_embargo(self, auth):\n \"\"\"Handles the actual early termination of an Embargoed registration.\n Adds a log to the registered_from Node.\n \"\"\"\n if not self.is_embargoed:\n raise NodeStateError('This node is not under active embargo')\n\n self.registered_from.add_log(\n action=NodeLog.EMBARGO_TERMINATED,\n params={\n 'project': self._id,\n 'node': self.registered_from._id,\n 'registration': self._id,\n },\n auth=None,\n save=True\n )\n self.embargo.mark_as_completed()\n for node in self.node_and_primary_descendants():\n node.set_privacy(\n self.PUBLIC,\n auth=None,\n log=False,\n save=True\n )\n return True\n\n def _initiate_retraction(self, user, justification=None):\n \"\"\"Initiates the retraction process for a registration\n :param user: User who initiated the retraction\n :param justification: Justification, if given, for retraction\n \"\"\"\n self.retraction = Retraction.objects.create(\n initiated_by=user,\n justification=justification or None, # make empty strings None\n state=Retraction.UNAPPROVED\n )\n self.save()\n admins = self.get_admin_contributors_recursive(unique_users=True)\n for (admin, node) in admins:\n self.retraction.add_authorizer(admin, node)\n self.retraction.save() # Save retraction approval state\n return self.retraction\n\n def retract_registration(self, user, justification=None, save=True):\n \"\"\"Retract public registration. Instantiate new Retraction object\n and associate it with the respective registration.\n \"\"\"\n\n if not self.is_public and not (self.embargo_end_date or self.is_pending_embargo):\n raise NodeStateError('Only public or embargoed registrations may be withdrawn.')\n\n if self.root_id != self.id:\n raise NodeStateError('Withdrawal of non-parent registrations is not permitted.')\n\n retraction = self._initiate_retraction(user, justification)\n self.registered_from.add_log(\n action=NodeLog.RETRACTION_INITIATED,\n params={\n 'node': self.registered_from._id,\n 'registration': self._id,\n 'retraction_id': retraction._id,\n },\n auth=Auth(user),\n )\n self.retraction = retraction\n if save:\n self.save()\n return retraction\n\n def copy_unclaimed_records(self):\n \"\"\"Copies unclaimed_records to unregistered contributors from the registered_from node\"\"\"\n registered_from_id = self.registered_from._id\n for contributor in self.contributors.filter(is_registered=False):\n record = contributor.unclaimed_records.get(registered_from_id)\n if record:\n contributor.unclaimed_records[self._id] = record\n contributor.save()\n\n def delete_registration_tree(self, save=False):\n logger.debug('Marking registration {} as deleted'.format(self._id))\n self.is_deleted = True\n for draft_registration in DraftRegistration.objects.filter(registered_node=self):\n # Allow draft registration to be submitted\n if draft_registration.approval:\n draft_registration.approval = None\n draft_registration.save()\n if not getattr(self.embargo, 'for_existing_registration', False):\n self.registered_from = None\n if save:\n self.save()\n self.update_search()\n for child in self.nodes_primary:\n child.delete_registration_tree(save=save)\n\n def add_tag(self, tag, auth=None, save=True, log=True, system=False):\n if self.retraction is None:\n super(Registration, self).add_tag(tag, auth, save, log, system)\n else:\n raise NodeStateError('Cannot add tags to withdrawn registrations.')\n\n def add_tags(self, tags, auth=None, save=True, log=True, system=False):\n if self.retraction is None:\n super(Registration, self).add_tags(tags, auth, save, log, system)\n else:\n raise NodeStateError('Cannot add tags to withdrawn registrations.')\n\n def remove_tag(self, tag, auth, save=True):\n if self.retraction is None:\n super(Registration, self).remove_tag(tag, auth, save)\n else:\n raise NodeStateError('Cannot remove tags of withdrawn registrations.')\n\n def remove_tags(self, tags, auth, save=True):\n if self.retraction is None:\n super(Registration, self).remove_tags(tags, auth, save)\n else:\n raise NodeStateError('Cannot remove tags of withdrawn registrations.')\n\n class Meta:\n # custom permissions for use in the OSF Admin App\n permissions = (\n ('view_registration', 'Can view registration details'),\n )\n\nclass DraftRegistrationLog(ObjectIDMixin, BaseModel):\n \"\"\" Simple log to show status changes for DraftRegistrations\n\n field - _id - primary key\n field - date - date of the action took place\n field - action - simple action to track what happened\n field - user - user who did the action\n \"\"\"\n date = NonNaiveDateTimeField(default=timezone.now)\n action = models.CharField(max_length=255)\n draft = models.ForeignKey('DraftRegistration', related_name='logs',\n null=True, blank=True, on_delete=models.CASCADE)\n user = models.ForeignKey('OSFUser', null=True, on_delete=models.CASCADE)\n\n SUBMITTED = 'submitted'\n REGISTERED = 'registered'\n APPROVED = 'approved'\n REJECTED = 'rejected'\n\n def __repr__(self):\n return ('').format(self=self)\n\n\nclass DraftRegistration(ObjectIDMixin, BaseModel):\n URL_TEMPLATE = settings.DOMAIN + 'project/{node_id}/drafts/{draft_id}'\n\n datetime_initiated = NonNaiveDateTimeField(auto_now_add=True)\n datetime_updated = NonNaiveDateTimeField(auto_now=True)\n deleted = NonNaiveDateTimeField(null=True, blank=True)\n\n # Original Node a draft registration is associated with\n branched_from = models.ForeignKey('Node', related_name='registered_draft',\n null=True, on_delete=models.CASCADE)\n\n initiator = models.ForeignKey('OSFUser', null=True, on_delete=models.CASCADE)\n provider = models.ForeignKey('RegistrationProvider', related_name='draft_registrations', null=True)\n\n # Dictionary field mapping question id to a question's comments and answer\n # {\n # : {\n # 'comments': [{\n # 'user': {\n # 'id': ,\n # 'name': \n # },\n # value: ,\n # lastModified: \n # }],\n # 'value': \n # }\n # }\n registration_metadata = DateTimeAwareJSONField(default=dict, blank=True)\n registration_schema = models.ForeignKey('RegistrationSchema', null=True, on_delete=models.CASCADE)\n registered_node = models.ForeignKey('Registration', null=True, blank=True,\n related_name='draft_registration', on_delete=models.CASCADE)\n\n approval = models.ForeignKey('DraftRegistrationApproval', null=True, blank=True, on_delete=models.CASCADE)\n\n # Dictionary field mapping extra fields defined in the RegistrationSchema.schema to their\n # values. Defaults should be provided in the schema (e.g. 'paymentSent': false),\n # and these values are added to the DraftRegistration\n # TODO: Use \"FIELD_ALIASES\"?\n _metaschema_flags = DateTimeAwareJSONField(default=dict, blank=True)\n notes = models.TextField(blank=True)\n\n def __repr__(self):\n return ('').format(self=self)\n\n # lazily set flags\n @property\n def flags(self):\n if not self._metaschema_flags:\n self._metaschema_flags = {}\n meta_schema = self.registration_schema\n if meta_schema:\n schema = meta_schema.schema\n flags = schema.get('flags', {})\n dirty = False\n for flag, value in flags.items():\n if flag not in self._metaschema_flags:\n self._metaschema_flags[flag] = value\n dirty = True\n if dirty:\n self.save()\n return self._metaschema_flags\n\n @flags.setter\n def flags(self, flags):\n self._metaschema_flags.update(flags)\n\n @property\n def url(self):\n return self.URL_TEMPLATE.format(\n node_id=self.branched_from._id,\n draft_id=self._id\n )\n\n @property\n def absolute_url(self):\n return urlparse.urljoin(settings.DOMAIN, self.url)\n\n @property\n def absolute_api_v2_url(self):\n node = self.branched_from\n path = '/nodes/{}/draft_registrations/{}/'.format(node._id, self._id)\n return api_v2_url(path)\n\n # used by django and DRF\n def get_absolute_url(self):\n return self.absolute_api_v2_url\n\n @property\n def requires_approval(self):\n return self.registration_schema.requires_approval\n\n @property\n def is_pending_review(self):\n return self.approval.is_pending_approval if (self.requires_approval and self.approval) else False\n\n @property\n def is_approved(self):\n if self.requires_approval:\n if not self.approval:\n return bool(self.registered_node)\n else:\n return self.approval.is_approved\n else:\n return False\n\n @property\n def is_rejected(self):\n if self.requires_approval:\n if not self.approval:\n return False\n else:\n return self.approval.is_rejected\n else:\n return False\n\n @property\n def status_logs(self):\n \"\"\" List of logs associated with this node\"\"\"\n return self.logs.all().order_by('date')\n\n @classmethod\n def create_from_node(cls, node, user, schema, data=None, provider=None):\n if not provider:\n provider = RegistrationProvider.load('osf')\n draft = cls(\n initiator=user,\n branched_from=node,\n registration_schema=schema,\n registration_metadata=data or {},\n provider=provider,\n )\n draft.save()\n return draft\n\n def update_metadata(self, metadata):\n changes = []\n # Prevent comments on approved drafts\n if not self.is_approved:\n for question_id, value in metadata.items():\n old_value = self.registration_metadata.get(question_id)\n if old_value:\n old_comments = {\n comment['created']: comment\n for comment in old_value.get('comments', [])\n }\n new_comments = {\n comment['created']: comment\n for comment in value.get('comments', [])\n }\n old_comments.update(new_comments)\n metadata[question_id]['comments'] = sorted(\n old_comments.values(),\n key=lambda c: c['created']\n )\n if old_value.get('value') != value.get('value'):\n changes.append(question_id)\n else:\n changes.append(question_id)\n self.registration_metadata.update(metadata)\n return changes\n\n def submit_for_review(self, initiated_by, meta, save=False):\n approval = DraftRegistrationApproval(\n meta=meta\n )\n approval.save()\n self.approval = approval\n self.add_status_log(initiated_by, DraftRegistrationLog.SUBMITTED)\n if save:\n self.save()\n\n def register(self, auth, save=False, child_ids=None):\n node = self.branched_from\n\n # Create the registration\n register = node.register_node(\n schema=self.registration_schema,\n auth=auth,\n data=self.registration_metadata,\n child_ids=child_ids,\n provider=self.provider\n )\n self.registered_node = register\n self.add_status_log(auth.user, DraftRegistrationLog.REGISTERED)\n if save:\n self.save()\n return register\n\n def approve(self, user):\n self.approval.approve(user)\n self.refresh_from_db()\n self.add_status_log(user, DraftRegistrationLog.APPROVED)\n self.approval.save()\n\n def reject(self, user):\n self.approval.reject(user)\n self.add_status_log(user, DraftRegistrationLog.REJECTED)\n self.approval.save()\n\n def add_status_log(self, user, action):\n log = DraftRegistrationLog(action=action, user=user, draft=self)\n log.save()\n\n def validate_metadata(self, *args, **kwargs):\n \"\"\"\n Validates draft's metadata\n \"\"\"\n return self.registration_schema.validate_metadata(*args, **kwargs)\n","sub_path":"osf/models/registrations.py","file_name":"registrations.py","file_ext":"py","file_size_in_byte":24682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"378350236","text":"from django.urls import path\nfrom .views import *\n\napp_name = 'my'\n\nurlpatterns = [\n path('', redirect_check, name='redirect'),\n path('book/', BookListUploaded.as_view(), name='book-list'),\n path('book/check/', upload_check, name='book-check'),\n path('book/upload/', UploadBook.as_view(), name='upload-a-book'),\n path('book//', BookDetail.as_view(), name='book-detail'),\n path('book//update', UpdateBook.as_view(), name='book-update'),\n path('book//delete/', BookDelete.as_view(), name='book-delete'),\n]\n","sub_path":"backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"30159088","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 31 12:19:01 2017\n\n@author: Daniel Salo (Modifications)\n\nFunctions for testing Faster RCNN net on Cluttered MNIST and getting Mean Average Precision\n\"\"\"\n\n# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick\n# --------------------------------------------------------\n\nimport numpy as np\nfrom tqdm import tqdm\n\n\ndef voc_ap(rec, prec):\n \"\"\" ap = voc_ap(rec, prec, [use_07_metric])\n Compute VOC AP given precision and recall.\n \"\"\"\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.], rec, [1.]))\n mpre = np.concatenate(([0.], prec, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef cluttered_mnist_eval(test_image_object, test_directory, ovthresh=0.5):\n \"\"\"\n Evalulates predicted detections on cluttered MNIST dataset\n :param test_image_object: array, obj[cls][image] = N x 5 [x1, y1, x2, y2, cls_score]\n :param test_directory: str, location of the \"Test\" folder. Should end with \"../Test/\".\n :param ovthresh: float, between 1 and 0, threshold for rejecting bbox\n :return: class_metrics: list, each index is a digit class which holds a tuple of rec, prec, and ap\n \"\"\"\n # Get Ground Truth numbers for classes\n total_num = np.zeros([11])\n print('Loading Grouth Truth Data to count number of grouth truth per class')\n for x in tqdm(range(len(test_image_object[0]))):\n key = 'img' + str(x)\n gt_boxes = np.loadtxt(test_directory + 'Annotations/' + key + '.txt', ndmin=2)\n for g in range(gt_boxes.shape[0]):\n label = int(gt_boxes[g, 4])\n total_num[label+1] += 1\n\n # Designate arrays to hold ap for each class\n class_metrics = list()\n\n # Calculate IoU for all classes and all images\n for c in range(len(test_image_object)): # loop through all classes (skip background class)\n print('Now Calculating average precision for class: %d' % c)\n class_tp = list()\n class_fp = list()\n\n # go down dets and mark TPs and FPs\n for i in range(len(test_image_object[c])): # loop through all images\n\n # Get image detections and preallocate arrays\n image_dets = test_image_object[c][i]\n nd = len(image_dets)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n\n # Get groundtruth\n key = 'img' + str(i)\n gt_boxes = np.loadtxt(test_directory + '/Annotations/' + key + '.txt', ndmin=2)\n\n bbgt = gt_boxes[:, :4]\n labels = gt_boxes[:, 4]\n labels_det = [False] * len(labels)\n ovmax = -np.inf # In case no overlaps result\n\n for d in range(nd): # loop through all dets in a given image\n\n # Store particular dets as bb\n bb = image_dets[d, :4]\n\n # compute overlaps intersection\n ixmin = np.maximum(bbgt[:, 0], bb[0])\n iymin = np.maximum(bbgt[:, 1], bb[1])\n ixmax = np.minimum(bbgt[:, 2], bb[2])\n iymax = np.minimum(bbgt[:, 3], bb[3])\n iw = np.maximum(ixmax - ixmin + 1., 0.)\n ih = np.maximum(iymax - iymin + 1., 0.)\n inters = iw * ih\n\n # union\n uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +\n (bbgt[:, 2] - bbgt[:, 0] + 1.) *\n (bbgt[:, 3] - bbgt[:, 1] + 1.) - inters)\n\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n\n # Threshold\n if ovmax > ovthresh:\n if not labels_det[jmax]:\n tp[d] = 1.\n labels_det[jmax] = True\n else:\n fp[d] = 1.\n else:\n fp[d] = 1.\n\n # Add scores from all dets in one image to the class true positives and false positives\n class_tp.append(tp)\n class_fp.append(fp)\n\n # compute precision recall\n fp = np.cumsum(class_fp)\n tp = np.cumsum(class_tp)\n rec = tp / float(total_num[c])\n\n # avoid divide by zero in case the first detection matches a difficult\n # ground truth\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n ap = voc_ap(rec, prec)\n class_metrics.append((rec, prec, ap))\n\n print('Finished Calculating average precisions.')\n return class_metrics\n","sub_path":"Lib/Datasets/eval_clutteredMNIST.py","file_name":"eval_clutteredMNIST.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"107785899","text":"#set up pygame\nimport pygame\npygame.init()\n\n#animated image class\nclass img(object):\n images = []\n index = 0\n max_index = 0\n def __init__(self, images):\n self.images = images\n self.max_index = len(images) - 1\n def update(self):\n self.index += 1\n if self.index > self.max_index:\n self.index = 0\n def return_img(self):\n return self.images[self.index]\n\n#images\nbackground = img([pygame.image.load('textures\\\\menu\\\\0.png'), pygame.image.load('textures\\\\menu\\\\1.png'), pygame.image.load('textures\\\\menu\\\\2.png'), pygame.image.load('textures\\\\menu\\\\1.png'), pygame.image.load('textures\\\\menu\\\\0.png'), ])\ncursor = img([pygame.image.load('textures\\cursor.png')])\ntxt_font = pygame.font.SysFont('Arial', 16, True)\n\nscreen_width = 400\nscreen_height = background.return_img().get_height()\nscreen = pygame.display.set_mode((screen_width, screen_height))\n\n#function to print background\ndef print_frame():\n screen.blit(background.return_img(), (0, 0))\n screen.blit(txt_font.render(\"Points\", 0, (255, 255, 255)), (40, 8))\n screen.blit(txt_font.render(\"Coins\", 0, (255, 255, 255)), (136, 8))\n screen.blit(txt_font.render(\"Lives\", 0, (255, 255, 255)), (232, 8))\n screen.blit(txt_font.render(\"Time\", 0, (255, 255, 255)), (328, 8))\n screen.blit(txt_font.render(\"0\", 0, (255, 255, 255)), (40, 24))\n screen.blit(txt_font.render(\"0\", 0, (255, 255, 255)), (136, 24))\n screen.blit(txt_font.render(\"3\", 0, (255, 255, 255)), (232, 24))\n screen.blit(txt_font.render(\"400\", 0, (255, 255, 255)), (328, 24))\n\n screen.blit(txt_font.render(\"Play\", 0, (255, 255, 255)), (40, 112))\n screen.blit(txt_font.render(\"Quit\", 0, (255, 255, 255)), (40, 136))\n screen.blit(cursor.return_img(), (24, 117.5 + (selected_item * 24)))\n pygame.display.update()\n\nitems = ['play', 'quit']\nselected_item = 0\nmax_items = 1\nrunning = True\ntime_count = 0\n\ndef run_level():\n global running\n global selected_item\n global max_items\n global time_count\n while running:\n #input\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n if selected_item > 0:\n selected_item -= 1\n elif event.key == pygame.K_DOWN:\n if selected_item < max_items:\n selected_item += 1\n elif event.key == pygame.K_RETURN or event.key == pygame.K_SPACE:\n return items[selected_item]\n\n #update images\n if time_count % 250 == 0:\n background.update()\n \n #print images\n print_frame()\n pygame.time.delay(5)\n time_count += 5\n return 'quit'","sub_path":"Menu.py","file_name":"Menu.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"278373472","text":"import argparse\nimport os\nimport numpy as np\nimport random\nfrom tqdm import tqdm, trange\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nfrom mypath import Path\nfrom dataloaders import make_data_loader\nimport torch.nn.functional as F\nfrom utils_.saver import Saver\nfrom utils_.summaries import TensorboardSummary\nfrom utils_.metrics import Evaluator\nfrom trainer_nanqing import *\nfrom utils_.visualize import visualize_plot\n\nclass adda:\n def __init__(self, args):\n kwargs = {'num_workers': 4, 'pin_memory': True}\n self.source_loader, self.target_loader, self.test_loader, self.nclass = make_data_loader(args, **kwargs)\n self.tbar = tqdm(self.test_loader, desc='\\r')\n self.trainer = adda_trainer(args, 2)\n self.evaluator = Evaluator(2)\n self.best_IoU = {'disc': 0.77, 'cup': 0.65}\n self.attempt = 3\n self.validation(args, self.trainer.target_model, self.tbar )\n self.trainer_dda(args)\n\n def loop_iterable(self, iterable):\n while True:\n yield from iterable\n\n\n def save_model(self, epoch):\n print('Validation:')\n Acc = self.evaluator.Pixel_Accuracy([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n Acc_class = self.evaluator.Pixel_Accuracy_Class([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n mIoU = self.evaluator.Mean_Intersection_over_Union([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n FWIoU = self.evaluator.Frequency_Weighted_Intersection_over_Union([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n print(\"epoch:{}, Acc:{}, Acc_class:{}, mIoU:{}, fwIoU: {}\".format(epoch, Acc, Acc_class, mIoU, FWIoU))\n if ( mIoU['cup'] > self.best_IoU['cup']):\n #model save\n self.best_IoU = mIoU\n print('---- MODEL SAVE ---')\n torch.save({'epoch': epoch + 1, 'state_dict': self.trainer.target_model.state_dict(), 'best_auc': str(mIoU['cup']),\n 'optimizer' : self.trainer.target_optim.state_dict()}, 'm-' + str(mIoU['cup']) + \"v_\" + str(self.attempt) + '.pth.tar')\n return mIoU\n\n def trainer_dda(self, args):\n self.trainer.target_model.train()\n self.trainer.disc_model.train()\n self.evaluator.reset()\n max_epochs = args.epochs\n for epoch in range(1, max_epochs+1):\n self.trainer.target_model.train()\n batch_iterator = zip(self.loop_iterable(self.source_loader), self.loop_iterable(self.target_loader))\n total_loss = 0\n total_loss_tgt = 0\n loss_critic = 0\n loss_tgt = 0\n total_accuracy = 0\n len_dataloader = max(len(self.source_loader), len(self.target_loader))\n torch.manual_seed(1 + epoch)\n for step in trange(len_dataloader, leave=True):\n p = float(step + epoch*len_dataloader)/args.epochs/len_dataloader #(1+len)/epochs/\n alpha = 2./(1.+np.exp(-10*p)) - 1\n try:\n data = next(batch_iterator)\n except StopIteration:\n batch_iterator = zip(self.loop_iterable(self.source_loader), self.loop_iterable(self.target_loader))\n data = next(batch_iterator)\n\n for i in range(args.k_disc):\n source_x, src_labels = data[0][0].cuda(), data[0][1].transpose(3,1).cuda()\n target_x, target_lab = data[1][0].cuda(), data[1][1].transpose(3,1).cuda()\n #target_x = self.trainer.adv_aug.perturb(target_x, target_lab, self.trainer.target_criterion, random_start=False )\n dda_loss, tgt_loss = self.trainer.update_weights(source_x, src_labels, target_x, target_lab, 0.1,'train_disc')\n\n for i in range(args.k_src):\n source_x, src_labels = data[0][0].cuda(), data[0][1].transpose(3,1).cuda()\n target_x, target_lab = data[1][0].cuda(), data[1][1].transpose(3,1).cuda()\n #target_x = self.trainer.adv_aug.perturb(target_x, target_lab, self.trainer.target_criterion, random_start=False )\n dda_loss, tgt_loss = self.trainer.update_weights(source_x, src_labels, target_x, target_lab, 0.1,'train_gen')\n total_loss+=dda_loss\n total_loss_tgt +=tgt_loss\n #if(step%100 == 0):\n # print(\"Target_loss:{}, disc_loss:{}\".format(total_loss_tgt/(step+1), total_loss/(step+1)))\n self.trainer.scheduler(self.trainer.dda_optim, step, epoch, self.best_IoU['cup'])\n self.trainer.target_model.eval()\n self.trainer.disc_model.eval()\n for st, data in enumerate(self.tbar):\n image, target = data[0], data[1]\n target = target.transpose(3,1)\n image, target = image.cuda(), target.cuda()\n with torch.no_grad():\n output,_ = self.trainer.target_model(image)\n test_loss = self.trainer.target_criterion(output, target)\n pred = output.data.cpu().numpy()\n target = target.cpu().numpy()\n pred[pred >= 0.5] = 1\n pred[pred < 0.5] = 0\n # Add batch sample into evaluator\n self.evaluator.add_batch(target, pred)\n self.evaluator.add_test_loss(test_loss/(st+1))\n mIoU = self.evaluator.Mean_Intersection_over_Union([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n print(\"mIoU:{}\".format(mIoU))\n total_accuracy =0\n if ((epoch + 1) % 1== 0):\n print(\"Epoch [{}/{}] Step [{}/{}]:\"\n \"d_loss={:.5f} g_loss={:.5f} acc={:.5f}\"\n .format(epoch + 1,\n max_epochs,\n epoch + 1,\n len(self.source_loader),\n total_loss/((step+1)),\n total_loss_tgt/(step+1),total_accuracy))\n mIoU = self.save_model(epoch)\n\n\n def validation(self, args, model, tbar):\n best_pred = {'cup':0, 'disc':0}\n model.eval()\n self.evaluator.reset()\n test_loss = 0.0\n for i, data in enumerate(tbar):\n image, target = data[0], data[1]\n target = target.transpose(3,1)\n image, target = image.cuda(), target.cuda()\n with torch.no_grad():\n output,_ = model(image)\n test_loss = self.trainer.target_criterion(output, target)\n pred = output.data.cpu().numpy()\n target = target.cpu().numpy()\n pred[pred >= 0.5] = 1\n pred[pred < 0.5] = 0\n # Add batch sample into evaluator\n self.evaluator.add_batch(target, pred)\n self.evaluator.add_test_loss(test_loss/(i+1))\n\n mIoU = self.evaluator.Mean_Intersection_over_Union([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n #evaluator.Plot_Loss(1)\n print('Validation:')\n #print('[Epoch: %d, numImages: %5d]' % (epoch, i * args.batch_size + image.data.shape[0]))\n print(\"mIoU:{}\".format(mIoU))\n print('Loss: %.3f' % test_loss)\n new_pred = mIoU\n if new_pred['cup'] > best_pred['cup']:\n is_best = True\n best_pred = new_pred\ndef main():\n parser = argparse.ArgumentParser(description=\"PyTorch DeeplabV3Plus Training\")\n parser.add_argument('--backbone', type=str, default='resnet',\n choices=['resnet', 'xception', 'drn', 'mobilenet'],\n help='backbone name (default: resnet)')\n parser.add_argument('--dataset', type=str, default='glaucoma',\n choices=['pascal', 'coco', 'cityscapes', 'glaucoma'],\n help='dataset name (default: pascal)')\n\n parser.add_argument('--batch-size', type=int, default=2,\n metavar='N', help='input batch size for \\\n training (default: auto)')\n\n parser.add_argument('--lr', type=float, default=None, metavar='LR',\n help='learning rate (default: auto)')\n parser.add_argument('--lr-scheduler', type=str, default='poly',\n choices=['poly', 'step', 'cos'],\n help='lr scheduler mode: (default: poly)')\n parser.add_argument('--momentum', type=float, default=0.9,\n metavar='M', help='momentum (default: 0.9)')\n parser.add_argument('--weight-decay', type=float, default=5e-4,\n metavar='M', help='w-decay (default: 5e-4)')\n parser.add_argument('--nesterov', action='store_true', default=False,\n help='whether use nesterov (default: False)')\n # cuda, seed and logging\n parser.add_argument('--no-cuda', action='store_true', default=\n False, help='disables CUDA training')\n parser.add_argument('--gpu-ids', type=str, default='0',\n help='use which gpu to train, must be a \\\n comma-separated list of integers only (default=0)')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n\n parser.add_argument('--loss-type', type=str, default='bce',\n choices=['ce', 'focal', 'bce'],\n help='loss func type (default: ce)')\n parser.add_argument('--lr_critic', type=int, default=1e-4,\n help='skip validation during training')\n parser.add_argument('--gamma', type=int, default=10,\n help='skip validation during training')\n parser.add_argument('--lambda_g', type=int, default=1,\n help='skip validation during training')\n parser.add_argument('--epochs', type=int, default=400, metavar='N',\n help='number of epochs to train (default: auto)')\n\n parser.add_argument('--k_disc', type=int, default=1,\n help='skip validation during training')\n parser.add_argument('--k_src', type=int, default=2,\n help='skip validation during training')\n parser.add_argument('--k_targ', type=int, default=1,\n help='skip validation during training')\n # checking point\n parser.add_argument('--resume', type=str, default= \"pretrained/deeplab-resnet.pth.tar\", #\"run/glaucoma/best_experiment_2.pth.tar\",\n help='put the path to resuming file if needed')\n args = parser.parse_args()\n args.cuda = not args.no_cuda and torch.cuda.is_available()\n if args.cuda:\n try:\n args.gpu_ids = [int(s) for s in args.gpu_ids.split(',')]\n except ValueError:\n raise ValueError('Argument --gpu_ids must be a comma-separated list of integers only')\n args.batch_size = 4\n if args.lr is None:\n lrs = {\n 'coco': 0.1,\n 'cityscapes': 0.01,\n 'pascal': 0.007,\n 'glaucoma': 0.007,\n }\n args.lr = 0.001\n torch.manual_seed(1)\n torch.cuda.manual_seed(1)\n np.random.seed(1)\n random.seed(1)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.enabled = False\n torch.backends.cudnn.benchmark = False\n adda(args)\n\nmain()\n","sub_path":"trainer_sing_source/train_dda.py","file_name":"train_dda.py","file_ext":"py","file_size_in_byte":11526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"50634971","text":"import tkinter as tk\r\n\r\n\r\ndef encrypt(plaintext, col_key, row_key):\r\n \"\"\" Use a column transformation to encrypt the message.\"\"\"\r\n return encrypt_decrypt(plaintext, col_key, row_key, False)\r\n\r\ndef decrypt(ciphertext, col_key, row_key):\r\n \"\"\" Use a column transformation to decrypt the message.\"\"\"\r\n return encrypt_decrypt(ciphertext, col_key, row_key, True)\r\n\r\ndef encrypt_decrypt(plaintext, col_key, row_key, decrypt):\r\n \"\"\" Use a column transformation to encrypt or decrypt the message.\"\"\"\r\n # Calculate the number of rows.\r\n num_columns = len(col_key)\r\n num_rows = int(1 + (len(plaintext) - 1) / num_columns)\r\n\r\n # Pad the string if necessary to make it fit the rectangle evenly.\r\n if num_rows * num_columns != len(plaintext):\r\n plaintext += \"X\" * (num_rows * num_columns - len(plaintext))\r\n\r\n # Make the key mappings.\r\n forward_col_mapping, inverse_col_mapping = make_key_mapping(col_key)\r\n forward_row_mapping, inverse_row_mapping = make_key_mapping(row_key)\r\n if decrypt:\r\n col_mapping = forward_col_mapping\r\n row_mapping = forward_row_mapping\r\n else:\r\n col_mapping = inverse_col_mapping\r\n row_mapping = inverse_row_mapping\r\n\r\n # Construct the encrypted/decrypted string.\r\n result = \"\"\r\n for row in range(num_rows):\r\n # Read this row in permuted order.\r\n for col in range(num_columns):\r\n index = row_mapping[row] * num_columns + col_mapping[col]\r\n result += plaintext[index]\r\n\r\n return result\r\n\r\ndef make_key_mapping(key):\r\n \"\"\" Make a mapping for this key.\"\"\"\r\n # Sort the characters.\r\n chars = list(key)\r\n chars.sort()\r\n sorted_key = \"\".join(chars)\r\n\r\n # Make the mapping.\r\n mapping = []\r\n for i in range(len(key)):\r\n mapping.append(sorted_key.index(key[i]))\r\n\r\n # Make the inverse mapping.\r\n inverse_mapping = [0 for i in range(len(key))]\r\n for i in range(len(key)):\r\n inverse_mapping[mapping[i]] = i\r\n\r\n return mapping, inverse_mapping\r\n\r\ndef to_n_grams(message):\r\n \"\"\" Break the text into 5-character chunks.\"\"\"\r\n # Pad the message in case its length isn't a multiple of 5.\r\n message += \" \"\r\n\r\n # Create the 5-character chunks.\r\n result = \"\"\r\n for i in range(0, len(message) - 5, 5):\r\n result += message[i: i + 5] + \" \"\r\n\r\n # Remove trailing spaces.\r\n return result.rstrip()\r\n\r\n\r\nclass App:\r\n def kill_callback(self):\r\n self.window.destroy()\r\n\r\n def __init__(self):\r\n self.window = tk.Tk()\r\n self.window.title(\"swap_rows_and_columns\")\r\n self.window.protocol(\"WM_find_WINDOW\", self.kill_callback)\r\n self.window.geometry(\"320x230\")\r\n\r\n self.window.columnconfigure(1, weight=1)\r\n\r\n label = tk.Label(self.window, text=\"Message:\")\r\n label.grid(padx=5, pady=5, row=0, column=0, sticky=tk.W)\r\n self.message_entry = tk.Entry(self.window, width=12)\r\n self.message_entry.grid(padx=5, pady=5, row=0, column=1, sticky=tk.EW)\r\n self.message_entry.insert(0, \"THIS IS A SECRET MESSAGE\")\r\n\r\n label = tk.Label(self.window, text=\"Key 1:\")\r\n label.grid(padx=5, pady=5, row=1, column=0, sticky=tk.W)\r\n self.key1_entry = tk.Entry(self.window, width=12)\r\n self.key1_entry.grid(padx=5, pady=5, row=1, column=1, sticky=tk.W)\r\n self.key1_entry.insert(0, \"CARTS\")\r\n\r\n label = tk.Label(self.window, text=\"Key 2:\")\r\n label.grid(padx=5, pady=5, row=2, column=0, sticky=tk.W)\r\n self.key2_entry = tk.Entry(self.window, width=12)\r\n self.key2_entry.grid(padx=5, pady=5, row=2, column=1, sticky=tk.W)\r\n self.key2_entry.insert(0, \"FISH\")\r\n\r\n encrypt_button = tk.Button(self.window, width=8, text=\"Encrypt\", command=self.encrypt)\r\n encrypt_button.grid(padx=5, pady=5, row=3, column=0, columnspan=2)\r\n\r\n label = tk.Label(self.window, text=\"Ciphertext:\")\r\n label.grid(padx=5, pady=5, row=4, column=0, sticky=tk.W)\r\n self.ciphertext_entry = tk.Entry(self.window, width=12)\r\n self.ciphertext_entry.grid(padx=5, pady=5, row=4, column=1, sticky=tk.EW)\r\n\r\n decrypt_button = tk.Button(self.window, width=8, text=\"Decrypt\", command=self.decrypt)\r\n decrypt_button.grid(padx=5, pady=5, row=5, column=0, columnspan=2)\r\n\r\n label = tk.Label(self.window, text=\"Plaintext:\")\r\n label.grid(padx=5, pady=5, row=6, column=0, sticky=tk.W)\r\n self.plaintext_entry = tk.Entry(self.window, width=12)\r\n self.plaintext_entry.grid(padx=5, pady=5, row=6, column=1, sticky=tk.EW)\r\n\r\n # Bind some keys.\r\n self.window.bind('', (lambda e, button=encrypt_button: encrypt_button.invoke())) \r\n\r\n # Force focus so Alt+F4 closes this window and not the Python shell.\r\n self.message_entry.focus_force()\r\n self.window.mainloop()\r\n\r\n def encrypt(self):\r\n \"\"\" Use a column transformation to encrypt the message.\"\"\"\r\n message = self.message_entry.get().upper().replace(\" \", \"\")\r\n col_key = self.key1_entry.get()\r\n row_key = self.key2_entry.get()\r\n ciphertext = encrypt(message, col_key, row_key)\r\n self.ciphertext_entry.delete(0, tk.END)\r\n self.ciphertext_entry.insert(tk.END, to_n_grams(ciphertext))\r\n self.plaintext_entry.delete(0, tk.END)\r\n\r\n def decrypt(self):\r\n \"\"\" Use a column transformation to decrypt the message.\"\"\"\r\n ciphertext = self.ciphertext_entry.get().upper().replace(\" \", \"\")\r\n col_key = self.key1_entry.get()\r\n row_key = self.key2_entry.get()\r\n plaintext = decrypt(ciphertext, col_key, row_key)\r\n self.plaintext_entry.delete(0, tk.END)\r\n self.plaintext_entry.insert(tk.END, to_n_grams(plaintext))\r\n\r\n\r\nif __name__ == '__main__':\r\n app = App()\r\n\r\n# app.root.destroy()\r\n","sub_path":"algs2e_python/Chapter 16/python/swap_rows_and_columns.py","file_name":"swap_rows_and_columns.py","file_ext":"py","file_size_in_byte":5826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"13765889","text":"from deck import Deck, deserialize_deck, serialize_deck\nfrom proto.cards_pb2 import Card\n\nTWENTYNINE_DECK_NAME = '29.deck'\nSTANDARD_DECK_NAME = 'standard.deck'\n\n\ndef create_standard_deck() -> Deck:\n suits = ['H', 'S', 'D', 'C']\n labels = ['A', 'K', 'Q', 'J', '10', '9', '8', '7',\n '6', '5', '4', '3', '2'] # in rank order\n values = {'J': 3, '9': 2, 'A': 1, '10': 1}\n cards = []\n for suit in suits:\n for rank, label in enumerate(labels):\n rank = rank + 1\n value = values[label] if label in values else 0\n cards.append(Card(label=label, suit=suit, rank=rank, value=value))\n return Deck(cards=cards)\n\n\ndef create_twentynine_deck() -> Deck:\n suits = ['H', 'S', 'D', 'C']\n labels = ['J', '9', 'A', '10', 'K', 'Q', '8', '7'] # in rank order\n values = {'J': 3, '9': 2, 'A': 1, '10': 1}\n cards = []\n for suit in suits:\n for rank, label in enumerate(labels):\n rank = rank + 1\n value = values[label] if label in values else 0\n cards.append(Card(label=label, suit=suit, rank=rank, value=value))\n return Deck(cards=cards)\n\n\ndef serialize_twentynine_deck() -> None:\n deck = create_twentynine_deck()\n serialize_deck(deck, TWENTYNINE_DECK_NAME)\n\n\ndef new_twentynine_deck() -> Deck:\n return deserialize_deck(TWENTYNINE_DECK_NAME)\n\n\ndef serialize_standard_deck() -> None:\n deck = create_standard_deck()\n serialize_deck(deck, STANDARD_DECK_NAME)\n\n\ndef new_standard_deck() -> Deck:\n return deserialize_deck(STANDARD_DECK_NAME)\n","sub_path":"src/deck_builder.py","file_name":"deck_builder.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"420113927","text":"# Copyright 2019 Michael J Simms\n\"\"\"Dscribes a workout to be performed.\"\"\"\n\nfrom __future__ import print_function\nimport datetime\nimport json\nimport inspect\nimport os\nimport sys\nimport time\nimport uuid\nimport IcsWriter\nimport Keys\nimport Units\nimport UserMgr\nimport ZwoWriter\n\n# Locate and load the ZwoTags module.\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nzworeaderdir = os.path.join(currentdir, 'ZwoReader')\nsys.path.insert(0, zworeaderdir)\nimport ZwoTags\n\nclass Workout(object):\n \"\"\"Class that describes a workout to be performed.\"\"\"\n\n def __init__(self, user_id):\n self.user_id = user_id\n self.user_mgr = UserMgr.UserMgr(None)\n self.type = \"\"\n self.sport_type = \"\"\n self.scheduled_time = None # The time at which this workout is to be performed\n self.warmup = {} # The warmup interval\n self.cooldown = {} # The cooldown interval\n self.intervals = [] # The workout intervals\n self.needs_rest_day_afterwards = False # Used by the scheduler\n self.can_be_doubled = False # Used by the scheduler to know whether or not this workout can be doubled up with other workouts\n self.workout_id = uuid.uuid4() # Unique identifier for the workout\n\n def __getitem__(self, key):\n if key == Keys.WORKOUT_ID_KEY:\n return self.workout_id\n if key == Keys.WORKOUT_TYPE_KEY:\n return self.type\n if key == Keys.WORKOUT_SPORT_TYPE_KEY:\n return self.sport_type\n if key == Keys.WORKOUT_WARMUP_KEY:\n return self.warmup\n if key == Keys.WORKOUT_COOLDOWN_KEY:\n return self.cooldown\n if key == Keys.WORKOUT_INTERVALS_KEY:\n return self.intervals\n if key == Keys.WORKOUT_SCHEDULED_TIME_KEY and self.scheduled_time is not None:\n dt = time.mktime(self.scheduled_time.timetuple())\n return datetime.datetime(dt.year, dt.month, dt.day)\n return None\n\n def to_dict(self):\n \"\"\"Converts the object representation to a dictionary, only converting what is actually useful, as opposed to __dict__.\"\"\"\n output = {}\n output[Keys.WORKOUT_ID_KEY] = self.workout_id\n output[Keys.WORKOUT_TYPE_KEY] = self.type\n output[Keys.WORKOUT_SPORT_TYPE_KEY] = self.sport_type\n output[Keys.WORKOUT_WARMUP_KEY] = self.warmup\n output[Keys.WORKOUT_COOLDOWN_KEY] = self.cooldown\n output[Keys.WORKOUT_INTERVALS_KEY] = self.intervals\n if self.scheduled_time is not None:\n output[Keys.WORKOUT_SCHEDULED_TIME_KEY] = time.mktime(self.scheduled_time.timetuple())\n else:\n output[Keys.WORKOUT_SCHEDULED_TIME_KEY] = None\n return output\n\n def from_dict(self, input):\n \"\"\"Sets the object's members from a dictionary.\"\"\"\n if Keys.WORKOUT_ID_KEY in input:\n self.workout_id = input[Keys.WORKOUT_ID_KEY]\n if Keys.WORKOUT_TYPE_KEY in input:\n self.type = input[Keys.WORKOUT_TYPE_KEY]\n if Keys.WORKOUT_SPORT_TYPE_KEY in input:\n self.sport_type = input[Keys.WORKOUT_SPORT_TYPE_KEY]\n if Keys.WORKOUT_WARMUP_KEY in input:\n self.warmup = input[Keys.WORKOUT_WARMUP_KEY]\n if Keys.WORKOUT_COOLDOWN_KEY in input:\n self.cooldown = input[Keys.WORKOUT_COOLDOWN_KEY]\n if Keys.WORKOUT_INTERVALS_KEY in input:\n self.intervals = input[Keys.WORKOUT_INTERVALS_KEY]\n if Keys.WORKOUT_SCHEDULED_TIME_KEY in input and input[Keys.WORKOUT_SCHEDULED_TIME_KEY] is not None:\n self.scheduled_time = datetime.datetime.fromtimestamp(input[Keys.WORKOUT_SCHEDULED_TIME_KEY]).date()\n\n def add_warmup(self, seconds):\n \"\"\"Defines the workout warmup.\"\"\"\n self.warmup = {}\n self.warmup[ZwoTags.ZWO_ATTR_NAME_DURATION] = seconds\n self.warmup[ZwoTags.ZWO_ATTR_NAME_POWERLOW] = 0.25\n self.warmup[ZwoTags.ZWO_ATTR_NAME_POWERHIGH] = 0.75\n self.warmup[ZwoTags.ZWO_ATTR_NAME_PACE] = None\n\n def add_cooldown(self, seconds):\n \"\"\"Defines the workout cooldown.\"\"\"\n self.cooldown = {}\n self.cooldown[ZwoTags.ZWO_ATTR_NAME_DURATION] = seconds\n self.cooldown[ZwoTags.ZWO_ATTR_NAME_POWERLOW] = 0.75\n self.cooldown[ZwoTags.ZWO_ATTR_NAME_POWERHIGH] = 0.25\n self.cooldown[ZwoTags.ZWO_ATTR_NAME_PACE] = None\n\n def add_interval(self, repeat, distance, pace, recovery_distance, recovery_pace):\n \"\"\"Appends an interval to the workout.\"\"\"\n interval = {}\n interval[Keys.INTERVAL_REPEAT_KEY] = int(repeat)\n interval[Keys.INTERVAL_DISTANCE_KEY] = float(distance)\n interval[Keys.INTERVAL_PACE_KEY] = float(pace)\n interval[Keys.INTERVAL_RECOVERY_DISTANCE_KEY] = float(recovery_distance)\n interval[Keys.INTERVAL_RECOVERY_PACE_KEY] = float(recovery_pace)\n self.intervals.append(interval)\n\n def export_to_zwo(self, file_name):\n \"\"\"Creates a ZWO-formatted file that describes the workout.\"\"\"\n writer = ZwoWriter.ZwoWriter()\n writer.create_zwo(file_name)\n writer.store_description(self.type)\n writer.store_sport_type(self.sport_type)\n writer.start_workout()\n\n # Add the warmup (if applicable).\n if self.warmup is not None:\n writer.store_workout_warmup(self.warmup[ZwoTags.ZWO_ATTR_NAME_DURATION], self.warmup[ZwoTags.ZWO_ATTR_NAME_POWERLOW], self.warmup[ZwoTags.ZWO_ATTR_NAME_POWERHIGH], self.warmup[ZwoTags.ZWO_ATTR_NAME_PACE])\n\n # Add each interval.\n for interval in self.intervals:\n interval_meters = interval[Keys.INTERVAL_DISTANCE_KEY]\n interval_pace_minute = interval[Keys.INTERVAL_PACE_KEY]\n recovery_meters = interval[Keys.INTERVAL_RECOVERY_DISTANCE_KEY]\n recovery_pace_minute = interval[Keys.INTERVAL_RECOVERY_PACE_KEY]\n\n # Convert distance and pace to time. Distance is given in meters/minute. The final result should be a whole number of seconds.\n on_duration = float(interval_meters) / ((interval_pace_minute) / 60.0)\n on_duration = int(on_duration)\n if recovery_pace_minute == 0:\n recovery_duration = 0\n else:\n recovery_duration = float(recovery_meters) / (float(recovery_pace_minute) / 60.0)\n recovery_duration = int(recovery_duration)\n writer.store_workout_intervals(interval[Keys.INTERVAL_REPEAT_KEY], on_duration, recovery_duration, None, 0)\n\n # Add the cooldown (if applicable).\n if self.cooldown is not None:\n writer.store_workout_cooldown(self.cooldown[ZwoTags.ZWO_ATTR_NAME_DURATION], self.cooldown[ZwoTags.ZWO_ATTR_NAME_POWERLOW], self.cooldown[ZwoTags.ZWO_ATTR_NAME_POWERHIGH], self.cooldown[ZwoTags.ZWO_ATTR_NAME_PACE])\n\n writer.end_workout()\n writer.close()\n\n file_data = writer.buffer()\n\n with open(file_name, 'wt') as local_file:\n local_file.write(file_data)\n\n def export_to_text(self):\n \"\"\"Creates a string that describes the workout.\"\"\"\n\n unit_system = self.user_mgr.retrieve_user_setting(self.user_id, Keys.PREFERRED_UNITS_KEY)\n\n result = \"Workout Type: \"\n result += self.type\n result += \"\\nSport: \"\n result += self.sport_type\n result += \"\\n\"\n\n # Add the warmup (if applicable).\n if self.warmup is not None and ZwoTags.ZWO_ATTR_NAME_DURATION in self.warmup:\n result += \"Warmup: \"\n result += str(self.warmup[ZwoTags.ZWO_ATTR_NAME_DURATION])\n result += \" seconds.\\n\"\n\n # Add each interval.\n for interval in self.intervals:\n interval_meters = interval[Keys.INTERVAL_DISTANCE_KEY]\n interval_pace_minute = interval[Keys.INTERVAL_PACE_KEY]\n recovery_meters = interval[Keys.INTERVAL_RECOVERY_DISTANCE_KEY]\n recovery_pace_minute = interval[Keys.INTERVAL_RECOVERY_PACE_KEY]\n\n result += \"Interval: \"\n result += Units.convert_to_string_in_specified_unit_system(unit_system, interval_meters, Units.UNITS_DISTANCE_METERS, None, Keys.TOTAL_DISTANCE)\n result += \" at \"\n result += Units.convert_to_string_in_specified_unit_system(unit_system, interval_pace_minute, Units.UNITS_DISTANCE_METERS, Units.UNITS_TIME_MINUTES, Keys.INTERVAL_PACE_KEY)\n if recovery_meters > 0:\n result += \" with \"\n result += Units.convert_to_string_in_specified_unit_system(unit_system, recovery_meters, Units.UNITS_DISTANCE_METERS, None, Keys.TOTAL_DISTANCE)\n result += \" recovery at \"\n result += Units.convert_to_string_in_specified_unit_system(unit_system, recovery_pace_minute, Units.UNITS_DISTANCE_METERS, Units.UNITS_TIME_MINUTES, Keys.INTERVAL_PACE_KEY)\n result += \".\\n\"\n\n # Add the cooldown (if applicable).\n if self.cooldown is not None and ZwoTags.ZWO_ATTR_NAME_DURATION in self.cooldown:\n result += \"Cooldown: \"\n result += str(self.cooldown[ZwoTags.ZWO_ATTR_NAME_DURATION])\n result += \" seconds.\\n\"\n\n # Add an string that describes how this workout fits into the big picture.\n if self.type == Keys.WORKOUT_TYPE_INTERVAL_SESSION:\n result += \"Purpose: Interval sessions are designed to build speed and strength.\\n\"\n elif self.type == Keys.WORKOUT_TYPE_TEMPO_RUN:\n result += \"Purpose: Tempo runs build a combination of speed and endurance. They should be performed at a pace you can hold for roughly one hour.\\n\"\n elif self.type == Keys.WORKOUT_TYPE_EASY_RUN:\n result += \"Purpose: Easy runs build aerobic capacity while keeping the wear and tear on the body to a minimum.\\n\"\n\n return result\n\n def export_to_json_str(self):\n \"\"\"Creates a JSON string that describes the workout.\"\"\"\n result = self.to_dict()\n result[Keys.WORKOUT_ID_KEY] = str(self.workout_id)\n result[Keys.WORKOUT_DESCRIPTION_KEY] = self.export_to_text()\n return json.dumps(result, ensure_ascii=False)\n\n def export_to_ics(self, file_name):\n \"\"\"Creates a ICS-formatted file that describes the workout.\"\"\"\n ics_writer = IcsWriter.IcsWriter()\n file_data = ics_writer.create(self.workout_id, self.scheduled_time, self.scheduled_time, self.type, self.export_to_text())\n\n with open(file_name, 'wt') as local_file:\n local_file.write(file_data)\n","sub_path":"Workout.py","file_name":"Workout.py","file_ext":"py","file_size_in_byte":10491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"269577969","text":"import graphlab.connect as _mt\nfrom graphlab.util import _raise_error_if_not_of_type\nfrom graphlab.data_structures.sgraph import SGraph as _SGraph\n\n\ndef submit_training_job(env, graph, label_field,\n threshold=1e-3,\n weight_field='',\n self_weight=1.0,\n undirected=False,\n max_iterations=None,\n _single_precision=False):\n \"\"\"\n Given a weighted graph with observed class labels of a subset of vertices,\n infer the label probability for the unobserved vertices using the\n \"label propagation\" algorithm.\n\n The algorithm iteratively updates the label probability of current vertex\n as a weighted sum of label probability of self and the neighboring vertices\n until converge. See\n :class:`graphlab.label_propagation.LabelPropagationModel` for the details\n of the algorithm.\n\n Notes: label propagation works well with small number of labels, i.e. binary\n labels, or less than 1000 classes. The toolkit will throw error\n if the number of classes exceeds the maximum value (1000).\n\n Parameters\n ----------\n env : graphlab.deploy.hadoop_cluster.HadoopCluster\n Hadoop cluster to submit the training job\n\n graph : SGraph\n The graph on which to compute the label propagation.\n\n label_field: str\n Vertex field storing the initial vertex labels. The values in\n must be [0, num_classes). None values indicate unobserved vertex labels.\n\n threshold : float, optional\n Threshold for convergence, measured in the average L2 norm\n (the sum of squared values) of the delta of each vertex's\n label probability vector.\n\n max_iterations: int, optional\n The max number of iterations to run. Default is unlimited.\n If set, the algorithm terminates when either max_iterations\n or convergence threshold is reached.\n\n weight_field: str, optional\n Vertex field for edge weight. If empty, all edges are assumed\n to have unit weight.\n\n self_weight: float, optional\n The weight for self edge.\n\n undirected: bool, optional\n If true, treat each edge as undirected, and propagates label in\n both directions.\n\n _single_precision : bool, optional\n If true, running label propagation in single precision. The resulting\n probability values may less accurate, but should run faster\n and use less memory.\n\n Returns\n -------\n out : :class:`~graphlab.distributed._dml_job_status.DMLJobStatus`\n An object that tracks the execution of the distributed training job.\n\n References\n ----------\n - Zhu, X., & Ghahramani, Z. (2002). `Learning from labeled and unlabeled data\n with label propagation `_.\n\n Examples\n --------\n If given an :class:`~graphlab.SGraph` ``g``, we can create\n a :class:`~graphlab.label_propagation.LabelPropagationModel` as follows:\n\n >>> hdp_env = graphlab.deploy.hadoop_cluster.create('my-first-hadoop-cluster',\n ... 'hdfs://path-to-turi-distributed-installation')\n >>> g = graphlab.load_graph('http://snap.stanford.edu/data/email-Enron.txt.gz',\n ... format='snap')\n # Initialize random classes for a subset of vertices\n # Leave the unobserved vertices with None label.\n >>> import random\n >>> def init_label(vid):\n ... x = random.random()\n ... if x < 0.2:\n ... return 0\n ... elif x > 0.9:\n ... return 1\n ... else:\n ... return None\n >>> g.vertices['label'] = g.vertices['__id'].apply(init_label, int)\n >>> distr_obj = graphlab.distributed.label_propagation.submit_training_job(hdp_env, g, 'label')\n >>> model = distr_job.get_results()\n\n We can obtain for each vertex the predicted label and the probability of\n each label in the graph ``g`` using:\n\n >>> labels = m['labels'] # SFrame\n >>> labels\n +------+-------+-----------------+-------------------+----------------+\n | __id | label | predicted_label | P0 | P1 |\n +------+-------+-----------------+-------------------+----------------+\n | 5 | 1 | 1 | 0.0 | 1.0 |\n | 7 | None | 0 | 0.8213214997 | 0.1786785003 |\n | 8 | None | 1 | 5.96046447754e-08 | 0.999999940395 |\n | 10 | None | 0 | 0.534984718273 | 0.465015281727 |\n | 27 | None | 0 | 0.752801638549 | 0.247198361451 |\n | 29 | None | 1 | 5.96046447754e-08 | 0.999999940395 |\n | 33 | None | 1 | 5.96046447754e-08 | 0.999999940395 |\n | 47 | 0 | 0 | 1.0 | 0.0 |\n | 50 | None | 0 | 0.788279032657 | 0.211720967343 |\n | 52 | None | 0 | 0.666666666667 | 0.333333333333 |\n +------+-------+-----------------+-------------------+----------------+\n [36692 rows x 5 columns]\n\n See Also\n --------\n LabelPropagationModel\n \"\"\"\n _mt._get_metric_tracker().track('distributed.graph_analytics.label_propagation.create')\n\n _raise_error_if_not_of_type(label_field, str)\n _raise_error_if_not_of_type(weight_field, str)\n\n if not isinstance(graph, _SGraph):\n raise TypeError('graph input must be a SGraph object.')\n\n if graph.vertices[label_field].dtype() != int:\n raise TypeError('label_field %s must be integer typed.' % label_field)\n\n opts = {'label_field': label_field,\n 'threshold': threshold,\n 'weight_field': weight_field,\n 'self_weight': self_weight,\n 'undirected': undirected,\n 'max_iterations': max_iterations,\n 'single_precision': _single_precision,\n 'graph': graph.__proxy__}\n\n from ... import _dml\n dml_obj = _dml.run('distributed_labelprop', 'label_propagation', opts, env)\n\n return dml_obj\n","sub_path":"env/lib/python2.7/site-packages/graphlab/distributed/toolkits/graph_analytics/label_propagation.py","file_name":"label_propagation.py","file_ext":"py","file_size_in_byte":6003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"278939817","text":"# -*- coding: utf-8 -*-\n\n#############################################################################\n# #\n# EIDEParser #\n# #\n# This file is part of the library EIDEGraphics. Please, refer file #\n# EIDE.py for further information and LICENSE notice. #\n# #\n#############################################################################\n\n\"\"\"\n\nClass 'EIDEParser'. It inherits from the class\n'configparser.configparser' (configparser python library). Adds to\nconfigparser.configparser a 'bullet proof' method -'optionsListC'- to\nfilter out any inconsistency in the configuration ('*.txt') files.\n\n\"\"\"\n\nimport os.path\nimport configparser\n##import ConfigParser # python 2.7\nimport EIDESystem\n\n\n############################### EIDEParser #########################\nclass EIDEParser(configparser.ConfigParser):\n \"\"\" Specific parser for EIDE 'txt' files \"\"\"\n\n\n# EIDEParser #########################\n def __init__(self, path, fichero, parameters):\n configparser.ConfigParser.__init__(self)\n\n self.wholePath = os.path.join(path,fichero)\n self.read(self.wholePath)\n self.fichero = fichero\n self.parameters = parameters\n\n\n# EIDEParser #########################\n def sectionsList(self):\n \"\"\" Return a list on the sections in the file \"\"\"\n return self.sections()\n\n\n# EIDEParser #########################\n def optionsList(self, seccion):\n \"\"\" Return a list with the options -fields- of a given section.\n No check \"\"\"\n return self.items(seccion)\n\n\n# EIDEParser #########################\n def optionsListC(self, seccion):\n \"\"\" Return a 'converted' list with the options -fields- in the\n section. Checks for existence and validity of data.\"\"\"\n\n\n \"\"\"\n Key:2nd field in 'parameters' returns\n ------------------------- -------------------\n - 1: integer integer\n - 2: float float\n - 3: triad triad \n - 4: text text\n - 5: coordinates coordinates object\n - 6: colour values colour tuple\n - 7: user print format\t python print format string\n \n \"\"\"\n \n lista = self.items(seccion)\n retorno = []\n \n for contador, i in enumerate(self.parameters):\n # Check for variable in section\n if not(self.has_option(seccion, i[0])):\n # Variable not in section. Compose error message\n message = EIDESystem.errorTexts.errorTextReturn(\n '0010', [i[0], seccion])\n raise Exception(message)\n\n\n # Check each contents according to type\n if i[1] == 1:\n # Integer\n try:\n self.getint(seccion, lista[contador][0])\n retorno.append((lista[contador][0],\n self.getint(seccion, lista[contador][0])))\n\n except ValueError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0040', [self.fichero, seccion, i[0]])\n raise Exception(message)\n except:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0000', \"\")\n raise Exception(message)\n\n\n elif i[1] == 2:\n # Float\n try:\n self.getfloat(seccion, lista[contador][0])\n retorno.append((lista[contador][0],self.getfloat(seccion,\n lista[contador][0])))\n\n except ValueError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0050', [self.fichero, seccion, i[0]])\n raise Exception(message)\n\n except:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0000', \"\")\n raise Exception(message)\n\n\n elif i[1] == 3: \n # Field is a 'triad': test it for consistency (has to\n # have three fields; last one a valid corner\n # designation)\n x = self.get(seccion, lista[contador][0])\n try:\n y = EIDESystem.triad1(x.split(\",\")[0],\n x.split(\",\")[1], x.split(\",\")[2])\n y.test()\n retorno.append((lista[contador][0],\n self.get(seccion, lista[contador][0])))\n\n except IndexError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0100', [self.fichero, seccion, i[0]])\n raise Exception(message)\n\n except ReferenceError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0021', [self.fichero, seccion, i[0]])\n raise Exception(message)\n \n\n elif i[1] == 4:\n # Field is a text. No test.\n retorno.append((lista[contador][0], self.get(seccion,\n lista[contador][0])))\n\n\n elif i[1] == 5:\n # Coordinates (two integers)\n x = self.get(seccion, lista[contador][0])\n try:\n y = EIDESystem.coordinates(x.split(\",\")[0],\n x.split(\",\")[1])\n retorno.append((lista[contador][0],\n self.get(seccion, lista[contador][0])))\n\n except ValueError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0051', [self.fichero, seccion, i[0]])\n raise Exception(message)\n\n except IndexError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0100', [self.fichero, seccion, i[0]])\n raise Exception(message)\n \n\n elif i[1] == 6:\n # RGB color\n try:\n rgb = self.get(seccion, lista[contador][0]).split(\",\")\n color = tuple(map(int, rgb))\n for j in color:\n if j < 0 or j > 255:\n raise ValueError\n retorno.append((lista[contador][0], color))\n\n except ValueError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0080', [self.fichero, seccion, i[0]])\n raise Exception(message)\n \n\n elif i[1] == 7:\n # User print (decimals) format\n retorno.append((lista[contador][0], self.get(seccion, lista[contador][0])))\n\n # Test format for consistency ('0' .. '0.000')\n try:\n y = EIDESystem.formatoText(self.get(seccion,\n lista[contador][0]))\n y.test()\n\n except ValueError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0110', [self.fichero, seccion, i[0]])\n raise Exception(message)\n \n return retorno\n\n############################### EIDEParser end #####################\n\n\n","sub_path":"EIDEGraphics/EIDEParser.py","file_name":"EIDEParser.py","file_ext":"py","file_size_in_byte":7737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"352769176","text":"# -*- coding:utf-8 -*-\nimport csv\nimport datetime\nimport logging\nimport math\n\nlogfile_prefix = 'ARP'\n\ninfile_folder = 'infile'\noutfile_folder = 'outfile'\nlogfile_folder = 'log'\nlast_version = '8229'\n\n\ndef init_oag_location(file_path='infile/oag_loc.txt'):\n global dic_oag_location\n with open(file_path, 'r') as fin:\n for line in fin.readlines():\n if line.strip() and line[7] != ' ':\n arp = line[:3]\n latitude_list = line[94:102].split('.')\n latitude_list = [int(latitude_list[0]), int(latitude_list[1]), int(latitude_list[2]), line[102]]\n longitude_list = line[103:112].split('.')\n longitude_list = [int(longitude_list[0]), int(longitude_list[1]), int(longitude_list[2]), line[112]]\n location_name = line[8:47].strip()\n if location_name == '':\n location_name = arp\n dic_oag_location[arp] = [(line[47:49] + line[92:94]),\n latitude_list, longitude_list,\n (line[6], line[7]), location_name]\n\n\ndef init_af_airport(file_path_1='infile/airports.ids', file_path_2='infile/airportexception.ids'):\n global dic_af_airport\n with open(file_path_1, 'r') as fin:\n reader = csv.reader(fin, delimiter='#')\n for row in reader:\n if row[-1] == '32767':\n latitude_ = row[3][0]\n latitude_str = row[3][1:-1]\n longitude_ = row[4][0]\n longitude_str = row[4][1:-1]\n latitude_list = latitude_str.replace('null', '0').split(';')\n latitude_list = [int(latitude_list[0]), int(latitude_list[1]), int(latitude_list[2]), latitude_]\n longitude_list = longitude_str.replace('null', '0').split(';')\n longitude_list = [int(longitude_list[0]), int(longitude_list[1]), int(longitude_list[2]), longitude_]\n dic_af_airport[row[0]] = ['', latitude_list, longitude_list, row]\n with open(file_path_2, 'r') as fin:\n reader = csv.reader(fin, delimiter='#')\n for row in reader:\n if row[-1] == '32767':\n dic_af_airport[row[0]][0] = row[5]\n dic_af_airport[row[0]].append(row)\n\n\ndef init_oag_dst(file_path='infile/oag_dst.dat'):\n global dic_oag_dst\n with open(file_path, 'r') as fin:\n for line in fin.readlines():\n std_offset_h = int(line[7:9])\n std_offset_m = int(line[9:11])\n std_offset_minutes = std_offset_h * 60 + std_offset_m\n if line[6] == '-':\n std_offset_minutes = -std_offset_minutes\n dic_oag_dst[line[:4]] = std_offset_minutes\n\n\ndef init_omis_airport(file_path='infile/omis-airport.csv'):\n global dic_omis_airport\n with open(file_path, 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n if row[2] != '':\n m_s = row[2][1:]\n if len(m_s) == 2:\n std_offset_h = int(m_s[0:2])\n std_offset_m = 0\n elif len(m_s) == 5:\n std_offset_h = int(m_s[0:2])\n std_offset_m = int(m_s[3:5])\n else:\n dic_omis_airport[row[3]] = (0, row[1], row[2], None, row[5])\n continue\n std_offset_minutes = std_offset_h * 60 + std_offset_m\n if row[2][0] == 'W':\n std_offset_minutes = -std_offset_minutes\n dic_omis_airport[row[3]] = (1, row[1], row[2], std_offset_minutes, row[5])\n else:\n dic_omis_airport[row[3]] = (0, row[1], row[2], None, row[5])\n\n\ndef init_apg_airport(file_path='infile/apg_airport.csv'):\n global dic_apg_airport\n with open(file_path, 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n # print(row)\n arp = row[0]\n arp_name = row[1]\n country_code = row[6]\n latitude_float = float(row[10]) if row[10] != '' else 0\n latitude_ = 'N' if latitude_float >=0 else 'S'\n latitude_o = abs(latitude_float)\n latitude_o, latitude_1 = math.modf(latitude_o)\n latitude_o, latitude_2 = math.modf(latitude_o * 60)\n latitude_o, latitude_3 = math.modf(latitude_o * 60)\n latitude_list = [int(latitude_1), int(latitude_2), int(latitude_3), latitude_]\n longitude_float = float(row[11]) if row[11] != '' else 0\n longitude_ = 'E' if longitude_float >= 0 else 'W'\n longitude_o = abs(longitude_float)\n longitude_o, longitude_1 = math.modf(longitude_o)\n longitude_o, longitude_2 = math.modf(longitude_o * 60)\n longitude_o, longitude_3 = math.modf(longitude_o * 60)\n longitude_list = [int(longitude_1), int(longitude_2), int(longitude_3), longitude_]\n dic_apg_airport[arp] = [country_code, latitude_list, longitude_list, arp_name, row]\n\ndef show_dic(dic):\n for k, v in dic.items():\n print('%s: %s' % (k, v))\n\n\ndef compare_oag_af_arp():\n af_arp_output_list = []\n af_arpexcp_output_list = []\n oag_arp_list = dic_oag_location.keys()\n af_arp_list = list(dic_af_airport.keys())\n af_arp_list.sort()\n common_list = list(set(oag_arp_list).intersection(set(af_arp_list)))\n common_list.sort()\n only_oag_list = list(set(oag_arp_list).difference(set(af_arp_list)))\n only_oag_list.sort()\n only_af_list = list(set(af_arp_list).difference(set(oag_arp_list)))\n only_af_list.sort()\n\n for arp in af_arp_list:\n af_info = dic_af_airport[arp]\n af_timezone = af_info[0]\n af_country_code = af_timezone[:2]\n af_latitude = af_info[1]\n af_longitude = af_info[2]\n af_arp_output = af_info[3].copy()\n if arp in common_list:\n oag_info = dic_oag_location[arp]\n oag_timezone = oag_info[0]\n oag_country_code = oag_timezone[:2]\n oag_latitude = oag_info[1]\n oag_longitude = oag_info[2]\n oag_arp_name = oag_info[4]\n if len(af_info) == 5:\n af_arpexcp_output = af_info[4].copy()\n else:\n logger.info('Fill Blank Timezone: %s' %af_info)\n af_arpexcp_output = [arp, '010170', '00:00', '311258', '23:59', oag_timezone, last_version, '32767']\n if oag_timezone != af_timezone:\n if oag_country_code != af_country_code:\n logger.info('Country Diff %s:%sOAG:%s%sAF: %s' %(arp, '\\n'+' '*32, oag_info, '\\n'+' '*32, af_info))\n af_arp_output[2] = oag_country_code\n if af_timezone != '':\n af_arp_output[1] = oag_arp_name.upper()\n else:\n logger.info('TimeZone Diff %s:%sOAG:%s%sAF: %s' % (arp, '\\n'+' '*32, oag_info, '\\n'+' '*32, af_info))\n af_arpexcp_output[5] = oag_timezone\n logger.info('AF Revised to: %s' % af_arp_output)\n if oag_latitude != af_latitude:\n oag_latitude_int = oag_latitude[0]*100 + oag_latitude[1]\n af_latitude_int = af_latitude[0]*100 + af_latitude[1]\n if abs(oag_latitude_int - af_latitude_int) <= 50:\n logger.debug('Latitude Diff %s: OAG:%s AF:%s' % (arp, oag_latitude, af_latitude))\n else:\n logger.info('Latitude Diff %s: OAG:%s AF:%s' % (arp, oag_latitude, af_latitude))\n latitude_str = '%s%d;%d;%d;' % (oag_latitude[-1], oag_latitude[0], oag_latitude[1], oag_latitude[2])\n af_arp_output[3] = latitude_str\n logger.debug('AF Revised to: %s' % af_arp_output)\n if oag_longitude != af_longitude:\n oag_longitude_int = oag_longitude[0]*100 + oag_longitude[1]\n af_longitude_int = af_longitude[0]*100 + af_longitude[1]\n if abs(oag_longitude_int - af_longitude_int) <= 50:\n logger.debug('Latitude Diff %s: OAG:%s AF:%s' % (arp, oag_longitude, af_longitude))\n else:\n logger.info('Latitude Diff %s: OAG:%s AF:%s' % (arp, oag_longitude, af_longitude))\n longitude_str = \"%s%d;%d;%d;\" % (oag_longitude[-1], oag_longitude[0], oag_longitude[1], oag_longitude[2])\n af_arp_output[4] = longitude_str\n logger.debug('AF Revised to: %s' % af_arp_output)\n af_arp_output_list.append(bytes(('#'.join(af_arp_output) + '\\n'), encoding='utf-8'))\n af_arpexcp_output_list.append(bytes(('#'.join(af_arpexcp_output) + '\\n'), encoding='utf-8'))\n else:\n af_arp_output_list.append(bytes(('#'.join(af_arp_output) + '\\n'), encoding='utf-8'))\n if len(af_info) == 5:\n af_arpexcp_output = af_info[4].copy()\n af_arpexcp_output_list.append(bytes(('#'.join(af_arpexcp_output) + '\\n'), encoding='utf-8'))\n\n for arp in only_oag_list:\n oag_info = dic_oag_location[arp]\n oag_timezone = oag_info[0]\n oag_country_code = oag_timezone[:2]\n oag_latitude = oag_info[1]\n oag_longitude = oag_info[2]\n oag_arp_name = oag_info[4]\n af_arp_output = [arp, '', '', '', '', '-', last_version, '32767']\n af_arp_output[1] = oag_arp_name.upper()\n af_arp_output[2] = oag_country_code\n latitude_str = '%s%d;%d;%d;' % (oag_latitude[-1], oag_latitude[0], oag_latitude[1], oag_latitude[2])\n af_arp_output[3] = latitude_str\n longitude_str = \"%s%d;%d;%d;\" % (oag_longitude[-1], oag_longitude[0], oag_longitude[1], oag_longitude[2])\n af_arp_output[4] = longitude_str\n af_arpexcp_output = [arp, '010170', '00:00', '311258', '23:59', oag_timezone, last_version, '32767']\n logger.info('Add Airport %s from OAG to AF: %s %s' % (arp, af_arp_output, af_arpexcp_output))\n af_arp_output_list.append(bytes(('#'.join(af_arp_output) + '\\n'), encoding='utf-8'))\n af_arpexcp_output_list.append(bytes(('#'.join(af_arpexcp_output) + '\\n'), encoding='utf-8'))\n out1, out2 = af_arp_output_list, af_arpexcp_output_list\n write_results(out1, 'airports.ids')\n write_results(out2, 'airportexception.ids')\n\n\ndef compare_oag_apg_arp():\n oag_arp_list = dic_oag_location.keys()\n apg_arp_list = dic_apg_airport.keys()\n common_list = list(set(oag_arp_list).intersection(set(apg_arp_list)))\n common_list.sort()\n only_oag_list = list(set(oag_arp_list).difference(set(apg_arp_list)))\n only_oag_list.sort()\n only_apg_list = list(set(apg_arp_list).difference(set(oag_arp_list)))\n only_apg_list.sort()\n\n for arp in common_list:\n oag_info = dic_oag_location[arp]\n oag_timezone = oag_info[0]\n oag_country_code = oag_timezone[:2]\n oag_latitude = oag_info[1]\n oag_longitude = oag_info[2]\n oag_arp_name = oag_info[4]\n apg_info = dic_apg_airport[arp]\n apg_country_code = apg_info[0]\n apg_latitude = apg_info[1]\n apg_longitude = apg_info[2]\n apg_arp_name = apg_info[3]\n if oag_country_code != apg_country_code:\n print('Country Diff, %s,OAG,%s,%s,,APG,%s,%s' %(arp, oag_country_code, oag_arp_name, apg_country_code, apg_arp_name))\n # oag_latitude_int = oag_latitude[0] * 100 + oag_latitude[1]\n # apg_latitude_int = apg_latitude[0] * 100 + apg_latitude[1]\n # if abs(oag_latitude_int - apg_latitude_int) > 50:\n # print('Latitude Diff: %s OAG:%s APG:%s' %(arp, oag_latitude, apg_latitude ))\n # oag_longitude_int = oag_longitude[0] * 100 + oag_longitude[1]\n # apg_longitude_int = apg_longitude[0] * 100 + apg_longitude[1]\n # if abs(oag_longitude_int - apg_longitude_int) > 50:\n # print('Longitude Diff: %s OAG:%s APG:%s' %(arp, oag_longitude, apg_longitude))\n\n print(only_apg_list)\n\ndef diff(listA, listB):\n # 求交集的两种方式\n retA = [i for i in listA if i in listB]\n retB = list(set(listA).intersection(set(listB)))\n\n print(\"retA is: \", retA)\n print(\"retB is: \", retB)\n\n # 求并集\n retC = list(set(listA).union(set(listB)))\n print(\"retC is: \", retC)\n\n # 求差集,在B中但不在A中\n retD = list(set(listB).difference(set(listA)))\n print(\"retD is: \", retD)\n\n retE = [i for i in listB if i not in listA]\n print(\"retE is: \", retE)\n\n\ndef write_results(output_content_lists, file_name):\n file_folder = outfile_folder\n file_path = '%s/%s' % (file_folder, file_name)\n logger.info('Start writing ' + file_path)\n with open(file_path, 'wb') as fout:\n fout.writelines(output_content_lists)\n logger.info('Finish writing' + file_path)\n\n\ndef set_logger(logger_name, logfile_path=None):\n current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n if logfile_path is None:\n logfile_path = '%s/%s_%s.log' % (logfile_folder, logfile_prefix, current_time)\n logger = logging.getLogger(logger_name)\n logger.setLevel(logging.DEBUG)\n fh = logging.FileHandler(logfile_path)\n fh.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n logger.addHandler(fh)\n logger.addHandler(ch)\n logger.info('Log file: %s' % logfile_path)\n return logger\n\n\ndef main():\n init_oag_location()\n init_af_airport()\n # init_apg_airport()\n # show_dic(dic_oag_location)\n # show_dic(dic_af_airport)\n compare_oag_af_arp()\n # show_dic(dic_apg_airport)\n # compare_oag_apg_arp()\n\n\ndic_oag_location = {}\ndic_oag_dst = {}\ndic_af_airport = {}\ndic_omis_airport = {}\ndic_apg_airport = {}\n\nlogger = logging.getLogger('arp_logger')\n\n\nif __name__ == '__main__':\n set_logger('arp_logger')\n main()\n","sub_path":"AirChina/AVPS/airport.py","file_name":"airport.py","file_ext":"py","file_size_in_byte":13970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"366364737","text":"import scrapy\nimport re\nimport json\n\nfrom City58.TypeItem import FilterItems\n\n# 该爬虫主要得到所有的职业类型\nclass CitytypeSpider(scrapy.Spider):\n\tname = 'cityType'\n\tallowed_domains = ['bj.58.com']\n\tstart_urls = []\n\n\n\t# 正则匹配钩子\n\treHook = {\n\t\t# group(4)\n\t\t'pnLink' : r'(http|https)://(.+)/(pn(\\d+?))/.*',\n\t\t# group(3)\n\t\t'subLink' : r'(http|https)://(.+)/(.+/).*',\n\t}\n\n\tdef __init__(self):\n\t\tprint(\">> cityType.spider\")\n\t\tself.filterItems = FilterItems\n\n\t\tself.rootURL = \"http://bj.58.com/\"\n\t\tself.subURL = self.filterItems[0]['subLink']\n\n\t\tself._next_url = self.rootURL + self.subURL\n\t\tself.start_urls = [ self._next_url ]\n\t\t\n\tdef parse(self, response):\n\t\told = self.filterItems\n\t\told.extend(self.getFilterItem(response))\n\t\tprint(newItems)\n\n\t\t# 测试\n\t\tfs = open('type.json', 'w')\n\t\tfs.write('{\"data\":')\n\t\tfs.write(json.dumps(newItems))\n\t\tfs.write('}')\n\t\tfs.close()\n\n\n\tdef getFilterItem(self, response):\n\t\tfilters = response.xpath(\"//div[@class='filter_item'][1]/ul/li[not(@class='select')]\")\n\t\tfItems = []\n\t\tfor f in filters:\n\t\t\tdic = {}\n\t\t\tlink = f.xpath(\"./a/@href\").extract()[0]\n\t\t\tdic['type'] = f.xpath(\"./a/text()\").extract()[0]\n\t\t\tdic['subLink'] = re.search(self.reHook['subLink'], link).group(3)\n\t\t\tfItems.append(dic)\n\n\t\treturn fItems","sub_path":"python-scrapy-City58/City58/spiders/cityType.py","file_name":"cityType.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"196065441","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nimport numpy as np\n\nimport argparse\nimport keras\nfrom keras.models import load_model\n\nfrom utils import load_images, custom_object_scope, ensemble\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--input_dir', type=str, required=True, help='Input directory with images.')\n parser.add_argument('--output_file', type=str, required=True, help='Output file to save labels.')\n args = parser.parse_args()\n\n batch_size = 2\n image_height = 299\n image_width = 299\n nb_channels = 3\n \n batch_shape = [100, image_height, image_width, nb_channels]\n num_classes = 1000\n \n with custom_object_scope():\n adv_inception_resnet_v2 = load_model('models/adv_inception_resnet_v2.model', compile=False)\n adv_inception_v3 = load_model('models/adv_inception_v3.model', compile=False)\n\n inception_resnet_v2 = load_model('models/inception_resnet_v2.model', compile=False)\n inception_v3 = load_model('models/inception_v3.model', compile=False)\n resnet50 = load_model('models/resnet50.model', compile=False)\n vgg16 = load_model('models/vgg16.model', compile=False)\n vgg19 = load_model('models/vgg19.model', compile=False)\n xception = load_model('models/xception.model', compile=False)\n \n white_box_models = [adv_inception_resnet_v2, \n adv_inception_v3,\n inception_resnet_v2,\n inception_v3,\n vgg16,\n vgg19,\n xception,\n resnet50\n ]\n \n voting_model = ensemble(white_box_models, logits=True)\n \n with open(args.output_file, 'w') as f:\n for filenames, images in load_images(args.input_dir, batch_shape):\n logits = voting_model.predict(images, batch_size=batch_size, verbose=1)\n labels = np.argmax(logits, axis=-1) + 1\n\n\n for filename, label in zip(filenames, labels):\n f.write('{},{}\\n'.format(filename, label))\n","sub_path":"defence/defense.py","file_name":"defense.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"373660887","text":"from app.home.dao.NewsDao import queryNews\r\n\r\n\r\ndef queryAll():\r\n \"\"\"\r\n 返回父系列,以及对应的子系列\r\n \"\"\"\r\n results = queryNews()\r\n return results\r\n\r\n\r\nif __name__ == '__main__':\r\n a = queryAll()\r\n print(type(a))\r\n for item in a:\r\n print(item.content)\r\n # import json\r\n # list1=[]\r\n # list1.append(1)\r\n # list1.append(2)\r\n # list1.append(3)\r\n # jsonstr=json.dumps(list1)\r\n # print(jsonstr)\r\n","sub_path":"bxcf/app/home/service/NewsService.py","file_name":"NewsService.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"359342526","text":"from __future__ import absolute_import\n\nfrom datetime import datetime\n\nfrom django.test import TestCase\n\nfrom .models import Article, Person\n\n\nclass LatestTests(TestCase):\n def test_first(self):\n # Because no Articles exist yet, first() raises ArticleDoesNotExist.\n self.assertRaises(Article.DoesNotExist, Article.objects.first)\n\n a1 = Article.objects.create(\n headline=\"Article 1\", pub_date=datetime(2005, 7, 26),\n expire_date=datetime(2005, 9, 1)\n )\n a2 = Article.objects.create(\n headline=\"Article 2\", pub_date=datetime(2005, 7, 27),\n expire_date=datetime(2005, 7, 28)\n )\n a3 = Article.objects.create(\n headline=\"Article 3\", pub_date=datetime(2005, 7, 28),\n expire_date=datetime(2005, 8, 27)\n )\n a4 = Article.objects.create(\n headline=\"Article 4\", pub_date=datetime(2005, 7, 28),\n expire_date=datetime(2005, 7, 30)\n )\n\n # Get the first Article.\n self.assertEqual(Article.objects.first(), a1)\n # Get the first Article that matches certain filters.\n self.assertEqual(\n Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).first(),\n a2\n )\n\n # Pass a custom field name to first() to change the field that's used\n # to determine the first object.\n self.assertEqual(Article.objects.first('expire_date'), a2)\n self.assertEqual(\n Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).first('expire_date'),\n a2,\n )\n\n # Ensure that first() overrides any other ordering specified on the query. Refs #11283.\n self.assertEqual(Article.objects.order_by('id').first(), a1)\n\n def test_latest(self):\n # Because no Articles exist yet, latest() raises ArticleDoesNotExist.\n self.assertRaises(Article.DoesNotExist, Article.objects.latest)\n\n a1 = Article.objects.create(\n headline=\"Article 1\", pub_date=datetime(2005, 7, 26),\n expire_date=datetime(2005, 9, 1)\n )\n a2 = Article.objects.create(\n headline=\"Article 2\", pub_date=datetime(2005, 7, 27),\n expire_date=datetime(2005, 7, 28)\n )\n a3 = Article.objects.create(\n headline=\"Article 3\", pub_date=datetime(2005, 7, 27),\n expire_date=datetime(2005, 8, 27)\n )\n a4 = Article.objects.create(\n headline=\"Article 4\", pub_date=datetime(2005, 7, 28),\n expire_date=datetime(2005, 7, 30)\n )\n\n # Get the latest Article.\n self.assertEqual(Article.objects.latest(), a4)\n # Get the latest Article that matches certain filters.\n self.assertEqual(\n Article.objects.filter(pub_date__lt=datetime(2005, 7, 27)).latest(),\n a1\n )\n\n # Pass a custom field name to latest() to change the field that's used\n # to determine the latest object.\n self.assertEqual(Article.objects.latest('expire_date'), a1)\n self.assertEqual(\n Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).latest('expire_date'),\n a3,\n )\n\n # Ensure that latest() overrides any other ordering specified on the query. Refs #11283.\n self.assertEqual(Article.objects.order_by('id').latest(), a4)\n\n def test_latest_manual(self):\n # You can still use latest() with a model that doesn't have\n # \"get_latest_by\" set -- just pass in the field name manually.\n p1 = Person.objects.create(name=\"Ralph\", birthday=datetime(1950, 1, 1))\n p2 = Person.objects.create(name=\"Stephanie\", birthday=datetime(1960, 2, 3))\n self.assertRaises(AssertionError, Person.objects.latest)\n\n self.assertEqual(Person.objects.latest(\"birthday\"), p2)\n","sub_path":"tests/modeltests/get_latest/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"83660677","text":"import random\nimport os\nimport time\nfrom selenium import webdriver\nfrom net import ips\n\ndef get12306Cookie():\n proxy = random.choice(ips)\n chromeOptions = webdriver.ChromeOptions()\n chromeOptions.add_argument(\"'--proxy-server={}\".format(proxy))\n browser = webdriver.Chrome(chrome_options=chromeOptions, executable_path=os.path.dirname(\n os.path.dirname(os.path.realpath(__file__))) + '/cookie/chromedriver')\n browser.get(\"https://www.12306.cn/index/\")\n flag = False\n res = {}\n while (flag == False):\n cookies = browser.get_cookies()\n for cookie in cookies:\n if cookie['name'] == 'RAIL_DEVICEID':\n res['RAIL_DEVICEID'] = cookie['value']\n flag = True\n elif cookie['name'] == 'RAIL_EXPIRATION':\n res['RAIL_EXPIRATION'] = cookie['value']\n time.sleep(1)\n browser.quit()\n return res\n\n\nif __name__ == '__main__':\n cookies = get12306Cookie()\n print(cookies)\n","sub_path":"train/cookie/getCookie.py","file_name":"getCookie.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"252758440","text":"\"\"\" L-curve regularization parameter finding.\n\nThis set of functions are used to find an optimal regularization parameter\nfor a under determined system of equations. The optimal parameter is found\naccording to the L-curve criteria, described in\n\nDiscrete Inverse Problems - insight and algorithms, Per Christian Hansen,\nTechnical University of Denmark, DTU compute, 2010\n\nThe code was adapted from http://www.imm.dtu.dk/~pcha/Regutools/ by\nPer Christian Hansen, DTU Compute, October 27, 2010 - originally implemented in Matlab\n\nThis version is only for the under determined case.\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io as scio\nfrom scipy import linalg # for svd\nfrom scipy import optimize\nimport warnings\n\ndef curvature(lambd, sig, beta, xi):\n \"\"\" computes the NEGATIVE of the curvature.\n\n Parameters\n ----------\n lambd : float\n regularization parameter\n sig : numpy 1darray\n singular values\n beta: numpy 1darray\n conj(u) @ bm\n xi : numpy 1darray\n beta / sig\n Returns\n -------\n curv : numpy 1darray\n negative curvature\n \"\"\"\n # Initialization.\n phi = np.zeros(lambd.shape)\n dphi = np.zeros(lambd.shape)\n psi = np.zeros(lambd.shape)\n dpsi = np.zeros(lambd.shape)\n eta = np.zeros(lambd.shape)\n rho = np.zeros(lambd.shape)\n if len(beta) > len(sig): # A possible least squares residual.\n LS = True\n rhoLS2 = beta[-1] ** 2\n beta = beta[0:-2]\n else:\n LS = False\n # Compute some intermediate quantities.\n for jl, lam in enumerate(lambd):\n f = np.divide((sig ** 2), (sig ** 2 + lam ** 2)) # ok\n cf = 1 - f # ok\n eta[jl] = np.linalg.norm(f * xi) # ok\n rho[jl] = np.linalg.norm(cf * beta)\n f1 = -2 * f * cf / lam \n f2 = -f1 * (3 - 4*f)/lam\n phi[jl] = np.sum(f*f1*np.abs(xi)**2) #ok\n psi[jl] = np.sum(cf*f1*np.abs(beta)**2)\n dphi[jl] = np.sum((f1**2 + f*f2)*np.abs(xi)**2)\n dpsi[jl] = np.sum((-f1**2 + cf*f2)*np.abs(beta)**2) #ok\n\n if LS: # Take care of a possible least squares residual.\n rho = np.sqrt(rho ** 2 + rhoLS2)\n\n # Now compute the first and second derivatives of eta and rho\n # with respect to lambda;\n deta = np.divide(phi, eta) #ok\n drho = -np.divide(psi, rho)\n ddeta = np.divide(dphi, eta) - deta * np.divide(deta, eta)\n ddrho = -np.divide(dpsi, rho) - drho * np.divide(drho, rho)\n\n # Convert to derivatives of log(eta) and log(rho).\n dlogeta = np.divide(deta, eta)\n dlogrho = np.divide(drho, rho)\n ddlogeta = np.divide(ddeta, eta) - (dlogeta)**2\n ddlogrho = np.divide(ddrho, rho) - (dlogrho)**2\n # curvature.\n curv = - np.divide((dlogrho * ddlogeta - ddlogrho * dlogeta),\n (dlogrho**2 + dlogeta**2)**(1.5))\n return curv\n\ndef l_corner(rho,eta,reg_param,u,sig,bm):\n \"\"\" Computes the corner of the L-curve.\n\n Uses the function \"curvature\"\n\n Parameters\n ----------\n rho : numpy 1darray\n computed in l_curve function (residual norm) - related to curvature\n eta : numpy 1darray\n computed in l_curve function (solution norm) - related to curvature\n reg_param : numpy 1darray\n computed in l_curve function\n u : numpy ndarray\n left singular vectors\n sig : numpy 1darray\n singular values\n bm: numpy 1darray\n your measurement vector (size: Nm x 1)\n Returns\n -------\n reg_c : float\n optimal regularization parameter\n \"\"\"\n # Set threshold for skipping very small singular values in the analysis of a discrete L-curve.\n s_thr = np.finfo(float).eps # Neglect singular values less than s_thr.\n # Set default parameters for treatment of discrete L-curve.\n deg = 2 # Degree of local smooting polynomial.\n q = 2 # Half-width of local smoothing interval.\n order = 4 # Order of fitting 2-D spline curve.\n # Initialization.\n if (len(rho) < order):\n print('I will fail. Too few data points for L-curve analysis')\n Nm, Nu = u.shape\n p = sig.shape\n beta = (np.conj(u)) @ bm \n beta = np.reshape(beta[0:int(p[0])], beta.shape[0])\n b0 = (bm - (beta.T @ u).T)\n xi = np.divide(beta[0:int(p[0])], sig)\n # Call curvature calculator\n curv = curvature(reg_param, sig, beta, xi) # ok\n # Minimize 1\n curv_id = np.argmin(curv)\n x1 = reg_param[int(np.amin([curv_id+1, len(curv)-1]))]\n x2 = reg_param[int(np.amax([curv_id-1, 0]))]\n # x1 = reg_param[int(np.amin([curv_id+1, len(curv)]))]\n # x2 = reg_param[int(np.amax([curv_id-1, 0]))]\n # Minimize 2 - set tolerance first (new versions of scipy need that)\n tolerance = np.amin([x1/50, x2/50, 1e-5])\n reg_c = optimize.fminbound(curvature, x1, x2, args = (sig, beta, xi), xtol=tolerance,\n full_output=False, disp=False)\n kappa_max = - curvature(reg_c, sig, beta, xi) # Maximum curvature.\n if kappa_max < 0:\n lr = len(rho)\n reg_c = reg_param[lr-1]\n rho_c = rho[lr-1]\n eta_c = eta[lr-1]\n else:\n f = np.divide((sig**2), (sig**2 + reg_c**2))\n eta_c = np.linalg.norm(f * xi)\n rho_c = np.linalg.norm((1-f) * beta[0:len(f)])\n if Nm > Nu:\n rho_c = np.sqrt(rho_c ** 2 + np.linalg.norm(b0)**2)\n return reg_c\n\ndef csvd(A):\n \"\"\" Computes the SVD based on the size of A.\n\n Parameters\n ----------\n A : numpy ndarray\n sensing matrix (Nm x Nu). Nm are the number of measurements\n and Nu the number of unknowns\n Returns\n -------\n u : numpy ndarray\n left singular vectors\n sig : numpy 1darray\n singular values\n v : numpy ndarray\n right singular vectors\n \"\"\"\n Nm, Nu = A.shape\n if Nm >= Nu: # more measurements than unknowns\n u, sig, v = np.linalg.svd(A, full_matrices=False)\n else:\n v, sig, u = np.linalg.svd(np.conjugate(A.T), full_matrices=False)\n return u, sig, v\n\ndef l_cuve(u, sig, bm, plotit = False):\n \"\"\" Find the optimal regularizatin parameter.\n\n This function uses the L-curve and computes its curvature in\n order to find its corner - optimal regularization parameter.\n\n Uses the function \"l_corner\"\n\n Parameters\n ----------\n u : numpy ndarray\n left singular vectors\n sig : numpy 1darray\n singular values\n bm: numpy 1darray\n your measurement vector (size: Nm x 1)\n plotit : bool\n whether to plot the L curve or not. Default is False\n Returns\n -------\n lam_opt : float\n optimal regularization parameter\n \"\"\"\n # Set defaults.\n npoints = 200 # Number of points on the L-curve\n smin_ratio = 16*np.finfo(float).eps # Smallest regularization parameter.\n # Initialization.\n Nm, Nu = u.shape\n p = sig.shape\n beta = np.conjugate(u) @ bm\n beta2 = np.linalg.norm(bm) ** 2 - np.linalg.norm(beta)**2\n s = sig\n beta = np.reshape(beta[0:int(p[0])], beta.shape[0])\n xi = np.divide(beta[0:int(p[0])],s)\n xi[np.isinf(xi)] = 0\n\n eta = np.zeros((npoints,1))\n rho = np.zeros((npoints,1)) #eta\n reg_param = np.zeros((npoints,1))\n s2 = s ** 2\n reg_param[-1] = np.amax([s[-1], s[0]*smin_ratio])\n ratio = (s[0]/reg_param[-1]) ** (1/(npoints-1))\n for i in np.arange(start=npoints-2, step=-1, stop = -1):\n reg_param[i] = ratio*reg_param[i+1]\n for i in np.arange(start=0, step=1, stop = npoints):\n f = s2 / (s2 + reg_param[i] ** 2)\n eta[i] = np.linalg.norm(f * xi)\n rho[i] = np.linalg.norm((1-f) * beta[:int(p[0])])\n if (Nm > Nu and beta2 > 0):\n rho = np.sqrt(rho ** 2 + beta2)\n # Compute the corner of the L-curve (optimal regularization parameter)\n lam_opt = l_corner(rho,eta,reg_param,u,sig,bm)\n # want to plot the L curve?\n if plotit:\n fig = plt.figure()\n fig.canvas.set_window_title(\"L-curve\")\n plt.loglog(rho, eta, label='Reg. par: ' + \"%.6f\" % lam_opt)\n plt.xlabel(r'Residual norm $||Ax - b||_2$')\n plt.ylabel(r'Solution norm $||x||_2$')\n plt.legend(loc = 'best')\n plt.grid(linestyle = '--', which='both')\n plt.tight_layout()\n return lam_opt\n\ndef tikhonov(u,s,v,b,lambd_value):\n \"\"\" Tikhonov regularization. Needs some work\n\n Computes the Tikhonov regularized solution x_lambda, given the SVD or\n GSVD as computed via csvd or cgsvd, respectively. The SVD is used,\n i.e. if U, s, and V are specified, then standard-form regularization\n is applied:\n min { || A x - b ||^2 + lambda^2 || x - x_0 ||^2 } .\n Valid for underdetermined systems.\n Based on the matlab routine by: Per Christian Hansen, DTU Compute, April 14, 2003.\n Reference: A. N. Tikhonov & V. Y. Arsenin, \"Solutions of Ill-Posed\n Problems\", Wiley, 1977.\n\n Parameters\n ----------\n u : numpy ndarray\n left singular vectors\n sig : numpy 1darray\n singular values\n v : numpy ndarray\n right singular vectors\n bm: numpy 1darray\n your measurement vector (size: Nm x 1)\n lam_opt : float\n optimal regularization parameter\n Returns\n -------\n x_lambda : numpy 1darray\n estimated solution to inverse problem\n \"\"\"\n # warn that lambda should be bigger than 0\n if lambd_value < 0:\n warnings.warn(\"Illegal regularization parameter lambda. I'll set it to 1.0\")\n lambd_value = 1.0\n # m = u.shape[0]\n # n = v.shape[0]\n p = len(s)\n # ps = 1\n beta = np.conjugate(u[:,0:p]).T @ b\n zeta = s * beta\n # ll = length(lambda); x_lambda = zeros(n,ll);\n # rho = zeros(ll,1); eta = zeros(ll,1);\n # The standard-form case.\n x_lambda = v[:,0:p] @ np.divide(zeta, s**2 + lambd_value**2)\n \n # because csvd takes the hermitian of h_mtx and only the first m collumns of v\n # phi_factors = (s**2)/(s**2+lambd_value**2)\n # x = (v @ np.diag(phi_factors/s) @ np.conjugate(u)) @ b\n # beta_try = np.conjugate(u) @ b\n # zeta_try = s*beta_try\n # x_try = v @ np.divide(zeta_try, s**2 + lambd_value**2) #np.diag(s/(s**2+lambd_value**2)) @ beta_try\n return x_lambda\n\n\n# np.random.seed(0)\n# H = np.random.randn(7, 10)\n# p = np.random.randn(7)\n# u, sig, v = csvd(H)\n# lambd_value = l_cuve(u, sig, p, plotit=False)\n# tikhonov(u, sig, v, p, lambd_value)\n# H = np.array([[1, 7, 10],[2.3, 5.4, 13.2]])\n# p = np.array([1.4, 8.54])\n# u, sig, v = csvd(H)\n# x_lambda = tikhonov(u, sig, v, p, 0.3)\n# print(x_lambda)\n\n ","sub_path":"insitu/lcurve_functions.py","file_name":"lcurve_functions.py","file_ext":"py","file_size_in_byte":10612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"176954407","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Dec 10 19:34:00 2017\r\n\r\n@author: clara\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\nfrom numpy import linalg as LA\r\nimport math\r\n\r\n \r\nclass Ball:\r\n \r\n \"\"\"\r\n This class creates a ball, with a specific position and velocity. \r\n The mass, radius and color can also be decided.\r\n \"\"\"\r\n K_b=1.38 #defines the Boltzmann constant\r\n \r\n def __init__(self,r=[0.0,0.0], v=[0.0,0.0],mass=16, rad=0.5,clr='r' ):\r\n self.__r=np.array(r, dtype='float') \r\n self.v=np.array(v, dtype='float')\r\n self.radius=rad\r\n self.mass=mass\r\n self.__patch = plt.Circle(self.__r, self.radius, fc=clr)\r\n \r\n \r\n def pos(self):\r\n \"\"\"Returns the position of the ball\"\"\"\r\n return self.__r\r\n \r\n def vel(self):\r\n \"\"\"Returns the velocity of the ball\"\"\"\r\n return self.v\r\n \r\n def move(self,dt):\r\n \"\"\"Moves the ball by a time step dt\"\"\"\r\n self.__r= self.__r+(self.v *dt)\r\n self.__patch.center = self.__r\r\n return self.__r\r\n \r\n def time_to_collision(self, other):\r\n \"\"\"Solves the quadratic equation for the time to the next collision\"\"\"\r\n R= (self.__r-other.__r)\r\n V= (self.v-other.v)\r\n RA= self.radius+other.radius #This is for collision with another ball\r\n a_term= 2*np.dot(R,V)\r\n b_term= (((a_term)**2)-4*(LA.norm(R)**2-RA**2)*(LA.norm(V)**2)) \r\n dt1=(-a_term+np.sqrt(b_term))/(2*(LA.norm(V)**2))\r\n dt2=(-a_term-np.sqrt(b_term))/(2*(LA.norm(V)**2))\r\n if dt1<=5e-10 or dt1!=dt1: \r\n newdt1=np.inf \r\n else:\r\n newdt1=dt1\r\n if dt2<=5e-10 or dt2!=dt2:\r\n newdt2=np.inf\r\n else:\r\n newdt2=dt2 #this removes unwanted solutions, and the nan case.\r\n return np.amin(np.array([newdt1,newdt2]))\r\n\r\n def collide(self,other):#takes the other ball as argument\r\n \"\"\"By converting to the center of mass frame, changes the speed of the balls\"\"\"\r\n reduced_mass= (self.mass - other.mass)/(self.mass +other.mass)\r\n bigger_mass=2/(self.mass+other.mass)\r\n \r\n R=self.__r-other.__r\r\n R_mag= (np.dot(R,R))**0.5 #magnitude of R\r\n R_hat= R/R_mag\r\n \r\n parallel_v1= np.dot(self.v,R_hat)*R_hat\r\n perpendicular_v1=self.v-parallel_v1\r\n \r\n parallel_v2= np.dot(other.v,R_hat)*R_hat\r\n perpendicular_v2=other.v-parallel_v2\r\n \r\n new_parallel_v1= reduced_mass*parallel_v1+(other.mass *bigger_mass*parallel_v2) \r\n new_parallel_v2=(self.mass*bigger_mass*parallel_v1)- (reduced_mass*parallel_v2)\r\n \r\n \r\n if other.mass==np.inf: #special case of the container\r\n new_parallel_v1=-parallel_v1\r\n new_parallel_v2=0\r\n mom_2_initial=0.0\r\n mom_2_final=0.0\r\n KE_2_initial=0\r\n \r\n \r\n \r\n #update speeds\r\n new_v1= new_parallel_v1+perpendicular_v1\r\n new_v2= new_parallel_v2+perpendicular_v2\r\n \r\n #momentum conservation check\r\n mom_1_initial=self.mass*self.v\r\n mom_2_initial=other.mass*other.v\r\n mom_initial= LA.norm(mom_1_initial+mom_2_initial)\r\n \r\n mom_1_final=self.mass*new_v1\r\n mom_2_final=other.mass*new_v2\r\n mom_final=LA.norm(mom_1_final+mom_2_final)\r\n \r\n if other.mass==np.inf:\r\n mom_initial=LA.norm(mom_1_initial)\r\n mom_final= LA.norm(mom_1_final)\r\n \r\n \r\n \r\n if np.abs(1-((mom_final)/(LA.norm(mom_initial))))>0.01: #conservation laws\r\n print ('No violation of conservation of momentum hypothesis rejected to 1%')\r\n \r\n #KE conservation check\r\n KE_1_initial=self.mass*0.5*(LA.norm(self.v)**2)\r\n KE_2_initial=other.mass*0.5*(LA.norm(other.v)**2) \r\n \r\n KE_1_final=self.mass*0.5*(LA.norm(new_v1)**2)\r\n KE_2_final=other.mass*0.5*(LA.norm(new_v2)**2)\r\n \r\n if other.mass==np.inf:\r\n KE_2_initial=0\r\n KE_2_final=0\r\n \r\n if np.abs(1-((KE_1_initial+KE_2_initial)/(KE_1_final+KE_2_final)))>0.01: \r\n print ('No violation of conservation of energy hypothesis rejected at 1%')\r\n \r\n self.v=new_v1\r\n other.v=new_v2\r\n \r\n return self.v, other.v\r\n \r\n \r\n def time_to_container(self,container_radius): \r\n \"\"\"Solves the quadratic equation for the case of the container\"\"\"\r\n \r\n R= (self.__r)\r\n V= (self.v)\r\n RA= container_radius-self.radius \r\n a_term= 2*np.dot(R,V)\r\n b_term= (((a_term)**2)-4*(LA.norm(R)**2-RA**2)*(LA.norm(V)**2))\r\n dt1=(-a_term+np.sqrt(b_term))/(2*(LA.norm(V)**2))\r\n dt2=(-a_term-np.sqrt(b_term))/(2*(LA.norm(V)**2))\r\n if dt1<=5e-10 or dt1!=dt1:\r\n newdt1=np.inf\r\n else:\r\n newdt1=dt1\r\n if dt2<=5e-10 or dt2 !=dt2: #removes nan\r\n newdt2=np.inf\r\n else:\r\n newdt2=dt2 #ignores the negative solutions to allow us to find smallest dt\r\n \r\n return np.amin(np.array([newdt1,newdt2])) \r\n \r\n def get_patch(self):\r\n \"\"\"Used to access the hidden attribute patch\"\"\"\r\n return self.__patch\r\n \r\n \r\n def __repr__(self):\r\n \"\"\"Ball representation\"\"\"\r\n return \"A ball with (r=array[%g,%g], v=array[%g,%g], mass = %g, radius= %g)\"%(self.pos()[0], self.pos()[1],self.v[0],self.v[1], self.mass,self.radius) \r\n\r\n def __str__(self):\r\n return \"%g,%g,%g,%g,%g,%g\" %(self.pos()[0], self.pos()[1],self.v[0],self.v[1], self.mass,self.radius)\r\n ","sub_path":"Ball.py","file_name":"Ball.py","file_ext":"py","file_size_in_byte":5764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"129522866","text":"#!/usr/bin/env python\n\nimport os\ntry:\n # Try using ujson as replacement for json\n import ujson as json\nexcept:\n # Fallback to standard json package\n import json\nimport redis\nimport uuid\nimport platform\n\n\nclass Worker(object):\n def __init__(self, key=None, config=None, expire=300):\n self.config = {\n 'host': 'localhost',\n 'port': 6379,\n 'db': 0,\n 'password': None,\n }\n if config is not None:\n self.config.update(config)\n\n self.rdb = None\n self.expire = expire\n self.connected = False\n self.registered = False\n if key is None:\n self.key = \"reworker-{}:{}:{}\".format(platform.node(), os.getpid(), str(uuid.uuid4().hex))\n else:\n self.key = \"reworker-{}\".format(key)\n self.connect()\n\n def list(self):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n try:\n return [Worker(key=name[9:].decode(), config=self.config) for name in self.rdb.keys(\"reworker-*\")]\n except redis.exceptions.ConnectionError as err:\n raise ConnectionError(str(err))\n\n def connect(self):\n config = self.config\n self.rdb = redis.Redis(config['host'], config['port'], config['db'], config['password'])\n try:\n info = self.rdb.info()\n self.connected = True\n except redis.ConnectionError:\n return False\n return True\n\n def register(self):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n self.rdb.set(self.key, \"{}\")\n if self.expire > 0:\n self.rdb.expire(self.key, self.expire)\n self.registered = True\n return True\n\n def unregister(self):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n if not self.registered:\n raise ConnectionError('Worker is not registered')\n self.rdb.delete(self.key, \"{}\")\n return True\n\n def set_status(self, **kwargs):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n if not self.registered:\n raise ConnectionError('Worker is not registered')\n status = json.dumps(kwargs)\n self.rdb.set(self.key, status)\n if self.expire > 0:\n self.rdb.expire(self.key, self.expire)\n return True\n\n def get_status(self):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n status = self.rdb.get(self.key)\n return json.loads(status)\n\n def get_ttl(self):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n return self.rdb.ttl(self.key)\n","sub_path":"reworker/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"90296483","text":"import heapq \r\n\r\nn = int(input())\r\n\r\n#각 노드에 연결된 간선 정보를 담기 위한 연결리스트\r\ngraph = [ [] for _ in range(n+1) ]\r\noutdegree = [0]*(n+1)\r\nresult = [0]*(n+1)\r\n\r\nfor i in range(1,n+1):\r\n infos = list(map(int,input()))\r\n\r\n for idx, val in enumerate(infos):\r\n if val == 1:\r\n graph[idx + 1].append(i)\r\n outdegree[i] += 1\r\n\r\ndef topology_sort(n):\r\n #큐에 여러노드가 있을 경우 인덱스가 큰 노드를 먼저 큐에서 빼내야함\r\n #답이 여러개 일 경우 사전 순으로 제일 앞서는 것 출력\r\n heap = []\r\n\r\n for i in range(1, n+1):\r\n if outdegree[i] == 0:\r\n heapq.heappush(heap, -i)\r\n \r\n while heap:\r\n # 인덱스가 가장 큰 노드를 꺼내고\r\n #해당 노드와 연결된 노드들의 차수를 뺀다\r\n #큐에서 빼낸 노드번호를 인덱스로 result리스트에 저장\r\n now = -heapq.heappop(heap)\r\n result[now] = n\r\n\r\n for adj in graph[now]:\r\n outdegree[adj] -= 1\r\n if outdegree[adj] == 0:\r\n heapq.heappush(heap, -adj)\r\n \r\n n -= 1\r\n\r\ntopology_sort(n)\r\n\r\n#그래프 번호를 수정할 수 없는 노드가 2개 이상이라면 -1\r\n#사이클이 돌려면 최소 3개의 노드가 서로 가리키고 있어야하는데\r\n#그러면 2개 이상의 노드는 진출 차수가 0이 될 수 없다.\r\n\r\nif result.count(0) > 2:\r\n print(-1)\r\nelse:\r\n print(' '.join(map(str,result[1:])))\r\n \r\n\r\n\r\n","sub_path":"백준/Platinum/1432. 그래프 수정/그래프 수정.py","file_name":"그래프 수정.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"525259667","text":"# 즉시 실행 모드\nfrom tensorflow.python.framework.ops import disable_eager_execution\nimport tensorflow as tf\n\nprint(tf.executing_eagerly()) # False\n\ntf.compat.v1.disable_eager_execution() # tensorflow2에서 tensorflow1 코딩을 가능하게 만듬\nprint(tf.executing_eagerly()) # False\n\nprint(tf.__version__) # 2.3.1\n\nimport numpy as np\ntf.compat.v1.set_random_seed(66)\n\n# 1. 데이터\nfrom tensorflow.keras.datasets import cifar10\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\nfrom tensorflow.keras.utils import to_categorical\ny_train = to_categorical(y_train)\ny_test = to_categorical(y_test)\n\nx_train = x_train.reshape(50000, 32, 32, 3).astype('float32')/255\nx_test = x_test.reshape(10000, 32, 32, 3).astype('float32')/255\n\nlearning_rate = 0.001\ntraining_epochs = 30\nbatch_size = 100\ntotal_batch = int(len(x_train)/batch_size) # 60000 / 100\n\nx = tf.compat.v1.placeholder(tf.float32,[None, 32, 32, 3])\ny = tf.compat.v1.placeholder(tf.float32,[None, 10])\n\n# 2. 모델 구성\n\n# L1.\nw1 = tf.compat.v1.get_variable('w1', shape=[3, 3, 3, 32]) # (kernel_size, channel, filter(output))\nL1 = tf.nn.conv2d(x, w1, strides=[1,1,1,1], padding='SAME') # stiride를 (2,2)로 주려면 [1,2,2,1]\nL1 = tf.compat.v1.layers.batch_normalization(L1)\n# L1 = tf.compat.v1.layers.BatchNormalization(L1)\n\nprint(L1) # Tensor(\"Conv2D:0\", shape=(?, 28, 28, 32), dtype=float32)\n# Conv2D(filter, kernel_size, input_shape) Summary\n# Conv2D(10, (3,2), input_shape=(7,7,1)) -> (kernel_size*channel(color, input_dim) + bias)*filter(output) -> 70\n# 다음 레이어로 갈때 (28,28,32)로 간다 -> padding='SAME'이고 output 32가 channel자리로 간다.\n# conv2d 안에 bias 포함되어 있음.\nL1 = tf.nn.selu(L1)\nL1 = tf.nn.max_pool(L1, ksize=[1,2,2,1], strides=[1,2,2,1,],padding='SAME')\nprint(L1) # Tensor(\"MaxPool:0\", shape=(?, 14, 14, 32), dtype=float32)\n# L2.\n\nw2 = tf.compat.v1.get_variable('w2', shape=[3, 3, 32, 64])\nL2 = tf.nn.conv2d(L1, w2, strides=[1,1,1,1], padding='SAME')\nprint(L2) # Tensor(\"Conv2D_1:0\", shape=(?, 14, 14, 64), dtype=float32)\nL2 = tf.compat.v1.layers.batch_normalization(L2)\n# L2 = tf.compat.v1.layers.BatchNormalization(L2)\nL2 = tf.nn.elu(L2)\nL2 = tf.nn.max_pool(L2, ksize=[1,2,2,1], strides=[1,2,2,1,],padding='SAME')\nprint(L2) # Tensor(\"MaxPool_1:0\", shape=(?, 7, 7, 64), dtype=float32)\n\n# L3.\nw3 = tf.compat.v1.get_variable('w3', shape=[3, 3, 64, 128])\nL3 = tf.nn.conv2d(L2, w3, strides=[1,1,1,1], padding='SAME')\nprint(L3) # Tensor(\"Conv2D_2:0\", shape=(?, 7, 7, 128), dtype=float32)\nL3 = tf.compat.v1.layers.batch_normalization(L3)\n# L3 = tf.compat.v1.layers.BatchNormalization(L3)\nL3 = tf.nn.relu(L3)\nL3 = tf.nn.max_pool(L3, ksize=[1,2,2,1], strides=[1,2,2,1,],padding='SAME')\nprint(L3) # Tensor(\"MaxPool_2:0\", shape=(?, 4, 4, 128), dtype=float32)\n\n# L4.\nw4 = tf.compat.v1.get_variable('w4', shape=[3, 3, 128, 64])\nL4 = tf.nn.conv2d(L3, w4, strides=[1,1,1,1], padding='SAME')\nL4 = tf.compat.v1.layers.batch_normalization(L4)\n# L4 = tf.compat.v1.layers.BatchNormalization(L4)\nprint(L4) # Tensor(\"Conv2D_3:0\", shape=(?, 4, 4, 64), dtype=float32)\nL4 = tf.nn.selu(L4)\nL4 = tf.nn.max_pool(L4, ksize=[1,2,2,1], strides=[1,2,2,1,],padding='SAME')\nprint(L4) # Tensor(\"MaxPool_3:0\", shape=(?, 2, 2, 64), dtype=float32)\n\n# Flatten\nL_flat = tf.reshape(L4, [-1,2*2*64])\nprint(L_flat) # Tensor(\"Reshape:0\", shape=(?, 256), dtype=float32)\n\n# L5.\nw5 = tf.compat.v1.get_variable('w5', shape=[2*2*64, 64], initializer=tf.compat.v1.initializers.he_normal())\nb5 = tf.compat.v1.Variable(tf.random.normal([64]), name='b1')\nL5 = tf.nn.selu(tf.matmul(L_flat, w5) + b5)\nL5 = tf.nn.dropout(L5, rate=0.2)\nprint(L5) # Tensor(\"dropout/mul_1:0\", shape=(?, 64), dtype=float32)\n\n# L6.\nw6 = tf.compat.v1.get_variable('w6', shape=[64, 32], initializer=tf.compat.v1.initializers.he_normal())\nb6 = tf.compat.v1.Variable(tf.random.normal([32]), name='b2')\nL6 = tf.nn.selu(tf.matmul(L5, w6) + b6)\nprint(L6) # Tensor(\"dropout/mul_1:0\", shape=(?, 64), dtype=float32)\n\n# L7.\nw7 = tf.compat.v1.get_variable('w7', shape=[32, 10], initializer=tf.compat.v1.initializers.he_normal())\nb7 = tf.compat.v1.Variable(tf.random.normal([10]), name='b3')\nhypothesis = tf.nn.softmax(tf.matmul(L6, w7) + b7)\nprint(hypothesis) # Tensor(\"Softmax:0\", shape=(?, 10), dtype=float32)\n\n# 3. 컴파일, 훈련\nloss = tf.reduce_mean(-tf.reduce_sum(y*tf.math.log(hypothesis), axis=1)) # categorical_crossentropy\noptimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.0001).minimize(loss)\n\n# 훈련\nsess = tf.compat.v1.Session()\nsess.run(tf.compat.v1.global_variables_initializer())\n\nfor epoch in range(training_epochs):\n avg_cost = 0\n\n for i in range(total_batch): # 600번 돈다\n start = i * batch_size\n end = start + batch_size\n\n batch_x, batch_y = x_train[start:end], y_train[start:end]\n feed_dict = {x:batch_x, y:batch_y}\n c, _ = sess.run([loss, optimizer], feed_dict=feed_dict)\n avg_cost += c/total_batch\n print('Epoch :', '%04d'%(epoch + 1), 'cost = {:.9f}'.format(avg_cost))\nprint('훈련 끗!!!')\n\nprediction = tf.equal(tf.math.argmax(hypothesis,1), tf.math.argmax(y,1))\naccuracy = tf.reduce_mean(tf.cast(prediction, dtype=tf.float32))\n\nprint('Acc :', sess.run(accuracy, feed_dict={x:x_test, y:y_test}))\n\n# Epoch : 0015 cost = 0.442068111\n# Acc : 0.7015 -> adam(0.0003)\n\n# Epoch : 0030 cost = 0.151768006\n# Acc : 0.6916 -> adam(0.0003)\n\n# Epoch : 0030 cost = 0.532191409\n# Acc : 0.7013 -> adam(0.0001)\n","sub_path":"tf114/tf18_cnn_cifar10.py","file_name":"tf18_cnn_cifar10.py","file_ext":"py","file_size_in_byte":5438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"485125841","text":"import time\n\nfrom Algorithms.Constraints.better_treatment_constraint import Constraint\nfrom Algorithms.constrained_greedy import ConstrainedGreedy\nfrom Algorithms.Approximators.statistical_approximator import StatisticalApproximator\nfrom Algorithms.Constraints.true_constraint import TrueConstraint\nfrom DataGenerator.data_generator import split_patients, generate_data, generate_test_data\nfrom DataGenerator.distributions import DiscreteDistributionWithSmoothOutcomes\n\n\ndef setup_data_sets(n_z, n_x, n_a, n_y, n_training_samples, n_test_samples, seed):\n start = time.time()\n print(\"Generating training and test data\")\n dist = DiscreteDistributionWithSmoothOutcomes(n_z, n_x, n_a, n_y, seed=seed)\n training_data = split_patients(generate_data(dist, n_training_samples))\n test_data = generate_test_data(dist, n_test_samples)\n print(\"Generating data took {:.3f} seconds\".format(time.time() - start))\n return dist, training_data, test_data\n\n\ndef setup_algorithms(training_data, dist, delta):\n start = time.time()\n n_x = dist.n_x\n n_a = dist.n_a\n n_y = dist.n_y\n statistical_approximation_prior = StatisticalApproximator(n_x, n_a, n_y, training_data, smoothing_mode='gaussian')\n\n constraint_upper = Constraint(training_data, n_a, n_y, approximator=statistical_approximation_prior, delta=delta, bound='upper')\n constraint_lower = Constraint(training_data, n_a, n_y, approximator=statistical_approximation_prior, delta=delta, bound='lower')\n constraint_exact = TrueConstraint(dist, approximator=statistical_approximation_prior, delta=delta)\n\n algorithms = [\n #ConstrainedDynamicProgramming(n_x, n_a, n_y, training_data, constraint_upper, statistical_approximation_prior, name=\"Dynamic Programming Upper Bound\", label=\"CDP_U\"),\n #ConstrainedDynamicProgramming(n_x, n_a, n_y, training_data, constraint_lower, statistical_approximation_prior, name=\"Dynamic Programming Lower bound\", label=\"CDP_L\"),\n #ConstrainedDynamicProgramming(n_x, n_a, n_y, training_data, constraint_exact, statistical_approximation_prior, name=\"Dynamic Programming Exact Bound\", label=\"CDP_E\"),\n ConstrainedGreedy(n_x, n_a, n_y, training_data, constraint_upper, statistical_approximation_prior, name=\"Greedy Upper Bound\", label=\"CG_U\"),\n ConstrainedGreedy(n_x, n_a, n_y, training_data, constraint_lower, statistical_approximation_prior, name=\"Greedy Lower Bound\", label=\"CG_L\"),\n ConstrainedGreedy(n_x, n_a, n_y, training_data, constraint_exact, statistical_approximation_prior, name=\"Greedy Exact Bound\", label=\"CG_E\"),\n ]\n\n print(\"Setting up algorithms took {:.3f} seconds\".format(time.time() - start))\n return algorithms\n\n\ndef load_settings():\n starting_seed = 90821\n n_data_sets = 10\n n_deltas = 40\n n_z = 2\n n_x = 1\n n_a = 5\n n_y = 3\n n_training_samples = 15000\n n_test_samples = 3000\n file_name_prefix = \"GBounds_15ksamples_\"\n\n return starting_seed, n_data_sets, n_deltas, n_z, n_x, n_a, n_y, n_training_samples, n_test_samples, file_name_prefix","sub_path":"Main/SingleEvaluations/Settings/GBoundsSettings.py","file_name":"GBoundsSettings.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"369220909","text":"from __future__ import print_function\r\nimport torch.utils.data as data\r\nfrom PIL import Image\r\nimport os\r\nimport os.path\r\nimport errno\r\nimport numpy as np\r\nimport torch\r\nimport codecs\r\nimport random\r\nfrom path import Path\r\nfrom scipy.misc import imread, imresize\r\nimport scipy.io as sio\r\nimport cv2\r\nimport csv\r\n\r\nJESTER_CLASSES = ('hand')\r\nJESTER_ROOT = '/Data/Jester-v1'\r\n# file_csv = 'jester-v1-test.csv'\r\n\r\nclass JESTER(data.Dataset):\r\n \"\"\"`LISA_DRIVER_DATASET `_ Dataset.\r\n\r\n Args:\r\n root (string): Root directory of dataset\r\n train (bool, optional): If True, creates dataset from ``training.pt``,\r\n otherwise from ``test.pt``.\r\n download (bool, optional): If true, downloads the dataset from the internet and\r\n puts it in root directory. If dataset is already downloaded, it is not\r\n downloaded again.\r\n transform (callable, optional): A function/transform that takes in an PIL image\r\n and returns a transformed version. E.g, ``transforms.RandomCrop``\r\n target_transform (callable, optional): A function/transform that takes in the\r\n target and transforms it.\r\n \"\"\"\r\n \r\n training_file = 'jester-v1-test.csv'\r\n test_file = 'jester-v1-test.csv'\r\n \r\n def __init__(self, root, train=True, transform=None, target_transform='scale', download=False, vis=False):\r\n self.root = os.path.expanduser(root)\r\n self.transform = transform\r\n self.target_transform = target_transform\r\n self.train = train # training set or test set\r\n self.vis = vis\r\n self.name = 'LISA'\r\n if self.train:\r\n self.train_root = (Path(self.root) / self.training_file / 'pos')\r\n self.train_samples = self.collect_samples(self.train_root, self.training_file)\r\n else:\r\n self.test_root = (Path(self.root) / self.test_file) # Jester_pos pos RHD_pos ZJU_pos\r\n self.test_samples = self.collect_samples(self.test_root, self.test_file)\r\n\r\n \r\n def collect_samples(self, root, file):\r\n samples = []\r\n dirs = read_csv(root)\r\n \r\n imgs = sorted(root.glob('*.png'))\r\n imgs += sorted(root.glob('*.jpg'))\r\n for img in imgs:\r\n _img = img.basename().split('.')[0]\r\n label = (Path(self.root) / file / 'posGt' / _img + '.txt')\r\n if self.train:\r\n if not label.exists():\r\n continue\r\n assert label.exists()\r\n sample = {'img': img, 'label': label}\r\n samples.append(sample)\r\n return samples\r\n \r\n def load_samples(self, s):\r\n image = cv2.imread(s['img'])\r\n try:\r\n target = list()\r\n if not s['label'].exists():\r\n target = [[0, 0, 0, 0, 0]]\r\n print('{}.png has no gt {}'.format(s['img'].namebase, s['label']))\r\n \r\n # assert s['label'].exists()\r\n else:\r\n with open(s['label']) as f:\r\n label = f.readlines()\r\n num_objs = len(label) - 1\r\n for i, obj in enumerate(label[1:]):\r\n obj = obj.split(' ')\r\n x, y, h, w = map(int, [obj[1], obj[2], obj[3], obj[4]])\r\n target.append([x, y, x + h, y + w, 0])\r\n # target:# [xmin, ymin, xmax, ymax, label_idx]\r\n except:\r\n print('error {}'.format(s))\r\n \r\n return [image, target]\r\n \r\n def __getitem__(self, index):\r\n \"\"\"\r\n Args:\r\n index (int): Index\r\n\r\n Returns:\r\n tuple: (image, target) where target is index of the target class.\r\n \"\"\"\r\n img, target, h, w, image_ori = self.pull_item(index)\r\n return img, target\r\n \r\n def __len__(self):\r\n if self.train:\r\n return len(self.train_samples)\r\n else:\r\n return len(self.test_samples)\r\n \r\n def target_scale(self, target, h, w):\r\n target_trans = []\r\n scale = np.array([h, w, h, w])\r\n for i, label in enumerate(target):\r\n box = list(np.array(label[:4]) / scale)\r\n box.append(label[4])\r\n target_trans.append(box)\r\n return target_trans\r\n \r\n def pull_item(self, index):\r\n if self.train:\r\n s = self.train_samples[index]\r\n else:\r\n s = self.test_samples[index]\r\n \r\n image, target = self.load_samples(s)\r\n # doing this so that it is consistent with all other datasets\r\n w, h, _ = image.shape\r\n target = self.target_scale(target, h, w)\r\n \r\n # target = Image.fromarray(np.array(image))\r\n # h, w = img.size[0], img.size[1]\r\n if self.transform is not None:\r\n target = np.array(target)\r\n img, boxes, labels = self.transform(image, target[:, :4], target[:, 4])\r\n img = img[:, :, (2, 1, 0)]\r\n target = np.hstack((boxes, np.expand_dims(labels, axis=1)))\r\n \r\n return torch.from_numpy(img).permute(2, 0, 1), target, h, w, image\r\n \r\n def __repr__(self):\r\n fmt_str = 'Dataset ' + self.__class__.__name__ + '\\n'\r\n fmt_str += ' Number of datapoints: {}\\n'.format(self.__len__())\r\n tmp = 'train' if self.train is True else 'test'\r\n fmt_str += ' Split: {}\\n'.format(tmp)\r\n fmt_str += ' Root Location: {}\\n'.format(self.root)\r\n tmp = ' Transforms (if any): '\r\n fmt_str += '{0}{1}\\n'.format(tmp, self.transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\r\n tmp = ' Target Transforms (if any): '\r\n fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\r\n return fmt_str\r\n \r\ndef read_csv(csvfile):\r\n rows=[]\r\n with open(csvfile, 'r') as f:\r\n csvreader = csv.reader(f)\r\n for row in csvreader:\r\n rows.append(row)\r\n return rows\r\n\r\ndef visual_box(data, output, i):\r\n import cv2\r\n import scipy\r\n img = Image.fromarray(np.array(data).squeeze(), mode='RGB')\r\n h, w = img.size[0], img.size[1]\r\n output = np.array(output).squeeze()\r\n output[::2] = output[::2] * w\r\n output[1::2] = output[1::2] * h\r\n img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)\r\n for j in range(0, 8, 2):\r\n cv2.circle(img, (int(output[j + 1]), int(output[j])), 5, (255, 255, 0), -1)\r\n # box format (w1, h1, w2, h2, ...)\r\n cv2.imwrite('/Data/hand_dataset_ox/vis/{:05d}.jpg'.format(i), img)\r\n print('img saving to \\'/Data/hand_dataset_ox/vis/{:05d}.jpg\\''.format(i))\r\n\r\n\r\ndef copy_images():\r\n import os\r\n import shutil\r\n root = '/Data/LISA_handetect/detectiondata/test/Jester_pos/'\r\n dirs = [root + x for x in os.listdir(root) if os.path.isdir(root + x)]\r\n dirs.sort()\r\n for dir in dirs:\r\n idx = Path(dir).stem\r\n imgs = Path(dir).glob('*.jpg')\r\n for img in imgs:\r\n shutil.copyfile(img, root + str(idx) + '_{}.jpg'.format(img.stem))\r\n print('writing {}_{}.jpg'.format(idx, img.stem))\r\n\r\ndef Jester_mini():\r\n import shutil\r\n n = 1500\r\n csv_file = Path(JESTER_ROOT) / 'jester-v1-test.csv'\r\n save_root = Path(JESTER_ROOT) / 'mini' / 'test'\r\n save_root.mkdir_p()\r\n dirs = read_csv(csv_file)[:n]\r\n \r\n for i, label in enumerate(dirs):\r\n idx = label[0].split(';')[0]\r\n imgs_file = Path(JESTER_ROOT) / '20bn-jester-v1' / idx\r\n try:\r\n shutil.copytree(imgs_file, save_root / idx)\r\n except:\r\n print('{} already exists'.format(save_root/idx))\r\n print('copying {}/{}'.format(i,n))\r\n \r\n csv_new = Path(JESTER_ROOT)/'test_label.csv'\r\n with open(csv_new, 'w') as f:\r\n writer = csv.writer(f)\r\n writer.writerows(dirs)\r\n \r\n print('finished')\r\n \r\n \r\n \r\n \r\nif __name__ == '__main__':\r\n # process_hand_mask()\r\n import shutil\r\n Jester_mini()\r\n # from utils.augmentations import SSDAugmentation\r\n # # from data import *\r\n # from data import detection_collate\r\n #\r\n # train_set = JESTER(JESTER_ROOT, train=False, transform=SSDAugmentation(300))\r\n # train_loader = torch.utils.data.DataLoader(\r\n # train_set,\r\n # batch_size=8, shuffle=True,\r\n # num_workers=0, collate_fn=detection_collate,\r\n # pin_memory=True)\r\n #\r\n # for i_step, (input, target) in enumerate(train_loader):\r\n # print(input)\r\n # print(target)\r\n #\r\n # print(1)\r\n # file = '/Data/LISA_handetect/detectiondata/train/posGt/11_0000530_0_0_0_0.txt'\r\n # with open(file) as f:\r\n # label = f.readlines()\r\n # print(label)","sub_path":"data/Jester.py","file_name":"Jester.py","file_ext":"py","file_size_in_byte":8774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"642170046","text":"# \n# \n# from parlai.core.agents import Agent\n# from parlai.core.dict import DictionaryAgent\n# from parlai.core.utils import PaddingUtils, round_sigfigs\n# from parlai.core.thread_utils import SharedTable\n# from .modules import RNNModel\n\nfrom parlai.agents.language_model.language_model import LanguageModelAgent\nfrom parlai.core.dict import DictionaryAgent\n\nfrom parlai.misc.idf_counter import IDFScorer\n\nimport torch\n# from torch.autograd import Variable\nimport torch.nn as nn\n\n# import os\n# import math\n# import json\nimport copy\nfrom nltk.tokenize import sent_tokenize\n\n# to accomodate functions imported from torch_agent.py\nfrom parlai.core.distributed_utils import is_primary_worker\nfrom parlai.core.build_data import modelzoo_path\n\n\n\nclass LanguageModelRetrieverAgent(LanguageModelAgent):\n \"\"\" Modified from LanguageModelAgent:\n Agent which trains an RNN on a language modeling task.\n It is adapted from the language model featured in Pytorch's examples repo\n here: .\n \"\"\"\n\n @staticmethod\n def dictionary_class():\n return DictionaryAgent\n\n @staticmethod\n def add_cmdline_args(argparser):\n \"\"\"Add command-line arguments specifically for this agent.\"\"\"\n argparser.set_defaults(batch_sort=False)\n agent = argparser.add_argument_group('Language Model Arguments')\n agent.add_argument('--init-model', type=str, default=None,\n help='load dict/features/weights/opts from this file')\n agent.add_argument('-hs', '--hiddensize', type=int, default=200,\n help='size of the hidden layers')\n agent.add_argument('-esz', '--embeddingsize', type=int, default=200,\n help='size of the token embeddings')\n agent.add_argument('-nl', '--numlayers', type=int, default=2,\n help='number of hidden layers')\n agent.add_argument('-dr', '--dropout', type=float, default=0.2,\n help='dropout rate')\n agent.add_argument('-clip', '--gradient-clip', type=float, default=0.25,\n help='gradient clipping')\n agent.add_argument('--no-cuda', action='store_true', default=False,\n help='disable GPUs even if available')\n agent.add_argument('-rnn', '--rnn-class', default='LSTM',\n help='type of recurrent net (RNN_TANH, RNN_RELU, LSTM, GRU)')\n agent.add_argument('-sl', '--seq-len', type=int, default=35,\n help='sequence length')\n agent.add_argument('-tied', '--emb-tied', action='store_true',\n help='tie the word embedding and softmax weights')\n agent.add_argument('-seed', '--random-seed', type=int, default=1111,\n help='random seed')\n agent.add_argument('--gpu', type=int, default=-1,\n help='which GPU device to use')\n agent.add_argument('-tr', '--truncate-pred', type=int, default=50,\n help='truncate predictions')\n agent.add_argument('-rf', '--report-freq', type=float, default=0.1,\n help='report frequency of prediction during eval')\n agent.add_argument('-pt', '--person-tokens', type='bool', default=True,\n help='append person1 and person2 tokens to text')\n # learning rate parameters\n agent.add_argument('-lr', '--learningrate', type=float, default=20,\n help='initial learning rate')\n agent.add_argument('-lrf', '--lr-factor', type=float, default=1.0,\n help='mutliply learning rate by this factor when the \\\n validation loss does not decrease')\n agent.add_argument('-lrp', '--lr-patience', type=int, default=10,\n help='wait before decreasing learning rate')\n agent.add_argument('-lrm', '--lr-minimum', type=float, default=0.1,\n help='minimum learning rate')\n agent.add_argument('-sm', '--sampling-mode', type='bool', default=False,\n help='sample when generating tokens instead of taking \\\n the max and do not produce UNK token (when bs=1)')\n \n \n # my arguments\n # from torch_agent.py\n agent.add_argument(\n '-emb', '--embedding-type', default='random',\n choices=['random', 'glove', 'glove-fixed', 'glove-twitter-fixed',\n 'fasttext', 'fasttext-fixed', 'fasttext_cc',\n 'fasttext_cc-fixed'],\n help='Choose between different strategies for initializing word '\n 'embeddings. Default is random, but can also preinitialize '\n 'from Glove or Fasttext. Preinitialized embeddings can also '\n 'be fixed so they are not updated during training.')\n \n agent.add_argument(\n '-wcidf', '--weight-criterion-idf', type='bool', default=False,\n help='Whether to weight the loss with the idf weights '\n '(must be pre-calculated)')\n \n \n LanguageModelAgent.dictionary_class().add_cmdline_args(argparser)\n return agent\n\n def __init__(self, opt, shared=None):\n \"\"\"Set up model if shared params not set, otherwise no work to do.\"\"\"\n super().__init__(opt, shared)\n # self.episode_history = [self.END_IDX,] # OAD\n self.episode_history = [] # OAD\n# self.episode_history_text = 'endofmessage endofsegment' # OAD\n self.episode_history_text = 'endofsegment' # OAD\n \n \n if not self.states and opt['embedding_type'] != 'random':\n # `not states`: only set up embeddings if not loading model\n self._copy_embeddings(self.model.encoder.weight, opt['embedding_type'])\n \n # Weight token importance, if desired. \n if opt['weight_criterion_idf']:\n \n idf_scorer = IDFScorer(opt)\n min_idf = min(idf_scorer.vectorizer.idf_)\n word_weights = min_idf * torch.ones(len(self.dict.freq.keys()))\n \n for tok in self.dict.freq.keys(): \n \n if tok != self.dict.null_token:\n \n try:\n word_idf = idf_scorer.vectorizer.idf_[idf_scorer.vectorizer.vocabulary_[tok]]\n word_weights[self.dict.tok2ind[tok]] = word_idf\n except: \n if tok in [self.dict.start_token, \n self.dict.end_token, \n self.dict.unk_token]:\n pass # leave set to minimum idf, as initialized.\n \n else: \n print('there is no idf for token: ', tok, ' type: ', type(tok))\n# import sys; sys.exit()\n \n # word_weights[self.dict.tok2ind[tok]] = 1./(float(self.dict.freq[tok]) + 1.)**.5\n \n # set up criteria\n self.criterion = nn.CrossEntropyLoss(ignore_index=self.NULL_IDX,\n size_average=False, \n weight=word_weights)\n if self.use_cuda:\n # push to cuda\n self.criterion.cuda() \n \n self.id = 'LanguageModelRetriever'\n \n \n def reset(self):\n \"\"\"Reset observation and episode_done.\"\"\"\n self.observation = None\n # self.episode_history = [self.END_IDX,] # OAD\n self.episode_history = [] # OAD\n# self.episode_history_text = 'endofmessage endofsegment' # OAD\n self.episode_history_text = 'endofsegment' # OAD\n self.reset_metrics()\n \n def observe(self, observation):\n return self.observe_appending_special_tokens(observation) \n \n \n def observe_appending_special_tokens(self, observation):\n \n \"\"\"Save observation for act.\n If multiple observations are from the same episode, concatenate them.\n \"\"\"\n # shallow copy observation (deep copy can be expensive)\n obs = observation.copy()\n seq_len = self.opt['seq_len']\n is_training = True\n \n if 'labels' not in obs:\n is_training = False\n if 'is_training_lambda' in self.opt and self.opt['is_training_lambda']:\n is_training = False\n \n \n if obs['turn_num'] == 0: \n \n if obs['first_message'] != '':\n \n response_formated = ' endofsegment '.join(sent_tokenize(obs['first_message']))\n response_formated += ' endofsegment endofmessage'\n \n self.episode_history_text = response_formated\n self.episode_history = self.parse(obs['first_message']\n + ' endofmessage endofsegment')\n \n \n if is_training:\n \n if 'labels' in obs:\n \n obs['labels'][0] = obs['labels'][0]\n \n vec = self.parse(obs['labels'][0])\n vec.append(self.END_IDX)\n# self.next_observe += vec\n \n # OAD: stop accumulating at the end of an episode.\n if obs['episode_done']:\n self.episode_history = [self.END_IDX,]\n# self.episode_history = []\n# self.episode_history_text = 'endofmessage endofsegment'\n self.episode_history_text = 'endofsegment'\n \n else:\n # accumulate episode history.\n self.episode_history += vec\n# self.episode_history_text = ' '.join([self.episode_history_text, \n# obs['labels'][0]]) \n self.episode_history_text = ' '.join([self.episode_history_text, \n obs['labels'][0] + ' endofsegment']) \n \n \n if len(self.episode_history) < (seq_len + 1):\n # not enough to return to make a batch\n # we handle this case in vectorize\n # labels indicates that we are training\n self.observation = {'labels': ''}\n return self.observation\n \n else:\n vecs_to_return = []\n overlap = 3 \n \n # first obs will overlap 1 with current observation\n start = max(0, len(self.episode_history) - (len(vec) + seq_len)) \n stop = len(self.episode_history) - (seq_len + 1)\n \n # take observations of seq-len that overlap with just observed \n for i in range(start, stop, overlap):\n vecs_to_return.append(self.episode_history[i:i+seq_len+1])\n \n \n dict_to_return = {'text': '', 'labels': '', 'text2vec': vecs_to_return}\n self.observation = dict_to_return\n \n return dict_to_return\n else:\n \n if 'text' in obs:\n \n # truncate to approximate multiple of seq_len history\n obs['text'] = ' '.join(self.episode_history_text.split(' ')[-4*seq_len:])\n \n # OAD: stop accumulating at the end of an episode.\n if obs['episode_done']:\n# self.episode_history_text = 'endofmessage endofsegment'\n self.episode_history_text = 'endofsegment'\n else:\n # add end tokens between message moves #TODO: replace sent_tokenize with spacy\n response_formated = ' endofsegment '.join(sent_tokenize(obs['eval_labels'][0]))\n response_formated += ' endofsegment endofmessage' # endofsegment'\n# response_formated = ' '.join(sent_tokenize(obs['eval_labels'][0]))\n# response_formated += ' endofmessage'\n \n # note: don't end history on EOS, as that's added to the input (history) \n # automatically at decode time. This should probably be a TODO to change. \n \n # accumulate episode history\n if self.episode_history_text == 'endofsegment':\n self.episode_history_text = ' '.join([self.episode_history_text, \n response_formated])\n else: \n self.episode_history_text = ' '.join([self.episode_history_text, \n 'endofsegment',\n response_formated])\n \n self.observation = obs\n \n return obs\n \n \n \n \n def _get_embtype(self, emb_type):\n \n ''' copied from torch_agent.py '''\n \n # set up preinitialized embeddings\n try:\n import torchtext.vocab as vocab\n except ImportError as ex:\n print('Please install torch text with `pip install torchtext`')\n raise ex\n pretrained_dim = 300\n if emb_type.startswith('glove'):\n if 'twitter' in emb_type:\n init = 'glove-twitter'\n name = 'twitter.27B'\n pretrained_dim = 200\n else:\n init = 'glove'\n name = '840B'\n embs = vocab.GloVe(\n name=name, dim=pretrained_dim,\n cache=modelzoo_path(self.opt.get('datapath'),\n 'models:glove_vectors'))\n elif emb_type.startswith('fasttext_cc'):\n init = 'fasttext_cc'\n from parlai.zoo.fasttext_cc_vectors.build import url as fasttext_cc_url\n embs = vocab.Vectors(\n name='crawl-300d-2M.vec',\n url=fasttext_cc_url,\n cache=modelzoo_path(self.opt.get('datapath'),\n 'models:fasttext_cc_vectors'))\n elif emb_type.startswith('fasttext'):\n init = 'fasttext'\n embs = vocab.FastText(\n language='en',\n cache=modelzoo_path(self.opt.get('datapath'),\n 'models:fasttext_vectors'))\n else:\n raise RuntimeError('embedding type {} not implemented. check arg, '\n 'submit PR to this function, or override it.'\n ''.format(emb_type))\n return embs, init\n \n \n def _project_vec(self, vec, target_dim, method='random'):\n \n ''' copied from torch_agent.py '''\n \n \"\"\"If needed, project vector to target dimensionality.\n Projection methods implemented are the following:\n random - random gaussian matrix multiplication of input vector\n :param vec: one-dimensional vector\n :param target_dim: dimension of returned vector\n :param method: projection method. will be used even if the dim is\n not changing if method ends in \"-force\".\n \"\"\"\n pre_dim = vec.size(0)\n if pre_dim != target_dim or method.endswith('force'):\n if method.startswith('random'):\n # random projection\n if not hasattr(self, 'proj_rp'):\n self.proj_rp = torch.Tensor(pre_dim, target_dim).normal_()\n # rescale so we're not destroying norms too much\n # http://scikit-learn.org/stable/modules/random_projection.html#gaussian-random-projection\n self.proj_rp /= target_dim\n return torch.mm(vec.unsqueeze(0), self.proj_rp)\n else:\n # TODO: PCA\n # TODO: PCA + RP\n # TODO: copy\n raise RuntimeError('Projection method not implemented: {}'\n ''.format(method))\n else:\n return vec\n \n \n def _copy_embeddings(self, weight, emb_type, log=True):\n \n ''' copied from torch_agent.py '''\n \n \"\"\"Copy embeddings from the pretrained embeddings to the lookuptable.\n :param weight: weights of lookup table (nn.Embedding/nn.EmbeddingBag)\n :param emb_type: pretrained embedding type\n \"\"\"\n if not is_primary_worker():\n # we're in distributed mode, copying embeddings in the workers\n # slows things down considerably\n return\n embs, name = self._get_embtype(emb_type)\n cnt = 0\n for w, i in self.dict.tok2ind.items():\n if w in embs.stoi:\n vec = self._project_vec(embs.vectors[embs.stoi[w]],\n weight.size(1))\n weight.data[i] = vec\n cnt += 1\n\n if log:\n print('Initialized embeddings for {} tokens ({}%) from {}.'\n ''.format(cnt, round(cnt * 100 / len(self.dict), 1), name))\n","sub_path":"parlai/agents/language_model_retriever/language_model_retriever.py","file_name":"language_model_retriever.py","file_ext":"py","file_size_in_byte":17647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"625874212","text":"__author__ = 'Mac'\n\nimport os\n\n\nos.environ['FTRACK_SERVER'] = 'http://192.168.9.200'\nos.environ['FTRACK_APIKEY'] = 'b445309f-1c5d-40ac-b68b-3fdfb4f3ccb9'\nos.environ['LOGNAME'] = 'andyguo'\n\n# :coding: utf-8\n# :copyright: Copyright (c) 2015 ftrack\n\nimport sys\nimport argparse\nimport logging\n\nimport ftrack\n# import ftrack_connect.application\n\n\nclass MyAction(ftrack.Action):\n '''Describe your action here.'''\n\n #: Action identifier.\n identifier = 'com.phenom-films.createfolders' # Unique identifier for your action.\n\n #: Action label.\n label = 'create folders' # Action label which the user will see in the interface.\n\n def launch(self, event):\n '''Callback method for action.'''\n selection = event['data'].get('selection', [])\n self.logger.info(u'Launching action with selection {0}'.format(selection))\n\n # Validate selection and abort if not valid\n if not self.validateSelection(selection):\n self.logger.warning('Selection is not valid, aborting action')\n return\n\n # Implement your action logic here, return a UI or run some\n # code and return your result.\n #\n # If you are doing any heavy lifting, consider running offloading that\n # to a separate thread and returning quickly.\n #\n # To report back to the user you can utilize ftrack.createJob and then\n # update it's status and / or description.\n\n task = ftrack.Shot(id=selection[0]['entityId'])\n parents = task.getParents()\n for index, item in enumerate(parents):\n print(index, item)\n\n foldername = '/Users/mac/Desktop'\n for index in xrange(len(parents) - 1, -1, -1):\n foldername = os.path.join(foldername, parents[index].get('name'))\n # print foldername\n os.makedirs(foldername)\n\n\n pass\n\n return {\n 'success': True,\n 'message': 'createfolders completed successfully'\n }\n\n def discover(self, event):\n '''Return action config.'''\n selection = event['data'].get('selection', [])\n self.logger.info('%s', event)\n # self.logger.info(u'Discovering action with selection: {0}'.format(selection))\n\n\n\n\n # validate selection, and only return action if it is valid.\n if self.validateSelection(selection):\n return super(MyAction, self).discover(event)\n\n def validateSelection(self, selection):\n '''Return True if *selection* is valid'''\n # Replace with custom logic for validating selection.\n # For example check the length or entityType of items in selection.\n return True\n\n\n\n\n\ndef register(registry, **kw):\n '''Register action. Called when used as an event plugin.'''\n action = MyAction()\n action.register()\n\n\ndef main(arguments=None):\n '''Set up logging and register action.'''\n if arguments is None:\n arguments = []\n\n parser = argparse.ArgumentParser()\n # Allow setting of logging level from arguments.\n loggingLevels = {}\n for level in (\n logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING,\n logging.ERROR, logging.CRITICAL\n ):\n loggingLevels[logging.getLevelName(level).lower()] = level\n\n parser.add_argument(\n '-v', '--verbosity',\n help='Set the logging output verbosity.',\n choices=loggingLevels.keys(),\n default='info'\n )\n namespace = parser.parse_args(arguments)\n\n # Set up basic logging\n logging.basicConfig(level=loggingLevels[namespace.verbosity])\n\n # Subscribe to action.\n ftrack.setup()\n action = MyAction()\n action.register()\n\n # Wait for events\n ftrack.EVENT_HUB.wait()\n\n\nif __name__ == '__main__':\n raise SystemExit(main(sys.argv[1:]))\n\n\n\n\n","sub_path":"createFolders.py","file_name":"createFolders.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"428915809","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 18 00:14:11 2015\n\n@author: stoimenoff\n\"\"\"\nclass Heap:\n def __init__(self):\n self.items = []\n def get_min_child_index(self, index):\n min_child_index = index #return same value as input = no child\n if 2*index + 1 < len(self.items):\n min_child_index = 2*index + 1\n if 2*index + 2 < len(self.items):\n if self.items[2*index + 2] < self.items[min_child_index]:\n min_child_index = 2*index + 2\n return min_child_index\n def add(self, item):\n self.items.append(item)\n self.bubble_up(len(self.items) - 1)\n def bubble_up(self, index):\n while self.items[index] < self.items[ (index-1) >> 1 ] and index != 0:\n swap = self.items[index]\n self.items[index] = self.items[(index - 1) >> 1]\n self.items[(index - 1) >> 1] = swap\n index = (index - 1) >> 1\n def pop(self):\n minimum = self.items[0]\n self.items[0] = self.items[-1]\n del self.items[-1]\n index = 0\n min_child_index = self.get_min_child_index(index)\n while self.items != [] and self.items[index] > self.items[min_child_index]:\n swap = self.items[index]\n self.items[index] = self.items[min_child_index]\n self.items[min_child_index] = swap\n index = min_child_index\n min_child_index = self.get_min_child_index(index)\n return minimum\n def get_root(self):\n return self.items[0]\n def is_empty(self):\n if self.items == []:\n return True\n return False\n def size(self):\n return len(self.items)\n def print_heap(self):\n for item in self.items:\n print (item, end = \" \")\n print(\"\")\n\nclass Junction:\n def __init__(self, id, prev = None, distance = float(\"inf\")):\n self.id = id\n self.prev = prev\n self.distance = distance\n def __gt__(self, junction):\n return self.distance > junction.distance\n def __lt__(self, junction):\n return self.distance < junction.distance\n\nclass Navigation:\n def __init__(self, matrix, n):\n self.matrix = matrix\n self.n = n\n def navigate(self, start, end):\n heap = Heap()\n for i in range(self.n):\n heap.add( Junction(i) )\n heap.items[start].distance = 0\n heap.bubble_up(start)\n while heap.size() > 0:\n current = heap.pop()\n if current.id == end:\n return current\n for i in range(heap.size()):\n cur_to_i = self.matrix[current.id][heap.items[i].id]\n if cur_to_i > 0:\n if current.distance + cur_to_i < heap.items[i].distance:\n heap.items[i].distance = current.distance + cur_to_i\n heap.items[i].prev = current\n heap.bubble_up(i)\n return \"NO WAY\"\n\ndef main():\n init = [int(item) for item in input().split()]\n n = init[0]\n m = init[1]\n start = init[2]\n end = init[3]\n matrix = [[0 for i in range(n)] for i in range(n)]\n for i in range(m):\n edge = [int(item) for item in input().split()]\n matrix[edge[0] - 1][edge[1] - 1] = edge[2]\n matrix[edge[1] - 1][edge[0] - 1] = edge[2]\n nav = Navigation(matrix, n)\n result = []\n ending = nav.navigate(start - 1, end - 1)\n print(ending.distance)\n while ending != None:\n result.append(ending.id + 1)\n ending = ending.prev\n for i in range(len(result)-1, -1, -1):\n print(result[i], end = \" \")\n print(\"\")\nmain()","sub_path":"week6/2-Navigation/navigation.py","file_name":"navigation.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"100372471","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2019/7/2 15:49\r\n# @Author : panxiaotong\r\n# @Description : extract features and labels\r\n\r\nimport argparse\r\nimport jieba\r\nimport random\r\n\r\nparser = argparse.ArgumentParser(description='segmentation and extract features from file')\r\nparser.add_argument('--input', type=str, default='./nlp/mi_pv.dat', help='input file')\r\nparser.add_argument('--trainratio', type=int, default=80, help='train set ratio')\r\nparser.add_argument('--trainset', type=str, default='./nlp/train.dat', help='train output file')\r\nparser.add_argument('--validationset', type=str, default='./nlp/val.dat', help='validation output file')\r\nargs = parser.parse_args()\r\n\r\nsample_list = []\r\nlabel_list = []\r\nword_dict = {}\r\nlabel_dict = {}\r\ntext_total_length = 0\r\nwith open(args.input, 'r') as f:\r\n for line in f:\r\n elements = line.strip('\\r\\n').split('\\t')\r\n if len(elements) < 2:\r\n continue\r\n query = elements[0]\r\n seg_list = [item for item in jieba.cut(query, cut_all=False)]\r\n id_list = []\r\n for word in seg_list:\r\n if word not in word_dict:\r\n word_dict[word] = len(word_dict)\r\n id_list.append(word_dict[word])\r\n sample_list.append(id_list)\r\n text_total_length += len(id_list)\r\n label = elements[1]\r\n if label not in label_dict:\r\n label_dict[label] = len(label_dict)\r\n label_list.append(label_dict[label])\r\n f.close()\r\nprint('word size is %d, label size is %d' % (len(word_dict), len(label_dict)))\r\n\r\n'''\r\nsample_length = len(sample_list)\r\navg_length = int(text_total_length / sample_length) + 1\r\nprint('avg length is %d' % avg_length)\r\nvalidation_size = int((100 - args.trainratio) * sample_length / 100)\r\nvalidation_idx_list = random.sample(range(sample_length), validation_size)\r\n\r\ntrain_f = open(args.trainset, 'w')\r\nvalidation_f = open(args.validationset, 'w')\r\nfor idx, sample in enumerate(sample_list):\r\n if idx in validation_idx_list:\r\n if len(sample) < avg_length:\r\n for i in range(avg_length - len(sample)):\r\n sample.append(0)\r\n validation_f.write((',').join([str(item) for item in sample[:avg_length]]) + '\\t' + str(label_list[idx]) + '\\n')\r\n else:\r\n if len(sample) < avg_length:\r\n for i in range(avg_length - len(sample)):\r\n sample.append(0)\r\n train_f.write((',').join([str(item) for item in sample[:avg_length]]) + '\\t' + str(label_list[idx]) + '\\n')\r\ntrain_f.close()\r\nvalidation_f.close()\r\n'''","sub_path":"feature_extractor.py","file_name":"feature_extractor.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"333852365","text":"#!/usr/bin/env python3\n\nimport boto3\nimport unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\n\n\ndef lookupDeviceFarmProjectARN():\n # Set the region for SSM via an environment variable\n ssm = boto3.client(\"ssm\")\n parameter = ssm.get_parameter(Name='DeviceFarmProjectArn', WithDecryption=True)\n deviceFarmProjectARN = parameter['Parameter']['Value']\n return deviceFarmProjectARN\n\n\nclass PythonOrgSearch(unittest.TestCase):\n\n def setUp(self):\n devicefarm_client = boto3.client(\"devicefarm\", region_name=\"us-west-2\")\n testgrid_url_response = devicefarm_client.create_test_grid_url(\n projectArn=lookupDeviceFarmProjectARN(), expiresInSeconds=300)\n self.driver = webdriver.Remote(testgrid_url_response[\"url\"], webdriver.DesiredCapabilities.FIREFOX)\n\n# def setUp(self):\n# self.driver = webdriver.Remote(\n# command_executor='http://127.0.0.1:4444/wd/hub',\n# desired_capabilities=DesiredCapabilities.CHROME)\n\n def test_search_in_python_org(self):\n driver = self.driver\n driver.get(\"http://www.python.org\")\n self.assertIn(\"Python\", driver.title)\n elem = driver.find_element_by_name(\"q\")\n elem.send_keys(\"pycon\")\n elem.send_keys(Keys.RETURN)\n assert \"No results found.\" not in driver.page_source\n\n def tearDown(self):\n# self.driver.close()\n self.driver.quit()\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"simple_usage-unittest.py","file_name":"simple_usage-unittest.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"228962379","text":"from flask import redirect, url_for, render_template, current_app, request\nfrom flask_security import current_user, login_required, roles_accepted, logout_user\n\nimport assets\nfrom controllers import shops, shopify\nfrom webapp.helpers import catch_errors, verify_required_condition, generate_success_response_from_obj\nfrom webapp.dashboard_q_and_a import forms as q_and_a_forms\nfrom webapp.shop_dashboard import shop_dashboard\nfrom webapp.shop_dashboard.api import dashboard\n\n\ndef verify_shop_owner(shop_id):\n shop = shops.get_shop(shop_id)\n verify_required_condition(condition=shop.owner_id == current_user.id,\n error_msg=assets.ExceptionMessages.NOT_YOUR_INSTANCE.format(instance='shop'))\n return shop\n\n\n@shop_dashboard.route(\"/shops//dashboard\", defaults={'shop_id': 0})\n@shop_dashboard.route(\"/shops//dashboard\")\n@login_required\n@roles_accepted(assets.Roles.SHOP_OWNER_ROLE)\n@catch_errors()\ndef route_shop_dashboard(shop_id):\n \"\"\"\n View Shop dashboard\n :param shop_id: The shop id for the dashboard\n\n **Access**\n * Logged in shop owner user\n\n **Request context**\n * Render the shop dashboard\n \"\"\"\n ######## If subscription is inactive, always go to the account tab by default\n\n if request.args.get(\"anchor\"):\n anchor = request.args.get(\"anchor\")\n return redirect(url_for(\"shop_dashboard.route_shop_dashboard\", shop_id=shop_id, _anchor=anchor, anchored=\"true\"))\n\n if not current_user.customer.subscription.active and not request.args.get(\"anchored\"):\n return redirect(url_for(\"shop_dashboard.route_shop_dashboard\", shop_id=shop_id, anchor=\"account\"))\n ########\n\n if current_user.password is None:\n return redirect(url_for(\"auth.shopify_install_setup_user\", user_id=current_user.id))\n\n shop = verify_shop_owner(shop_id)\n answer_form = q_and_a_forms.AnswerCreateForm()\n\n ctx = {'dashboard': dashboard,\n 'shop': shop,\n 'answer_form': answer_form,\n 'js_is_available': not current_app.testing,\n 'subscription_active': current_user.customer.has_active_subscription()}\n return render_template('dashboard.html', **ctx)\n\n\n@shop_dashboard.route(\"/shops//dashboard/\", defaults={'shop_id': 0, 'tab_name': ''})\n@shop_dashboard.route(\"/shops//dashboard/\")\n@login_required\n@roles_accepted(assets.Roles.SHOP_OWNER_ROLE)\n@catch_errors()\ndef route_dashboard_load_tab(shop_id, tab_name):\n \"\"\"\n Load a tab name\n :param shop_id: The shop id for the dashboard\n :param tab_name: The tab_name to load\n\n **Access**\n * Logged in shop owner user\n\n **Request context**\n * Render the shop dashboard\n \"\"\"\n\n if current_user.password is None:\n return ''\n\n shop = verify_shop_owner(shop_id)\n\n if not current_user.customer.subscription.active and tab_name not in [\"account\"]:\n return render_template('tab-inactive-subscription.html', shop=shop)\n\n plugin = dashboard.get_plugin_by_name(tab_name)\n if not plugin:\n return ''\n ctx = plugin.load_context(shop=shop)\n answer_form = q_and_a_forms.AnswerCreateForm()\n ctx['answer_form'] = answer_form\n ctx['shop'] = shop\n return render_template(plugin.template, **ctx)\n\n\n# TODO(pisquared): This should be in Shopify\n@shop_dashboard.route(\"/shops//setup-billing\", defaults={'shop_id': 0})\n@shop_dashboard.route(\"/shops//setup-billing\")\n@login_required\n@roles_accepted(assets.Roles.SHOP_OWNER_ROLE)\n@catch_errors()\ndef shop_setup_billing_shopify(shop_id):\n \"\"\"\n If shop is on Shopify Billing, return a url to be redirected to Shopify\n page where the user will accept or decline the charge\n\n **Access**\n * Shop owner\n\n \"\"\"\n url = shopify.setup_billing(shop_id)\n return redirect(url)\n\n\n@shop_dashboard.route(\"/shops//uninstall\", methods=[\"POST\"])\n@login_required\n@roles_accepted(assets.Roles.SHOP_OWNER_ROLE)\n@catch_errors()\ndef shop_uninstall_app(shop_id):\n \"\"\"\n Shop gets uninstalled cleanly\n\n **Access**\n * Shop owner\n\n \"\"\"\n shopify.clean_uninstall_shop.delay(shop_id)\n logout_user()\n return generate_success_response_from_obj(success_message=assets.ExceptionMessages.UNINSTALLED)\n","sub_path":"webapp/shop_dashboard/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"68522428","text":"import myPeriod\nimport myPlot\n\nplt, fig, ax1, ax2 = myPlot.createPlot([0], windowSize=10, sigma=3.0, rolling=True) # 그래프 생성\n\ncpu_thread = myPeriod.period()\ncpu_thread.run(plt, fig, ax1, ax2)\n\nwhile cpu_thread.on:\n cpu_thread.on = bool(input()) # \"\"를 입력할때까지","sub_path":"resMon/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"471520992","text":"# Problem 4\n# Write a function is_triangular that meets the specification below. A triangular number is a number obtained by the continued summation of integers starting from 1. For example, 1, 1+2, 1+2+3, 1+2+3+4, etc., corresponding to 1, 3, 6, 10, etc., are triangular numbers.\n\ndef is_triangular(k):\n \"\"\"\n k, a positive integer\n returns True if k is triangular and False if not\n \"\"\"\n x = 0\n total = 0\n while total <= k:\n if total == k:\n return True\n x+=1\n total+=x\n return False\n\n\n# Problem 5\n# Write a Python function that takes in a string and prints out a version of this string that does not contain any vowels, according to the specification below. Vowels are uppercase and lowercase 'a', 'e', 'i', 'o', 'u'.\n\n# For example, if s = \"This is great!\" then print_without_vowels will print Ths s grt!. If s = \"a\" then print_without_vowels will print the empty string .\n\ndef print_without_vowels(s):\n '''\n s: the string to convert\n Finds a version of s without vowels and whose characters appear in the \n same order they appear in s. Prints this version of s.\n Does not return anything\n '''\n vowels = 'aeiou'\n new_string = ''\n for c in s:\n if c not in vowels:\n new_string += c\n print(new_string)\n\n\n# Problem 6\n# Write a function that satisfies the following docstring:\n\n# For example, if\n\n# largest_odd_times([2,2,4,4]) returns None\n# largest_odd_times([3,9,5,3,5,3]) returns 9\n\ndef largest_odd_times(L):\n \"\"\" Assumes L is a non-empty list of ints\n Returns the largest element of L that occurs an odd number\n of times in L. If no such element exists, returns None \"\"\"\n counts = {}\n largest = 0\n\n for i in L:\n counts[i] = counts.get(i,0) + 1\n\n for i in counts:\n if counts[i] % 2 == 1 and i > largest:\n largest = i\n\n if not largest:\n return None\n else:\n return largest\n\n\n# Problem 7\n# Write a function called dict_invert that takes in a dictionary with immutable values and returns the inverse of the dictionary. The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d. The value for a key in the inverse dictionary is a sorted list (increasing order) of all keys in d that have the same value in d.\n\n# Here are two examples:\n\n# If d = {1:10, 2:20, 3:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3]}\n# If d = {1:10, 2:20, 3:30, 4:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3, 4]}\n# If d = {4:True, 2:True, 0:True} then dict_invert(d) returns {True: [0, 2, 4]}\n\ndef dict_invert(d):\n '''\n d: dict\n Returns an inverted dictionary according to the instructions above\n '''\n new_dict = {}\n #iterate through original dict\n for k in d:\n #add value of key as new key to new_dict, with list(original key) as value\n if d[k] not in new_dict:\n new_dict[d[k]] = [k]\n #if key is already in new_dict, append the list with original key value\n else:\n new_dict[d[k]].append(k)\n for k in new_dict:\n new_dict[k].sort()\n return new_dict\n\n\n# Problem 8\n# Write a function called general_poly, that meets the specifications below. For example, general_poly([1, 2, 3, 4])(10) should evaluate to 1234 because 1∗103+2∗102+3∗101+4∗100.\n\ndef general_poly(L):\n \"\"\" L, a list of numbers (n0, n1, n2, ... nk)\n Returns a function, which when applied to a value x, returns the value \n n0 * x^k + n1 * x^(k-1) + ... nk * x^0 \"\"\"\n def evaluate(x):\n total = 0\n exp = len(L)-1\n for n in L:\n total += n * x**exp\n exp -= 1\n return total\n return evaluate\n\n\n# Write a Python function that takes in two lists and calculates whether they are permutations of each other. The lists can contain both integers and strings. We define a permutation as follows:\n\n# - the lists have the same number of elements\n# - list elements appear the same number of times in both lists\n\n# If the lists are not permutations of each other, the function returns False. \n# If they are permutations of each other, the function returns a tuple consisting of the following elements:\n\n# - the element occuring the most times\n# - how many times that element occurs\n# - the type of the element that occurs the most times\n\n# If both lists are empty return the tuple (None, None, None). If more than one element occurs the most number of times, you can return any of them.\n\n# For example,\n\n# if L1 = ['a', 'a', 'b'] and L2 = ['a', 'b'] then is_list_permutation returns False\n# if L1 = [1, 'b', 1, 'c', 'c', 1] and L2 = ['c', 1, 'b', 1, 1, 'c'] then is_list_permutation returns (1, 3, ) because the integer 1 occurs the most, 3 times, and the type of 1 is an integer (note that the third element in the tuple is not a string).\n\ndef is_list_permutation(L1, L2):\n '''\n L1 and L2: lists containing integers and strings\n Returns False if L1 and L2 are not permutations of each other. \n If they are permutations of each other, returns a \n tuple of 3 items in this order: \n the element occurring most, how many times it occurs, and its type\n '''\n def count(L):\n d = {}\n for i in L:\n d[i] = d.get(i, 0) + 1\n return d\n\n L1_count = count(L1)\n L2_count = count(L2)\n\n if not L1 and not L2:\n return (None, None, None)\n elif L1_count == L2_count:\n most_freq = max(L1_count, key = lambda x: L1_count[x])\n return most_freq, L1_count[most_freq], type(most_freq)\n else:\n return False\n\n\n\n\n\n\n\n\n\n","sub_path":"Midterm.py","file_name":"Midterm.py","file_ext":"py","file_size_in_byte":5646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"65143560","text":"import pickle\nimport pandas as pd\nfrom datetime import datetime\n\nclass FileNotExist(Exception):\n\tpass\n\nclass Results:\n\n\tdef __init__(self, path):\n\t\tself.path = path\n\t\tself.results = []\n\t\ttry:\n\t\t\twith open(self.path, \"r\") as f:\n\t\t\t\tcontent = pd.read_csv(f)\n\t\texcept FileNotFoundError:\n\t\t\traise FileNotExist(\"\\nFile \\\"%s\\\" does not exist\" % os.path.basename(self.path))\n\t\theader_convert = {\n\t\t\t\"IP_ADDRESS\": \"ip\",\n\t\t\t\"TEST_DATE\": \"time\",\n\t\t\t\"TIME_ZONE\": \"time_zone\",\n\t\t\t\"DOWNLOAD_MEGABITS\": \"download\",\n\t\t\t\"UPLOAD_MEGABITS\": \"upload\",\n\t\t\t\"LATENCY_MS\": \"latency\",\n\t\t\t\"SERVER_NAME\": \"server\",\n\t\t\t\"DISTANCE_KILOMETERS\": \"server_distance\",\n\t\t\t\"CONNECTION_MODE\": \"mode\",\n\t\t}\n\t\tfor index, row in content.iterrows():\n\t\t\tdata = {}\n\t\t\tfor header in content:\n\t\t\t\tif header_convert[header] == \"time\":\n\t\t\t\t\ttry:\n\t\t\t\t\t\trow[header] = datetime.strptime(row[header], \"%m/%d/%Y %I:%M AM\")\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\trow[header] = datetime.strptime(row[header], \"%m/%d/%Y %I:%M PM\")\n\t\t\t\telif header_convert[header] == \"mode\":\n\t\t\t\t\trow[header] = row[header].capitalize()\n\t\t\t\tdata[header_convert[header]] = row[header]\n\t\t\tself.results.append(data)\n\n\tdef Save(self, path=\"data.pickle\"):\n\t\twith open(path, \"wb\") as f:\n\t\t\tpickle.dump(self, f)\n\n\tdef Load(self, path=\"data.pickle\"):\n\t\twith open(path, \"rb\") as f:\n\t\t\treturn pickle.load(f)\n\n\tdef __getitem__(self, key):\n\t\treturn self.results[key]\n\n\tdef __missing__(self, key):\n\t\tpass\n\n\tdef __repr__(self):\n\t\tpreview = \"\"\n\t\tpreview_format = \"Ip:\\t\\t\\t%s\\nDownload Speed:\\t\\t%s\\nUpload Speed:\\t\\t%s\\n\\n\"\n\t\tif len(self.results) > 6:\n\t\t\tfor result in self.results[:3]:\n\t\t\t\tpreview += preview_format % (result[\"ip\"], result[\"download\"], result[\"upload\"])\n\t\t\tpreview += \"......................................\\n......................................\\n......................................\\n\\n\"\n\t\t\tfor result in self.results[-3:]:\n\t\t\t\tpreview += preview_format % (result[\"ip\"], result[\"download\"], result[\"upload\"])\n\t\telse:\n\t\t\tfor result in self.results:\n\t\t\t\tpreview += str(result) + \"\\n\"\n\t\treturn preview[:-2]\n\n\tdef __str__(self):\n\t\treturn self.__repr__()\n\n\tdef __list__(self):\n\t\treturn self.results\n\n\tdef __len__(self):\n\t\treturn len(self.results)\n\n\tdef __iter__(self):\n\t\treturn iter(self.results)\n","sub_path":"speedtest.py","file_name":"speedtest.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"273051750","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: ProxyValidSchedule.py\n Description : 验证useful_proxy_queue中的代理,将不可用的移出\n Author : JHao\n date: 2017/3/31\n-------------------------------------------------\n Change Activity:\n 2017/3/31: 验证useful_proxy_queue中的代理\n-------------------------------------------------\n\"\"\"\n__author__ = 'JHao'\n\nimport sys\nfrom time import sleep\n\nsys.path.append('../')\n\nfrom Util.utilFunction import validUsefulProxy\nfrom Manager.ProxyManager import ProxyManager\nfrom Util.LogHandler import LogHandler\nfrom Queue import Queue\nfrom threading import Thread\n\nMAX_THREADS = 20\nproxies_queue = Queue(maxsize=MAX_THREADS)\n\n\nclass ProxyValidSchedule(ProxyManager):\n def __init__(self):\n ProxyManager.__init__(self)\n self.log = LogHandler('valid_schedule')\n self.db.changeTable(self.useful_proxy_queue)\n\n def __validProxy(self):\n \"\"\"\n 验证代理\n :return:\n \"\"\"\n def valid_proxy_in_queue():\n while True:\n proxy = proxies_queue.get()\n if isinstance(proxy, bytes):\n proxy = proxy.decode('utf-8')\n\n if validUsefulProxy(proxy):\n # 成功->计数器加1\n self.db.inckey(proxy, 1)\n self.log.debug('validProxy_b: {} validation pass'.format(proxy))\n else:\n # 失败->计数器减一\n self.db.inckey(proxy, -1)\n # self.db.delete(proxy)\n self.log.info('validProxy_b: {} validation fail'.format(proxy))\n value = self.db.getvalue(proxy)\n if value and int(value) < -5:\n # 计数器小于-5删除该代理\n self.db.delete(proxy)\n\n for i in range(MAX_THREADS):\n thread = Thread(target=valid_proxy_in_queue)\n thread.daemon = True\n thread.start()\n\n while True:\n for each_proxy in self.db.getAll():\n proxies_queue.put(each_proxy)\n sleep(300)\n\n def main(self):\n self.__validProxy()\n\n\ndef run():\n p = ProxyValidSchedule()\n p.main()\n\n\nif __name__ == '__main__':\n p = ProxyValidSchedule()\n p.main()\n","sub_path":"Schedule/ProxyValidSchedule.py","file_name":"ProxyValidSchedule.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"330995989","text":"import re\nimport numpy as np\nimport LU as temp\nimport Gauss_Jordan\nimport Gaussian_elimination\nimport seidel\ncon = \"\"\nstring = \"\"\nflag = 0\n\ndef Parse(equations,type,n,IntialGuesses,ea,it): # It will read the entire file\n\n global con\n global a\n global x\n a = np.zeros((n, n + 1))\n x = np.zeros(n)\n k=0\n alphabets = {}\n while k < n:\n con = equations[k]\n con=con.replace(' ','')\n for element in con:\n if element.isalpha():\n alphabets[element] = 0\n k += 1\n j = 0\n for i in alphabets:\n alphabets[i] = j\n j += 1\n k = 0\n while k < n:\n con = equations[k]\n con=con.replace(' ','')\n count=0\n while(count < len(con)):\n if con[count].isalpha() and ((con[count-2].isdigit() == False and con[count-1].isdigit() == False) or (count == 0)):\n con = con[:count] + '1*' + con[count:]\n count += 1\n count = 0\n z = re.findall(r\"[+-]?\\d+(?:\\.\\d+)?\", con)\n f=0\n for element in con:\n if element.isalpha() and (con[count-2].isdigit() or con[count-1].isdigit()):\n a[k][alphabets[element]]=z[f]\n f += 1\n if count+1 >= len(con) and element.isdigit():\n a[k][n] = -1*float(z[f])\n f += 1\n elif count+1 < len(con) and element.isdigit():\n if con[count + 1] != \"*\" and con[count + 1] != \".\" and con[count + 1].isdigit()==False and con[count + 1].isalpha()==False:\n a[k][n] = -1*float(z[f])\n f += 1\n count += 1\n k += 1\n\n if type == 'LU':\n arr1=temp.LU(a)\n f = open(\"LU.txt\", \"w\")\n for i in range (0 , len(arr1)):\n f.write(str(arr1[i]))\n f.write(\" \")\n f.close()\n return arr1,string\n elif type==\"Gaussian-jordan\":\n arr2 = Gauss_Jordan.Gaussian_jordan(a)\n f = open(\"jordan.txt\", \"w\")\n for i in range(0, len(arr2)):\n f.write(str(arr2[i]))\n f.write(\" \")\n f.close()\n\n\n elif type=='Gaussian-elimination':\n arr3 =Gaussian_elimination.Gaussian_elimination(a)\n f = open(\"elimination.txt\", \"w\")\n for i in range(0, len(arr3)):\n f.write(str(arr3[i]))\n f.write(\" \")\n f.close()\n\n elif type == 'seidel':\n results=[]\n errors=[]\n seidel.seidel(a,IntialGuesses,ea,it)\n\n f = open(\"seidel.txt\", \"w\")\n for i in range(0, len(results)):\n f.write(str(i))\n f.write(\" \")\n for j in range (0,len(a)):\n\n f.write(str(results[i][j]))\n f.write(\" \")\n for j in range(0, len(a)):\n if(i>0):\n f.write(str(errors[i-1][j]))\n f.write(\" \")\n f.write(\"\\n\")\n f.close()\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Parse.py","file_name":"Parse.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"592590354","text":"from setupy.core.model import Setup\nfrom setupy.core.setting import Setting\nfrom setupy.core.serialize import serialize_imports, serialize_settings, serialize_features\nfrom test.mocks import MockDependencyLoader\n\n\ndef test_serializer_can_serialize_with_imports():\n setup = Setup(MockDependencyLoader())\n setup.add_import(\"from setuptools import setup\")\n setup.add_import(\"from setuptools import find_packages\")\n setup.add_import(\"from os import path\")\n setup.add_import(\"from io import open\")\n\n assert serialize_imports(setup) == \"\"\"from io import open\nfrom os import path\n\nfrom setuptools import find_packages, setup\n\"\"\"\n\n\ndef test_serializer_can_serialize_features():\n mdl = MockDependencyLoader()\n mdl.a_feature(\"test\", code=\"\"\"def merge(*dicts):\n r = {}\n for d in dicts:\n r.update(d)\n return r\"\"\")\n\n mdl.a_feature(\"test2\", code=\"\"\"def merge(*dicts):\n r = {}\n for d in dicts:\n r.update(d)\n return r\"\"\")\n\n setup = Setup(mdl)\n setup.add_feature(\"test\")\n setup.add_feature(\"test2\")\n\n assert serialize_features(setup) == \"\"\"def merge(*dicts):\n r = {}\n for d in dicts:\n r.update(d)\n return r\n\ndef merge(*dicts):\n r = {}\n for d in dicts:\n r.update(d)\n return r\"\"\"\n\n\ndef test_serializer_can_serialize_settings():\n mdl = MockDependencyLoader()\n mdl.a_setting('BASE', properties={\n \"name\": \"\\\"setupy\\\"\",\n \"version\": \"\\\"0.1.0\\\"\",\n \"packages\": \"find_packages(exclude=['contrib', 'docs', 'test'])\"\n })\n\n setup = Setup(mdl)\n setup.add_setting('BASE')\n\n serialized_settings, _ = serialize_settings(setup)\n\n assert serialized_settings == \"\"\"BASE = {\n \"name\": \"setupy\",\n \"version\": \"0.1.0\",\n \"packages\": find_packages(exclude=['contrib', 'docs', 'test'])\n}\"\"\"\n\n\ndef test_serializer_can_deserialize_nested_dictionary_setting():\n mdl = MockDependencyLoader()\n mdl.a_setting('BASE', properties={\n \"name\": \"\\\"setupy\\\"\",\n \"version\": \"\\\"0.1.0\\\"\",\n \"packages\": \"find_packages(exclude=['contrib', 'docs', 'test'])\",\n \"extra_requires\": {\n \"dev\": [\"\\\"pytest\\\"\"]\n }\n })\n\n setup = Setup(mdl)\n setup.add_setting('BASE')\n\n serialized_settings, _ = serialize_settings(setup)\n\n assert serialized_settings == \"\"\"BASE = {\n \"name\": \"setupy\",\n \"version\": \"0.1.0\",\n \"packages\": find_packages(exclude=['contrib', 'docs', 'test']),\n \"extra_requires\": {\n \"dev\": [\"pytest\"]\n }\n}\"\"\"\n","sub_path":"test/test_serializer.py","file_name":"test_serializer.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"225359867","text":"#!/usr/bin/python3.7\n# -*-coding:Utf-8 -*\n\ndef check_file(filename):\n exist = True\n try:\n fd_file = open(filename, \"r\")\n except FileNotFoundError:\n fd_file = open(filename, \"w\")\n exist = False\n finally:\n fd_file.close()\n return exist\n\ndef player_score(name, add=0):\n if check_file(\"scores.ini\") == False:\n score = {name: 0 + add}\n else:\n fd_file = open(\"scores.ini\", \"rb\")\n file_unpick = Unpickler(fd_file)\n score = file_unpick.load()\n fd_file.close()\n if name in score:\n score[name] += add\n else:\n score[name] = add\n fd_file = open(\"scores.ini\", \"wb\")\n file_pick = Pickler(fd_file)\n file_pick.dump(score)\n fd_file.close()\n return score[name]\n","sub_path":"file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"516647774","text":"'''\nawk-py.standalone 0.0.0 Canary\n'''\nimport sys\npath = sys.argv[0]\nencoding = 'utf-8'\nif len(sys.argv) >= 2 and sys.argv[1] != 'utf-8':\n encoding = sys.argv[1]\nfile = open(path,'r')\nsource = file.read()\nfile.close()\ndel file\nfile = open(path,'w')\nlines = source.split('\\n')\noptions = sys.argv[2:]\ndef end(file,source):\n file.write(source)\n file.close()\n","sub_path":"core/lib/standalone.py","file_name":"standalone.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"142216309","text":"import unittest\n\nimport numpy as np\nimport numpy.testing as npt\n\nfrom biomodel import periodic\n\n\nclass TestPeriodicBox(unittest.TestCase):\n\n def setUp(self):\n self.box = periodic.PeriodicBox(np.array([10.0, 10.0, 10.0]))\n\n def test_difference(self):\n npt.assert_almost_equal(\n self.box.difference(\n np.array([1.0, 1.0, 1.0]),\n np.array([2.0, 2.0, 2.0])\n ),\n np.array([-1.0, -1.0, -1.0])\n )\n npt.assert_almost_equal(\n self.box.difference(\n np.array([4.9, 4.9, 4.9]),\n np.array([-4.9, -4.9, -4.9])\n ),\n np.array([-0.2, -0.2, -0.2])\n )\n\n def test_center(self):\n npt.assert_almost_equal(\n self.box.center(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]])),\n np.array([1.5, 1.5, 1.5])\n )\n","sub_path":"tests/test_periodic.py","file_name":"test_periodic.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"548954287","text":"from __future__ import division\nfrom collections import defaultdict\nfrom nltk.tokenize import TweetTokenizer\nfrom nltk.tag import PerceptronTagger\nfrom collections import Counter\nfrom nltk.data import find\nimport re\n\nfrom bigFiveFeatureExtraction import BigFiveFeatureExtraction\n\nPICKLE = \"averaged_perceptron_tagger.pickle\"\nAP_MODEL_LOC = 'file:'+str(find('taggers/averaged_perceptron_tagger/'+PICKLE))\n\nclass OpenFeatureExtraction(BigFiveFeatureExtraction):\n\n def __init__(self, users, truth_users, stopwords_file, swagwords_file, emotion_words_files):\n self.structural_features = defaultdict(list)\n self.type = 6\n self.data = defaultdict(list)\n self.perceptron_tagger = PerceptronTagger(load=False)\n self.perceptron_tagger.load(AP_MODEL_LOC)\n\n super(OpenFeatureExtraction, self).__init__(users, truth_users, stopwords_file, swagwords_file, emotion_words_files)\n\n\n def extract_features(self):\n docs=[]\n trigram_count = {}\n\n for key, value in self.sorted_users.iteritems():\n\n text, url_count = self.process_links(value)\n #self.structural_features[key].append(url_count)\n\n text, mention_count = self.process_mentions(text)\n #self.structural_features[key].append(mention_count)\n\n text, hashtag_count = self.process_hashtags(text)\n self.structural_features[key].append(hashtag_count)\n\n # uppercase words count\n uppercase_words_count = self.uppercase_words_count(text)\n #self.structural_features[key].append(uppercase_words_count)\n\n stopwords_count = self.count_stopwords(text)\n #self.structural_features[key].append(stopwords_count)\n\n # character overload count\n char_count = self.char_count(''.join(value))\n char_overload_count = self.char_overload_count(''.join(value))\n #self.structural_features[key].append(char_overload_count/char_count)\n\n # tweet length ratio\n tweet_length_avg = self.tweet_length_avg(value)\n self.structural_features[key].append(tweet_length_avg)\n\n # word length ratio\n word_length_avg = self.word_length_avg(value)\n #self.structural_features[key].append(word_length_avg)\n\n # positive words count\n positive_words_count = self.count_feature_from_file(text, self.positive_words)\n # self.structural_features[key].append(positive_words_count)\n\n # negative words count\n negative_words_count = self.count_feature_from_file(text, self.negative_words)\n # self.structural_features[key].append(negative_words_count)\n\n\n pos_tags = self.get_pos_tags(text)\n F_score = self.calculate_F_Score(pos_tags)\n self.structural_features[key].append(F_score)\n\n docs.append('||'.join(text))\n\n self.data = self.join_users_truth(self.structural_features, self.do_nothing, self.type)\n self.feature_number = len(self.structural_features.values()[0])\n\n\n def get_train_test_data(self):\n return self.prepare_data(self.data, self.feature_number)\n\n # returns pos tags of all tweets for one user in nested list format - [[pos_tags_first_tweet],[pos_tags_second_tweet], ... ,[pos_tags_last_tweet]]\n def get_pos_tags(self, input):\n tweet_tokenizer = TweetTokenizer()\n sentences = [tweet_tokenizer.tokenize(re.sub(r'[\"]', '', tweet)) for tweet in input]\n return self.perceptron_tagger.tag_sents(sentences)\n\n # calculates F_score based on pos tags for each user\n def calculate_F_Score(self, tagged):\n counts = Counter(tag[:2] for tagged_sentence in tagged for word, tag in tagged_sentence)\n F_score = 0.5 * ((counts['NN'] + counts['JJ'] + counts['IN'] + counts['DT']) -\n (counts['PR'] + counts['WP'] + counts['WD'] + counts['VB'] +\n counts['MD'] + counts['RB'] + counts['WR'] + counts['UH']) + 100)\n return F_score\n\n\n def do_nothing(self, args):\n return float(args)*1.0","sub_path":"AuthorProfiling/openFeatureExtraction.py","file_name":"openFeatureExtraction.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"587966608","text":"from distutils.core import setup, Extension\n\nexample_module = Extension('_mode7', sources=['mode7_wrap.c', 'mode7.c'])\n\nsetup(name='examplec', version='0.1', \n author='Hendrik Leibrandt', \n description=\"\"\"Builds the C++ module for directly access the pixel\ndata of an pygame SDL bindingsurface refference, to do boost up speed\nwhen doing the Mode7-effect.\"\"\", \n ext_modules=[example_module], py_modules=['mode7'])\n","sub_path":"lib/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"375698927","text":"import os\r\nimport glob\r\nimport random\r\nimport shutil\r\n\r\ndef data_split():\r\n\r\n # Set data directory\r\n data_dir = '/home/teo/storage/Data'\r\n\r\n # Get mask list\r\n msk_list = sorted(glob.glob(data_dir + '/Masks/car_imagenet/*.csv'))\r\n\r\n # Define train and val folders:\r\n paths = []\r\n img_trainpath = data_dir + '/Images/car_imagenet/train'\r\n paths.append(img_trainpath)\r\n img_valpath = data_dir + '/Images/car_imagenet/val'\r\n paths.append(img_valpath)\r\n img_testpath = data_dir + '/Images/car_imagenet/test'\r\n paths.append(img_testpath)\r\n msk_trainpath = data_dir + '/Masks/car_imagenet/train'\r\n paths.append(msk_trainpath)\r\n msk_valpath = data_dir + '/Masks/car_imagenet/val'\r\n paths.append(msk_valpath)\r\n msk_testpath = data_dir + '/Masks/car_imagenet/test'\r\n paths.append(msk_testpath)\r\n\r\n # Check if folders exist and create them otherwise\r\n for f in paths:\r\n if os.path.isdir(f) == 0:\r\n os.mkdir(f)\r\n\r\n # Randomize data\r\n random.seed(1)\r\n num_msk = len(msk_list)\r\n idx = [i for i in range(num_msk)]\r\n random.shuffle(idx)\r\n\r\n small = len(idx)\r\n\r\n # Move data to corresponding folders\r\n for i in range(small):\r\n name = os.path.basename(msk_list[idx[i]][0:-9])\r\n msk_dir = data_dir + '/Masks/car_imagenet/' + name + '_mask.csv'\r\n img_dir = data_dir + '/Images/car_imagenet/' + name + '.JPEG'\r\n\r\n if i < 0.2*small - 1:\r\n msk_dest = data_dir + '/Masks/car_imagenet/test/' + name + '_mask.csv'\r\n img_dest = data_dir + '/Images/car_imagenet/test/' + name + '.JPEG'\r\n\r\n elif i < 0.36*small - 1:\r\n msk_dest = data_dir + '/Masks/car_imagenet/val/' + name + '_mask.csv'\r\n img_dest = data_dir + '/Images/car_imagenet/val/' + name + '.JPEG'\r\n\r\n else:\r\n msk_dest = data_dir + '/Masks/car_imagenet/train/' + name + '_mask.csv'\r\n img_dest = data_dir + '/Images/car_imagenet/train/' + name + '.JPEG'\r\n\r\n # Move the data -> be careful\r\n shutil.move(img_dir, img_dest)\r\n shutil.move(msk_dir, msk_dest)\r\n\r\nif __name__ == '__main__':\r\n data_split()","sub_path":"Python/scripts/utils/data_split.py","file_name":"data_split.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"108624919","text":"#!/usr/bin/env python3\n\nimport sys\nimport random\n\ndef maximum(lst):\n assert len(lst) > 0\n\n # base case (singleton)\n if len(lst) == 1:\n return lst[0]\n\n # recursive case (split the lists up, return the larger list)\n split = len(lst)//2\n return maxi(maximum(lst[:split]), maximum(lst[split:]))\n\n\n# charles daly\ndef maxi(a, b):\n if a >= b:\n return a\n else:\n return b\n\n\ndef main():\n args = sys.argv[1:]\n a = [int(arg) for arg in args]\n print(maximum(a))\n for i in range(100):\n rand = [random.randint(-100, 100) for n in range(100)]\n max_native = max(rand)\n max_implem = maximum(rand)\n if max_native != max_implem:\n print(i)\n print(rand, max_native, max_implem)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"year2_1819/computer_programming_3_algorithms_data_structures/labs/w1/recursive_max_dev.py","file_name":"recursive_max_dev.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"51579573","text":"N = int(input())\n*A, = map(int, input().split())\nans = 0\nwhile True:\n ok = True\n for i in range(N):\n if A[i] % 2 != 0:\n ok = False\n break\n A[i] //= 2\n if not ok:\n break\n ans += 1\nprint(ans)\n","sub_path":"atcoder/ABC/081/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"364403834","text":"# ==================================================================================================\n# Copyright 2011 Twitter, Inc.\n# --------------------------------------------------------------------------------------------------\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this work except in compliance with the License.\n# You may obtain a copy of the License in the LICENSE file, or at:\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==================================================================================================\n\n__author__ = 'John Sirios'\n\nfrom twitter.common.collections import OrderedSet\nfrom twitter.pants.ant.ide import _extract_target\n\nimport unittest\n\nclass MockTarget(object):\n def __init__(self,\n name,\n is_codegen = False,\n internal_dependencies = None,\n jar_dependencies = None,\n rev = None):\n self.name = name\n self.is_codegen = is_codegen\n self.internal_dependencies = OrderedSet(internal_dependencies)\n self.jar_dependencies = OrderedSet(jar_dependencies)\n self.excludes = []\n self.rev = rev\n\n def __repr__(self):\n return self.name\n\n\nclass IdeTest(unittest.TestCase):\n def test_extract_target(self):\n jar1 = MockTarget('jar1', rev = 1)\n jar2 = MockTarget('jar2', rev = 1)\n jar3 = MockTarget('jar3', rev = 1)\n jar4 = MockTarget('jar4', rev = 1)\n\n f = MockTarget('f', is_codegen = True)\n b = MockTarget('b', is_codegen = True, internal_dependencies = [f])\n d = MockTarget('d', internal_dependencies = [f], jar_dependencies = [jar1])\n e = MockTarget('e', jar_dependencies = [jar2])\n\n # This codegen target has a jar dependency, but it should not be rolled up since the codegen\n # target itself is grafted into the dep tree\n c = MockTarget('c',\n is_codegen = True,\n internal_dependencies = [d, e],\n jar_dependencies = [jar3])\n\n a = MockTarget('a', internal_dependencies = [c, b, e], jar_dependencies = [jar4])\n\n internal_deps, jar_deps = _extract_target(a, lambda target: True)\n\n self.assertEquals(OrderedSet([c, b]), internal_deps)\n self.assertEquals(OrderedSet([f]), c.internal_dependencies,\n 'Expected depth first walk to roll up f to 1st visited dependee')\n self.assertEquals(OrderedSet(), b.internal_dependencies,\n 'Expected depth first walk to roll up f to 1st visited dependee')\n\n self.assertEquals(set([jar1, jar2, jar4]), set(jar_deps))\n","sub_path":"tests/python/twitter/pants/ant/test-ide.py","file_name":"test-ide.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"183255248","text":"import unittest\nfrom src.blockcipher.modules import transform\n\nclass TestTransform(unittest.TestCase):\n\n\tdef test_32_transform(self):\n\t\t# test 64 bit\n\t\tinput_variable = b'TEST'\n\t\texpected = b'TETS'\n\t\ttransformed_bytes = transform.shift_rows(input_variable)\n\t\tself.assertEqual(transformed_bytes, expected)\n\n\tdef test_64_transform(self):\n\t\t# test 64 bit\n\t\tinput_variable = b'TESTFRED'\n\t\texpected = b'TETSFRDE'\n\t\ttransformed_bytes = transform.shift_rows(input_variable)\n\t\tself.assertEqual(transformed_bytes, expected)\n\n\tdef test_128_transform(self):\t\n\t\t# test 128 bit\n\t\tinput_variable = b'TESTFREDTESTFRED'\n\t\texpected = b'TESTDFRESTTEREDF'\n\t\ttransformed_bytes = transform.shift_rows(input_variable)\n\t\tself.assertEqual(transformed_bytes, expected)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test/test_modules/test_transform.py","file_name":"test_transform.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"241943810","text":"# un dictionnaire\n{\"nom\": \"Le Docteur\", \"Origine\": \"Gallifrey\", \"Race\": \"Maître du temps\"}\n\nd = {\"nom\": \"Le Docteur\", \"Origine\": \"Gallifrey\", \"Race\": \"Maître du temps\"}\ndir(d)\n\n# récupération d'un élément\nd[\"nom\"]\n\n# ajout d'un émément\nd[\"Vaisseau\"] = \"TARDIS\"\n\n# suppression d'un élément\ndel(d[\"Vaisseau\"])\n\n# la liste des clés\nd.keys()\nlist(d.keys())\n\n# la liste des valeurs\nlist(d.values())\n","sub_path":"fichiers_source_decouverte_de_python/Chapitre_01/06.les dictionnaires.py","file_name":"06.les dictionnaires.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"622657318","text":"\"\"\"\nBellman-Ford\n\nGiven times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source 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 the signal? If it is impossible, return -1.\n\nInput: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2\nOutput: 2\n\"\"\"\n\nfrom typing import List\nimport math\n\ndef networkDelayTime(times: List[List[int]], N: int, K: int) -> int:\n dist = [float('inf')] * (N + 1)\n dist[K] = 0\n\n for i in range(N):\n for t in times:\n u, v, w = t[0], t[1], t[2]\n if math.isfinite(dist[u]) and dist[v] > dist[u] + w:\n dist[v] = dist[u] + w\n \n maxweight = max(dist[1:])\n if math.isinf(maxweight):\n return -1\n else:\n return maxweight\n","sub_path":"graph/network_delay.py","file_name":"network_delay.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"502620053","text":"import graphene\nfrom graphql import GraphQLError\nfrom graphql_jwt.decorators import login_required\n\nfrom healthid.apps.consultation.models import CustomerConsultation\nfrom healthid.apps.outlets.models import Outlet\nfrom healthid.apps.products.models import Product\nfrom healthid.apps.sales.models import (SalesPrompt, Sale, SaleReturn)\nfrom healthid.apps.sales.schema.sales_schema import (\n ConsultationPaymentType, SalesPromptType,\n SaleType, SaleReturnType)\nfrom healthid.utils.app_utils.database import (SaveContextManager,\n get_model_object)\nfrom healthid.utils.auth_utils.decorator import user_permission\nfrom healthid.apps.receipts.models import Receipt\nfrom healthid.apps.receipts.schema.receipt_schema import ReceiptType\nfrom healthid.utils.messages.sales_responses import (SALES_ERROR_RESPONSES,\n SALES_SUCCESS_RESPONSES)\nfrom healthid.utils.messages.common_responses import SUCCESS_RESPONSES\n\n\nclass CreateSalesPrompts(graphene.Mutation):\n \"\"\"\n This Creates a Sales Prompt for a group of products particular Product\n \"\"\"\n sales_prompts = graphene.List(SalesPromptType)\n message = graphene.String()\n\n class Arguments:\n prompt_titles = graphene.List(graphene.String, required=True)\n descriptions = graphene.List(graphene.String, required=True)\n product_ids = graphene.List(graphene.Int, required=True)\n outlet_ids = graphene.List(graphene.Int, required=True)\n\n @login_required\n @user_permission('Manager')\n def mutate(self, info, **kwargs):\n product_ids = kwargs.get('product_ids')\n titles = kwargs.get('prompt_titles')\n prompt_descriptions = kwargs.get('descriptions')\n outlet_ids = kwargs.get('outlet_ids')\n sales_prompt_count = 0\n valid_list = all(len(product_ids) == len(list_inputs)\n for list_inputs in\n [titles, prompt_descriptions, outlet_ids])\n\n if not valid_list or len(product_ids) < 1:\n raise GraphQLError(SALES_ERROR_RESPONSES[\"incomplete_list\"])\n\n for title, description in zip(titles, prompt_descriptions):\n if title.strip() == \"\" or description.strip() == \"\":\n raise GraphQLError(SALES_ERROR_RESPONSES[\"title_error\"])\n created_prompts = []\n for index, title in enumerate(titles, 0):\n params = {'model': SalesPrompt}\n sales_prompt = SalesPrompt(\n prompt_title=title.title(),\n description=prompt_descriptions[index],\n product_id=get_model_object(Product, 'id',\n product_ids[index]).id,\n outlet_id=get_model_object(Outlet, 'id',\n outlet_ids[index]).id)\n\n with SaveContextManager(sales_prompt, **params) as sales_prompt:\n created_prompts.append(sales_prompt)\n sales_prompt_count += 1\n\n return CreateSalesPrompts(\n sales_prompts=created_prompts,\n message=SUCCESS_RESPONSES[\n \"creation_success\"].format(\n \"Sales prompt \" + str(\n sales_prompt_count)))\n\n\nclass UpdateSalesPrompt(graphene.Mutation):\n \"\"\"\n This Updates a Sales prompt\n \"\"\"\n success = graphene.String()\n salesPrompt = graphene.Field(SalesPromptType)\n\n class Arguments:\n id = graphene.Int(required=True)\n prompt_title = graphene.String()\n description = graphene.String()\n product_id = graphene.Int()\n outlet_id = graphene.Int()\n\n @login_required\n @user_permission('Manager')\n def mutate(self, info, id, **kwargs):\n salesPrompt = get_model_object(SalesPrompt, 'id', id)\n for key, value in kwargs.items():\n if key in [\"prompt_title\", \"description\"]:\n if value.strip() == \"\":\n raise GraphQLError(SALES_ERROR_RESPONSES[\"title_error\"])\n setattr(salesPrompt, key, value)\n params = {'model': SalesPrompt}\n with SaveContextManager(salesPrompt, **params) as salesPrompt:\n return UpdateSalesPrompt(\n success=SUCCESS_RESPONSES[\n \"update_success\"].format(\"Sales prompt\"),\n salesPrompt=salesPrompt)\n\n\nclass DeleteSalesPrompt(graphene.Mutation):\n \"\"\"\n This deletes a Sales prompt\n \"\"\"\n id = graphene.Int()\n success = graphene.String()\n\n class Arguments:\n id = graphene.Int()\n\n @login_required\n @user_permission('Manager')\n def mutate(self, info, id):\n user = info.context.user\n prompt = get_model_object(SalesPrompt, 'id', id)\n prompt.delete(user)\n return DeleteSalesPrompt(\n success=SUCCESS_RESPONSES[\n \"deletion_success\"].format(\"Sales prompt\"))\n\n\nclass Batches(graphene.InputObjectType):\n \"\"\"\n This class defines necessary fields of a product to be sold\n \"\"\"\n batch_id = graphene.ID()\n # product_id = graphene.Int()\n quantity = graphene.Int()\n discount = graphene.Float()\n price = graphene.Float()\n note = graphene.String()\n\n\nclass CreateSale(graphene.Mutation):\n \"\"\"\n Create a sale\n \"\"\"\n sale = graphene.Field(SaleType)\n message = graphene.String()\n error = graphene.String()\n receipt = graphene.Field(ReceiptType)\n\n class Arguments:\n customer_id = graphene.String()\n outlet_id = graphene.Int(required=True)\n batches = graphene.List(Batches, required=True)\n discount_total = graphene.Float(graphene.Float, required=True)\n sub_total = graphene.Float(graphene.Float, required=True)\n amount_to_pay = graphene.Float(graphene.Float, required=True)\n paid_amount = graphene.Float(graphene.Float, required=True)\n change_due = graphene.Float(graphene.Float, required=True)\n payment_method = graphene.String(graphene.String, required=True)\n notes = graphene.String()\n\n @login_required\n def mutate(self, info, **kwargs):\n new_sale = Sale()\n new_receipt = Receipt()\n sale = new_sale.create_sale(info=info, **kwargs)\n receipt = new_receipt.create_receipt(sale, kwargs.get('outlet_id'))\n return CreateSale(sale=sale,\n receipt=receipt,\n message=SALES_SUCCESS_RESPONSES[\n \"create_sales_success\"])\n\n\nclass ConsultationPayment(graphene.Mutation):\n \"\"\"\n Make payment for a consultation\n Args:\n customer_consultation_id (id) id of the consultation item\n discount_total (float) discount given if any\n sub_total (float) sale subtotal\n paid_amount (float) amount client has given\n change_due (float) change due to client\n payment_method (str) payment option chosen\n notes (str) Narrative for the sale\n returns:\n sale object for the consultation,\n otherwise a GraphqlError is raised\n \"\"\"\n sale = graphene.Field(ConsultationPaymentType)\n message = graphene.String()\n receipt = graphene.Field(ReceiptType)\n\n class Arguments:\n customer_consultation_id = graphene.Int(required=True)\n discount_total = graphene.Float(graphene.Float, required=True)\n sub_total = graphene.Float(graphene.Float, required=True)\n paid_amount = graphene.Float(graphene.Float, required=True)\n change_due = graphene.Float(graphene.Float, required=True)\n payment_method = graphene.String(graphene.String, required=True)\n notes = graphene.String()\n\n @login_required\n def mutate(self, info, **kwargs):\n user = info.context.user\n customer_consultation_id = kwargs.get('customer_consultation_id')\n customer_consultation = get_model_object(\n CustomerConsultation, 'id', customer_consultation_id)\n outlet = customer_consultation.outlet\n\n if customer_consultation.paid:\n raise GraphQLError(SALES_ERROR_RESPONSES[\"already_marked_as_paid\"])\n\n price = customer_consultation.consultation_type.price_per_session\n new_sale = Sale(\n sales_person=user, customer=customer_consultation.customer,\n outlet=outlet,\n amount_to_pay=price)\n\n del kwargs['customer_consultation_id']\n for (key, value) in kwargs.items():\n setattr(new_sale, key, value)\n\n with SaveContextManager(new_sale, model=Sale) as new_sale:\n pass\n\n customer_consultation.paid = True\n customer_consultation.sale_record = new_sale\n customer_consultation.save()\n\n new_receipt = Receipt()\n receipt = new_receipt.create_receipt(new_sale, outlet.id)\n\n return ConsultationPayment(\n sale=new_sale, receipt=receipt, message='message')\n\n\nclass SalesReturnEnum(graphene.Enum):\n CustomerError = 'wrong product bought'\n RetailerError = 'Returned to Distributor'\n DamagedProduct = 'Damaged Product'\n ExpiredProduct = 'Expired Product'\n Others = 'Others'\n\n\nclass PayEnum(graphene.Enum):\n \"\"\"\n This class defines choices for refund compensation type\n \"\"\"\n Cash = 'cash'\n StoreCredit = 'store credit'\n\n\nclass ReturnedProducts(graphene.InputObjectType):\n \"\"\"\n This class defines necessary fields of a product to be returned\n \"\"\"\n batch_id = graphene.ID(required=True)\n # product_id = graphene.Int(required=True)\n quantity = graphene.Int(required=True)\n price = graphene.Float(required=True)\n resellable = graphene.Boolean(required=True)\n return_reason = graphene.Argument(SalesReturnEnum, required=True)\n\n\nclass InitiateSaleReturn(graphene.Mutation):\n \"\"\"\n initiate a sales return by user(Cashier, manager or accountant)\n \"\"\"\n message = graphene.String()\n sales_return_initiated = graphene.Field(SaleReturnType)\n error = graphene.String()\n\n class Arguments:\n sale_id = graphene.Int(required=True)\n returned_batches = graphene.List(ReturnedProducts, required=True)\n outlet_id = graphene.Int(required=True)\n return_amount = graphene.Float(required=True)\n return_note = graphene.String()\n refund_compensation_type = graphene.Argument(PayEnum, required=True)\n\n @login_required\n def mutate(self, info, **kwargs):\n new_return = SaleReturn()\n return_initiated = new_return.create_return(\n user=info.context.user, **kwargs)\n return InitiateSaleReturn(\n message=SALES_SUCCESS_RESPONSES[\"sale_intiate_success\"],\n sales_return_initiated=return_initiated)\n\n\nclass ApproveSalesReturn(graphene.Mutation):\n sales_return = graphene.Field(SaleReturnType)\n message = graphene.String()\n\n class Arguments:\n sales_return_id = graphene.Int(required=True)\n sales_id = graphene.Int(required=True)\n returned_sales = graphene.List(graphene.Int, required=True)\n\n @login_required\n @user_permission('Manager')\n def mutate(self, info, **kwargs):\n sales_id = kwargs.get('sales_id')\n returned_sales = kwargs.get('returned_sales')\n\n if not returned_sales:\n raise GraphQLError(SALES_ERROR_RESPONSES[\"empty_sales_return\"])\n\n receipt = get_model_object(Receipt, 'sale_id', sales_id)\n\n new_return = SaleReturn()\n sales_return = new_return.approve_sales_return(\n user=info.context.user, receipt=receipt, **kwargs)\n\n return ApproveSalesReturn(\n sales_return=sales_return,\n message=SALES_SUCCESS_RESPONSES[\"sales_return_approved\"])\n\n\nclass Mutation(graphene.ObjectType):\n create_salesprompts = CreateSalesPrompts.Field()\n delete_salesprompt = DeleteSalesPrompt.Field()\n update_salesprompt = UpdateSalesPrompt.Field()\n create_sale = CreateSale.Field()\n consultation_payment = ConsultationPayment.Field()\n initiate_sales_return = InitiateSaleReturn.Field()\n approve_sales_return = ApproveSalesReturn.Field()\n","sub_path":"healthid/apps/sales/schema/sales_mutation.py","file_name":"sales_mutation.py","file_ext":"py","file_size_in_byte":12022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"161244592","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"closed_listings\", views.closed_listings, name=\"closed_listings\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"create_listing\", views.create_listing, name=\"create_listing\"),\n path(\"listing/\", views.listing_page, name=\"listing_page\"),\n path(\"bidding/\", views.bidding, name=\"bidding\"),\n path(\"watchlist\", views.watchlist, name=\"watchlist\"),\n path(\"add_to_watchlist/\", views.add_to_watchlist, name=\"add_to_watchlist\"),\n path(\"watchlist_remove/\", views.watchlist_remove, name=\"watchlist_remove\"),\n path(\"end_listing//\", views.end_listing, name=\"end_listing\"),\n path(\"categories\", views.categories, name=\"categories\"),\n path(\"category/\", views.category_listings, name=\"category_listings\"),\n path(\"comments/\", views.add_comments, name=\"add_comments\")\n]\n","sub_path":"auctions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"101388328","text":"import urllib.request\nimport urllib.parse\nimport time\nimport os\nimport contextlib\nimport tempfile\nimport datetime\n\nimport flask\nimport flask.json\nimport dateutil.parser\n\nfrom common import utils\nfrom www import server\nfrom www import login\n\n\nCACHE_TIMEOUT = 5*60\n\nBEFORE_BUFFER = datetime.timedelta(minutes=15)\nAFTER_BUFFER = datetime.timedelta(minutes=15)\n\n@utils.cache(CACHE_TIMEOUT, params=[0, 1])\ndef archive_feed_data(channel, broadcasts):\n\turl = \"https://api.twitch.tv/kraken/channels/%s/videos?broadcasts=%s&limit=%d\" % (urllib.parse.quote(channel, safe=\"\"), \"true\" if broadcasts else \"false\", 100)\n\tfp = urllib.request.urlopen(url)\n\tdata = fp.read()\n\tfp.close()\n\tdata = data.decode()\n\n\t# For broadcasts:\n\t# {'videos': [{'_id': 'a508090853',\n\t# '_links': {'channel': 'https://api.twitch.tv/kraken/channels/loadingreadyrun',\n\t# 'self': 'https://api.twitch.tv/kraken/videos/a508090853'},\n\t# 'broadcast_id': 8737631504,\n\t# 'channel': {'display_name': 'LoadingReadyRun',\n\t# 'name': 'loadingreadyrun'},\n\t# 'description': None,\n\t# 'game': 'Prince of Persia: Warrior Within',\n\t# 'length': 9676,\n\t# 'preview': 'http://static-cdn.jtvnw.net/jtv.thumbs/archive-508090853-320x240.jpg',\n\t# 'recorded_at': '2014-03-04T02:40:58Z',\n\t# 'title': \"Beej's Backlog - Playing PoP: WW\",\n\t# 'url': 'http://www.twitch.tv/loadingreadyrun/b/508090853',\n\t# 'views': 0},\n\t# ...]}\n\t# For highlights:\n\t# {'videos': [{'_id': 'c3518839',\n\t# '_links': {'channel': 'https://api.twitch.tv/kraken/channels/loadingreadyrun',\n\t# 'self': 'https://api.twitch.tv/kraken/videos/c3518839'},\n\t# 'broadcast_id': 8137157616,\n\t# 'channel': {'display_name': 'LoadingReadyRun',\n\t# 'name': 'loadingreadyrun'},\n\t# 'description': \"Beej's gets up to speed in Prince of Persia: Warrior Within\",\n\t# 'game': 'Prince of Persia: Warrior Within',\n\t# 'length': 3557,\n\t# 'preview': 'http://static-cdn.jtvnw.net/jtv.thumbs/archive-493319305-320x240.jpg',\n\t# 'recorded_at': '2014-01-07T04:16:42Z',\n\t# 'title': \"Beej's Backlog —2014-01-06 PT2\",\n\t# 'url': 'http://www.twitch.tv/loadingreadyrun/c/3518839',\n\t# 'views': 466},\n\t# ...]}\n\n\tvideos = flask.json.loads(data)['videos']\n\tfor video in videos:\n\t\tvideo[\"recorded_at\"] = dateutil.parser.parse(video[\"recorded_at\"])\n\treturn videos\n\n@server.app.route('/archive')\n@login.with_session\ndef archive(session):\n\tchannel = flask.request.values.get('channel', 'loadingreadyrun')\n\tbroadcasts = 'highlights' not in flask.request.values\n\treturn flask.render_template(\"archive.html\", videos=archive_feed_data(channel, broadcasts), broadcasts=broadcasts, session=session)\n\n@server.app.route('/archivefeed')\ndef archive_feed():\n\tchannel = flask.request.values.get('channel', 'loadingreadyrun')\n\tbroadcasts = 'highlights' not in flask.request.values\n\trss = flask.render_template(\"archive_feed.xml\", videos=archive_feed_data(channel, broadcasts), broadcasts=broadcasts)\n\treturn flask.Response(rss, mimetype=\"application/xml\")\n\n@utils.with_postgres\ndef chat_data(conn, cur, starttime, endtime, target=\"#loadingreadyrun\"):\n\tcur.execute(\"SELECT messagehtml FROM log WHERE target = %s AND time BETWEEN %s AND %s ORDER BY time ASC\", (\n\t\ttarget,\n\t\tstarttime,\n\t\tendtime\n\t))\n\treturn [message for (message,) in cur]\n\n@utils.cache(CACHE_TIMEOUT, params=[0])\ndef get_video_data(videoid):\n\ttry:\n\t\twith contextlib.closing(urllib.request.urlopen(\"https://api.twitch.tv/kraken/videos/%s\" % videoid)) as fp:\n\t\t\tvideo = flask.json.load(fp)\n\t\tstart = dateutil.parser.parse(video[\"recorded_at\"])\n\t\treturn {\n\t\t\t\"start\": start,\n\t\t\t\"end\": start + datetime.timedelta(seconds=video[\"length\"]),\n\t\t\t\"title\": video[\"title\"],\n\t\t\t\"id\": videoid,\n\t\t\t\"channel\": video[\"channel\"][\"name\"]\n\t\t}\n\texcept:\n\t\treturn None\n\n@server.app.route('/archive/')\ndef archive_watch(videoid):\n\tstarttime = utils.parsetime(flask.request.values.get('t'))\n\tif starttime:\n\t\tstarttime = int(starttime.total_seconds())\n\tvideo = get_video_data(videoid)\n\tif video is None:\n\t\treturn \"Unrecognised video\"\n\tchat = chat_data(video[\"start\"] - BEFORE_BUFFER, video[\"end\"] + AFTER_BUFFER)\n\treturn flask.render_template(\"archive_watch.html\", video=video, chat=chat, starttime=starttime)\n","sub_path":"www/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":4517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"492882440","text":"from __future__ import print_function\n\nimport csv\n\nfrom Implementations.setup import Setup\nfrom Implementations.common_functions import CommonFunctions\n\nimport sys\nimport os\nimport re\nimport traceback\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom ConfigFiles import paths,logger_util\n\n\nclass CEDFunctions(CommonFunctions):\n def __init__(self,test_class_name):\n super().__init__(test_class_name)\n self.ced_func_log = logger_util.get_logger(test_class_name +\" :: \" +__name__)\n\n # log = CommonFunctions.log\n if paths.input_files_path is not None:\n input_file_path = paths.input_files_path\n else:\n input_file_path = Setup.testfilespath\n\n # input_files_path = Setup.testfilespath\n result_files_path = Setup.resultFilePath\n runTime = datetime.now().strftime(\"%d%b%Y_%H.%M.%S\") # current time in ddmmyyyy_hh24mmss\n report = \"Result_\" + str(runTime) + \"\"\n\n # def getIndex(self,searchColumn,content):\n # try:\n # for row in content:\n # row = row.strip().replace('\\\"', '')\n # listOfColumns = re.split(',',row)\n # indexOfSearchCol = listOfColumns.index(searchColumn)\n # indexOfEventStoredDt = listOfColumns.index(\"EVENT_STORED_DT\")\n # # print(\"Index of Search COlumn is :\", indexOfSearchCol, \"and Index of Event Stored Date is :\",\n # indexOfEventStoredDt)\n # except Exception as e:\n # print('\\n*****ERROR ON LINE {}'.format(sys.exc_info()[-1].tb_lineno), \",\", type(e).__name__, \":\", e,\n # \"*****\\n\")\n # print(traceback.format_exc())\n #\n # return indexOfSearchCol, indexOfEventStoredDt\n #\n # def getSearchColumn(self,cedFile):\n #\n # searchKey = \"LAUNCH_ID\"\n # if re.match(r'[0-9]+_' + 'OPT', cedFile):\n # searchColumn = 'RIID'\n # elif re.match(r'[0-9]+_' + 'SMS_OPT', cedFile):\n # searchColumn = 'RIID'\n # elif re.match(r'[0-9]+_' + 'FORM', cedFile):\n # searchColumn = 'FORM_ID'\n # elif re.match(r'[0-9]+_' + 'FORM_STATE', cedFile):\n # searchColumn = 'FORM_ID'\n # elif re.match(r'[0-9]+_' + 'PROGRAM', cedFile):\n # searchColumn = 'PROGRAM_ID'\n # elif re.match(r'[0-9]+_' + 'PROGRAM_STATE', cedFile):\n # searchColumn = 'PROGRAM_ID'\n # elif re.match(r'[0-9]+_' + 'HOLDOUT', cedFile):\n # searchColumn = 'PROGRAM_ID'\n # elif re.match(r'[0-9]+_' + 'PUSH_UNINSTALL', cedFile):\n # searchColumn = 'RIID'\n # else:\n # searchColumn = searchKey\n #\n # return searchColumn\n #\n # def findFiles(self):\n # count = 0\n # try:\n # files = os.listdir(self.input_file_path)\n # for fname in range(len(files)):\n # count += 1\n # print(\"\\nThere are total\", count, \"files to processed:\")\n # print(*files, sep=\"\\n\")\n # except Exception as e:\n # print('\\n*****ERROR ON LINE {}'.format(sys.exc_info()[-1].tb_lineno), \",\", type(e).__name__, \":\", e,\n # \"*****\\n\")\n # print(traceback.format_exc())\n #\n # return files\n\n # def get_ids_from_ced(self, ced_file):\n # IDs = []\n # event_stored_date = defaultdict(list)\n # unique_IDs = defaultdict(list)\n # try:\n # with open(os.path.join(CEDFunctions.input_file_path, ced_file), 'r') as f:\n # content = f.readlines()\n # header_row = content[:1]\n # event_type = re.split(r\"\\d+\", ced_file)\n # event_type = event_type[1].strip('_')\n #\n # search_column = self.get_search_column(ced_file)\n # index_Of_search_column, index_Of_event_stored_date = self.get_index(search_column, ced_file)\n #\n # for row in content[1:]:\n # row = row.strip().replace('\\\"', '')\n # col_data = re.split(';|,|\\t|\\||\"\"', row)\n # id_value = col_data[index_Of_search_column]\n # event_stored_time = col_data[index_Of_event_stored_date]\n # IDs.append(id_value)\n # event_stored_date[id_value].append(event_stored_time)\n #\n # unique_IDs = set(IDs)\n # self.ced_func_log.info(\"There are %s records in file %s & the Unique %s are :: %s\" %(len(IDs),ced_file ,search_column,len(unique_IDs)))\n #\n # return IDs, unique_IDs, event_stored_date, search_column, event_type\n # except Exception as e:\n # self.ced_func_log.error('*** ERROR ON LINE %s , %s : %s ***' % (format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e))\n def get_ids_from_ced(self, ced_file,delimiter,quotechar):\n IDs = []\n event_stored_date = defaultdict(list)\n unique_IDs = defaultdict(list)\n try:\n with open(os.path.join(CEDFunctions.input_file_path, ced_file), 'r') as file:\n content = csv.reader(file,delimiter=delimiter,quotechar=quotechar)\n header_row = next(content)\n event_type = re.split(r\"\\d+\", ced_file)\n event_type = event_type[1].strip('_')\n search_column = self.get_search_column(ced_file)\n index_Of_search_column = header_row.index(search_column)\n index_Of_event_stored_date = header_row.index(\"EVENT_STORED_DT\")\n for row in content:\n # for col in row:\n id_value = row[index_Of_search_column]\n event_stored_time = row[index_Of_event_stored_date]\n IDs.append(id_value)\n event_stored_date[id_value].append(event_stored_time)\n unique_IDs = set(IDs)\n self.ced_func_log.info(\"There are %s records in file %s & the Unique %s are :: %s\" %(len(IDs),ced_file ,search_column,len(unique_IDs)))\n return IDs, unique_IDs, event_stored_date, search_column, event_type\n except Exception as e:\n self.ced_func_log.error('*** ERROR ON LINE %s , %s : %s ***' % (format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e))\n\n def get_count_from_ced(self, IDs, uniqueIDs):\n d_count_from_ced = defaultdict(list)\n try:\n # self.ced_func_log.info(\"Getting count from CED file.\")\n for id in uniqueIDs:\n count = IDs.count(id)\n d_count_from_ced[id].append(count)\n # print(\"Count for the ID \" +str(id) + \" is : \" + str(count) )\n except Exception as e:\n message = \"*****ERROR ON LINE {}\".format(sys.exc_info()[-1].tb_lineno), \",\", type(e).__name__, \":\", e, \"*****\"\n self.ced_func_log.info(message)\n return d_count_from_ced\n\n def read_data_from_ced(self,file, unique_IDs, search_column):\n print(\"*** Reading Data From File :: \", file , \" for each ID's ***\")\n self.ced_func_log.info(\"Reading Data From File :: \", file , \" for each ID's\")\n ced_data = defaultdict(list)\n\n for id in unique_IDs:\n with open(os.path.join(CEDFunctions.input_file_path, file), 'r') as f:\n content = f.readlines()\n\n for row in content[:1]:\n stripped_row = row.strip().replace('\\\"', '')\n all_columns = re.split(';|,|\\t|\"\"', stripped_row)\n for i in all_columns:\n if i == 'EVENT_STORED_DT':\n index_Of_stored_date = all_columns.index(i)\n break\n # index_Of_stored_date[file].append(stored_date_index)\n\n for row in content[1:]:\n if id in row:\n row = row.strip()\n split_columns = re.split(',(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)',row)\n # strippedRow = row.strip().replace('\\\"', '')\n # strippedRow = row.strip()\n pattern = ',|\\t|\"\"'\n # all_columns_Of_row = re.split(pattern, strippedRow)\n # all_columns_Of_row = (lambda col : col.strip('\"') ,split_columns)\n for eachColumn in split_columns:\n eachColumn = eachColumn.strip('\"')\n ced_data[id].append(eachColumn)\n # all_data[id].append(event_data)\n\n # print(\"Data for ID \", id, \" is:\", allData)\n # print(\"Data for file \", cedFile,\" is:\",allData[cedFile])\n # print(\"\\nData is :\\n\",ced_data)\n return ced_data, index_Of_stored_date\n\n def read_ced_data_for_validation(self,file, unique_IDs, search_column,delimiter,quotechar):\n # print(\"*** Reading Data From File :: \", file , \" ***\")\n ced_data = defaultdict(lambda: defaultdict(list))\n index_Of_stored_date = None\n\n with open(os.path.join(CEDFunctions.input_file_path, file), 'r') as file:\n content = csv.reader(file,delimiter=delimiter,quotechar=quotechar)\n header = next(content)\n index_Of_stored_date = header.index(\"EVENT_STORED_DT\")\n\n for id in unique_IDs:\n rownum = 0\n for rowData in content:\n if id in rowData:\n for eachColumn in rowData:\n ced_data[id][rownum].append(eachColumn)\n rownum +=1\n # rownum = 0\n return ced_data, index_Of_stored_date\n\n# cedFiles = CEDFunctions().findFiles()\n# # CEDFunctions().getIndex()\n# CEDFunctions().getIDsFromCED(cedFiles)\n","sub_path":"Implementations/ced_functions.py","file_name":"ced_functions.py","file_ext":"py","file_size_in_byte":9566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"63900736","text":"from flask import make_response, jsonify\nfrom flask_restful import Resource, reqparse\nfrom backendflask.adapters.memoryrepository import MemoryRepository\nfrom backendflask.adapters.gcloudrepository import GCloudRepository\nfrom backendflask.domain_models.review import Review\nfrom backendflask.domain_models.movie import Movie\nimport json\n\n# DB Connection\ndb = MemoryRepository()\n#b = GCloudRepository()\n\n# Request Parser\nparser = reqparse.RequestParser()\n\nparser.add_argument('reviewID',\n help=\"Review Identifier\")\nparser.add_argument('personID',\n help=\"User ID of the user who posted the review\")\nparser.add_argument('movieTitle',\n help=\"Title of the movie being reviewed\")\nparser.add_argument('reviewText',\n help=\"Text content of the review posted\")\n\n\nclass ReviewList(Resource):\n\n def get(self):\n response = {\n \"reviews\": [review.toJSON() for review in db.get_all_reviews()]\n }\n return make_response(jsonify(response), 200)\n\n def post(self):\n args = parser.parse_args()\n response = {\n \"successful\": False,\n \"personID\": args['personID'],\n \"movieTitle\": args['movieTitle'],\n \"reviewText\": args['reviewText']\n }\n response['successful'] = True if db.add_review(\n Review(\n reviewID=args['reviewID'],\n personID=args['personID'],\n movie=Movie(title=args['movieTitle']),\n review_text=args['reviewText'],\n )\n ) else False\n if response['successful']:\n return make_response(jsonify(response), 201)\n else:\n return make_response(jsonify(response), 400)\n","sub_path":"backendflask/api/review_list.py","file_name":"review_list.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"215331179","text":"\nfrom tilegamelib import Frame, Vector, TileFactory, TiledMap\nfrom tilegamelib import EventGenerator, ExitListener, FigureMoveListener, FigureColorListener\nfrom tilegamelib.sprites import Sprite\nfrom tilegamelib.draw_timer import draw_timer\nfrom tilegamelib.move import wait_for_move\nfrom tilegamelib.game import Game\nfrom tilegamelib.vector import RED, BLUE, YELLOW, PURPLE, GREEN, ORANGE\nfrom pygame import Rect\nimport pygame\nimport time\n\n\nFRUITMAP = \"\"\"##########\n#b.#...aa#\n##.#.#####\n#h.#.e#.c#\n##.#.##.##\n##a#.#f..#\n#*..b..#g#\n##########\"\"\"\n\n\nFIGURE_COLORS = {\n RED: 'b.pac_up',\n BLUE: 'b.pac_down',\n YELLOW: 'b.pac_left',\n PURPLE: 'b.ghost',\n GREEN: 'b.tail',\n ORANGE: 'b.dot'\n}\n\n\nclass Colors:\n\n def __init__(self, screen):\n self.screen = screen\n self.frame = Frame(self.screen, Rect(0, 0, 640, 640))\n self.tile_factory = TileFactory('data/tiles.conf')\n self.tm = TiledMap(self.frame, self.tile_factory)\n self.player = Sprite(self.frame, self.tile_factory.get('b.pac_right'),\n Vector(4, 1), speed=2)\n self.tm.set_map(FRUITMAP)\n self.draw()\n self.events = None\n self.score = 0\n\n def draw(self):\n self.tm.draw()\n self.player.draw()\n pygame.display.update()\n\n def move(self, direction):\n nearpos = self.player.pos + direction\n near = self.tm.at(nearpos)\n if near == '#':\n return\n self.player.add_move(direction)\n wait_for_move(self.player, self.screen, self.draw, 0.01)\n self.check_player_square()\n\n def set_color(self, color):\n self.player.tile = self.tile_factory.get(FIGURE_COLORS[color])\n\n def check_player_square(self):\n field = self.tm.at(self.player.pos)\n if field == '*':\n time.sleep(1)\n self.events.exit_signalled()\n elif field in 'abcdefgh':\n self.score += 100\n self.tm.set_tile(self.player.pos, '.')\n self.tm.cache_map()\n self.draw()\n\n def run(self):\n self.events = EventGenerator()\n self.events.add_listener(FigureMoveListener(self.move))\n self.events.add_listener(FigureColorListener(self.set_color))\n self.events.add_listener(ExitListener(self.events.exit_signalled))\n with draw_timer(self, self.events):\n self.events.event_loop()\n\n\nif __name__ == '__main__':\n game = Game('data/collect_fruit.conf', Colors) #Change to data/colors.conf after creating title screen\n game.run()\n","sub_path":"examples/colors.py","file_name":"colors.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"21639400","text":"import os\n\n\ndef main(j, args, params, tags, tasklet):\n params.result = page = args.page\n\n try:\n spaces = j.portal.tools.server.active.getSpaces()\n for space_name in spaces:\n space = j.portal.tools.server.active.getSpace(space_name, ignore_doc_processor=True)\n space_path = os.path.abspath(space.model.path)\n j.system.process.execute('cd %s;git pull' % space_path)\n page.addMessage('Pulled and Updated')\n except Exception as error:\n page.addMessage('Something went wrong with updating one more or more of the spaces')\n\n return params\n\n\ndef match(j, args, params, tags, tasklet):\n return True\n","sub_path":"apps/portalbase/macros/page/pull_update/1_pull_update.py","file_name":"1_pull_update.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"11993980","text":"import copy\nimport numpy as np\n\nfrom itertools import product\nfrom pprint import pprint\n\nfrom d3m import exceptions, utils, index as d3m_index\nfrom d3m.metadata import base as metadata_base\nfrom d3m.metadata.pipeline import Pipeline, PrimitiveStep\nfrom configuration_space import SimpleConfigurationSpace, ConfigurationPoint\n\n\nclass DSBoxTemplate():\n def __init__(self):\n self.primitive = d3m_index.search()\n self.argmentsmapper = {\n \"container\": metadata_base.ArgumentType.CONTAINER,\n \"data\": metadata_base.ArgumentType.DATA,\n \"value\": metadata_base.ArgumentType.VALUE,\n \"primitive\": metadata_base.ArgumentType.PRIMITIVE\n }\n self.stepcheck = None # Generate a step check matrix\n\n self.step_number = {}\n self.addstep_mapper = {\n (\"\",\n \"\"): \"d3m.primitives.data.DataFrameToNDArray\",\n # (\"\", \"\"): \"d3m.primitives.data_cleaning.imputer.SKlearn\",\n (\"\",\n \"\"): \"d3m.primitives.data.NDArrayToDataFrame\"\n }\n self.description_info = \"\"\n self.need_add_reference = False\n\n # Need to be set by subclass inheriting DSBoxTemplate\n # self.template = \"\"\n\n def __str__(self):\n if hasattr(self, 'template') and 'name' in getattr(self, 'template'):\n return f\"DSBoxTemplate:{self.template['name']}\"\n else:\n return f\"DSBoxTemplate:BLANK\"\n\n def __repr__(self):\n return self.__str__()\n\n def add_stepcheck(self):\n check = np.zeros(shape=(len(self.primitive), len(self.primitive))).astype(int)\n for i, v in enumerate(self.primitive.keys()):\n inputs = self.primitive[v].metadata.query()[\"primitive_code\"][\"class_type_arguments\"][\n \"Inputs\"]\n for j, u in enumerate(self.primitive.keys()):\n outputs = self.primitive[u].metadata.query()[\"primitive_code\"][\"class_type_arguments\"][\"Outputs\"]\n try:\n inp = inputs.__args__\n if outputs in inp:\n check[i][j] = 1\n except Exception:\n if inputs == outputs:\n check[i][j] = 1\n self.stepcheck = check\n\n def to_pipeline(self, configuration_point: ConfigurationPoint) -> Pipeline:\n \"\"\"\n converts the configuration point to the executable pipeline based on\n ta2 competitions format\n Args:\n configuration_point (ConfigurationPoint):\n\n Returns:\n The executable pipeline with full hyperparameter settings\n\n Examples:\n configuration_point =\n {\n \"my_step1\" : {\n \"primitive\": \"dsbox.a.b\",\n \"hyperparameters\": {\n \"x\": 1\n }\n },\n \"my_step2\" : {\n \"primitive\": \"sklearn.a.b\",\n \"hyperparameters\": {}\n }\n }\n dstemp = DSBoxTemplate(...)\n dstemp.to_pipeline(configuration_point)\n \"\"\"\n # print(\"*\" * 20)\n # print(\"[INFO] to_pipeline:\")\n # pprint(configuration_point)\n # return self._to_pipeline(configuration_point)\n\n # add inputs to the configuration point\n ioconf = self.add_inputs_to_confPonit(configuration_point)\n\n # binding = configuration_point\n binding, sequence = self.add_intermediate_type_casting(ioconf)\n # print(\"[INFO] Binding:\")\n # pprint(binding)\n return self._to_pipeline(binding, sequence)\n\n def add_inputs_to_confPonit(self,\n configuration_point: ConfigurationPoint) -> ConfigurationPoint:\n\n io_conf = copy.deepcopy(configuration_point)\n for step in self.template['steps']:\n io_conf[step['name']]['inputs'] = step['inputs']\n return io_conf\n\n def add_intermediate_type_casting(\n self, configuration_point: ConfigurationPoint) \\\n -> ConfigurationPoint:\n \"\"\"\n This method parses the information in the template and adds the\n necessary type casting primitives in the pipeline. These type\n information is associated with each individual primitive present in\n the template and is governed by d3m's primitive rules.\n Args:\n configuration_point: Configuration\n\n Returns:\n binding: Configuration\n\n \"\"\"\n # binding = ....\n binding = configuration_point\n checked_binding = {}\n sequence = []\n # for step in self.template[\"steps\"]:\n for step_num, step in enumerate(self.template[\"steps\"]):\n # First element in the inputs array is always the input of the\n # step in configuration point. In order to check the need for\n # adding intermediate step we first extract metadata information\n # of steps and by comparing the IO type information we decide on\n # whether intermediate type caster is necessary or not\n\n inputs = step[\"inputs\"]\n fill_in = copy.deepcopy(inputs)\n name = step[\"name\"]\n for in_arg in inputs:\n in_primitive_value = d3m_index.get_primitive(binding[name][\"primitive\"]).metadata.query()[\n \"primitive_code\"][\"class_type_arguments\"][\"Inputs\"]\n\n if in_arg == \"template_input\":\n continue\n\n # Check if the input name is valid and available in template\n if in_arg not in binding:\n print(\"[ERROR] step {} input {} is not available!\".format(step_num, in_arg))\n print(\"binding: \")\n pprint(binding)\n return 1\n\n # get information of the producer of the input\n out_primitive_value = \\\n d3m_index.get_primitive(binding[in_arg][\"primitive\"]).metadata.query()[\n \"primitive_code\"][\"class_type_arguments\"][\"Outputs\"]\n if not self.iocompare(in_primitive_value,\n out_primitive_value):\n check_key = (str(out_primitive_value),\n str(in_primitive_value))\n print(\"[INFO] Different types!\")\n try:\n # inter_name = \"{}_{}_{}\".format(name,in_arg,solution)\n solution = self.addstep_mapper[check_key]\n inter_name = \"{}_{}_{}\".format(name, in_arg, solution)\n intermediate_step = {\n \"primitive\": solution,\n \"hyperparameters\": {},\n \"inputs\": [in_arg]\n }\n # binding[inter_name] = intermediate_step\n # binding[name]['inputs'][0] = inter_name\n # checked_binding[inter_name] = intermediate_step\n pos = binding[name][\"inputs\"].index(in_arg)\n # checked_binding[name][\"inputs\"][pos] = inter_name\n checked_binding[inter_name] = intermediate_step\n fill_in[pos] = in_arg\n sequence.append(inter_name)\n print(\"[INFO] \", solution, \"added to step\",\n name)\n except:\n print(\"Warning!\", name,\n \"'s primitive\",\n # Fixme:\n # conf_step[-1][\"primitive\"],\n \"'s inputs does not match\",\n binding[in_arg][-1][\"primitive\"],\n \"and there is no converter found\")\n\n # temporary fix for CMU clustering tempalte (with special input called \"reference\")\n\n mystep = {\n \"primitive\": binding[name][\"primitive\"],\n \"hyperparameters\": binding[name][\"hyperparameters\"],\n \"inputs\": fill_in\n }\n\n if \"runtime\" in step:\n mystep[\"runtime\"] = step[\"runtime\"]\n\n sequence.append(name)\n checked_binding[name] = mystep\n\n return checked_binding, sequence\n\n def iocompare(self, i, o):\n try:\n i = i.__args__\n if (o in i) or (i in o):\n return True\n except Exception:\n if o == i:\n return True\n return False\n\n def bind_primitive_IO(self, primitive: PrimitiveStep, *templateIO):\n # print(templateIO)\n if len(templateIO) > 0:\n primitive.add_argument(\n name=\"inputs\",\n argument_type=metadata_base.ArgumentType.CONTAINER,\n data_reference=templateIO[0])\n\n if len(templateIO) > 1:\n arguments = primitive.primitive.metadata.query()['primitive_code']['instance_methods'][\n 'set_training_data']['arguments']\n if \"outputs\" in arguments:\n # Some primitives (e.g. GreedyImputer) require \"outputs\", while others do\n # not (e.g. MeanImputer)\n primitive.add_argument(\"outputs\", metadata_base.ArgumentType.CONTAINER,\n templateIO[1])\n if len(templateIO) > 2:\n raise exceptions.InvalidArgumentValueError(\n \"Should be less than 3 arguments!\")\n\n def _to_pipeline(self, binding, sequence) -> Pipeline:\n \"\"\"\n Args:\n binding:\n\n Returns:\n\n \"\"\"\n\n # define an empty pipeline with the general dataset input primitive\n # generate empty pipeline with i/o/s/u =[]\n # pprint(binding)\n # print(sequence)\n # print(\"[INFO] list:\",list(map(str, metadata_base.Context)))\n pipeline = Pipeline(name=self.template['name'] + \":\" + str(id(binding)),\n context=metadata_base.Context.PRETRAINING,\n description=self.description_info) # 'PRETRAINING'\n templateinput = pipeline.add_input(\"input dataset\")\n\n # save temporary output for another step to take as input\n outputs = {}\n outputs[\"template_input\"] = templateinput\n\n # iterate through steps in the given binding and add each step to the\n # pipeline. The IO and hyperparameter are also handled here.\n for i, step in enumerate(sequence):\n self.step_number[step] = i\n # primitive_step = PrimitiveStep(self.primitive[binding[step][\n # \"primitive\"]].metadata.query())\n primitive_name = binding[step][\"primitive\"]\n if primitive_name in self.primitive:\n primitive_desc = dict(d3m_index.get_primitive(primitive_name).metadata.query())\n\n primitive_step = PrimitiveStep(primitive_desc)\n\n # D3M version v2019.1.21 removes primitive description. Need another way\n # to pass \"runtime\"\n if \"runtime\" in binding[step]:\n # primitive_desc[\"runtime\"] = binding[step][\"runtime\"]\n primitive_step.__dict__['_dsbox_runtime'] = binding[step][\"runtime\"]\n # print('==== ', primitive_step._dsbox_runtime)\n\n else:\n raise exceptions.InvalidArgumentValueError(\"Error, can't find the primitive : \",\n primitive_name)\n\n if binding[step][\"hyperparameters\"] != {}:\n hyper = binding[step][\"hyperparameters\"]\n for hyperName in hyper:\n primitive_step.add_hyperparameter(\n # argument_type should be fixed type not the type of the data!!\n name=hyperName, argument_type=self.argmentsmapper[\"value\"],\n data=hyper[hyperName])\n\n if self.need_add_reference and primitive_name == 'd3m.primitives.data_transformation.construct_predictions.DataFrameCommon':\n primitive_step.add_argument(\"reference\",metadata_base.ArgumentType.CONTAINER,\"steps.0.produce\")\n\n templateIO = binding[step][\"inputs\"]\n\n # first we need to extract the types of the primtive's input and\n # the generators's output type.\n # then we need to compare those and in case we have different\n # types, add the intermediate type caster in the pipeline\n # print(outputs)\n self.bind_primitive_IO(primitive_step,\n *map(lambda io: outputs[io], templateIO))\n pipeline.add_step(primitive_step)\n # pre v2019.1.21\n # outputs[step] = primitive_step.add_output(\"produce\")\n primitive_step.add_output(\"produce\")\n outputs[step] = f'steps.{primitive_step.index}.produce'\n # END FOR\n\n # Add final output as the prediction of target attribute\n general_output = outputs[self.template[\"steps\"][-1][\"name\"]]\n # print(general_output)\n pipeline.add_output(general_output, \"predictions of input dataset\")\n\n return pipeline\n\n def generate_configuration_space(self) -> SimpleConfigurationSpace:\n steps = self.template[\"steps\"]\n conf_space = {}\n for each_step in steps:\n name = each_step[\"name\"]\n values = []\n\n # description: typing.Dict\n for description in each_step[\"primitives\"]:\n value_step = []\n # primitive with no hyperparameters\n if isinstance(description, str):\n value_step.append({\n \"primitive\": description,\n \"hyperparameters\": {}\n })\n # one primitive with hyperparamters\n elif isinstance(description, dict):\n value_step += self.description_to_configuration(description)\n # list of primitives\n elif isinstance(description, list):\n for prim in description:\n value_step += self.description_to_configuration(prim)\n else:\n # other data format, not supported, raise error\n print(\"Error: Wrong format of the description: \"\n \"Unsupported data format found : \", type(description))\n\n values += value_step\n\n # END FOR\n if len(values) > 0:\n conf_space[name] = values\n # END FOR\n return SimpleConfigurationSpace(conf_space)\n\n def description_to_configuration(self, description):\n value = []\n # if the desciption is an dictionary:\n # it maybe a primitive with hyperparameters\n if \"primitive\" not in description:\n print(\"Error: Wrong format of the configuration space data: \"\n \"No primitive name found!\")\n else:\n if \"hyperparameters\" not in description:\n description[\"hyperparameters\"] = {}\n\n # go through the hypers and if anyone has empty value just remove it\n hyperDict = dict(filter(lambda kv: len(kv[1]) > 0,\n description[\"hyperparameters\"].items()))\n\n # go through the hyper values for single tuples and convert them\n # to a list with single tuple element\n hyperDict = dict(map(\n lambda kv:\n (kv[0], [kv[1]]) if isinstance(kv[1], tuple) else (kv[0], kv[1]),\n hyperDict.items()\n ))\n\n # iterate through all combinations of the hyperparamters and add\n # each as a separate configuration point to the space\n for hyper in _product_dict(hyperDict):\n value.append({\n \"primitive\": description[\"primitive\"],\n \"hyperparameters\": hyper,\n })\n return value\n\n def get_target_step_number(self):\n # self.template[0].template['output']\n return self.step_number[self.template['output']]\n\n def get_output_step_number(self):\n return self.step_number[self.template['output']]\n\n\ndef _product_dict(dct):\n keys = dct.keys()\n vals = dct.values()\n for instance in product(*vals):\n yield dict(zip(keys, instance))\n","sub_path":".travis/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":16736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"330231042","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport random\nimport time\nimport os\nimport hashlib\n\nclass BaseSpider(object):\n def __init__(self):\n pass\n\n def get_html(self, url):\n headers = [\n 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',\n 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',\n 'Mozilla/5.0 (Windows NT 6.2; rv:16.0) Gecko/20100101 Firefox/16.0'\n ]\n header = {'user-agent': random.choice(headers)}\n\n rep = requests.get(url,headers=header)\n # time.sleep(random.random())\n if rep.status_code is 200:\n return rep.text\n else:\n return ''\n\n\n def parse_html(self, content, pattern):\n result = re.findall(pattern, content, re.S)\n\n return result\n\n def delete_like_img(self, path):\n md5_list = []\n img_list = os.listdir(path)\n for img in img_list:\n img = path + img\n f = open(img,'rb')\n md5obj = hashlib.md5()\n md5obj.update(f.read())\n hash = md5obj.hexdigest()\n f.close()\n md5 = str(hash).upper()\n if md5 in md5_list:\n print('已删除重复图片: %s'%img)\n os.remove(img)\n else:\n md5_list.append(md5)\n\n\nclass HuabanSpider(object):\n\n def __init__(self):\n self.base_url = 'http://huaban.com/search/?q=%s'\n self.url_info = '&page=%s&per_page=20'\n\n\n def get_image(self, result_list):\n total_num = len(result_list)\n successs_num = 0\n for result in result_list:\n url = 'http://img.hb.aicdn.com/%s_/fw/10000'%result\n content = requests.get(url).content\n # time.sleep(random.random())\n self.save_img(content, result)\n successs_num += 1\n print('本页面搜索到%s张图片,成功保存%s张图片' % (total_num, successs_num))\n\n def save_img(self, content, id):\n suffix = str(time.time()).split('.')[1]\n path = '%s/'%self.search_key\n isExists=os.path.exists(path)\n if not isExists:\n os.makedirs(path)\n r_name = '%s/%s_%s_%s.jpg' % (self.search_key, self.search_key, suffix, id)\n with open(r_name, 'wb') as f:\n f.write(content)\n\n def run(self):\n url_prefix = self.base_url%self.search_key\n if self.total_page == 0:\n num = 20000\n else:\n num = self.total_page\n for i in range(1, num):\n bs = BaseSpider()\n url = url_prefix + self.url_info%i\n print('正在抓取第%s页'%i)\n content = bs.get_html(url)\n pattern = r'\"pin_id\":.*?\"key\":\"(.*?)\",.*?key.*?extra.*?'\n result_list = bs.parse_html(content, pattern)\n if not result_list:\n break\n self.get_image(result_list)\n bs.delete_like_img('%s/'%self.search_key)\n\n\nif __name__ == '__main__':\n hbspider = HuabanSpider()\n hbspider.search_key = input('请输入要抓取的关键字: ')\n hbspider.total_page = int(input('请输入要爬取得总页码数(每页默认20张图片,如果不限制,请输入数字0,或者输入需要的页码数): '))\n hbspider.run()","sub_path":"爬虫/花瓣网图片下载/花瓣网图片下载.py","file_name":"花瓣网图片下载.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"354361045","text":"#!/usr/bin/env python3\n\n# Copyright (C) 2015 Matt Doyle\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# Base test case for python-tools modules.\n\nimport mock\nimport unittest\n\n\nclass TestCase(unittest.TestCase):\n\n def PatchObject(self, target, attribute, **kwargs):\n patcher = mock.patch.object(target, attribute, **kwargs)\n self.addCleanup(patcher.stop)\n return patcher.start()\n","sub_path":"testcase.py","file_name":"testcase.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"357825161","text":"# Using break to Exit a Loop\n# To exit while loop immediately without running any remaining code in the loop, regardless of the results of any conditional test, use the break statement. \n# The break statement directs the flow of your program: you can use it to control which lines of code are executed and which aren't, to the program only executes code that you want it to, when you want it to.\n# For example, consider a program that asks the user about places they've visited. We can stop the while loop in this program by calling break as soon as the user enters the 'quit' value:\n\n\nprompt = \"\\nPlease enter the name of a city you have visited:\"\nprompt += \"\\n(Enter 'quit' when you are finished.) \"\n\nwhile True:\n city = input(prompt)\n\n if city == 'quit':\n break \n else:\n print(\"I'd love to go to \" + city.title() + \"!\")\n \n\n# A loop that starts with while True will run forever unless it reaches a break statement. The loop in this program continues asking the user to enter the names of cities they've been to until they enter 'quit'. \n# When they enter 'quit', the break statement runs, causing Python to exit the loop:\n\n# You can use the break statement in any of Python's loops. For example, you could use break to quit a for loop that's working through a list or a dictionary.","sub_path":"chapter_07/break_to_exit_loop.py","file_name":"break_to_exit_loop.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"145700414","text":"import time\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\n\n\nlink = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/\"\n\n\ndef test_check_add_to_basket_button(browser: webdriver.Chrome):\n print(\"start test\")\n browser.get(link)\n # time.sleep(30)\n browser.implicitly_wait(10)\n try:\n button = browser.find_element(By.CLASS_NAME, \"btn-add-to-basket\")\n print(f\"button text = {button.text}\")\n except NoSuchElementException:\n assert False, 'button has not find'\n print(\"finish test1\")","sub_path":"test_items.py","file_name":"test_items.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"233327543","text":"from d4rl.offline_env import OfflineEnv\nfrom ICQ.icq import ICQ\nimport argparse\nimport gym\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--algorithm\", default=\"ICQ\")\n parser.add_argument(\"--env\",\n default=\"antmaze-umaze-diverse-v0\") # hopper-random-v0\n parser.add_argument(\"--exp_name\", default=\"data/dump\")\n parser.add_argument(\"--num_expert_trajs\", default=5, type=int)\n parser.add_argument(\"--seed\", default=100, type=int)\n args = parser.parse_args()\n env_fn = gym.make(args.env)\n env_name = args.env\n\n if 'ICQ' in args.algorithm:\n agent = ICQ(env_fn,\n env_name,\n logger_kwargs={\n 'output_dir': args.exp_name + '_s' + str(args.seed),\n 'exp_name': args.exp_name\n },\n batch_size=1024,\n seed=args.seed,\n algo=args.algorithm)\n else:\n raise NotImplementedError\n\n agent.populate_replay_buffer()\n agent.run()","sub_path":"run_agent.py","file_name":"run_agent.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"620993276","text":"# Copyright 2013 Donald Stufft\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.\nimport pytest\n\nfrom warehouse.datastructures import AttributeDict\n\n\ndef test_basic_attribute_dict_access():\n adict = AttributeDict({\n \"foo\": None,\n \"bar\": \"Success!\"\n })\n\n assert adict.foo is adict[\"foo\"]\n assert adict.bar is adict[\"bar\"]\n\n\ndef test_attribute_dict_unknown_access():\n adict = AttributeDict()\n\n with pytest.raises(AttributeError):\n adict.unknown\n\n\ndef test_convert_to_attribute_dict():\n adict = AttributeDict({\"a\": {\"b\": 1, \"c\": 2}})\n\n assert adict.a == {\"b\": 1, \"c\": 2}\n assert adict.a.b == 1\n assert adict.a.c == 2\n","sub_path":"tests/test_datastructures.py","file_name":"test_datastructures.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"463298936","text":"from typing import List\n\nclass Solution:\n \"\"\"\n 529. 扫雷游戏\n https://leetcode-cn.com/problems/minesweeper/\n 给定一个代表游戏板的二维字符矩阵。 'M' 代表一个未挖出的地雷,'E' 代表一个未挖出的空方块,'B' 代表没有相邻(上,下,左,右,和所有4个对角线)地雷的已挖出的空白方块,数字('1' 到 '8')表示有多少地雷与这块已挖出的方块相邻,'X' 则表示一个已挖出的地雷。\n 现在给出在所有未挖出的方块中('M'或者'E')的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板:\n 1. 如果一个地雷('M')被挖出,游戏就结束了- 把它改为 'X'。\n 2. 如果一个没有相邻地雷的空方块('E')被挖出,修改它为('B'),并且所有和其相邻的未挖出方块都应该被递归地揭露。\n 3. 如果一个至少与一个地雷相邻的空方块('E')被挖出,修改它为数字('1'到'8'),表示相邻地雷的数量。\n 4. 如果在此次点击中,若无更多方块可被揭露,则返回面板。\n \"\"\"\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n # 定义8个方向\n direction = ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, 1), (-1, -1), (1, -1))\n # 如果点击区域是雷区,直接返回\n if board[click[0]][click[1]] == 'M':\n board[click[0]][click[1]] = 'X'\n return board\n self.m, self.n = len(board), len(board[0])\n\n # 计算每个点周边的雷数\n def check(i, j):\n cnt = 0\n for x, y in direction:\n x, y = x + i, y + j\n if 0 <= x < self.m and 0 <= y < self.n and board[x][y] == 'M':\n cnt += 1\n return cnt\n\n def dfs(i, j):\n cnt = check(i, j)\n if not cnt:\n board[i][j] = 'B'\n for x, y in direction:\n x, y = x + i, y + j\n if 0 <= x < self.m and 0 <= y < self.n and board[x][y] == 'E': dfs(x, y)\n else:\n board[i][j] = str(cnt)\n\n dfs(click[0], click[1])\n return board\n\nso = Solution()\nprint(so.updateBoard([['E', 'E', 'E', 'E', 'E'],\n ['E', 'E', 'M', 'E', 'E'],\n ['E', 'E', 'E', 'E', 'E'],\n ['E', 'E', 'E', 'E', 'E']], [3,0]\n))\n","sub_path":"bfs.minesweeper.py","file_name":"bfs.minesweeper.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"393592221","text":"from unittest.mock import patch\nfrom app.modules.domain.healthrecord import HealthRecord\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_init(mock_fhir):\n mock_fhir.get_id.return_value = ({}, 200)\n hr = HealthRecord(id=1)\n mock_fhir.get_id.return_value = ({}, 404)\n try:\n hr = HealthRecord(id=1)\n assert True == False\n except Exception as err:\n assert \"ID is invalid.\" == str(err)\n\n mock_fhir.query_patient.return_value = ({'total': 1, 'entry': [{'resource': {}}]}, 200)\n hr = HealthRecord.query_patient(patient_id=1)\n mock_fhir.query_patient.return_value = ({}, 400)\n try:\n hr = HealthRecord.query_patient(patient_id=1)\n assert True == False\n except Exception as err:\n assert \"FHIR Condition API ERROR or FHIR SYSTEM Down\" == str(err)\n\n hr = HealthRecord(hr={})\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_create(mock_fhir):\n date = \"2000-10-10\"\n patient_id = 1\n name = \"test\"\n identifier = \"H123456789\"\n code = \"1234\"\n medication = \"12345\"\n mock_fhir.create.return_value = return_value = ({\n \"resourceType\": \"Condition\",\n \"recordedDate\": date,\n \"subject\": {\n \"reference\": \"Patient/{}\".format(patient_id),\n \"display\": name,\n \"identifier\": {\n 'value': identifier\n },\n },\n \"code\": {\n \"text\": code\n },\n \"note\": {\n \"text\": medication\n }\n }, 201)\n hr = HealthRecord.create(patient_id, code, medication, date, identifier, name)\n assert hr.get() == return_value[0]\n\n mock_fhir.create.return_value = ({}, 400)\n try:\n hr = HealthRecord.create(patient_id, code, medication, date, identifier, name)\n assert True == False\n except Exception as err:\n assert \"health_record data is invalid.\" == str(err)\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_delete(mock_fhir):\n _hr = {\"id\": 0}\n hr = HealthRecord(hr=_hr)\n hr.delete()\n mock_fhir.delete.assert_called_once()\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_update(mock_fhir):\n _hr = {\n \"resourceType\": \"Condition\",\n \"id\": \"96\",\n \"meta\": {\n \"versionId\": \"1\",\n \"lastUpdated\": \"2019-12-18T15:29:03.000+00:00\"\n },\n \"code\": {\n \"text\": \"ghhgofh\"\n },\n \"subject\": {\n \"reference\": \"Patient/56\",\n \"identifier\": {\n \"value\": \"H123456789\"\n },\n \"display\": \"姓氏名字\"\n },\n \"recordedDate\": \"2019-12-18\",\n \"note\": [{\n \"text\": \"ghhggfh\"\n }]\n }\n\n hr = HealthRecord(hr=_hr)\n\n mock_fhir.update.return_value = (_hr, 200)\n hr.update(\"1\", \"2\", \"3\", \"4\")\n mock_fhir.update.return_value = (_hr, 400)\n try:\n hr.update(\"1\", \"2\", \"3\", \"4\")\n assert True == False\n except Exception as err:\n assert \"health_record data is invalid.\" == str(err)\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_get(mock_fhir):\n _hr = {\n \"resourceType\": \"Condition\",\n \"id\": \"96\",\n \"meta\": {\n \"versionId\": \"1\",\n \"lastUpdated\": \"2019-12-18T15:29:03.000+00:00\"\n },\n \"code\": {\n \"text\": \"ghhgofh\"\n },\n \"subject\": {\n \"reference\": \"Patient/56\",\n \"identifier\": {\n \"value\": \"H123456789\"\n },\n \"display\": \"姓氏名字\"\n },\n \"recordedDate\": \"2019-12-18\",\n \"note\": [{\n \"text\": \"ghhggfh\"\n }]\n }\n\n hr = HealthRecord(hr=_hr)\n\n assert hr.get() == _hr\n assert hr.id == \"96\"\n assert hr.code == \"ghhgofh\"\n assert hr.medication == \"ghhggfh\"\n assert hr.date == \"2019-12-18\"\n assert hr.identifier == \"H123456789\"\n assert hr.name == \"姓氏名字\"\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_get_all(mock_fhir):\n _hrs = {\n \"total\":\n 1,\n \"count\":\n 20,\n \"offset\":\n 0,\n \"entry\": [{\n \"resource\": {\n \"resourceType\": \"Condition\",\n \"id\": \"96\",\n \"meta\": {\n \"versionId\": \"1\",\n \"lastUpdated\": \"2019-12-18T15:29:03.000+00:00\"\n },\n \"code\": {\n \"text\": \"ghhgofh\"\n },\n \"subject\": {\n \"reference\": \"Patient/56\",\n \"identifier\": {\n \"value\": \"H123456789\"\n },\n \"display\": \"姓氏名字\"\n },\n \"recordedDate\": \"2019-12-18\",\n \"note\": [{\n \"text\": \"ghhggfh\"\n }]\n }\n }]\n }\n\n mock_fhir.get_all.return_value = return_value = (_hrs, 200)\n hrs = HealthRecord.get_all()\n mock_fhir.get_all.assert_called_once()\n\n mock_fhir.get_all.return_value = return_value = ({}, 400)\n\n try:\n hrs = HealthRecord.get_all()\n assert True == False\n except Exception as err:\n assert \"FHIR Condition API ERROR or FHIR SYSTEM Down\" == str(err)\n","sub_path":"tests/unit/domain/test_health_record_domain.py","file_name":"test_health_record_domain.py","file_ext":"py","file_size_in_byte":5303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"381430342","text":"import collections\n# Given an array of integers, every element appears three times except for one. Find that single one.\n#\n# Note:\n# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\n\nclass Solution:\n # @param A, a list of integer\n # @return an integer\n def singleNumber(self, A):\n words_counts = collections.Counter(A)\n odd = min(words_counts.items(), key = lambda k: k[1])\n return odd[0]\n\n\ns = Solution()\n# odd = heapq.nsmallest(1, words_counts, key=lambda x: x[1])\nl = [5, 2, 2, 2, 3, 3, 3]\nprint(s.singleNumber(l))\n# m = [17, 12, 5, -6, 12, 4, 17, -5, 2, -3, 2, 4, 5, 16, -3, -4, 15, 15, -4, -5, -6]\n# print(s.singleNumber(m))\n","sub_path":"Math/SingleNumberII.py","file_name":"SingleNumberII.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"531330511","text":"\n# Drawing Book\n\"\"\"\n 책에 페이지를 최소한의 수로 넘기는 방법 찾기\n \n 시작이나 끝부터 시작 가능하고\n 1page는 오른쪽 페이지부터 시작함\n 그다음은 마지막 페이지말고는 항상 양 페이지에 있음\n\n 페이지 수랑 찾고자하는 페이지가 잇을 때 최소한의 수로 넘기는 방법 찾기\n\n 1 <= n <= 10^5\n 1 <= p <= n\n\n ex)\n 6 총 6페이지\n 2 찾고자하는 페이지 \n 처음부터 시작 |1 -> 2|3 = 1번\n 끝부터 시작 6| -> 4|5 -> 3|4 = 2번\n 정답 1번\n\n 5\n 4\n |1 -> 2|3 -> 4|5 = 2\n 4|5 = 0\n -> 0\n\"\"\"\n\ndef pageCount(n, p):\n start = end = 0\n\n if n % 2 == 0: # 짝수면 마지막페이지 왼쪽\n book = [0, 1, n, n+1]\n else: # 홀수면 오른쪽\n book = [0, 1, n-1, n]\n\n while(True):\n # 페이지 찾기 검사\n if book.count(p) >= 1:\n break\n start += 1\n end += 1\n book[0] += 2\n book[1] += 2\n book[2] -= 2\n book[3] -= 2\n\n if start < end:\n return start\n else:\n return end\n\nif __name__ == '__main__':\n n = int(input())\n p = int(input())\n\n result = pageCount(n,p)\n print(result)","sub_path":"Drawing Book/Drawing_Book.py","file_name":"Drawing_Book.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"40869757","text":"import sys\nimport time\nfrom database import *\n\nclass database:\n def __init__(self):\n self.data = []\n self.dict = {}\n self.index = -1 #index of the last element in the list\n \n def insert(self,key,value):\n if key in self.dict:\n index = self.dict.get(key)\n self.data[index] = value\n else:\n self.data.append(value)\n self.index = self.index + 1\n index = self.index\n self.dict[key] = index\n\n def search(self,key):\n if key in self.dict:\n return self.data[self.dict.get(key)]\n return \"NOT PRESENT\"\n\n def delete(self,key):\n self.dict.pop(key)\n\nif __name__ == \"__main__\":\n db = database()\n print(\"HASH TABLE:\")\n print_result(db, sys.argv[1])\n ","sub_path":"q1_ml6363_sl7151/hash_table_db.py","file_name":"hash_table_db.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"521514012","text":"import json\nimport os\nimport amqp_setup\nfrom sqlalchemy import Table, Column, Integer, String, DateTime, create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom os import environ\n\nimport datetime as dt\n\nBase = declarative_base()\n\n# engine = create_engine('mysql+mysqlconnector://root@localhost:3306/error')\nengine = create_engine(environ.get('dbURL') or 'mysql+mysqlconnector://root@localhost:3306/error')\n\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nclass Error(Base):\n __tablename__ = 'Error'\n error_id = Column(Integer(), primary_key=True)\n code = Column(Integer(), nullable=False)\n data = Column(String(1000), nullable=False)\n message = Column(String(128), nullable=False)\n timestamp= Column(DateTime, default=dt.datetime.now())\n\n def __init__(self, code, data, message):\n self.code = code\n self.data = data\n self.message = message\n\n def json(self):\n return {\"activity_id\": self.activity_id, \"code\": self.code, \"data\": self.data, \"message\": self.message, \"timestamp\": self.timestamp}\n\n\n\ndef callback(channel, method, properties, body): # required signature for the callback; no return\n print(\"\\nReceived a log by \" + __file__)\n processErrorLog(body)\n print() # print a new line feed\n\ndef processErrorLog(data):\n print(json.loads(data)['code'])\n data = json.loads(data.decode('UTF-8'))\n #check if send to activity or error depending on code\n log = Error(code=data['code'],data=json.dumps(data['data']),message=data['message'])\n\n\n session.add(log)\n session.commit()\n print(\"Recording an error log:\")\n print(log.json())\n\n\n#Setting up activity_log and error exchange\nprint('\\n --Setting up exchange-- \\n')\namqp_setup.channel.exchange_declare(exchange='activity_error_exchange', exchange_type='topic', durable=True)\n\n#Setting up error queue\nprint('--Setting up error queue-- \\n')\namqp_setup.channel.queue_declare(queue='error_queue', durable=True)\namqp_setup.channel.queue_bind(exchange='activity_error_exchange', queue='error_queue', routing_key='error')\n\nprint('--Initiate error worker-- \\n')\namqp_setup.channel.basic_consume(queue='error_queue', on_message_callback=callback, auto_ack=True)\n\nprint('\\n--Start listening for messages....-- \\n')\namqp_setup.channel.start_consuming() # an implicit loop waiting to receive messages; \n\n\n\n\n \n","sub_path":"simple/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"278581042","text":"# Author: ivy\n# Version: Python 3.8\n# Date: 2021/03/12\n\n# 功能:把行政区选择框内的从属关系及其对应的id爬取下来\n# 输出为 adcode.json\n# 需要先去”https://www.landchina.com/ExtendModule/WorkAction/EnumSelectEx.aspx?group=1&n=TAB_queryTblEnumItem_256\"的源码里把第一集的名字和id存下来\n# 网站中手动存下来的文件命名为 originNodes.json\n\nimport requests\nimport json\nimport random, time\nimport traceback\nimport sys\n\n\noNodes_path = \"originNodes.json\"\n\n# 读取初级节点文件\ndef read_json(json_path):\n with open(json_path, 'r', encoding='utf8') as f:\n data = json.load(f)\n return data[\"zNodes\"]\n\n\ndef req(id):\n url = \"https://www.landchina.com/ExtendModule/WorkAction/EnumHandler.ashx\"\n\n headers = {\n \"accept\": \"text/plain, */*; q=0.01\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"accept-language\": \"zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7\",\n \"content-length\": \"13\",\n \"content-type\": \"application/x-www-form-urlencoded\",\n \"cookie\": \"ASP.NET_SessionId=40g1s1kowx5md4035edrgv0g; Hm_lvt_83853859c7247c5b03b527894622d3fa=1615359545,1615425341,1615526595; Hm_lpvt_83853859c7247c5b03b527894622d3fa=1615526878\",\n \"dnt\": \"1\",\n \"origin\": \"https://www.landchina.com\",\n \"referer\": \"https://www.landchina.com/ExtendModule/WorkAction/EnumSelectEx.aspx?group=1&n=TAB_queryTblEnumItem_256\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36\"\n }\n\n data = {\n \"id\": id,\n \"group\": 1\n }\n\n try:\n time.sleep(random.randint(1,5))\n res = requests.post(url, headers=headers, data=data)\n data = res.json()\n return data\n except Exception as e:\n print(e)\n traceback.print_exc()\n sys.exit(1)\n\n\nfdata = []\noNodes = read_json(oNodes_path)\nfor level1_node in oNodes:\n # level 1\n level1_oname = level1_node[\"name\"]\n level1_oid = level1_node[\"value\"]\n print(\"Working on\", level1_oname, \"...\")\n\n level1_tmp = {\n \"name\": level1_oname,\n \"id\": level1_oid\n }\n\n if level1_node[\"isParent\"]:\n level2_nodes = req(level1_oid)\n\n level2_tmp_ls = []\n\n for level2_node in level2_nodes:\n # level 2\n level2_oname = level2_node[\"name\"]\n level2_oid = level2_node[\"value\"]\n\n print(\" Working on\", level2_oname, \"...\")\n\n level2_tmp = {\n \"name\": level2_oname,\n \"id\": level2_oid\n }\n\n if level2_node[\"isParent\"]:\n level3_nodes = req(level2_oid)\n\n level3_tmp_ls = []\n\n for level3_node in level3_nodes:\n print(\" Working on\", level3_node[\"name\"], \"...\")\n # level 3\n level3_tmp_ls.append({\n \"name\": level3_node[\"name\"],\n \"id\": level3_node[\"value\"]\n })\n \n level2_tmp[\"district\"] = level3_tmp_ls\n \n level2_tmp_ls.append(level2_tmp)\n\n level1_tmp[\"city\"] = level2_tmp_ls\n\n fdata.append(level1_tmp)\n\nwith open('adcode.json','w',encoding='utf8')as f:\n json.dump({\"code\": fdata}, f, ensure_ascii=False)\n\nprint(\"All done\")","sub_path":"getAdcode.py","file_name":"getAdcode.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"311261772","text":"# -*- coding:utf-8 -*-\nimport re\nimport os\nimport sys\nimport json\nimport random\nimport requests\nimport traceback\n\nfrom functools import wraps, partial\nfrom argparse import ArgumentParser\nfrom googletrans.gtoken import TokenAcquirer\n\n\nclass Translate:\n \"\"\"\n 翻译类\n \"\"\"\n proxy_list = [None]\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n \"Accept-Language\": \"en-US,en;q=0.5\",\n }\n\n def __init__(self, web_site, proxy_list=\"./proxy.list\", proxy_auth=None, retry_times=10, translate_timeout=5, load_module=None):\n self.web_site = web_site.split(\",\")\n self.proxy = {}\n self.proxy_auth = proxy_auth\n self.retry_times = retry_times\n self.translate_timeout = translate_timeout\n self.site_func = dict()\n self.session = requests.Session()\n self.acquirer = TokenAcquirer(session=self.session)\n\n if os.path.exists(proxy_list):\n self.proxy_list = [i.strip() for i in open(proxy_list).readlines() if (i.strip() and i.strip()[0] != \"#\")]\n\n if load_module:\n sys.path.insert(0, os.getcwd())\n attr = vars(__import__(load_module, fromlist=load_module))\n\n for k, v in attr.items():\n if hasattr(v, \"__call__\"):\n self.site_func[k] = v\n\n def __getattr__(self, item):\n if item in self.site_func:\n return partial(self.site_func[item], self=self)\n raise AttributeError(item)\n\n def proxy_choice(self):\n return self.proxy_list and self.proxy_list[0] and {\"http\": \"http://%s%s\"%(\n \"%s@\"%self.proxy_auth if self.proxy_auth else \"\" , random.choice(self.proxy_list))}\n\n def trans_error_handler(self, func_name, retry_time, e, *args, **kwargs):\n \"\"\"\n error_handler实现参数\n :param func_name: 重试函数的名字\n :param retry_time: 重试到了第几次\n :param e: 需要重试的异常\n :param args: 重试参数的参数\n :param kwargs: 重试参数的参数\n :return: 当返回True时,该异常不会计入重试次数\n \"\"\"\n print(\"Error in %s for retry %s times. Error: %s\"%(func_name, retry_time, e))\n args[1].update(self.proxy_choice())\n\n def translate(self, src):\n \"\"\"\n 翻译主函数\n :param src: 源\n :return: 结果\n \"\"\"\n try:\n # 找出大于号和小于号之间的字符,使用换行符连接,进行翻译\n pattern = re.compile(r\"(?:^|(?<=>))([\\s\\S]*?)(?:(?=<)|$)\")\n ls = re.findall(pattern, src.replace(\"\\n\", \"\"))\n src_data = \"\\n\".join(x.strip(\"\\t \") for x in ls if x.strip())\n if src_data.strip():\n # 对源中的%号进行转义\n src_escape = src.replace(\"%\", \"%%\")\n # 将源中被抽离进行翻译的部分替换成`%s`, 如果被抽离部分没有实质内容(为空),则省略\n src_template = re.sub(pattern, lambda x: \"%s\" if x.group(1).strip() else \"\", src_escape)\n return self.retry_wrapper(self.retry_times, self.trans_error_handler)(\n self._translate)(src_data, self.proxy or self.proxy_choice()\n or self.proxy, src_template)\n else:\n return src\n except Exception:\n print(\"Error in translate, finally, we could not get the translate result. src: %s, Error: %s\"%(\n src, traceback.format_exc()))\n return src\n\n def _translate(self, src, proxies, src_template):\n return getattr(self, random.choice(self.web_site).strip())(src, proxies, src_template)\n\n def youdao(self, src_data, proxies, src_template):\n \"\"\"\n 有道翻译的实现(废弃)\n :param src_data: 原生数据\n :param proxies: 代理\n :param src_template: 原生数据模板\n :return: 结果\n \"\"\"\n url = \"http://fanyi.youdao.com/translate\"\n resp = requests.post(url=url, data={\n 'keyfrom': 'fanyi.web',\n 'i': src_data,\n 'doctype': 'json',\n 'action': 'FY_BY_CLICKBUTTON',\n 'ue': 'UTF-8',\n 'xmlVersion': '1.8',\n 'type': 'AUTO',\n 'typoResult': 'true'}, headers=self.headers,\n timeout=self.translate_timeout, proxies=proxies)\n return src_template % tuple(map(lambda y: \"\".join(\n map(lambda x: x[\"tgt\"], y)), json.loads(resp.text)[\"translateResult\"]))\n\n def baidu(self, src_data, proxies, src_template):\n \"\"\"\n 百度翻译的实现, 百度翻译最长只能翻译5000个字符\n :param src_data: 原生数据\n :param proxies: 代理\n :param src_template: 原生数据模板\n :return: 结果\n \"\"\"\n url = \"http://fanyi.baidu.com/v2transapi\"\n resp = requests.post(url=url, data={\n 'from': 'en',\n 'to': 'zh',\n 'transtype': 'realtime',\n 'query': src_data,\n 'simple_means_flag': 3}, headers=self.headers,\n timeout=self.translate_timeout, proxies=proxies)\n return src_template % tuple(\n \"\".join(map(lambda x: x[\"src_str\"], json.loads(resp.text)[\"trans_result\"]['phonetic'])).split(\"\\n\"))\n\n def qq(self, src_data, proxies, src_template):\n \"\"\"\n 腾讯翻译的实现, 腾讯翻译最长只能翻译2000个字符\n :param src_data: 原生数据\n :param proxies: 代理\n :param src_template: 原生数据模板\n :return: 结果\n \"\"\"\n url = 'http://fanyi.qq.com/api/translate'\n resp = requests.post(\n url, data={'source': 'auto', 'target': 'en', 'sourceText': src_data},\n headers=self.headers, timeout=self.translate_timeout, proxies=proxies)\n print(resp.text)\n return src_template % tuple(\n record[\"targetText\"] for record in json.loads(resp.text)[\"records\"] if record.get(\"sourceText\") != \"\\n\")\n\n def google(self, src_data, proxies, src_template):\n url = 'https://translate.google.cn/translate_a/single'\n data = {\n 'client': 't',\n 'sl': \"auto\",\n 'tl': \"zh\",\n 'hl': \"zh\",\n 'dt': ['at', 'bd', 'ex', 'ld', 'md', 'qca', 'rw', 'rm', 'ss', 't'],\n 'ie': 'UTF-8',\n 'oe': 'UTF-8',\n 'otf': 1,\n 'ssel': 0,\n 'tsel': 0,\n 'tk': self.acquirer.do(src_data),\n 'q': src_data,\n }\n resp = self.session.get(url, params=data, headers=self.headers,\n timeout=self.translate_timeout, proxies=proxies)\n return self.merge_conflict(src_template, [line[0] for line in json.loads(resp.text)[0]])\n\n @staticmethod\n def merge_conflict(src_template, returns):\n return src_template % tuple(returns[:src_template.count(\"%s\")])\n\n @staticmethod\n def retry_wrapper(retry_times, error_handler=None):\n \"\"\"\n 重试装饰器\n :param retry_times: 重试次数\n :param error_handler: 重试异常处理函数\n :return:\n \"\"\"\n def out_wrapper(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n count = 0\n\n while True:\n try:\n return func(*args, **kwargs)\n except Exception as e:\n count += 1\n\n if error_handler:\n result = error_handler(func.__name__, count, e, *args, **kwargs)\n if result:\n count -= 1\n\n if count >= retry_times:\n raise\n return wrapper\n return out_wrapper\n\n @classmethod\n def parse_args(cls):\n parser = ArgumentParser()\n parser.add_argument(\"-ws\", \"--web-site\", default=\"baidu,qq,google\", help=\"Which site do you want to use for translating, split by `,`?\")\n parser.add_argument(\"-pl\", \"--proxy-list\", help=\"The proxy.list contains proxy to use for translating. default: ./proxy.list\")\n parser.add_argument(\"-pa\", \"--proxy-auth\", help=\"Proxy password if have. eg. user:password\")\n parser.add_argument(\"-rt\", \"--retry-times\", type=int, default=10, help=\"If translate failed retry times. default: 10\")\n parser.add_argument(\"-tt\", \"--translate-timeout\", type=int, default=5, help=\"Translate timeout. default: 5\")\n parser.add_argument(\"-lm\", \"--load-module\", help=\"The module contains custom web site functions which may use for translating. eg: trans.google\")\n parser.add_argument(\"src\", nargs=\"+\", help=\"The html you want to translate. \")\n data = vars(parser.parse_args())\n src = data.pop(\"src\")\n return cls(**dict(filter(lambda x: x[1], data.items()))).translate(\" \".join(src))\n\n\ndef main():\n print(Translate.parse_args())\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":9200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"364780605","text":"from django.conf.urls import patterns, url\n\nfrom med_social.decorators import member_required\n\nfrom vendors.views import (CreateVendorService, VendorServicesList, DeleteVendorService)\n\n# namespace = services\nurlpatterns = patterns('',\n url(r'^(?P\\d+)/create/$', member_required(CreateVendorService.as_view()),\n name='create'),\n url(r'^(?P\\d+)/list/$', member_required(VendorServicesList.as_view()),\n name='list'),\n url(r'^(?P\\d+)/delete/$', member_required(DeleteVendorService.as_view()), name='delete'),\n )\n","sub_path":"apps/vendors/services_urls.py","file_name":"services_urls.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"580362485","text":"from bs4 import BeautifulSoup\nimport urllib2\n\nrootUrl = \"https://www.etsy.com/search?q=\"\nitem = \"world%20globes\"\n\ndef get_soup(url,header):\n return BeautifulSoup(urllib2.urlopen(urllib2.Request(url,headers=header)),'html.parser')\n\n# soup settings \nurl = rootUrl + item\nheader={'User-Agent':\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36\"}\n\nsoup = get_soup(url,header)\n\nprices = soup.findAll(attrs={\"class\":\"currency-value\"})\nnames = soup.findAll(attrs={\"class\":\"text-gray text-truncate mb-xs-0 text-body\"})\n\nf = open('globePrices.txt', 'w')\n\nprint(names[0].string.split('\\n'))\n\nfor i in prices:\n\tf.write('$' + i.string + '\\n')\n\t\nf.close()\n","sub_path":"Scrapers/scrapey.py","file_name":"scrapey.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"483185834","text":"from django import forms\nfrom django.db.models import Count, F\nfrom scoring.settings import BLANK_CHOICE_DASH2\nfrom candidate.models import Candidate, Document, Questionnaire, DocumentTypes, Positions, Cities, Regions,\\\n REGULATIONS, SECURITY_SOLUTION, SEX_AND_EMPTY\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Fieldset, Div, Field, HTML # , ButtonHolder, Submit, MultiField, MultiWidgetField\nfrom bootstrap_datepicker_plus import DatePickerInput\n\n# class DatePickerBaseInputLocal(DatePickerBaseInput):\n#\n# def __init__(self, attrs={}, format=None, options={}):\n# super(DatePickerBaseInputLocal, self).__init__(attrs={}, format=None, options={})\n#\n# class Media:\n# js = (\n# 'bootstrap_datepicker_plus/js/moment-with-locales.min.js',\n# 'bootstrap_datepicker_plus/js/bootstrap-datetimepicker.min.js',\n# 'bootstrap_datepicker_plus/js/datepicker-widget.js'\n# )\n# css = {'all': (\n# 'bootstrap_datepicker_plus/css/bootstrap-datetimepicker.css',\n# 'bootstrap_datepicker_plus/css/datepicker-widget.css'\n# ), }\n#\n#\n# class DatePickerInputLocal(DatePickerBaseInputLocal):\n# picker_type = 'DATE'\n# format = '%m/%d/%Y'\n# format_key = 'DATE_INPUT_FORMATS'\n\n\nclass DDForm(forms.ModelForm):\n # doc_type = forms.CharField(label=\"\", required=False, disabled=True, widget=forms.Select(choices=DOC_TYPE))\n # reject_reason = forms.CharField(label=\"Изображение отклонено по причине:\", required=False, disabled=True,\n # max_length=512, widget=forms.Textarea()\n # )\n coment = forms.CharField(label=\"Комментарий:\", required=False, max_length=512, widget=forms.Textarea())\n\n attribute1 = forms.CharField(label=\"Серия\", required=False,widget=forms.TextInput())\n\n attribute2 = forms.CharField(label=\"Номер\", required=False, widget=forms.TextInput())\n\n # issue_date = forms.DateField(label=\"Дата выдачи\", required=False, #input_formats=['%d-%m-%Y'],\n # widget=forms.SelectDateWidget(empty_label=(\"Год\", \"Месяц\", \"День\"),\n # attrs={'style': 'width: 33%; display: inline-block;'}))\n\n issue_date = forms.DateField(label=\"Дата выдачи\", required=False,\n widget=DatePickerInput(format='%d.%m.%Y',\n options={\n \"locale\": \"ru\",\n \"showClose\": True,\n \"showClear\": True,\n \"showTodayButton\": False,\n },\n ))\n\n # widget=forms.DateInput(format=('%d-%m-%Y'),\n # attrs={'class': 'myDateClass', 'placeholder': 'Введите дату','style': 'font-size: large'}))\n\n def __init__(self, *args, **kwargs):\n super(DDForm, self).__init__(*args, **kwargs)\n\n self.instance = kwargs.get('instance', None)\n # self.fields['doc_type'].disabled = True\n # self.fields['doc_type'].required = False\n # self.fields['doc_type'].label = ''\n self.helper = FormHelper()\n # self.helper.form_id = 'id-DDForm'\n # self.helper.form_class = 'blueForms'\n # self.helper.form_method = 'post'\n # self.helper.form_action = 'document_details'\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n # self.fields['issue_date'].widget.attrs['class'] = 'datepicker'\n # if self.instance.reject_reason:\n # self.helper.layout.append(Div(Field('reject_reason', rows=1), css_class='alert alert-danger'))\n # self.helper.layout.append(HTML(\"\"\" \"\"\"))\n\n if self.instance.type.code == 'PASSPORT' and self.instance.doc_page_num == 1:\n self.fields['attribute1'].required = True\n self.fields['attribute2'].required = True\n\n self.fields['attribute3'].label = 'Фамилия'\n self.fields['attribute4'].label = 'Имя'\n self.fields['attribute5'].label = 'Отчество'\n self.fields['attribute6'].label = 'Дата рождения'\n self.fields['attribute6'].widget = DatePickerInput(format='%d.%m.%Y',\n options={\n \"locale\": \"ru\",\n \"showClose\": True,\n \"showClear\": True,\n \"showTodayButton\": False,\n },)\n self.helper.layout.append(\n Fieldset(\n 'Паспортные данные',\n Div(\n Field('attribute1', placeholder='',\n wrapper_class='col-md-3'),\n Field('attribute2', placeholder='',\n wrapper_class='col-md-4'),\n Field('issue_date', placeholder='ДД.ММ.ГГГГ',\n wrapper_class='col-md-5'),\n css_class='form-row'\n ),\n Div(\n Field('attribute3', placeholder='',\n wrapper_class='col-md-6'),\n Field('attribute4', placeholder='',\n wrapper_class='col-md-6'),\n css_class='form-row'\n ),\n Div(\n Field('attribute5', placeholder='',\n wrapper_class='col-md-7'),\n Field('attribute6', placeholder='',\n wrapper_class='col-md-5'),\n css_class='form-row'\n ),\n )\n # Field('reject_reason', rows=2)\n )\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n elif self.instance.type.code == 'SNILS' and self.instance.doc_page_num == 1:\n self.fields['attribute1'].required = True\n self.fields['attribute1'].label = 'Номер'\n self.helper.layout.append(\n Fieldset(\n 'Номер СНИЛС',\n Div(\n Field('attribute1', placeholder='',\n wrapper_class='col-md-8')\n ),\n )\n # Field('reject_reason', rows=2)\n )\n else:\n pass\n\n self.helper.layout.append(Div(Field('coment', rows=1)))\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n\n # def form_valid(self, form):\n # form.instance.net = form.instance.qty * form.instance.price\n # order = Order.objects.get(pk=self.kwargs['order_id'])\n # subtotal = OrdersPlaced.objects.filter(order=order).aggregate(Sum('net'))['net__sum']\n # order.subtotal = subtotal\n # order.save()\n # return super(DDForm, self).form_valid(form)\n\n # def save(self, commit=True):\n # self.cleaned_data = dict([(k, v) for k, v in self.cleaned_data.items() if v != \"\"])\n # return super(DDForm, self).save(commit=commit)\n\n # def queryset(self, request):\n # return super(DDForm, self).queryset(request).select_related('type')\n\n # def clean_issue_date(self):\n # cleaned_data = self.clean()\n # res = cleaned_data.get('issue_date')\n # if 1>0:\n # raise forms.ValidationError(\"You have forgotten about Fred!\")\n # return res\n\n class Meta:\n model = Document\n fields = [\"attribute1\", \"attribute2\", \"attribute3\", \"attribute4\", \"attribute5\", \"attribute6\",\n \"issue_date\", \"coment\"]\n\n\nclass DocAddForm(forms.ModelForm):\n doc_type = forms.ModelChoiceField(label=\"Тип документа\", required=True,\n queryset=DocumentTypes.objects.filter(can_manual_add='Y').order_by('name'))\n\n def __init__(self, *args, **kwargs):\n candidate_id = kwargs.pop('candidate_id', None)\n super(DocAddForm, self).__init__(*args, **kwargs)\n # self.instance = kwargs.get('instance', None)\n if candidate_id:\n exist_docs = Document.objects.filter(candidate_id=candidate_id). \\\n filter(doc_type_num__gte=F('type__max_documents')).values('type_id')\n # exclude(type__max_documents__gte=F('doc_type_num')).values('type_id')\n self.fields['doc_type'].queryset = DocumentTypes.objects.filter(can_manual_add='Y').\\\n exclude(id__in=exist_docs).order_by('name')\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n self.helper.layout.append(\n Div(Field('doc_type', wrapper_class='col-md-12')))\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n\n class Meta:\n model = DocumentTypes\n fields = [\"doc_type\"]\n\n\nclass StatementAddForm(forms.ModelForm):\n doc_number = forms.CharField(label=\"\", required=False)\n reason = forms.ModelChoiceField(label=\"\", required=True, empty_label=None, to_field_name='code',\n queryset=Questionnaire.objects.filter(quest_type='CANDIDATE').order_by('name'))\n\n def __init__(self, *args, **kwargs):\n super(StatementAddForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.fields['reason'].queryset = Questionnaire.objects.filter(quest_type=self.instance.type.code).\\\n order_by('name')\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n self.fields['type'].disabled = True\n self.fields['type'].label = ''\n if self.instance.type.code == 'SNILS':\n # self.fields['doc_number'].required = True\n self.helper.layout.append(\n Fieldset(\n 'Выберите основание для заявления',\n Div(\n Field('type',\n wrapper_class='col-md-3'),\n Field('reason',\n wrapper_class='col-md-6'),\n Field('doc_number',\n placeholder='Введите номер СНИЛС',\n wrapper_class='col-md-3'),\n css_class='form-row'\n )))\n else:\n self.helper.layout.append(\n Fieldset(\n 'Выберите основание для заявления',\n Div(\n Field('type',\n wrapper_class='col-md-3'),\n Field('reason',\n wrapper_class='col-md-9'),\n css_class='form-row'\n )))\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n\n class Meta:\n model = Document\n fields = [\"type\"]\n\n\nclass StateServiceForm(forms.ModelForm):\n # state_service_emp = forms.BooleanField(label=\"Я являлся государственным и/или муниципальным \"\n # \"государственным служащим в течении последних двух лет\",\n # required=False)\n state_organization = forms.CharField(label=\"Наименование организации\", required=False,\n widget=forms.TextInput(attrs={'style': 'font-size: large'}))\n\n state_position = forms.CharField(label=\"Должность в организации\", required=False,\n widget=forms.TextInput(attrs={'style': 'font-size: large'}))\n\n def __init__(self, *args, **kwargs):\n super(StateServiceForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.helper.layout.append(\n Fieldset(\n 'Наименование государственной организации и должность',\n Div(\n Field('state_organization',\n placeholder='Введите организацию',\n # css_class='form-control',\n wrapper_class='col-md-6'),\n Field('state_position',\n placeholder='Введите должность',\n # css_class='form-control',\n wrapper_class='col-md-4'),\n css_class='form-row'\n )))\n # self.helper.layout.append(HTML(\"\"\" \"\"\"))\n # self.helper.layout.append(Div(Field('state_service_emp')))\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n else:\n pass\n\n class Meta:\n model = Candidate\n fields = [\"state_service_emp\", \"state_organization\", \"state_position\"]\n\n\nclass CheckCandidateDataForm(forms.ModelForm):\n\n data_checked_comment = forms.CharField(label=\"Укажите какие данные заполнены неверно\", required=True,\n max_length=512, widget=forms.Textarea())\n\n data_checked = forms.NullBooleanField(label=u'Данные проверены кандидатом', widget=forms.HiddenInput(), initial=0)\n\n def __init__(self, *args, **kwargs):\n super(CheckCandidateDataForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.helper.layout.append(Div(Field('data_checked_comment', rows=1)))\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n else:\n pass\n\n def clean(self):\n cleaned_data = super().clean()\n cleaned_data[\"data_checked\"] = 0\n return cleaned_data\n\n class Meta:\n model = Candidate\n fields = [\"data_checked_comment\", \"data_checked\"]\n\n\nclass CandidateEmailUpdForm(forms.ModelForm):\n\n email = forms.CharField(label=\"Укажите адрес электронной почты\", required=True)\n\n def __init__(self, *args, **kwargs):\n super(CandidateEmailUpdForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.helper.layout.append(Div(Field('email')))\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n else:\n pass\n\n class Meta:\n model = Candidate\n fields = [\"email\"]\n\n\nclass AllowProcPersDataForm(forms.ModelForm):\n\n allow_process_personal_data = forms.BooleanField(label=\"Согласен\", required=True)\n\n # def clean_state_service_emp(self):\n # return True\n\n def __init__(self, *args, **kwargs):\n super(AllowProcPersDataForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n self.helper.layout.append(Div(HTML(\"\"\"
Нажимая кнопку \"Сохранить\" я даю согласие на обработку моих персональных \n данных в соответствии с Федеральным законом от 27.06.2006 года №152-ФЗ \"О персональных данных\" на условиях \n и для целей определенных в Согласии на обработку персональных данных. \"\"\"), css_class='border-top my-1'))\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n self.helper.layout.append(Div(Field('allow_process_personal_data'), css_class='border-top my-1'))\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n else:\n pass\n\n class Meta:\n model = Candidate\n fields = [\"allow_process_personal_data\"]\n\n\nclass CandidateUpdForm (forms.ModelForm):\n region = forms.ModelChoiceField(required=False, queryset=Regions.objects.all().order_by('name'),\n empty_label=BLANK_CHOICE_DASH2, to_field_name='code', label=u'Регион')\n\n city = forms.ModelChoiceField(required=False, queryset=Cities.objects.all().order_by('name'),\n empty_label=BLANK_CHOICE_DASH2, to_field_name='code', label=u'Город')\n\n # full_name = forms.CharField(required=True, label=u'ФИО')\n first_name = forms.CharField(required=True, label=u'Имя')\n last_name = forms.CharField(required=True, label=u'Фамилия')\n middle_names = forms.CharField(required=False, label=u'Отчество')\n sex = forms.ChoiceField(choices=SEX_AND_EMPTY, required=False, label=u'Пол')\n\n birth_date = forms.DateField(label=\"Дата рождения\", required=False,\n widget=DatePickerInput(format='%d.%m.%Y',\n options={\n \"locale\": \"ru\",\n \"showClose\": True,\n \"showClear\": True,\n \"showTodayButton\": False,\n }))\n\n position = forms.ModelChoiceField(required=False, queryset=Positions.objects.all().order_by('name'),\n empty_label=BLANK_CHOICE_DASH2, label=u'Предполагаемая должность')\n selling_office = forms.CharField(required=False, label=u'Предп. подразделение')\n start_work_date = forms.DateField(label=\"Предп. дата выхода\", required=False,\n widget=DatePickerInput(format='%d.%m.%Y',\n options={\n \"locale\": \"ru\",\n \"showClose\": True,\n \"showClear\": True,\n \"showTodayButton\": False,\n }))\n regulations = forms.ChoiceField(choices=REGULATIONS, required=False, label=u'Регламент')\n place_of_birth = forms.CharField(required=False, label=u'Место рождения')\n registration_address = forms.CharField(required=False, label=u'Адрес по прописке')\n passport_ser = forms.CharField(required=False, label=u'Серия паспорта')\n passport_num = forms.CharField(required=False, label=u'Номер паспорта')\n passport_date = forms.DateField(label=\"Дата выдачи\", required=False,\n widget=DatePickerInput(format='%d.%m.%Y',\n options={\n \"locale\": \"ru\",\n \"showClose\": True,\n \"showClear\": True,\n \"showTodayButton\": False,\n }))\n last_work_place = forms.CharField(required=False, label=u'Последнее место работы')\n last_work_place_region = forms.CharField(required=False, label=u'Регион посл. место работы')\n last_work_period = forms.CharField(required=False, label=u'Период работы')\n\n security_solution = forms.ChoiceField(choices=SECURITY_SOLUTION, required=False, label=u'Решение')\n\n def __init__(self, *args, **kwargs):\n super(CandidateUpdForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n\n if self.initial['security_solution']:\n self.fields['region'].disabled = True\n self.fields['city'].disabled = True\n self.fields['selling_office'].disabled = True\n self.fields['position'].disabled = True\n self.fields['regulations'].disabled = True\n self.fields['start_work_date'].disabled = True\n # self.fields['full_name'].disabled = True\n self.fields['first_name'].disabled = True\n self.fields['last_name'].disabled = True\n self.fields['middle_names'].disabled = True\n self.fields['sex'].disabled = True\n self.fields['birth_date'].disabled = True\n self.fields['passport_ser'].disabled = True\n self.fields['passport_num'].disabled = True\n self.fields['passport_date'].disabled = True\n self.fields['last_work_place'].disabled = True\n self.fields['last_work_place_region'].disabled = True\n self.fields['last_work_period'].disabled = True\n self.fields['registration_address'].disabled = True\n self.fields['place_of_birth'].disabled = True\n\n if self.instance:\n if not self.is_bound:\n try:\n region_code = self.instance.city.region.code\n if region_code:\n self.fields['region'].initial = region_code\n self.fields['city'].queryset = Cities.objects.filter(region=region_code).order_by('name')\n else:\n self.fields['city'].queryset = Cities.objects.none()\n except Exception as e:\n self.fields['city'].queryset = Cities.objects.none()\n\n self.helper.layout.append(\n Fieldset(\n 'Место работы',\n Div(Field('region',\n wrapper_class='col-md-2'),\n Field('city',\n wrapper_class='col-md-2'),\n Field('selling_office',\n wrapper_class='col-md-2'),\n Field('position',\n wrapper_class='col-md-3'),\n Field('start_work_date',\n wrapper_class='col-md-2'),\n Field('regulations',\n wrapper_class='col-md-1'),\n css_class='form-row')))\n self.helper.layout.append(\n Fieldset(\n 'Паспортные данные',\n Div(\n # Field('full_name', placeholder='', wrapper_class='col-md-5'),\n Field('last_name', placeholder='', wrapper_class='col-md-3'),\n Field('first_name', placeholder='', wrapper_class='col-md-3'),\n Field('middle_names', placeholder='', wrapper_class='col-md-3'),\n Field('sex', wrapper_class='col-md-1'),\n Field('birth_date', placeholder='ДД.ММ.ГГГГ', wrapper_class='col-md-2'),\n css_class='form-row'\n ),\n Div(\n Field('passport_ser', placeholder='',\n wrapper_class='col-md-2'),\n Field('passport_num', placeholder='',\n wrapper_class='col-md-2'),\n Field('passport_date', placeholder='ДД.ММ.ГГГГ',\n wrapper_class='col-md-2'),\n Field('place_of_birth', wrapper_class='col-md-2'),\n Field('registration_address', wrapper_class='col-md-4'),\n css_class='form-row'\n )\n )\n )\n self.helper.layout.append(\n Fieldset(\n 'Предыдущее место работы',\n Div(\n Field('last_work_place',\n wrapper_class='col-md-5'),\n Field('last_work_place_region',\n wrapper_class='col-md-4'),\n Field('last_work_period',\n wrapper_class='col-md-3'),\n css_class='form-row'\n ),\n )\n )\n # self.helper.layout.append(\n # Fieldset(\n # 'Адрес',\n # Div(\n # Field('registration_address',\n # wrapper_class='col-md-7'),\n # css_class='form-row'\n # ),\n # )\n # )\n # self.helper.layout.append(HTML(\"\"\" \"\"\"))\n else:\n pass\n\n def clean(self):\n cleaned_data = super().clean()\n city = cleaned_data.get(\"city\")\n region = cleaned_data.get(\"region\")\n if region and not city:\n raise forms.ValidationError(\"Выберите город из списка\")\n else:\n return cleaned_data\n\n class Meta:\n model = Candidate\n fields = ['city', 'position', 'selling_office', 'regulations', 'start_work_date',\n 'last_name', 'first_name', 'middle_names', 'sex', # 'full_name',\n 'birth_date', 'place_of_birth', 'registration_address',\n 'passport_ser', 'passport_num', 'passport_date',\n 'last_work_place', 'last_work_place_region', 'last_work_period', 'security_solution']\n\n\nclass CandidateUpdForm2 (forms.ModelForm):\n full_name2 = forms.CharField(label=\"ФИО в родительном падеже\", required=False,\n widget=forms.TextInput(attrs={'style': 'font-size: large'}))\n snils = forms.CharField(label=\"СНИЛС\", required=False,\n widget=forms.TextInput(attrs={'style': 'font-size: large'}))\n\n def __init__(self, *args, **kwargs):\n quest_id = kwargs.pop('quest_id', None)\n if quest_id:\n try:\n quest_code = Questionnaire.objects.values('code').get(id=quest_id)\n except Questionnaire.DoesNotExist:\n quest_code = ''\n\n super(CandidateUpdForm2, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n if quest_code['code'] == 'SNILS':\n self.helper.layout.append(\n Fieldset(\n 'Укажите данные для автоматической генерации документа',\n Div(\n Field('full_name2',\n wrapper_class='col-md-12'),\n css_class='form-row'\n )))\n elif quest_code['code'] == 'REQ_SNILS':\n self.helper.layout.append(\n Fieldset(\n 'Укажите данные для автоматической генерации документа',\n Div(\n Field('full_name2',\n wrapper_class='col-md-6'),\n Field('snils',\n wrapper_class='col-md-6'),\n css_class='form-row'\n )))\n # self.helper.layout.append(Div(Field('full_name2'), css_class='col-md-6'))\n # self.helper.layout.append(Div(Field('snils'), css_class='col-md-3'))\n self.helper.layout.append(HTML(\"\"\" \"\"\"))\n else:\n pass\n\n class Meta:\n model = Candidate\n fields = [\"full_name2\", \"snils\"]\n","sub_path":"candidate/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":29870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"82614607","text":"from django.http import Http404\n\nfrom datetime import date\n\nfrom rest_framework import viewsets, permissions, generics, filters, status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.pagination import PageNumberPagination\n\nfrom ..models import Task\nfrom .serializer import \\\n TaskDetailSerializer, \\\n TasksIndexSerializer, \\\n UserTasksSerializer, \\\n UpdateTaskStatusSerializer, \\\n CreateTaskSerializer\nfrom .permission import IsOwnerOrReadOnly\n\n\nclass TasksViewset(viewsets.ModelViewSet):\n permission_classes = (permissions.IsAdminUser,)\n queryset = Task.objects.all()\n serializer_class = TaskDetailSerializer\n\n\nclass TasksIndexAPIView(APIView):\n filter_backends = (filters.SearchFilter,)\n search_fields = ('name', 'description', 'creator__username')\n\n def get_queryset(self):\n return Task.objects.all()\n\n def filter_queryset(self, queryset):\n for obj in list(self.filter_backends):\n queryset = obj().filter_queryset(self.request, queryset, self)\n return queryset\n\n def check_if_tasks_are_delayed(self, queryset):\n checked_tasks = queryset\n for task in checked_tasks:\n if task.completion_date <= date.today() and task.status == 'Unfinished':\n task.warning_if_delayed = 'This task is delayed'\n task.save()\n else:\n task.warning_if_delayed = ''\n task.save()\n return checked_tasks\n\n def get(self, request):\n tasks_filter = self.filter_queryset(self.get_queryset())\n tasks_index = self.check_if_tasks_are_delayed(tasks_filter)\n pagination_class = PageNumberPagination()\n page = pagination_class.paginate_queryset(tasks_index, request)\n serializer = TasksIndexSerializer(page, many=True)\n return pagination_class.get_paginated_response(serializer.data)\n\n\nclass TaskDetailAPIView(APIView):\n\n def get_object(self, pk):\n try:\n return Task.objects.get(pk=pk)\n except Task.DoesNotExist:\n raise Http404\n\n def check_if_task_is_delayed(self, task):\n checked_task = task\n if checked_task.completion_date <= date.today() and checked_task.status == 'Unfinished':\n checked_task.warning_if_delayed = 'This task is delayed'\n checked_task.save()\n else:\n checked_task.warning_if_delayed = ''\n checked_task.save()\n return checked_task\n\n def get(self, request, pk):\n obtained_task = self.get_object(pk)\n task = self.check_if_task_is_delayed(obtained_task)\n serializer = TaskDetailSerializer(task)\n return Response(serializer.data)\n\n\nclass UserTasksAPIView(APIView):\n permission_classes = (permissions.IsAuthenticated,)\n\n def get_queryset(self):\n return Task.objects.filter(creator=self.request.user)\n\n def check_if_tasks_are_delayed(self, queryset):\n checked_tasks = queryset\n for task in checked_tasks:\n if task.completion_date <= date.today() and task.status == 'Unfinished':\n task.warning_if_delayed = 'This task is delayed'\n task.save()\n else:\n task.warning_if_delayed = ''\n task.save()\n return checked_tasks\n\n def get(self, request):\n user_tasks = self.get_queryset()\n tasks = self.check_if_tasks_are_delayed(user_tasks)\n serializer = UserTasksSerializer(tasks, many=True)\n return Response(serializer.data)\n\n def post(self, request):\n serializer = CreateTaskSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save(creator=self.request.user,)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass TaskUpdateStatusAPIView(generics.RetrieveUpdateAPIView):\n queryset = Task.objects.all()\n serializer_class = UpdateTaskStatusSerializer\n permission_classes = [IsOwnerOrReadOnly]\n\n","sub_path":"ToDo_list/tasks/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"334864496","text":"import matplotlib.pyplot as plt\nimport math\nimport numpy\n\nreports0 = []\ndirs0 = []\nsped0 = []\nreports1 = []\ndirs1 = []\nsped1 = []\n\nreports2 = []\ndirs2 = []\nsped2 = []\n\nfor line in open('data').readlines():\n r,d,s = line.split(\",\")\n if float(r) == 0:\n reports0.append( float(r) )\n dirs0.append( float(d) )\n sped0.append( float(s) )\n elif float(r) < 5:\n reports1.append( float(r) )\n dirs1.append( float(d) )\n sped1.append( float(s) )\n else:\n reports2.append( float(r) )\n dirs2.append( float(d) )\n sped2.append( float(s) )\n\nreports0 = numpy.array(reports0)\ndirs0 = numpy.array( dirs0 )\nsped0 = numpy.array( sped0 )\n\nreports1 = numpy.array(reports1)\ndirs1 = numpy.array( dirs1 )\nsped1 = numpy.array( sped1 )\n\nreports2 = numpy.array(reports2)\ndirs2 = numpy.array( dirs2 )\nsped2 = numpy.array( sped2 )\n\nimport matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(8,8))\nax = fig.add_subplot(111, polar=True)\n\n\ntheta_angles = numpy.arange(0, 360, 45)\ntheta_labels = ['E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE']\nax.set_thetagrids(angles=theta_angles, labels=theta_labels)\n#ax.set_rgrids(numpy.arange(0,30,5), angle=math.pi)\n\nax.set_title(\"SPC Tornado Watches in Iowa [1 Jan 2002 - 9 Jul 2011]\\nWatch Box Mean Wind [kts] and Tornado Reports\")\nax.scatter( - dirs0 + math.pi/2., sped0 / 0.514, marker='x', s=50, label='No Reports')\nax.scatter( - dirs1 + math.pi/2., sped1 / 0.514, marker='o', s=50, c='b', label='1-4')\nax.scatter( - dirs2 + math.pi/2., sped2 / 0.514, marker='o', s=50, c='r', label='5+')\nl = ax.legend(loc=(0.1,0.6))\n\n\nfig.savefig('test.ps')\nimport iemplot\niemplot.makefeature('test')","sub_path":"scripts/spc/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"404617116","text":"# framework for running the graders on our machines locally\n\nimport json\nfrom collections import namedtuple\nfrom contextlib import ExitStack\nimport random\n\nREPLAY_DIR = \"replays\" # relative to here, will be mkdired\n\n# interfaces\n\nCodeboxClass = []\n\nclass AbstractCodebox:\n HistoryEntry = namedtuple('HistoryEntry', 'event, kind, details')\n\n def __init__(self):\n self.hist = []\n self.keep_log = True\n self.alive = False\n\n def log(self, **kwargs):\n if self.keep_log: self.hist.append(self.HistoryEntry(**kwargs))\n\n def interaction_log(self):\n return self.hist\n \n def kill(self):\n if self.alive:\n self.alive = False\n self.destroy_box()\n err = self.get_stderr().strip()\n if err:\n # print(\"Program exited with error:\")\n print(err.decode())\n self.log(event='exit', kind='error', details=str(err))\n \n def restart(self):\n self.kill()\n self.initialize_box()\n self.alive = True\n self.log(event='restart', kind='ok', details=None)\n \n def write(self, data):\n if not self.alive:\n self.log(event='write', kind='skipped', details=None)\n return\n dumped = json.dumps(data)\n try:\n self.write_raw(dumped.encode() + b\"\\n\")\n self.log(event='write', kind='ok', details=dumped)\n except Exception as e:\n self.log(event='write', kind='error', details=str(e))\n self.kill()\n \n def read(self):\n if not self.alive:\n self.log(event='read', kind='skipped', details=None)\n return\n try:\n line = self.read_raw().strip()\n self.log(event='read', kind='ok', details=str(line))\n data = json.loads(line)\n return data\n except Exception as e:\n self.log(event='read', kind='error', details=str(e))\n self.kill()\n\n def __enter__(self):\n self.initialize_box()\n self.alive = True\n return self\n\n def __exit__(self, *args):\n self.kill()\n return False\n\ndef do_save_replay(game_name, replay_name, score, data):\n import os, time\n file_name = os.path.join(REPLAY_DIR, f\"{game_name}_{int(time.time())}_{score}_{replay_name}.json\")\n with open(file_name, \"w\") as f:\n f.write(json.dumps(data))\n\nclass OptGrader:\n def grade(self, inp, codebox):\n if inp['seed'] is None:\n inp['seed'] = random.randrange(1 << 30)\n\n with codebox.of_player_config(code=inp['code'], config=self.config) as cb:\n random.seed(inp['seed'])\n return self.optgrade(inp['gen'], cb)\n\n def test(self, source, gen, name=\"\", save_replay=False, seed=None, record_logs=False):\n player = {'code': open(source).read(), 'src_loc': source}\n\n if seed is None: seed = random.randrange(1 << 30)\n result = self.grade({'gen': gen, 'code': player, 'seed': seed}, Codebox)\n\n if not record_logs: del result['playerlogs']\n\n if save_replay:\n do_save_replay(self.name.lower(), name, result['summary'], result)\n else:\n print(result)\n \n def run(self):\n data = json.loads(input())\n task = json.loads(data['task'])\n gens = self.get_batch(task['gen'])\n res = [self.grade({ 'gen': gen, 'seed': seed, 'code': data['code']}, CodeboxClass[0]) for gen,seed in gens]\n\n print(json.dumps({\n 'summary': sum(r['summary'] for r in res),\n 'history': [r['history'] for r in res],\n 'playerlogs': [r['playerlogs'] for r in res],\n }))\n\nclass AIGrader:\n def grade(self, inp, codebox_cls):\n with ExitStack() as stack:\n players = [\n stack.enter_context(codebox_cls.of_player_config(\n code=player,\n config=self.config))\n for player in inp]\n result = self.aigrade(players)\n return result\n\n def test(self, sources, name=\"\", save_replay=True, record_logs=False):\n players = [{'code': open(src_loc).read(), 'src_loc': src_loc} for src_loc in sources]\n result = self.grade(players, Codebox)\n if not record_logs: del result['playerlogs']\n if save_replay:\n do_save_replay(self.name.lower(), name, max(x for x in result['summary']), result)\n else:\n print(result)\n\n def run(self):\n print(json.dumps(self.grade(json.loads(input()), CodeboxClass[0])))\n\n# sample competitor implementation, just runs file in place\n\nimport subprocess\nimport sys\nfrom threading import Timer\n\nclass Codebox(AbstractCodebox):\n def __init__(self, src_loc, config):\n super().__init__()\n self.config = config\n self.src_loc = src_loc\n self.timer_killed = False\n\n @classmethod\n def of_player_config(cls, code, config):\n return cls(code['src_loc'], config)\n\n def timer_kill(self):\n self.proc.kill()\n self.timer_killed = True\n\n def write_raw(self, data):\n try:\n t = Timer(self.config['timeout'], lambda: self.timer_kill())\n t.start()\n self.proc.stdin.write(data)\n self.proc.stdin.flush()\n finally:\n t.cancel()\n if self.timer_killed: raise Exception(\"timed out\")\n def read_raw(self):\n try:\n t = Timer(self.config['timeout'], lambda: self.timer_kill())\n t.start()\n return self.proc.stdout.readline()\n finally:\n t.cancel()\n if self.timer_killed: raise Exception(\"timed out\")\n def get_stderr(self):\n return self.proc.stderr.read()\n def initialize_box(self):\n self.proc = subprocess.Popen(\n [sys.executable, self.src_loc],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n def destroy_box(self):\n self.proc.kill()\n","sub_path":"Other/CMIMC/handout/local_test_framework.py","file_name":"local_test_framework.py","file_ext":"py","file_size_in_byte":5999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"58055174","text":"import json\nimport os, sys\nimport argparse\nimport pickle as pk\nimport gc\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport numpy as np\nsys.path.append('../../')\nsys.path.append('../pygcn/pygcn/')\nfrom tqdm import tqdm\n\n\nfrom torch.utils.data import DataLoader\nfrom mydataloader import *\nfrom helper import augment_bbox\n\npreprocessed_dire = '../../dataset/VRD/'\nsave_dire = './saved_model/'\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--epochs', type=int, default=10)\nparser.add_argument('--seed', type=int, default=42, help='Random seed.')\nparser.add_argument('--semantic_loss_weight', type=float, default=0.0005)\nargs = parser.parse_args()\n\npreprocessed_annotation_train = {}\npreprocessed_image_features_train = {}\npreprocessed_annotation_test = {}\npreprocessed_image_features_test = {}\n\ninfo_train = {}\ninfo_test = {}\n\nwith open(preprocessed_dire + 'preprocessed_annotation_train.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n preprocessed_annotation_train[img_name] = subSet\n except EOFError:\n break\nwith open(preprocessed_dire + 'preprocessed_image_features_train.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n preprocessed_image_features_train[img_name] = subSet\n except EOFError:\n break\nwith open(preprocessed_dire + 'preprocessed_annotation_test.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n preprocessed_annotation_test[img_name] = subSet\n except EOFError:\n break\nwith open(preprocessed_dire + 'preprocessed_image_features_test.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n preprocessed_image_features_test[img_name] = subSet\n except EOFError:\n break\n\nwith open(preprocessed_dire + 'info_train.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n info_train[img_name] = subSet\n except EOFError:\n break\nwith open(preprocessed_dire + 'info_test.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n info_test[img_name] = subSet\n except EOFError:\n break\n\n\ndef remove_tensor(info):\n info_clearn = []\n for pair in range(len(info)):\n info_clearn.append([])\n for iii in range(len(info[pair])):\n if iii == 0:\n info_clearn[-1].append(info[pair][iii][0])\n else:\n info_clearn[-1].append([])\n for jjj in range(len(info[pair][iii])):\n if jjj == 0:\n info_clearn[-1][-1].append(int(info[pair][iii][jjj][0]))\n else:\n info_clearn[-1][-1].append([])\n for kkk in range(len(info[pair][iii][jjj])):\n info_clearn[-1][-1][-1].append(int(info[pair][iii][jjj][kkk][0]))\n return info_clearn\n\n\nclass Relation_Pred(nn.Module):\n def __init__(self, MLP_hidden=30, num_relations=71):\n super(Relation_Pred, self).__init__()\n self.num_relations = num_relations\n\n self.num_features = 512\n self.num_labelvec = 300\n self.num_latent = 512\n\n\n self.MLP = nn.Sequential(nn.Linear(self.num_features + 2 * self.num_labelvec + 8, self.num_latent),\n nn.ReLU(),\n nn.Linear(self.num_latent, self.num_relations))\n\n def forward(self, inputs):\n\n prediction = self.MLP(inputs)\n return prediction\n\ndef semantic_loss(y_mlp):\n prob = torch.sigmoid(y_mlp)\n wmc_tmp = torch.zeros_like(prob)\n for i in range(y_mlp.shape[1]):\n one_situation = torch.ones_like(y_mlp).scatter_(1,torch.zeros_like(y_mlp[:,0]).fill_(i).unsqueeze(-1).long(),0)\n wmc_tmp[:,i] = torch.abs((one_situation - prob).prod(dim=1))\n #omp = 1.0 - prob\n #omp[:,i] = prob[:,i]\n #wmc_tmp[:,i] = omp.prod(dim=1)\n\n wmc_tmp = -1.0*torch.log(wmc_tmp.sum(dim=1))\n return wmc_tmp\n\n# Training\nnum_epoches = args.epochs\nlearning_rate = 0.001\nbatch_size = 1\nsemantic_loss_weight = args.semantic_loss_weight\nweg_name = '.weg'+str(semantic_loss_weight)\nseed_name = '.seed'+str(args.seed)\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\n\nmodel = Relation_Pred().cuda()\ncriterion = nn.CrossEntropyLoss()\n\n\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\ntrain_set_keys = list(preprocessed_annotation_train.keys())\ntest_set_keys = list(preprocessed_annotation_test.keys())\n\ntrain_set = VRD_dataset(train_set_keys, preprocessed_image_features_train, preprocessed_annotation_train, info_train)\ntrain_dataloader = DataLoader(train_set, batch_size=batch_size, shuffle=True, num_workers=0)\n\ntest_set = VRD_dataset_test(test_set_keys, preprocessed_image_features_test, preprocessed_annotation_test, info_test)\ntest_dataloader = DataLoader(test_set, batch_size=batch_size, shuffle=False, num_workers=0)\n\n\n\n# test dataset\ndef run_test(model_test, k=5):\n model_test.eval()\n with torch.no_grad():\n correct = 0\n total = 0\n avg_loss = None\n for i, batch in tqdm(enumerate(test_dataloader), total=len(test_dataloader)):\n x, y, info = batch\n x = x.squeeze(0).cuda()\n y = y.squeeze(0).cuda()\n info = remove_tensor(info)\n\n x = augment_bbox(x, info)\n\n prediction = model_test(x)\n loss = F.nll_loss(F.log_softmax(prediction,dim=1), y)\n if avg_loss is None:\n avg_loss = loss\n else:\n avg_loss += loss\n\n # _, predicted = torch.max(prediction.data, 1)\n _, predicted = torch.topk(prediction.data, k)\n pred = predicted.t()\n correct_num = pred.eq(y.view(1, -1).expand_as(pred))\n correct_k = correct_num[:k].view(-1).float().sum(0, keepdim=True)\n\n total += y.size(0)\n correct += correct_k[0]\n avg_loss = avg_loss / i\n acc = correct / total\n return avg_loss, acc\n\nloss_save = {}\nloss_save['train_avgloss_all'] = []\nloss_save['train_avgloss_ce'] = []\nloss_save['test_avgloss'] = []\nloss_save['train_acc'] = []\nloss_save['test_acc'] = []\nloss_by_iter = []\nceloss_by_iter = []\n\nmodel.train()\nbest_acc = 0\nfor iter in range(num_epoches):\n print('\\n Iteration: ', iter)\n correct = 0\n total = 0\n avg_loss_all = None\n avg_loss_ce = None\n for i, batch in tqdm(enumerate(train_dataloader), total=len(train_dataloader)):\n gc.collect()\n x, y, info = batch\n x = x.squeeze(0).cuda()\n y = y.squeeze(0).cuda()\n info = remove_tensor(info)\n\n x = augment_bbox(x, info)\n\n prediction = model(x)\n\n loss_entropy = F.nll_loss(F.log_softmax(prediction,dim=1), y)\n logic_loss = semantic_loss(prediction)\n loss = (loss_entropy + semantic_loss_weight * logic_loss).mean()\n\n loss_by_iter.append(float(loss))\n celoss_by_iter.append(float(loss_entropy))\n\n # calcuate the avg loss and accuracy\n if avg_loss_all is None:\n avg_loss_all = loss\n avg_loss_ce = loss_entropy\n else:\n avg_loss_all += loss\n avg_loss_ce += loss_entropy\n\n _, predicted = torch.max(prediction.data, 1)\n total += y.size(0)\n correct += (predicted == y).sum().item()\n\n # back propagation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n avg_loss_all = avg_loss_all / i\n avg_loss_ce = avg_loss_ce / i\n acc = correct / total\n loss_save['train_avgloss_all'].append(float(avg_loss_all))\n loss_save['train_avgloss_ce'].append(float(avg_loss_ce))\n loss_save['train_acc'].append(float(acc))\n print('Train Acc: {:0.4f} '.format(acc))\n print('Train AvgLoss_ALL: {:0.4f}'.format(avg_loss_all))\n print('Train AvgLoss_CE: {:0.4f}'.format(avg_loss_ce))\n\n if not os.path.exists(save_dire):\n os.mkdir(save_dire)\n\n # test model for this epoch\n test_avg_loss, test_acc = run_test(model)\n if test_acc > best_acc:\n best_acc = test_acc\n # save model for this epoch\n torch.save(model, save_dire + \"MLP{}{}.best\".format(seed_name,weg_name))\n torch.save(model, save_dire + \"MLP{}{}.latest\".format(seed_name,weg_name))\n \n loss_save['test_avgloss'].append(float(test_avg_loss))\n loss_save['test_acc'].append(float(test_acc))\n print('Test Acc: {:0.4f} '.format(test_acc) )\n print('Test AvgLoss_CE: {:0.4f}'.format(test_avg_loss))\n test_avg_loss, test_acc = run_test(model,k=1)\n print('Test Acc: {:0.4f} k=1'.format(test_acc) )\n print('Test AvgLoss_CE: {:0.4f} k=1'.format(test_avg_loss))\n\n # re-write the file\n json.dump(loss_save, open(save_dire + 'loss_save', 'w'), ensure_ascii=False)\n\n if not os.path.exists('./acc_loss/'):\n os.mkdir('./acc_loss/')\n json.dump(loss_save, open('./acc_loss/' + \"MLP{}{}.best\".format(seed_name,weg_name), 'w'),\n ensure_ascii=False)\n json.dump(loss_by_iter,\n open('./acc_loss/' + \"MLP{}{}.best\".format(seed_name,weg_name) + '.loss_by_iter',\n 'w'),\n ensure_ascii=False)\n json.dump(celoss_by_iter,\n open('./acc_loss/' + \"MLP{}{}.best\".format(seed_name,weg_name) + '.celoss_by_iter',\n 'w'),\n ensure_ascii=False)\n\nprint(f\"Best test acc: {max(loss_save['test_acc'])}, at epoch: {np.argmax(loss_save['test_acc'])}\")\n\n# load model to do the testing\nmodel_test = torch.load(save_dire + \"MLP{}{}.best\".format(seed_name,weg_name))\nmodel_test = model_test.cuda()\ntest_avg_loss, test_acc = run_test(model_test)\nprint('The final test avgloss: {:0.4f}; final test acc is: {:0.4f} k=5'.format(test_avg_loss, test_acc))\ntest_avg_loss, test_acc = run_test(model_test,k=1)\nprint('The final test avgloss: {:0.4f}; final test acc is: {:0.4f} k=1'.format(test_avg_loss, test_acc))","sub_path":"model/relation_prediction_semantic_loss/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"162250468","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('register', '0007_auto_20150611_0320'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='cliente',\n name='email',\n field=models.EmailField(max_length=254, default=datetime.datetime(2015, 6, 22, 13, 55, 46, 84872, tzinfo=utc)),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='proveedor',\n name='cliente',\n field=models.OneToOneField(to='register.Cliente'),\n ),\n ]\n","sub_path":"AQuienLlamo/register/migrations/0008_auto_20150622_1355.py","file_name":"0008_auto_20150622_1355.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"486361195","text":"from talon import Context, actions, ui, Module\nimport re\nimport os \nctx = Context()\nkey = actions.key\n\nextension_lang_map = {\n \"py\": \"python\",\n \"cs\": \"csharp\",\n \"cpp\": \"cplusplus\",\n \"h\": \"cplusplus\",\n \"talon\": \"talon\",\n \"gdb\": \"gdb\",\n \"md\": \"markdown\",\n \"sh\": \"bash\",\n \"go\": \"go\"\n}\n\n# The [^\\\\\\/] is specifically to avoid matching something like a .talon folder\n# that would otherwise cause the .talon file action to load\nforced_language = False\n\n@ctx.action_class('code')\nclass code_actions:\n def language(): \n result = \"\"\n if not forced_language:\n file_extension = actions.win.file_ext()\n file_name = actions.win.filename()\n\n if file_extension != \"\":\n result = file_extension\n #it should always be the last split...\n elif file_name != \"\" and \".\" in file_name:\n result = file_name.split(\".\")[-1]\n\n if result in extension_lang_map:\n result = extension_lang_map[result]\n \n #print(\"code.language: \" + result)\n return result\n\nmod = Module()\n\n#create a mode for each defined language\nfor __, lang in extension_lang_map.items():\n mod.mode(lang)\n\n@mod.action_class\nclass Actions:\n def code_set_language_mode(language: str):\n \"\"\"Sets the active language mode, and disables extension matching\"\"\"\n global forced_language\n for __, lang in extension_lang_map.items():\n if lang != language:\n actions.mode.disable(\"user.{}\".format(lang))\n else:\n actions.mode.enable(\"user.{}\".format(lang))\n\n forced_language = True\n\n def code_clear_language_mode():\n \"\"\"Clears the active language mode, and re-enables code.language: extension matching\"\"\"\n global forced_language\n forced_language = False\n\n for __, lang in extension_lang_map.items():\n actions.mode.disable(\"user.{}\".format(lang))\n\n\n ","sub_path":"code/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"475291275","text":"#!/usr/bin/python\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nfrom ansible.module_utils.basic import AnsibleModule\nimport os\nimport re\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['stableinterface'],\n 'supported_by': 'core'}\n\n\n# The AnsibleModule object\nmodule = None\n\nclass AnsibleModuleError(Exception):\n def __init__(self, results):\n self.results = results\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n param_file=dict(type='str'),\n script_file=dict(type='str')\n ),\n supports_check_mode=True\n )\n\n param_file = module.params['param_file']\n script_file = module.params['script_file']\n changed = False\n script_dict = dict()\n param_dict = dict()\n param_regex = re.compile(r\"^\\s*\\b\\w+\\b\\s+(\\w+)=(.*$)\")\n script_regex = re.compile(r\"\\${?\\s*\\w+\\s*}?\")\n filedata = ''\n\n if os.path.exists(param_file):\n if os.path.islink(param_file):\n param_file = os.path.realpath(param_file)\n if not os.access(param_file, os.R_OK) and not os.path.isfile(param_file):\n module.fail_json(msg=\"Destination %s not readable\" % (os.path.dirname(param_file)))\n else:\n if not os.path.exists(os.path.dirname(param_file)):\n try:\n os.stat(os.path.exists(param_file))\n except OSError as e:\n if \"permission denied\" in to_native(e).lower():\n module.fail_json(msg=\"Parameter's file directory %s is not accessible\"\\\n % (os.path.dirname(param_file)))\n module.fail_json(msg=\"Parameter's file directory %s does not exist\" % (os.path.dirname(param_file)))\n\n if os.path.exists(script_file):\n if os.path.islink(script_file):\n script_file = os.path.realpath(script_file)\n if not os.access(script_file, os.R_OK) and not os.access(script_file, os.W_OK)\\\n and not os.path.isfile(script_file):\n module.fail_json(msg=\"Destination %s not writable\" % (os.path.dirname(script_file)))\n else:\n if not os.path.exists(os.path.dirname(script_file)):\n try:\n os.stat(os.path.exists(script_file))\n except OSError as e:\n if \"permission denied\" in to_native(e).lower():\n module.fail_json(msg=\"Script's file directory %s is not accessible\"\\\n % (os.path.dirname(script_file)))\n module.fail_json(msg=\"Script's file directory %s does not exist\" % (os.path.dirname(script_file)))\n\n with open(param_file, 'r') as fd:\n for line in fd:\n result = param_regex.search(line)\n if result:\n param_dict[result.group(1).strip()] = result.group(2).strip('\\\"\\'')\n\n with open(script_file, 'r') as fd:\n for line in fd:\n result = script_regex.findall(line)\n if result:\n for var in result:\n if var not in script_dict:\n script_dict[re.sub(r'[${}]', '', var).strip()] = var.strip()\n\n if not param_dict:\n module.fail_json(msg=\"Module wasn't able to parse parameter's file, dictionary is empty\")\n\n if not script_dict:\n module.fail_json(msg=\"Module wasn't able to parse variable in script file, dictionary is empty\")\n\n try:\n with open(script_file, 'r') as fd:\n filedata = fd.read()\n for key in script_dict:\n filedata = filedata.replace(script_dict[key], param_dict[key])\n except KeyError:\n module.fail_json(msg=\"Variable name mismatching between parameters file and script file\")\n\n if not module.check_mode:\n with open(script_file, 'r+') as fd:\n fd.write(filedata)\n changed = True\n\n result = dict(changed=changed)\n module.exit_json(**result)\n\nif __name__ == '__main__':\n main()","sub_path":"params_to_script.py","file_name":"params_to_script.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"571102234","text":"import math\n\nimport pygame\nfrom pygame.sprite import Sprite\n\nfrom ecs import Component, System\nfrom scene import Scene, SceneManager\nfrom scenes.crash_results import CrashResultsScene\nfrom scenes.pause import PauseScene\nfrom utils import find_data_file\n\n\nclass GraphicComponent(Component):\n \"\"\"\n For visible entities that have a sprite.\n \"\"\"\n\n def __init__(self, sprite):\n metadata = {\"sprite\": sprite}\n Component.__init__(self, \"graphic\", metadata)\n\n\nclass PositionComponent(Component):\n \"\"\"\n For entities that exist somewhere on the coordinate grid\n (i.e., anything physically in the game world).\n \"\"\"\n\n def __init__(self, x, y):\n metadata = {\"x\": x, \"y\": y}\n Component.__init__(self, \"position\", metadata)\n\n\nclass PhysicsComponent(Component):\n \"\"\"\n For entities with some kind of physics-based movement.\n \"\"\"\n\n def __init__(self):\n metadata = {\"velocity\": 0, \"angle\": 0, \"acceleration\": 0}\n Component.__init__(self, \"physics\", metadata)\n\n\nclass RotationComponent(Component):\n \"\"\"\n For entities that rotate. Affects both graphics and physics.\n Maybe makes more sense as a RotationalVelocityComponent or something, that adds its speed to VelocityComponent's angle?\n \"\"\"\n\n def __init__(self, angle):\n metadata = {\"angle\": angle}\n Component.__init__(self, \"rotation\", metadata)\n\n\nclass GlidingComponent(Component):\n \"\"\"\n For any entity that requires gliding physics. Allows the GlidingSystem to find it.\n \"\"\"\n\n def __init__(self):\n Component.__init__(self, \"gliding\", {})\n\n\nclass GravityComponent(Component):\n \"\"\"\n For entities that should be affected by gravity.\n \"\"\"\n\n def __init__(self):\n Component.__init__(self, \"gravity\", {})\n\n\nclass PhysicsFrameResetSystem(System):\n def __init__(self):\n super().__init__()\n self.subscribe(\"physics_frame_reset\")\n\n def process(self, events, world):\n if world.find_component(\"context\")[\"paused\"]:\n return\n\n # If we haven't been asked to reset, don't reset\n events = self.pending()\n if not events:\n return\n\n # get entities that need reset\n physics_entities = set(world.filter(\"physics\"))\n\n for entity in physics_entities:\n\n # For now, this is the only thing that needs reset.\n # In in the future, we might also reset forces acting on the entity.\n entity.physics.acceleration = 0\n\n\nclass ForceSystem(System):\n def __init__(self):\n super().__init__()\n self.subscribe(\"physics_force\")\n\n def process(self, events, world):\n if world.find_component(\"context\")[\"paused\"]:\n return\n\n events = self.pending()\n physics_entities = set(world.filter(\"physics\"))\n\n for event in events:\n magnitude = event[\"magnitude\"]\n angle = event[\"angle\"]\n\n if magnitude == 0:\n continue\n\n for entity in physics_entities:\n if entity.physics.velocity == 0:\n entity.physics.angle = angle\n theta = math.radians(angle - entity.physics.angle)\n current_accel = entity.physics.acceleration\n\n new_accel = math.sqrt(\n pow(magnitude, 2)\n + pow(current_accel, 2)\n + 2 * magnitude * current_accel * math.cos(theta)\n ) * math.copysign(1, magnitude)\n new_angle = math.degrees(theta / 2)\n\n entity.physics.acceleration = new_accel\n entity.physics.angle += new_angle\n entity.physics.velocity += entity.physics.acceleration\n\n\nclass MovementSystem(System):\n def __init__(self):\n super().__init__()\n self.subscribe(\"move\")\n\n def process(self, events, world):\n if world.find_component(\"context\")[\"paused\"]:\n return\n\n # If we haven't been asked to move, don't move\n events = self.pending()\n if not events:\n return\n\n physics_entities = set(world.filter(\"physics\"))\n\n for entity in physics_entities:\n radians = math.radians(entity.physics.angle)\n speed = entity.physics.velocity\n\n xx = entity.position.x + math.cos(radians) * speed\n yy = entity.position.y + math.sin(radians) * speed\n\n # very simplistic gravity\n yy += 3\n\n entity.position.x = xx\n entity.position.y = yy\n\n\nclass GlidingSystem(System):\n def __init__(self):\n super().__init__()\n self.subscribe(\"glide\")\n self.angle_magnitude = 0.1\n\n def process(self, events, world):\n if world.find_component(\"context\")[\"paused\"]:\n return\n\n # If we haven't been asked to glide, don't glide\n events = self.pending()\n if not events:\n return\n\n gliders = world.filter(\"gliding\")\n\n # All gliders should have physics and rotation components\n for glider in gliders:\n\n # Trig math requires radians, so let's convert\n angle = glider.rotation.angle\n radians = math.radians(angle)\n magnitude = math.sin(radians) * self.angle_magnitude\n\n world.inject_event(\n {\"type\": \"physics_force\", \"magnitude\": magnitude, \"angle\": angle}\n )\n\n\nclass BackgroundComponent(Component):\n def __init__(self, image_path, y):\n metadata = {\n \"image\": pygame.image.load(find_data_file(image_path)),\n \"x\": 0,\n \"y\": y,\n }\n Component.__init__(self, \"background\", metadata)\n\n\nclass PlayerSprite(Sprite):\n def __init__(self, image_path):\n Sprite.__init__(self)\n\n self.image = pygame.image.load(find_data_file(image_path))\n self.rect = self.image.get_rect()\n\n\nclass CameraComponent(Component):\n def __init__(self, target_entity_id):\n metadata = {\n \"target_entity_id\": target_entity_id,\n \"x\": 0,\n \"y\": 0,\n }\n Component.__init__(self, \"camera\", metadata)\n\n\nclass CameraSystem(System):\n def __init__(self):\n super().__init__()\n\n def process(self, events, world):\n screen = world.find_component(\"context\")[\"screen\"]\n camera = world.find_component(\"camera\")\n player = world.get(camera[\"target_entity_id\"])\n\n x_max_off = screen.get_width() * 0.40\n x_min_off = screen.get_width() * 0.15\n\n y_top_off = screen.get_height() * 0.40\n y_bottom_off = screen.get_height() * 0.55\n\n # Keep the player with in the above bounds of the screen\n if camera.x <= player.position.x - x_max_off:\n camera.x = player.position.x - x_max_off\n if camera.x >= player.position.x - x_min_off:\n camera.x = player.position.x - x_min_off\n\n if camera.y >= player.position.y - y_top_off:\n camera.y = player.position.y - y_top_off\n if camera.y <= player.position.y - y_bottom_off:\n camera.y = player.position.y - y_bottom_off\n\n if camera.x < 0:\n camera.x = 0\n if camera.y > 0:\n camera.y = 0\n if camera.y < -2540:\n camera.y = -2540\n\n\ndef calculate_altitude(player, screen):\n sprite_height = player.graphic.sprite.image.get_height()\n return player.position.y - screen.get_height() + sprite_height\n\n\nclass GameScene(Scene):\n def __init__(self):\n self.font = pygame.font.Font(\n find_data_file(\"resources/dpcomic-font/DpcomicRegular-p3jD.ttf\"), 36\n )\n\n def setup(self, world):\n context = world.find_component(\"context\")\n screen = context[\"screen\"]\n\n # Create a sprite for the title\n self.help_message = pygame.sprite.Sprite()\n self.help_message.image = self.font.render(\n \"Press space to start flying\", 1, (240, 240, 240)\n )\n self.help_message.rect = self.help_message.image.get_rect(\n centerx=screen.get_width() // 2, centery=screen.get_height() // 2\n )\n\n # Player entity setup\n # player_entity = world.gen_entity()\n player_entity = world.find_entity(\"player\")\n player_entity.attach(\n GraphicComponent(PlayerSprite(\"resources/icarus_body.png\"))\n )\n player_entity.attach(PositionComponent(100, 0))\n player_entity.attach(PhysicsComponent())\n player_entity.attach(RotationComponent(0))\n # player_entity.attach(PlayerComponent())\n player_entity.attach(GlidingComponent())\n player_entity.attach(GravityComponent())\n\n # Scrolling background - layers defined by the y coord\n world.gen_entity().attach(BackgroundComponent(\"resources/bg_space.png\", -2540))\n world.gen_entity().attach(BackgroundComponent(\"resources/bg_space.png\", -2040))\n world.gen_entity().attach(\n BackgroundComponent(\"resources/bg_sky-space.png\", -1540)\n )\n world.gen_entity().attach(BackgroundComponent(\"resources/bg_sky.png\", -1040))\n world.gen_entity().attach(BackgroundComponent(\"resources/bg_sky.png\", -540))\n world.gen_entity().attach(BackgroundComponent(\"resources/bg_sky.png\", -40))\n world.gen_entity().attach(\n BackgroundComponent(\"resources/bg_cityscape.png\", 460)\n )\n\n # Create the camera\n camera_entity = world.gen_entity()\n camera_entity.attach(CameraComponent(player_entity.id))\n\n # System registration\n self.systems = [\n PhysicsFrameResetSystem(),\n ForceSystem(),\n MovementSystem(),\n GlidingSystem(),\n CameraSystem(),\n ]\n for sys in self.systems:\n world.register_system(sys)\n\n def update(self, events, world):\n context = world.find_component(\"context\")\n screen = context[\"screen\"]\n\n # There will only ever be one player entity, unless scope drastically changes\n player_entity = world.filter(\"player\")[0]\n\n # No physics until the player has jumped\n if player_entity.player.has_jumped:\n\n # First, clear out per-frame physics values\n world.inject_event({\"type\": \"physics_frame_reset\"})\n\n # TODO: Simulate gravity as a force, instead of just doing it in the movement system\n # world.inject_event({\"type\": \"physics_force\", \"magnitude\": 0, \"angle\": 90})\n\n # Then gliding, which translates rotation into acceleration\n world.inject_event({\"type\": \"glide\"})\n\n # Finally, we add movement after any events that could affect acceleration\n world.inject_event({\"type\": \"move\"})\n\n if calculate_altitude(player_entity, screen) > 0:\n for sys in self.systems:\n world.unregister_system(sys)\n return SceneManager.push(CrashResultsScene())\n\n world.process_all_systems(events)\n\n keys = pygame.key.get_pressed()\n\n # Before doing anything else, the player must jump off the cliff\n if not player_entity.player.has_jumped:\n\n if keys[pygame.K_SPACE]:\n\n # Tell everyone we've jumped\n player_entity.player.has_jumped = True\n\n # The jump itself\n world.inject_event(\n {\"type\": \"physics_force\", \"magnitude\": 5, \"angle\": -20}\n )\n\n # Start background music\n world.inject_event(\n {\n \"type\": \"sound\",\n \"action\": \"start\",\n \"sound\": \"background_music\",\n }\n )\n\n # We don't want to rotate before jumping.\n # TODO: or do we?\n else:\n\n # The player only has direct control over their angle from the ground.\n # Our rudimentary physics takes care of the rest.\n # Also, clamp the angle from straight up to straight down.\n if keys[pygame.K_RIGHT]:\n angle = player_entity.rotation.angle + 1\n player_entity.rotation.angle = min(angle, 90)\n if keys[pygame.K_LEFT]:\n angle = player_entity.rotation.angle - 1\n player_entity.rotation.angle = max(angle, -90)\n\n for event in events:\n # Use keyup here as a simple way to only trigger once and not repeatedly\n if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:\n return SceneManager.push(PauseScene())\n\n def render(self, world):\n context = world.find_component(\"context\")\n screen = context[\"screen\"]\n background = context[\"background\"]\n\n graphical_entities = world.filter(\"graphic\")\n player_entity = world.find_entity(\"player\")\n camera = world.find_component(\"camera\")\n\n # City background\n backgrounds = world.filter(\"background\")\n for background in backgrounds:\n background = background.background\n x = background.x - camera.x\n if x < -500:\n # TODO: does an offset help?\n background.x = camera.x # - (x + 500)\n if x > 0:\n # TODO: does an offset help?\n background.x = camera.x - 500 # + x\n y = background.y - camera.y\n screen.blit(background.image, (x, y))\n\n for entity in graphical_entities:\n # We're assuming all graphical entities also have a position and rotation.\n # TODO: Is there a better way to do this? Will there ever be a graphical entity WITHOUT a position/rotation?\n image = entity.graphic.sprite.image\n rotated_image = pygame.transform.rotate(image, entity.rotation.angle * -1)\n adjusted_x = entity.position.x - camera.x\n adjusted_y = entity.position.y - camera.y\n screen.blit(rotated_image, (adjusted_x, adjusted_y))\n\n # # text\n # text = self.font.render(\n # f\"image angle: {player_entity.rotation.angle}\", True, (10, 10, 10)\n # )\n # screen.blit(text, (10, 300))\n\n # text = self.font.render(\n # f\"vel angle: {player_entity.physics.angle}\", True, (10, 10, 10)\n # )\n # screen.blit(text, (10, 325))\n\n # text = self.font.render(\n # f\"vel magnitude: {player_entity.physics.velocity}\", True, (10, 10, 10)\n # )\n # screen.blit(text, (10, 350))\n\n # text = self.font.render(\n # f\"acc: {player_entity.physics.acceleration}\", True, (10, 10, 10)\n # )\n # screen.blit(text, (10, 375))\n\n # altitude = calculate_altitude(player_entity, screen)\n # text = self.font.render(f\"altitude: {altitude}\", True, (10, 10, 10))\n # screen.blit(text, (10, 450))\n\n text = self.font.render(\n f\"${player_entity.player.currency}\", True, (245, 245, 245)\n )\n screen.blit(text, (50, 50))\n\n if not player_entity.player.has_jumped:\n screen.blit(self.help_message.image, self.help_message.rect)\n\n def render_previous(self):\n return False\n\n def teardown(self, world):\n player = world.find_entity(\"player\")\n camera = world.find_entity(\"camera\")\n\n if player is not None:\n world.remove_entities([player, camera])\n else:\n world.remove_entities([camera])\n\n for sys in self.systems:\n world.unregister_system(sys)\n","sub_path":"scenes/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":15523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"480524671","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport pytest\n\nfrom enumnamecrawler.types import EnumElement, CrawlerCallbacks\nfrom enumnamecrawler.crawler import CrawlInstance\nfrom enumnamecrawler.valueassigner.increment import Incrementer\nfrom enumnamecrawler.lang.c import C_OutputCodeConfig, C_CodeCallbacks\n\n_EXPECT_DISCOVERED_MAIC_C = [\n\t\tEnumElement(\"TESTINPUT_DIVIDEND_NEGATIVE\", \"main.c\", 7),\n\t\tEnumElement(\"TESTINPUT_DIVISOR_NEGATIVE\", \"main.c\", 10),\n\t\tEnumElement(\"TESTINPUT_DIVIDE_BY_ZERO\", \"main.c\", 13),\n]\n\n_EXPECT_DISCOVERED_ERRORCODE_H = [\n\t\tEnumElement(\"TESTINPUT_DIVIDEND_NEGATIVE\", \"errorcode.h\", 4, -1),\n\t\tEnumElement(\"TESTINPUT_DIVISOR_NEGATIVE\", \"errorcode.h\", 5, -2),\n\t\tEnumElement(\"TESTINPUT_DIVIDE_BY_ZERO\", \"errorcode.h\", 6, -3),\n]\n\n_EXPECT_HEADER = [\n\t\t\"#ifndef _ERRORCODE_H_\",\n\t\t\"#define _ERRORCODE_H_ 1\",\n\t\t\"#ifdef __cplusplus\",\n\t\t\"extern \\\"C\\\" {\",\n\t\t\"#endif\",\n\t\t\"#define TESTINPUT_DIVIDE_BY_ZERO -1\",\n\t\t\"#define TESTINPUT_DIVIDEND_NEGATIVE -2\",\n\t\t\"#define TESTINPUT_DIVISOR_NEGATIVE -3\",\n\t\t\"char * errorcode_string(int c);\",\n\t\t\"#ifdef __cplusplus\",\n\t\t\"}\",\n\t\t\"#endif\",\n\t\t\"#endif\\t/* _ERRORCODE_H_ */\",\n]\n\n_EXPECT_STRINGER = [\n\t\t\"#include \\\"errorcode.h\\\"\",\n\t\t\"char * errorcode_string(int c) {\",\n\t\t\"switch(c) {\",\n\t\t\"case TESTINPUT_DIVIDE_BY_ZERO:\",\n\t\t\"return \\\"TESTINPUT_DIVIDE_BY_ZERO\\\";\",\n\t\t\"case TESTINPUT_DIVIDEND_NEGATIVE:\",\n\t\t\"return \\\"TESTINPUT_DIVIDEND_NEGATIVE\\\";\",\n\t\t\"case TESTINPUT_DIVISOR_NEGATIVE:\",\n\t\t\"return \\\"TESTINPUT_DIVISOR_NEGATIVE\\\";\",\n\t\t\"}\",\n\t\t\"return \\\"?\\\";\",\n\t\t\"}\",\n]\n\n_EXPECT_UNITTEST = [\n\t\t\"#include \",\n\t\t\"#include \\\"errorcode.h\\\"\",\n\t\t\"namespace {\",\n\t\t\"TEST(ErrorcodeTest, ToString) {\",\n\t\t\"EXPECT_STREQ(\\\"TESTINPUT_DIVIDE_BY_ZERO\\\", errorcode_string(TESTINPUT_DIVIDE_BY_ZERO));\",\n\t\t\"EXPECT_STREQ(\\\"TESTINPUT_DIVIDEND_NEGATIVE\\\", errorcode_string(TESTINPUT_DIVIDEND_NEGATIVE));\",\n\t\t\"EXPECT_STREQ(\\\"TESTINPUT_DIVISOR_NEGATIVE\\\", errorcode_string(TESTINPUT_DIVISOR_NEGATIVE));\",\n\t\t\"}\",\n\t\t\"}\",\n]\n\n\n@pytest.fixture\ndef bogus_callbacks_with_unittest():\n\toutput_config = C_OutputCodeConfig(\"/dev/proj/header.h\", \"/dev/proj/stringer.c\", \"/dev/proj/unittest.c\")\n\treturn C_CodeCallbacks(\"TESTINPUT\", output_config)\n\n\n@pytest.fixture\ndef bogus_output_config_without_unittest():\n\treturn C_OutputCodeConfig(\"/dev/proj/header.h\", \"/dev/proj/stringer.c\")\n\n\n@pytest.fixture\ndef bogus_callbacks_without_unittest(bogus_output_config_without_unittest):\n\toutput_config = bogus_output_config_without_unittest\n\treturn C_CodeCallbacks(\"TESTINPUT\", output_config)\n\n\ndef get_testoutput_paths():\n\tbasefolder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\"))\n\theader_path = os.path.join(basefolder, \"errorcode.h\")\n\tstringer_path = os.path.join(basefolder, \"errorcode.c\")\n\tunittest_path = os.path.join(basefolder, \"errorcode_test.cc\")\n\treturn (header_path, stringer_path, unittest_path)\n\n\n@pytest.fixture\ndef callbacks_with_unittest():\n\theader_path, stringer_path, unittest_path = get_testoutput_paths()\n\toutput_config = C_OutputCodeConfig(header_path, stringer_path, unittest_path)\n\treturn C_CodeCallbacks(\"TESTINPUT\", output_config)\n\n\n@pytest.fixture\ndef callbacks_with_unittest_ignore_gen():\n\theader_path, stringer_path, unittest_path = get_testoutput_paths()\n\toutput_config = C_OutputCodeConfig(header_path, stringer_path, unittest_path)\n\treturn C_CodeCallbacks(\"TESTINPUT\", output_config, codefile_ignore_patterns=(\"gen\", ))\n\n\n@pytest.fixture\ndef callbacks_without_unittest_ignore_gen():\n\theader_path, stringer_path, _unittest_path = get_testoutput_paths()\n\toutput_config = C_OutputCodeConfig(header_path, stringer_path)\n\treturn C_CodeCallbacks(\"TESTINPUT\", output_config, codefile_ignore_patterns=(\"gen\", ))\n\n\ndef test_C_OutputCodeConfig_include_path_1():\n\toutput_config = C_OutputCodeConfig(\"/home/d/project/include/proj/header.h\", \"/home/d/project/src/stringer.c\")\n\tassert output_config.include_path == \"proj/header.h\"\n\toutput_config.include_path = \"abc.h\"\n\tassert output_config.include_path == \"abc.h\"\n\n\ndef test_C_OutputCodeConfig_include_path_2():\n\toutput_config = C_OutputCodeConfig(\"/home/d/project/errcode.h\", \"/home/d/project/errcode.c\")\n\tassert output_config.include_path == \"errcode.h\"\n\n\ndef test_C_OutputCodeConfig_include_guard_symbol(bogus_output_config_without_unittest):\n\toutput_config = bogus_output_config_without_unittest\n\tassert output_config.include_guard_symbol == \"_HEADER_H_\"\n\toutput_config.include_guard_symbol = \"MY_HEADER_H\"\n\tassert output_config.include_guard_symbol == \"MY_HEADER_H\"\n\n\ndef test_C_OutputCodeConfig_stringer_func_name(bogus_output_config_without_unittest):\n\toutput_config = bogus_output_config_without_unittest\n\tassert output_config.stringer_func_name == \"header_string\"\n\toutput_config.stringer_func_name = \"enum_to_string\"\n\tassert output_config.stringer_func_name == \"enum_to_string\"\n\n\ndef test_C_OutputCodeConfig_testcase_name():\n\toutput_config = C_OutputCodeConfig(\"/dev/proj/enum_def.h\", \"/dev/proj/enum_stringer.c\")\n\tassert output_config.testcase_name == \"EnumDefTest\"\n\toutput_config.testcase_name = \"MyEnumTest\"\n\tassert output_config.testcase_name == \"MyEnumTest\"\n\n\ndef test_C_CodeCallbacks_outputpath_check_1(bogus_callbacks_without_unittest):\n\tcallbacks = bogus_callbacks_without_unittest\n\tassert callbacks.outputpath_check(\"/dev/proj/header.h\")\n\tassert callbacks.outputpath_check(\"/dev/proj/stringer.c\")\n\tassert not callbacks.outputpath_check(\"/dev/proj/unittest.c\")\n\tassert not callbacks.outputpath_check(\"/dev/proj/main.c\")\n\n\ndef test_C_CodeCallbacks_outputpath_check_2(bogus_callbacks_with_unittest):\n\tcallbacks = bogus_callbacks_with_unittest\n\tassert callbacks.outputpath_check(\"/dev/proj/header.h\")\n\tassert callbacks.outputpath_check(\"/dev/proj/stringer.c\")\n\tassert callbacks.outputpath_check(\"/dev/proj/unittest.c\")\n\tassert not callbacks.outputpath_check(\"/dev/proj/main.c\")\n\n\ndef test_C_CodeCallbacks_codefilepath_filter_1(callbacks_without_unittest_ignore_gen):\n\tcallbacks = callbacks_without_unittest_ignore_gen\n\tassert callbacks.codefilepath_filter(\"/dev/proj/gen.c\")\n\tassert callbacks.codefilepath_filter(\"/dev/proj/gen.cc\")\n\tassert callbacks.codefilepath_filter(\"/dev/proj/function.cpp\")\n\tbasefolder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\"))\n\tassert callbacks.codefilepath_filter(basefolder)\n\tassert not callbacks.codefilepath_filter(os.path.join(basefolder, \"gen\"))\n\n\ndef test_C_CodeCallbacks_codefilepath_filter_2(callbacks_with_unittest):\n\tcallbacks = callbacks_with_unittest\n\tassert callbacks.codefilepath_filter(\"/dev/proj/function.c\")\n\tassert callbacks.codefilepath_filter(\"/dev/proj/function.cc\")\n\tassert callbacks.codefilepath_filter(\"/dev/proj/function.cpp\")\n\tbasefolder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\"))\n\tassert callbacks.codefilepath_filter(basefolder)\n\tassert callbacks.codefilepath_filter(os.path.join(basefolder, \"gen\"))\n\tassert not callbacks.codefilepath_filter(\"/dev/proj/function.py\")\n\tassert not callbacks.codefilepath_filter(\"/dev/proj/function.o\")\n\tassert not callbacks.codefilepath_filter(\"/dev/proj/function.so\")\n\n\ndef test_C_CodeCallbacks_enumelement_discover_1(callbacks_with_unittest):\n\tcallbacks = callbacks_with_unittest\n\tfilepath = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\", \"main.c\"))\n\twith open(filepath, \"r\") as fp:\n\t\tdiscovered = list(callbacks.enumelement_discover(fp, \"main.c\"))\n\tassert _EXPECT_DISCOVERED_MAIC_C == discovered\n\n\ndef test_C_CodeCallbacks_enumelement_discover_2(callbacks_with_unittest):\n\tcallbacks = callbacks_with_unittest\n\tfilepath = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\", \"gen\", \"errorcode.h\"))\n\twith open(filepath, \"r\") as fp:\n\t\tdiscovered = list(callbacks.enumelement_discover(fp, \"errorcode.h\"))\n\tassert _EXPECT_DISCOVERED_ERRORCODE_H == discovered\n\n\ndef load_generated_file(n):\n\tp = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\", n))\n\twith open(p, \"r\") as fp:\n\t\tfor l in fp:\n\t\t\tl = l.strip()\n\t\t\tif l:\n\t\t\t\tyield l\n\n\ndef test_C_CodeCallbacks_run_1(callbacks_without_unittest_ignore_gen):\n\tcodecallbacks = callbacks_without_unittest_ignore_gen\n\tassigner = Incrementer(-1, -1)\n\tcallbacks = CrawlerCallbacks(\n\t\t\tcodecallbacks.outputpath_check,\n\t\t\tcodecallbacks.codefilepath_filter,\n\t\t\tcodecallbacks.enumelement_discover,\n\t\t\tassigner,\n\t\t\tcodecallbacks.codemap_write,\n\t)\n\tbasefolder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\"))\n\ttry:\n\t\tos.unlink(os.path.join(basefolder, \"errorcode.h\"))\n\texcept Exception:\n\t\tpass\n\tcrawler = CrawlInstance(basefolder, callbacks)\n\tcrawler.run()\n\tassert _EXPECT_HEADER == list(load_generated_file(\"errorcode.h\"))\n\tassert _EXPECT_STRINGER == list(load_generated_file(\"errorcode.c\"))\n\n\ndef test_C_CodeCallbacks_run_2(callbacks_with_unittest_ignore_gen):\n\tcodecallbacks = callbacks_with_unittest_ignore_gen\n\tassigner = Incrementer(-1, -1)\n\tcallbacks = CrawlerCallbacks(\n\t\t\tcodecallbacks.outputpath_check,\n\t\t\tcodecallbacks.codefilepath_filter,\n\t\t\tcodecallbacks.enumelement_discover,\n\t\t\tassigner,\n\t\t\tcodecallbacks.codemap_write,\n\t)\n\tbasefolder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\"))\n\ttry:\n\t\tos.unlink(os.path.join(basefolder, \"errorcode.h\"))\n\texcept Exception:\n\t\tpass\n\tcrawler = CrawlInstance(basefolder, callbacks)\n\tcrawler.run()\n\tassert _EXPECT_HEADER == list(load_generated_file(\"errorcode.h\"))\n\tassert _EXPECT_STRINGER == list(load_generated_file(\"errorcode.c\"))\n\tassert _EXPECT_UNITTEST == list(load_generated_file(\"errorcode_test.cc\"))\n","sub_path":"enumnamecrawlertests/lang/c/c_test.py","file_name":"c_test.py","file_ext":"py","file_size_in_byte":9442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"221813424","text":"import sys\n\n\nclass Student:\n\toperate_list = ['get_name', 'get_age']\n\tCLASS = '六班'\n\t\n\tdef __init__(self, name, age, gender, ident):\n\t\tself.name = name\n\t\tself.age = age\n\t\tself.gender = gender\n\t\tself.ident = ident\n\t\t\n\tdef get_name(self):\n\t\t# return '学生:%s' % self.name\n\t\tprint(\"这是一名学生\")\n\t\t\n\tdef get_age(self):\n\t\treturn '年龄:%s' % self.age\n\t\t# print(\"学生年龄为20岁\")\n\t\n\t# def modify_age(self, age):\n\t# \tself.age = age\n\t#\n\t# @staticmethod\n\t# def file():\n\t# \treturn sys.modules[__name__]\n\n\nif __name__ == \"__main__\":\n\ts1 = Student('李志', 20, '男', 'Student')\n\tprint(s1)\n\tprint(s1.get_age())\n\t\n\n\n\n\n\t","sub_path":"re_st/student_project/core/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"134989453","text":"# tests/test_game.py\nimport unittest\nimport string\nfrom game import Game\n\nclass TestGame(unittest.TestCase):\n def test_game_initialization(self):\n new_game = Game()\n grid = new_game.grid\n self.assertIsInstance(grid, list)\n self.assertEqual(len(grid), 9)\n for letter in grid:\n self.assertIn(letter, string.ascii_uppercase)\n\n def test_empty_word_is_invalid(self):\n new_game = Game()\n self.assertIs(new_game.is_valid(''), False)\n\n def test_is_valid(self):\n new_game = Game()\n new_game.grid = list('KWEUEAKRZ') # Force the grid to a test case:\n self.assertIs(new_game.is_valid('EUREKA'), True)\n self.assertEqual(new_game.grid, list('KWEUEAKRZ')) # Make sure the grid remained untouched\n\n def test_is_invalid(self):\n new_game = Game()\n new_game.grid = list('KWEUEAKRZ') # Force the grid to a test case:\n self.assertIs(new_game.is_valid('SANDWICH'), False)\n self.assertEqual(new_game.grid, list('KWEUEAKRZ')) # Make sure the grid remained untouched\n\n def test_unknown_word_is_invalid(self):\n new_game = Game()\n new_game.grid = list('KWIENFUQW') # Force the grid to a test case:\n self.assertIs(new_game.is_valid('FEUN'), False)\n self.assertEqual(new_game.grid, list('KWIENFUQW')) # Make sure the grid remained untouched\n","sub_path":"tests/test_game.py","file_name":"test_game.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"400452521","text":"# Copyright 2019,2021 IBM 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.\nfrom packaging import version\n\ntry:\n import snapml # type: ignore\n\n snapml_version = version.parse(getattr(snapml, \"__version__\"))\n\nexcept ImportError:\n snapml_version = None\n\nimport lale.datasets.data_schemas\nimport lale.docstrings\nimport lale.operators\n\n\nclass _SnapSVMClassifierImpl:\n def __init__(self, **hyperparams):\n assert (\n snapml_version is not None\n ), \"\"\"Your Python environment does not have snapml installed. Install using: pip install snapml\"\"\"\n\n if snapml_version <= version.Version(\"1.8.0\") and \"loss\" in hyperparams:\n del hyperparams[\"loss\"]\n\n if hyperparams.get(\"device_ids\", None) is None:\n hyperparams[\"device_ids\"] = [0]\n\n self._wrapped_model = snapml.SnapSVMClassifier(**hyperparams)\n\n def fit(self, X, y, **fit_params):\n X = lale.datasets.data_schemas.strip_schema(X)\n y = lale.datasets.data_schemas.strip_schema(y)\n self._wrapped_model.fit(X, y, **fit_params)\n return self\n\n def predict(self, X, **predict_params):\n X = lale.datasets.data_schemas.strip_schema(X)\n return self._wrapped_model.predict(X, **predict_params)\n\n def decision_function(self, X, **decision_function_params):\n X = lale.datasets.data_schemas.strip_schema(X)\n return self._wrapped_model.decision_function(X, **decision_function_params)\n\n\n_hyperparams_schema = {\n \"description\": \"Hyperparameter schema.\",\n \"allOf\": [\n {\n \"description\": \"This first sub-object lists all constructor arguments with their types, one at a time, omitting cross-argument constraints.\",\n \"type\": \"object\",\n \"relevantToOptimizer\": [\n \"fit_intercept\",\n \"regularizer\",\n \"max_iter\",\n \"kernel\",\n \"gamma\",\n \"n_components\",\n ],\n \"additionalProperties\": False,\n \"properties\": {\n \"max_iter\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"minimumForOptimizer\": 10,\n \"maximumForOptimizer\": 1000,\n \"default\": 100,\n \"description\": \"Maximum number of iterations used by the solver to converge.\",\n },\n \"regularizer\": {\n \"type\": \"number\",\n \"minimum\": 0.0,\n \"default\": 1.0,\n \"exclusiveMinimum\": True,\n \"minimumForOptimizer\": 1.0,\n \"maximumForOptimizer\": 100.0,\n \"distribution\": \"uniform\",\n \"description\": \"Larger regularization values imply stronger regularization.\",\n },\n \"use_gpu\": {\n \"type\": \"boolean\",\n \"default\": False,\n \"description\": \"Use GPU Acceleration.\",\n },\n \"device_ids\": {\n \"anyOf\": [\n {\"description\": \"Use [0].\", \"enum\": [None]},\n {\"type\": \"array\", \"items\": {\"type\": \"integer\"}},\n ],\n \"default\": None,\n \"description\": \"Device IDs of the GPUs which will be used when GPU acceleration is enabled.\",\n },\n \"class_weight\": {\n \"enum\": [\"balanced\", None],\n \"default\": None,\n \"description\": \"If set to 'balanced' samples weights will be applied to account for class imbalance, otherwise no sample weights will be used.\",\n },\n \"verbose\": {\n \"type\": \"boolean\",\n \"default\": False,\n \"description\": \"If True, it prints the training cost, one per iteration. Warning: this will increase the training time. For performance evaluation, use verbose=False.\",\n },\n \"n_jobs\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"default\": 1,\n \"description\": \"The number of threads used for running the training. The value of this parameter should be a multiple of 32 if the training is performed on GPU (use_gpu=True).\",\n },\n \"tol\": {\n \"type\": \"number\",\n \"minimum\": 0.0,\n \"default\": 0.001,\n \"exclusiveMinimum\": True,\n \"description\": \"The tolerance parameter. Training will finish when maximum change in model coefficients is less than tol.\",\n },\n \"generate_training_history\": {\n \"enum\": [\"summary\", \"full\", None],\n \"default\": None,\n \"description\": \"Determines the level of summary statistics that are generated during training.\",\n },\n \"fit_intercept\": {\n \"type\": \"boolean\",\n \"default\": True,\n \"description\": \"Add bias term -- note, may affect speed of convergence, especially for sparse datasets.\",\n },\n \"intercept_scaling\": {\n \"type\": \"number\",\n \"minimum\": 0.0,\n \"default\": 1.0,\n \"exclusiveMinimum\": True,\n \"description\": \"Scaling of bias term. The inclusion of a bias term is implemented by appending an additional feature to the dataset. This feature has a constant value, that can be set using this parameter.\",\n },\n \"normalize\": {\n \"type\": \"boolean\",\n \"default\": True,\n \"description\": \"Normalize rows of dataset (recommended for fast convergence).\",\n },\n \"kernel\": {\n \"enum\": [\"rbf\", \"linear\"],\n \"default\": \"rbf\",\n \"description\": \"Approximate feature map of a specified kernel function.\",\n },\n \"gamma\": {\n \"type\": \"number\",\n \"minimum\": 0.0,\n \"default\": 1.0,\n \"exclusiveMinimum\": True,\n \"minimumForOptimizer\": 0.01,\n \"maximumForOptimizer\": 100.0,\n \"distribution\": \"uniform\",\n \"description\": \"Parameter of RBF kernel: exp(-gamma * x^2).\",\n },\n \"n_components\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"default\": 100,\n \"minimumForOptimizer\": 10,\n \"maximumForOptimizer\": 200,\n \"description\": \"Dimensionality of the feature space when approximating a kernel function.\",\n },\n \"random_state\": {\n \"description\": \"Seed of pseudo-random number generator.\",\n \"anyOf\": [\n {\n \"description\": \"RandomState used by np.random\",\n \"enum\": [None],\n },\n {\"description\": \"Explicit seed.\", \"type\": \"integer\"},\n ],\n \"default\": None,\n },\n },\n },\n ],\n}\n\n_input_fit_schema = {\n \"description\": \"Fit the model according to the given train dataset.\",\n \"type\": \"object\",\n \"required\": [\"X\", \"y\"],\n \"properties\": {\n \"X\": {\n \"type\": \"array\",\n \"description\": \"The outer array is over samples aka rows.\",\n \"items\": {\n \"type\": \"array\",\n \"description\": \"The inner array is over features aka columns.\",\n \"items\": {\"type\": \"number\"},\n },\n },\n \"y\": {\n \"description\": \"The classes.\",\n \"anyOf\": [\n {\"type\": \"array\", \"items\": {\"type\": \"number\"}},\n {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n {\"type\": \"array\", \"items\": {\"type\": \"boolean\"}},\n ],\n },\n },\n}\n\n_input_predict_schema = {\n \"type\": \"object\",\n \"required\": [\"X\"],\n \"properties\": {\n \"X\": {\n \"type\": \"array\",\n \"description\": \"The outer array is over samples aka rows.\",\n \"items\": {\n \"type\": \"array\",\n \"description\": \"The inner array is over features aka columns.\",\n \"items\": {\"type\": \"number\"},\n },\n },\n \"n_jobs\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"default\": 0,\n \"description\": \"Number of threads used to run inference. By default inference runs with maximum number of available threads.\",\n },\n },\n}\n\n_output_predict_schema = {\n \"description\": \"The predicted classes.\",\n \"anyOf\": [\n {\"type\": \"array\", \"items\": {\"type\": \"number\"}},\n {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n {\"type\": \"array\", \"items\": {\"type\": \"boolean\"}},\n ],\n}\n\n_input_decision_function_schema = {\n \"type\": \"object\",\n \"properties\": {\n \"X\": {\n \"type\": \"array\",\n \"description\": \"The outer array is over samples aka rows.\",\n \"items\": {\n \"type\": \"array\",\n \"description\": \"The inner array is over features aka columns.\",\n \"items\": {\"type\": \"number\"},\n },\n },\n \"n_jobs\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"default\": 0,\n \"description\": \"Number of threads used to run inference. By default inference runs with maximum number of available threads.\",\n },\n },\n}\n\n_output_decision_function_schema = {\n \"type\": \"array\",\n \"description\": \"The outer array is over samples aka rows.\",\n \"items\": {\n \"type\": \"array\",\n \"description\": \"The inner array contains confidence scores corresponding to each class.\",\n \"items\": {\"type\": \"number\"},\n },\n}\n\n_combined_schemas = {\n \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n \"description\": \"\"\"`Support Vector Machine`_ from `Snap ML`_.\n\n.. _`Support Vector Machine`: https://snapml.readthedocs.io/en/latest/#snapml.SupportVectorMachine\n.. _`Snap ML`: https://www.zurich.ibm.com/snapml/\n\"\"\",\n \"documentation_url\": \"https://lale.readthedocs.io/en/latest/modules/lale.lib.snapml.snap_support_vector_machine.html\",\n \"import_from\": \"snapml\",\n \"type\": \"object\",\n \"tags\": {\"pre\": [], \"op\": [\"estimator\", \"classifier\"], \"post\": []},\n \"properties\": {\n \"hyperparams\": _hyperparams_schema,\n \"input_fit\": _input_fit_schema,\n \"input_predict\": _input_predict_schema,\n \"output_predict\": _output_predict_schema,\n \"input_decision_function\": _input_decision_function_schema,\n \"output_decision_function\": _output_decision_function_schema,\n },\n}\n\n\nSnapSVMClassifier = lale.operators.make_operator(\n _SnapSVMClassifierImpl, _combined_schemas\n)\n\nif snapml_version is not None and snapml_version > version.Version(\"1.8.0\"): # type: ignore # noqa\n from lale.schemas import Enum\n\n SnapSVMClassifier = SnapSVMClassifier.customize_schema(\n loss=Enum(\n desc=\"\"\"The loss function that will be used for training.\"\"\",\n values=[\"hinge\", \"squared_hinge\"],\n default=\"hinge\",\n forOptimizer=True,\n ),\n set_as_available=True,\n )\n\nlale.docstrings.set_docstrings(SnapSVMClassifier)\n","sub_path":"lale/lib/snapml/snap_svm_classifier.py","file_name":"snap_svm_classifier.py","file_ext":"py","file_size_in_byte":12175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"537188497","text":"\"\"\"\nConfiguration for sphinx\n\"\"\"\nimport os\nimport sys\n\nprint(os.getcwd())\n\nsys.path.insert(0, 'bardolph/controller')\nsys.path.insert(0, 'bardolph/fakes')\nsys.path.insert(0, 'bardolph/lib')\nsys.path.insert(0, 'bardolph/parser')\nsys.path.append('.')\nfrom bardolph.pygments import bardolph_lexer\n\nproject = 'Bardolph'\ncopyright = '2022, Al Fontes'\nauthor = 'Al Fontes'\n\nfrom sphinx.highlighting import lexers\nlexers ['lightbulb'] = bardolph_lexer.BardolphLexer()\nextensions = []\n\ntemplates_path = ['_templates']\n\nexclude_patterns = []\n\nhtml_favicon = 'www/logo_ico.png'\nhtml_static_path = ['web/static']\nhtml_theme = 'sphinx_rtd_theme'\nhtml_theme_options = {\n 'analytics_id': 'UA-162715494-1'\n}\n","sub_path":"conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"67704662","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 25 10:46:39 2020\n\n@author: qiaonan\n\"\"\"\nimport torch\nfrom torch.distributions.categorical import Categorical\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport torch.optim as optim\n\nimport seaborn as sb\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom bandit import BernoulliBanditDependantEnv\n\n#%% model\nclass AC_Net(nn.Module):\n def __init__(self, in_size, h_size, d_size, action_size):\n # d_size: output densly connected layer size\n # out_size: number of actions\n # default to one layer, one batch\n super(AC_Net, self).__init__()\n \n self.gru_num_layers = 1\n self.gru = nn.GRU(in_size, h_size, self.gru_num_layers)\n self.in_size, self.h_size, self.d_size, self.action_size \\\n = in_size, h_size, d_size, action_size\n self.reset_h()\n # # value net\n # self.v1 = nn.Linear(h_size,d_size)\n # self.v2 = nn.Linear(h_size,1)\n # policy net\n self.p1 = nn.Linear(h_size,d_size)\n self.p2 = nn.Linear(d_size,action_size)\n \n def reset_h(self):\n # def\n self.h = torch.zeros((self.gru_num_layers,1,self.h_size))\n \n def forward(self,x):\n # input x shape (1,1,h_size)\n x, self.h = self.gru(x,self.h)\n x = x[0,:,:]\n \n # # value net\n # v = F.leaky_relu(self.v1(x))\n # v = F.leaky_relu(self.v2(v))\n \n # action net\n p = F.leaky_relu(self.p1(x))\n logits = self.p2(p)\n cat = Categorical(logits=logits[0,:])\n \n # return v,cat\n return cat\n \n \n \n \n \n#%% material\n\n\n\n\n#env = BernoulliBanditDependantEnv()\n#m = Categorical(torch.tensor([ [0.25, 0.25],[ 0.25, 0.25] ]))\n\n#env = BernoulliBanditEnv(2)\n\n#env.reset_task(env.sample_tasks(1)[0])\n\n# policy_loss = (-self.log_probs * advantage.detach()).mean()\n# critic_loss = 0.5 * advantage.pow(2).mean()\n# entropy is summed not averaged\n## coef might be 0.01\n# ac_loss = actor_loss + critic_loss - coeff*entropy_loss\n\n#%% train\n# params\ntotal_eps_count = 20000\neps_len = 100\nd_size = 12\n\n# according to paper\nh_size = 48\n# beta_v = 0.05\nlr = 0.001\n# gamma = 0.8\n\nenv = BernoulliBanditDependantEnv() # two arm\nac_net = AC_Net(2,h_size,d_size,2) #two input, two output actions\noptimizer = optim.Adam(ac_net.parameters(), lr=lr)\n#beta_e annealing\nbeta_es = np.linspace(1,0,total_eps_count)\n\nfor i in range(total_eps_count):\n if (i+1) % 100 == 0:\n print(f'{i+1}th episode')\n \n beta_e = beta_es[i]\n env.reset_task(env.sample_tasks()[0])\n env.reset()\n # reset hidden state of ac_net\n ac_net.reset_h()\n \n a = env.action_space.sample()\n _, r, _, _ = env.step(a)\n \n eps = []\n v = 0\n for j in range(eps_len):\n item = torch.tensor([[[r,a]]],dtype=torch.float)\n cat = ac_net(item)\n a = cat.sample()\n logp = cat.log_prob(a)\n entropy = cat.entropy()\n _, r, _, _ = env.step(a.item())\n \n eps.append([r,logp,entropy])\n v += r/eps_len\n \n entropy_loss = 0\n actor_loss = 0\n # critic_arr = 0\n for k,item in enumerate(eps[::-1]):\n r, logp, entropy = item\n entropy_loss -= entropy\n adv = r - v\n actor_loss -= logp*adv\n \n loss = actor_loss.mean() + beta_e*entropy_loss\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if (i+1) % 2000 == 0:\n torch.save(ac_net.state_dict(),\n f'models/dependant/ac_net_{i+1}.pt')\n\n#%% test\n\ndef test_model(model_path,test_eps_count=300,\n h_size=48,d_size=12,eps_len=100):\n ac_net = AC_Net(2,h_size,d_size,2)\n ac_net.load_state_dict(torch.load(model_path))\n \n rec2 = []\n md = []\n for i in range(test_eps_count):\n if (i+1) % 50 == 0:\n print(f'{i+1}th episode')\n \n env.reset_task(env.sample_tasks()[0])\n env.reset()\n best_a = 0 if env._means[0] > env._means[1] else 1\n ac_net.reset_h()\n \n a = env.action_space.sample()\n _, r, _, _ = env.step(a)\n \n rec2_arr = []\n for j in range(eps_len):\n item = torch.tensor([[[r,a]]],dtype=torch.float)\n cat = ac_net(item)\n a = cat.sample()\n # logp = cat.log_prob(a)\n # entropy = cat.entropy()\n a = a.item()\n _, r, _, _ = env.step(a)\n \n item = 1 if a != best_a else 0\n rec2_arr.append(item)\n \n rec2.append(rec2_arr)\n md.append(abs(env._means[0]-env._means[1]))\n return rec2, md\n\n#%% plot\n# ind_rec, ind_md = \nrec, md = test_model('models/dependant/ac_net_20000.pt',1000)\n# rec2, md2 = test_model('models/dependant/ac_net_18000.pt')\nind_rec, ind_md = test_model('models/ac_net.pt',1000)\n\ndef get_recv(rec):\n rec = np.array(rec)\n recv = np.mean(rec,axis=0)\n return recv\n\nplt.figure()\nplt.plot(get_recv(rec),label='dependant model')\n# plt.plot(get_recv(rec2))\nplt.plot(get_recv(ind_rec),label='independant model')\nplt.legend()\nplt.xlabel('t')\nplt.ylabel('fraction of wrong pulls')\nplt.title('Averaged over 1000 test episodes')\n\n\nwrong_count = np.sum(rec,axis=1)\nplt.figure()\nplt.scatter(md,wrong_count,s=3)\nplt.xlabel('difference between the expected reward of two correlated arms')\nplt.ylabel('number of wrong pulls in a 100-step episode')\nplt.title('1000 test episodes')\n\n# plt.scatter(md,np.sum(ind_rec,axis=1),s=3)\n\n\n","sub_path":"bandit/train_dependant.py","file_name":"train_dependant.py","file_ext":"py","file_size_in_byte":5554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"156376461","text":"# -*- coding: utf-8 -*-\n# @Author: Bryant Hayes\n# @Date: 2017-11-06 15:01:39\n# @Last Modified by: Bryant Hayes\n# @Last Modified time: 2017-11-07 11:55:56\nfrom model.Message import Message, MsgType\nfrom controller.Logic import Logic\nfrom model.Player import Player\nfrom model.Entity import Entity\nfrom controller.AI import AIType\n\nimport random\n\nclass MyGameLogic(Logic):\n\tdef __init__(self, msgBus):\n\t\tLogic.__init__(self, msgBus)\n\t\tself.subscriptions.extend([MsgType.eMsgType_KeyPressed, MsgType.eMsgType_KeyReleased])\n\t\tself.shiftModifier = False\n\t\tself.entities = []\n\n\tdef addEntity(self, entity):\n\t\t# Send message to bus that a new entity is made\n\t\tmsg = Message(sender=self, target=None, msgType=MsgType.eMsgType_AddEntity, data=entity)\n\t\tself.msgBus.postMessage(msg)\n\t\tself.entities.append(entity)\n\n\tdef removeEntityAt(self, x, y):\n\t\ttoRemove = []\n\t\tfor entity in self.entities:\n\t\t\tif entity.x == x and entity.y == y:\n\t\t\t\tmsg = Message(sender=self, target=None, msgType=MsgType.eMsgType_RemoveEntity, data=entity)\n\t\t\t\tself.msgBus.postMessage(msg)\n\n\t\t\t\t# Mark for removal\n\t\t\t\ttoRemove.append(entity)\n\n\t\t# Remove all entities from local cache\n\t\tfor entity in toRemove:\n\t\t\tself.entities.remove(entity)\n\n\tdef init(self):\n\t\tLogic.init(self)\n\n\t\t# Init state of the game...\n\t\tself.player = Player(50, 50, \"@\", self.msgBus)#, aiType=AIType.AIType_Zombie)\n\t\tself.addEntity(self.player)\n\n\t\t# Force camera to follow player entity\n\t\tmsg = Message(sender=self, target=None, msgType=MsgType.eMsgType_CameraFollowEntity, data=self.player)\n\t\tself.msgBus.postMessage(msg)\n\n\t\tself.generateMap(100, 100)\n\n\tdef handleMessage(self, msg):\n\t\tif msg.msgType == MsgType.eMsgType_KeyPressed:\n\t\t\tself.keyPressed(msg.data)\n\t\tif msg.msgType == MsgType.eMsgType_KeyReleased:\n\t\t\tself.keyReleased(msg.data)\n\n\tdef move(self, entity, vector2D):\n\t\tmsg = Message(sender=self, target=None, msgType=MsgType.eMsgType_MoveEntity, data={\"entity\" : entity, \"vector2D\" : vector2D})\n\t\tself.msgBus.postMessage(msg)\n\n\tdef action(self, entity, vector2D):\n\t\t# WASD button handling to interact with world\n\t\tif self.shiftModifier:\n\t\t\tself.removeEntityAt(entity.x + vector2D[0], entity.y + vector2D[1])\n\t\telse:\n\t\t\tself.addEntity(Entity(entity.x + vector2D[0], entity.y + vector2D[1], \"#\", self.msgBus))\n\n\tdef keyReleased(self, key):\n\t\tif key.upper() == \"SHIFT\":\n\t\t\tself.shiftModifier = False\n\n\tdef keyPressed(self, key):\n\t\tif key.upper() in MOVEMENT_KEYS:\n\t\t\tself.move(self.player, MOVEMENT_KEYS[key.upper()])\n\t\telif key.upper() in ACTION_KEYS:\n\t\t\tself.action(self.player, ACTION_KEYS[key.upper()])\n\t\telif key.upper() == \"SHIFT\":\n\t\t\tself.shiftModifier = True\n\t\telif key.upper() == \"Q\":\n\t\t\tmsg = Message(sender=self, target=None, msgType=MsgType.eMsgType_Quit)\n\t\t\tself.msgBus.postMessage(msg)\n\n\tdef isTouchingCharacter(self, arr, ref, maxWidth, maxHeight, char):\n\t\tpossibilities = [[ref[0], ref[1]-1], [ref[0]-1, ref[1]], [ref[0], ref[1]+1], [ref[0]+1, ref[1]]]\n\t\tfor poss in possibilities:\n\t\t\tif poss[0] < 0 or poss[1] < 0 or poss[0] >= maxWidth or poss[1] >= maxHeight:\n\t\t\t\tcontinue\n\t\t\tcurr = arr[poss[0]][poss[1]]\n\t\t\tif curr != None and curr == char:\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef generateMap(self, width, height):\n\t\t# Make empty 2D array\n\t\tarr = []\n\t\tfor i in range(width):\n\t\t\tarr.append([])\n\t\t\tfor j in range(height):\n\t\t\t\tarr[i].append(None)\n\n\t\tfor y in range(height):\n\t\t\tfor x in range(width):\n\t\t\t\tif self.isTouchingCharacter(arr, (x, y), width, height, '#'):\n\t\t\t\t\tchance = .35\n\t\t\t\telse:\n\t\t\t\t\tchance = .1\n\n\t\t\t\t# If random chance, or edge piece, add wall\n\t\t\t\tif (random.uniform(0, 1) < chance) or (x == 0 or y == 0 or x == width-1 or y == height-1):\n\t\t\t\t\twall = Entity(x, y, \"#\", self.msgBus)\n\t\t\t\t\tself.addEntity(wall)\n\t\t\t\t\tarr[x][y] = wall.char\n\n\tdef update(self):\n\t\tpass\n\n# Create a dictionary that maps keys to vectors.\n# Names of the available keys can be found in the online documentation:\n# http://packages.python.org/tdl/tdl.event-module.html\nMOVEMENT_KEYS = {\n\t\t\t\t # standard arrow keys\n\t\t\t\t 'UP': [0, -1],\n\t\t\t\t 'DOWN': [0, 1],\n\t\t\t\t 'LEFT': [-1, 0],\n\t\t\t\t 'RIGHT': [1, 0],\n\n\t\t\t\t # diagonal keys\n\t\t\t\t # keep in mind that the keypad won't use these keys even if\n\t\t\t\t # num-lock is off\n\t\t\t\t 'HOME': [-1, -1],\n\t\t\t\t 'PAGEUP': [1, -1],\n\t\t\t\t 'PAGEDOWN': [1, 1],\n\t\t\t\t 'END': [-1, 1],\n\n\t\t\t\t # number-pad keys\n\t\t\t\t # These keys will always show as KPx regardless if num-lock\n\t\t\t\t # is on or off. Keep in mind that some keyboards and laptops\n\t\t\t\t # may be missing a keypad entirely.\n\t\t\t\t # 7 8 9\n\t\t\t\t # 4 6\n\t\t\t\t # 1 2 3\n\t\t\t\t 'KP1': [-1, 1],\n\t\t\t\t 'KP2': [0, 1],\n\t\t\t\t 'KP3': [1, 1],\n\t\t\t\t 'KP4': [-1, 0],\n\t\t\t\t 'KP6': [1, 0],\n\t\t\t\t 'KP7': [-1, -1],\n\t\t\t\t 'KP8': [0, -1],\n\t\t\t\t 'KP9': [1, -1],\n\t\t\t\t }\nACTION_KEYS = {\n\t\t\t\t 'W': [0, -1],\n\t\t\t\t 'S': [0, 1],\n\t\t\t\t 'A': [-1, 0],\n\t\t\t\t 'D': [1, 0]\n}","sub_path":"MyGameLogic.py","file_name":"MyGameLogic.py","file_ext":"py","file_size_in_byte":4752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"625545908","text":"def anagrams(lst):\n \"\"\"\n Function to find anagram pairs\n :param lst: A lst of strings\n :return: Group of anagrams\n \"\"\"\n\n # Empty dictionary which holds subsets of all anagrams together\n dictionary = {}\n\n # traversing all the lst strings\n for string in lst:\n\n # sorting the lst string and storing it in a key\n key = ''.join(sorted(string))\n\n # if the key is already in the dictionary then appending the original lst(Anagram).\n if key in dictionary.keys():\n dictionary[key].append(string)\n\n else: # If there is no key in the dictionary\n dictionary[key] = []\n dictionary[key].append(string)\n\n # traversing the whole dictionary and concatenating values and keys\n result = []\n for key, value in dictionary.items():\n if len(value) >= 2:\n result.append(value)\n result = sorted(result)\n return result\n","sub_path":"anagrams_finder/anagrams_finder.py","file_name":"anagrams_finder.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"591571999","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.6-intel/egg/interactive_judger/built_in_judger.py\n# Compiled at: 2018-08-03 01:49:43\n# Size of source mod 2**32: 4125 bytes\nfrom .judge_result import Result\n\ndef _fabs(x: float):\n if x < 0.0:\n return -x\n else:\n return x\n\n\ndef integer_judger(expected, actual: int):\n if expected == actual:\n return Result.AC\n else:\n return Result.WA\n\n\nequality_judger = integer_judger\n\ndef float_judger(expected: float, actual: float, boundless_error_accepted: float):\n if _fabs(expected - actual) <= boundless_error_accepted:\n return Result.AC\n else:\n return Result.WA\n\n\ndef charsequence_judger(expected: str, actual: str, multi_line=False, omit_trailing_spaces=True, omit_trailing_newlines=True):\n \"\"\"\n This judger can be applied to judge single line or multi-line strings\n :param expected: expected answer\n :param actual: actual answer yielded by the program\n :param multi_line: whether the answer contains more than a line of strings\n :param omit_trailing_spaces: <-\n :param omit_trailing_newlines: <-\n :return: Judge result\n \"\"\"\n\n def resolve_empty_line(xs: list):\n while not xs[(-1)]:\n xs = xs[:-1]\n\n return xs\n\n def resolve_trailing_spaces(x: str):\n return x.rstrip()\n\n def resolve_trailing_newlines(x: str):\n while x[(-1)] == '\\n':\n x = x[:-1]\n\n return x\n\n if multi_line:\n expected = expected.split('\\n')\n actual = actual.split('\\n')\n if omit_trailing_newlines:\n expected = resolve_empty_line(expected)\n actual = resolve_empty_line(actual)\n if len(expected) != len(actual):\n return Result.WA\n else:\n if omit_trailing_spaces:\n for e, a in zip(expected, actual):\n if resolve_trailing_spaces(e) != resolve_trailing_spaces(a):\n return Result.WA\n\n return Result.AC\n for e, a in zip(expected, actual):\n if e != a:\n if e.rstrip() == a.rstrip():\n return Result.PE\n else:\n return Result.WA\n\n return Result.AC\n else:\n if omit_trailing_newlines:\n expected = resolve_trailing_newlines(expected)\n actual = resolve_trailing_newlines(actual)\n if omit_trailing_spaces:\n expected = resolve_trailing_spaces(expected)\n actual = resolve_trailing_spaces(actual)\n if expected == actual[(-1)]:\n return Result.PE\n else:\n if expected == actual:\n return Result.AC\n return Result.WA\n\n\ndef iterative_judger(expected, actual, condiment={'boundless_error_accepted': 0.0}):\n \"\"\"\n This judger is designed to judge an iterative object contains data with different data types\n :param expected:\n :param actual:\n :param condiment:\n :return:\n \"\"\"\n if len(expected) != len(actual):\n return Result.WA\n else:\n if type(expected) != type(actual):\n return Result.WA\n\n def next_judge(exp, act):\n return {list: lambda : iterative_judger(exp, act), \n str: lambda : charsequence_judger(exp, act), \n int: lambda : integer_judger(exp, act), \n float: lambda : float_judger(exp, act, condiment['boundless_error_accepted'])}.get(type(exp), lambda : Result.WA)\n\n if type(expected) in (list, tuple, set, str):\n for e, a in zip(expected, actual):\n if type(e) != type(a):\n return Result.WA\n judge_result = next_judge(e, a)()\n if judge_result != Result.AC:\n return judge_result\n\n return Result.AC\n if isinstance(expected, dict):\n for e, a in zip(expected, actual):\n if type(e) != type(a) or type(expected[e]) != type(actual[a]):\n return Result.WA\n judge_result = next_judge(e, a)()\n if judge_result != Result.AC:\n return judge_result\n\n return Result.AC","sub_path":"pycfiles/interactive_judger_py-1.0.0-py3.6/built_in_judger.cpython-36.py","file_name":"built_in_judger.cpython-36.py","file_ext":"py","file_size_in_byte":4342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"295124268","text":"from __future__ import print_function\nfrom PIL import Image\nfrom math import sqrt, pow, sin, floor\n\n#imagen original\nim = Image.open(\"img1.jpg\")\npixels1 = im.load()\n\n#tamaño\nx = im.size[0]\ny = im.size[1]\ncx = x // 2\ncy = y // 2\n\n# Crear superficie deformante\nsuperficieDeformante = Image.new('RGB',(x,y))\n\nfor i in range(0, im.size[0]):\n\tfor j in range(0, im.size[1]):\n\t\tvalor = sin( 0.1 * sqrt( pow(i-cx,2) + pow(j-cy,2) ))\n\t\t#print ( abs (floor(valor * 255)) )\n\t\tpixels1[i,j] = ( int(abs (floor(valor * 255))), int(abs (floor(valor * 255))), int(abs (floor(valor * 255))))\nim.save(\"superfice.jpg\")\n\n#convolucion\n\nx = im.size[0]\ny = im.size[1]\npixels2 = im.load()\n\n#MX = [[-1,0,1],[-1,0,1],[-1,0,1]] #mascara lineas horizontales\nMX = [[-1,0,1],[-2,0,2],[-1,0,1]]\n\n#MY = [[1,1,1],[0,0,0],[-1,-1,-1]] #mascara lineas verticales\nMY = [[-1,-2,-1],[0,0,0],[1,2,1]]\n \nimagenNuevaX = Image.new('RGB',(x,y))\nimagenNuevaY = Image.new('RGB',(x,y))\nimn = Image.new('RGB',(x,y))\nfor j in range(y):\n\tfor i in range(x):\n\t\tsumatoria = 0\n\t\tsumatoriay = 0\n\t\tfor mj in range(-1,2):\n\t\t\tfor mx in range(-1,2):\n\t\t\t\ttry:\n\t\t\t\t\tsumatoria += MX[mj+1][mx+1]*pixels2[i+mx,j+mj][1]\n\t\t\t\t\tsumatoriay += MY[mj+1][mx+1]*pixels2[i+mx,j+mj][1] \n\t\t\t\texcept:\n\t\t\t\t\tsumatoria += 0\n\t\t\t\t\tsumatoriay += 0\n\t\tpunto1 = sumatoria\n\t\tpunto2 = sumatoriay\n\t\t\n\t\t#Normalizar\n\t\tpunto1 = abs(punto1)\n\t\tpunto2 = abs(punto2)\n\t\t#print (punto1)\n\t\t#print (punto2)\n\t\t\"\"\"\n\t\tif(punto1 < 0):\n\t\t\tpunto1 = 0\n\t\tif(punto1 > 255):\n\t\t\tpunto1 = 255\n\t\tif(punto2 < 0):\n\t\t\tpunto2 = 0\n\t\tif(punto2 > 255):\n\t\t\tpunto2 = 255\n\t\t\"\"\"\n\t\timagenNuevaX.putpixel((i,j),(punto1,punto1,punto1))\n\t\timagenNuevaY.putpixel((i,j),(punto2,punto2,punto2))\npx1 = imagenNuevaX.load()\npx2 = imagenNuevaY.load()\n\nimagenNuevaX.save(\"superficieX.jpg\")\nimagenNuevaY.save(\"superficieY.jpg\")\n#imn.save(\"aver.jpg\")\n\n########################\nimagenNuevaX = Image.new('RGB',(x,y))\nsuperficie = Image.open(\"superficie.jpg\")\nsuperficiePixels = superficie.load()\nfor i in range(x):\n\tfor j in range(y):\n\t\tprint (superficiePixels[x,y])\n\t\tprint (\"\")\n\t\t#imagenNuevaX.putpixel((i,j), i + (0.8 * superficiePixels","sub_path":"backup.py","file_name":"backup.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"49120254","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# \n\"\"\"Get some Blender particle objects translated to POV.\"\"\"\n\nimport bpy\n\n\ndef export_hair(file, ob, p_sys, global_matrix, write_matrix):\n \"\"\"Get Blender path particles (hair strands) objects translated to POV sphere_sweep unions.\"\"\"\n # tstart = time.time()\n textured_hair = 0\n if ob.material_slots[p_sys.settings.material - 1].material and ob.active_material is not None:\n pmaterial = ob.material_slots[p_sys.settings.material - 1].material\n # XXX Todo: replace by pov_(Particles?)_texture_slot\n for th in pmaterial.pov_texture_slots:\n povtex = th.texture # slot.name\n tex = bpy.data.textures[povtex]\n\n if th and th.use:\n if (tex.type == 'IMAGE' and tex.image) or tex.type != 'IMAGE':\n if th.use_map_color_diffuse:\n textured_hair = 1\n if pmaterial.strand.use_blender_units:\n strand_start = pmaterial.strand.root_size\n strand_end = pmaterial.strand.tip_size\n strand_shape = pmaterial.strand.shape\n else: # Blender unit conversion\n strand_start = pmaterial.strand.root_size / 200.0\n strand_end = pmaterial.strand.tip_size / 200.0\n strand_shape = pmaterial.strand.shape\n else:\n pmaterial = \"default\" # No material assigned in blender, use default one\n strand_start = 0.01\n strand_end = 0.01\n strand_shape = 0.0\n # Set the number of particles to render count rather than 3d view display\n # p_sys.set_resolution(scene, ob, 'RENDER') # DEPRECATED\n # When you render, the entire dependency graph will be\n # evaluated at render resolution, including the particles.\n # In the viewport it will be at viewport resolution.\n # So there is no need fo render engines to use this function anymore,\n # it's automatic now.\n steps = p_sys.settings.display_step\n steps = 2 ** steps # or + 1 # Formerly : len(particle.hair_keys)\n\n total_number_of_strands = p_sys.settings.count + p_sys.settings.rendered_child_count\n # hairCounter = 0\n file.write('#declare HairArray = array[%i] {\\n' % total_number_of_strands)\n for pindex in range(0, total_number_of_strands):\n\n # if particle.is_exist and particle.is_visible:\n # hairCounter += 1\n # controlPointCounter = 0\n # Each hair is represented as a separate sphere_sweep in POV-Ray.\n\n file.write('sphere_sweep{')\n if p_sys.settings.use_hair_bspline:\n file.write('b_spline ')\n file.write(\n '%i,\\n' % (steps + 2)\n ) # +2 because the first point needs tripling to be more than a handle in POV\n else:\n file.write('linear_spline ')\n file.write('%i,\\n' % (steps))\n # changing world coordinates to object local coordinates by\n # multiplying with inverted matrix\n init_coord = ob.matrix_world.inverted() @ (p_sys.co_hair(ob, particle_no=pindex, step=0))\n if (\n ob.material_slots[p_sys.settings.material - 1].material\n and ob.active_material is not None\n ):\n pmaterial = ob.material_slots[p_sys.settings.material - 1].material\n for th in pmaterial.pov_texture_slots:\n if th and th.use and th.use_map_color_diffuse:\n povtex = th.texture # slot.name\n tex = bpy.data.textures[povtex]\n # treat POV textures as bitmaps\n if (\n tex.type == 'IMAGE'\n and tex.image\n and th.texture_coords == 'UV'\n and ob.data.uv_textures is not None\n ):\n # or (\n # tex.pov.tex_pattern_type != 'emulator'\n # and th.texture_coords == 'UV'\n # and ob.data.uv_textures is not None\n # ):\n image = tex.image\n image_width = image.size[0]\n image_height = image.size[1]\n image_pixels = image.pixels[:]\n uv_co = p_sys.uv_on_emitter(mod, p_sys.particles[pindex], pindex, 0)\n x_co = round(uv_co[0] * (image_width - 1))\n y_co = round(uv_co[1] * (image_height - 1))\n pixelnumber = (image_width * y_co) + x_co\n r = image_pixels[pixelnumber * 4]\n g = image_pixels[pixelnumber * 4 + 1]\n b = image_pixels[pixelnumber * 4 + 2]\n a = image_pixels[pixelnumber * 4 + 3]\n init_color = (r, g, b, a)\n else:\n # only overwrite variable for each competing texture for now\n init_color = tex.evaluate((init_coord[0], init_coord[1], init_coord[2]))\n for step in range(0, steps):\n coord = ob.matrix_world.inverted() @ (p_sys.co_hair(ob, particle_no=pindex, step=step))\n # for controlPoint in particle.hair_keys:\n if p_sys.settings.clump_factor != 0:\n hair_strand_diameter = p_sys.settings.clump_factor / 200.0 * random.uniform(0.5, 1)\n elif step == 0:\n hair_strand_diameter = strand_start\n else:\n hair_strand_diameter += (strand_end - strand_start) / (\n p_sys.settings.display_step + 1\n ) # XXX +1 or not? # XXX use strand_shape in formula\n if step == 0 and p_sys.settings.use_hair_bspline:\n # Write three times the first point to compensate pov Bezier handling\n file.write(\n '<%.6g,%.6g,%.6g>,%.7g,\\n'\n % (coord[0], coord[1], coord[2], abs(hair_strand_diameter))\n )\n file.write(\n '<%.6g,%.6g,%.6g>,%.7g,\\n'\n % (coord[0], coord[1], coord[2], abs(hair_strand_diameter))\n )\n # Useless because particle location is the tip, not the root:\n # file.write(\n # '<%.6g,%.6g,%.6g>,%.7g'\n # % (\n # particle.location[0],\n # particle.location[1],\n # particle.location[2],\n # abs(hair_strand_diameter)\n # )\n # )\n # file.write(',\\n')\n # controlPointCounter += 1\n # total_number_of_strands += len(p_sys.particles)# len(particle.hair_keys)\n\n # Each control point is written out, along with the radius of the\n # hair at that point.\n file.write(\n '<%.6g,%.6g,%.6g>,%.7g' % (coord[0], coord[1], coord[2], abs(hair_strand_diameter))\n )\n\n # All coordinates except the last need a following comma.\n\n if step != steps - 1:\n file.write(',\\n')\n else:\n if textured_hair:\n # Write pigment and alpha (between Pov and Blender,\n # alpha 0 and 1 are reversed)\n file.write(\n '\\npigment{ color srgbf < %.3g, %.3g, %.3g, %.3g> }\\n'\n % (init_color[0], init_color[1], init_color[2], 1.0 - init_color[3])\n )\n # End the sphere_sweep declaration for this hair\n file.write('}\\n')\n\n # All but the final sphere_sweep (each array element) needs a terminating comma.\n if pindex != total_number_of_strands:\n file.write(',\\n')\n else:\n file.write('\\n')\n\n # End the array declaration.\n\n file.write('}\\n')\n file.write('\\n')\n\n if not textured_hair:\n # Pick up the hair material diffuse color and create a default POV-Ray hair texture.\n\n file.write('#ifndef (HairTexture)\\n')\n file.write(' #declare HairTexture = texture {\\n')\n file.write(\n ' pigment {srgbt <%s,%s,%s,%s>}\\n'\n % (\n pmaterial.diffuse_color[0],\n pmaterial.diffuse_color[1],\n pmaterial.diffuse_color[2],\n (pmaterial.strand.width_fade + 0.05),\n )\n )\n file.write(' }\\n')\n file.write('#end\\n')\n file.write('\\n')\n\n # Dynamically create a union of the hairstrands (or a subset of them).\n # By default use every hairstrand, commented line is for hand tweaking test renders.\n file.write('//Increasing HairStep divides the amount of hair for test renders.\\n')\n file.write('#ifndef(HairStep) #declare HairStep = 1; #end\\n')\n file.write('union{\\n')\n file.write(' #local I = 0;\\n')\n file.write(' #while (I < %i)\\n' % total_number_of_strands)\n file.write(' object {HairArray[I]')\n if not textured_hair:\n file.write(' texture{HairTexture}\\n')\n else:\n file.write('\\n')\n # Translucency of the hair:\n file.write(' hollow\\n')\n file.write(' double_illuminate\\n')\n file.write(' interior {\\n')\n file.write(' ior 1.45\\n')\n file.write(' media {\\n')\n file.write(' scattering { 1, 10*<0.73, 0.35, 0.15> /*extinction 0*/ }\\n')\n file.write(' absorption 10/<0.83, 0.75, 0.15>\\n')\n file.write(' samples 1\\n')\n file.write(' method 2\\n')\n file.write(' density {cylindrical\\n')\n file.write(' color_map {\\n')\n file.write(' [0.0 rgb <0.83, 0.45, 0.35>]\\n')\n file.write(' [0.5 rgb <0.8, 0.8, 0.4>]\\n')\n file.write(' [1.0 rgb <1,1,1>]\\n')\n file.write(' }\\n')\n file.write(' }\\n')\n file.write(' }\\n')\n file.write(' }\\n')\n file.write(' }\\n')\n\n file.write(' #local I = I + HairStep;\\n')\n file.write(' #end\\n')\n\n write_matrix(global_matrix @ ob.matrix_world)\n\n file.write('}')\n print('Totals hairstrands written: %i' % total_number_of_strands)\n print('Number of tufts (particle systems)', len(ob.particle_systems))\n\n # Set back the displayed number of particles to preview count\n # p_sys.set_resolution(scene, ob, 'PREVIEW') #DEPRECATED\n # When you render, the entire dependency graph will be\n # evaluated at render resolution, including the particles.\n # In the viewport it will be at viewport resolution.\n # So there is no need fo render engines to use this function anymore,\n # it's automatic now.\n","sub_path":"render_povray/object_particles.py","file_name":"object_particles.py","file_ext":"py","file_size_in_byte":11483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"109178163","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 28 09:09:58 2018\n\nThis process is not fast and should only be done while connected to ethernet\n\nScript based off of Kai Fan\n\"\"\"\n\nimport pandas as pd\nimport time\n#Set state\n\n# =============================================================================\n# species = ['o3','pm_FRM/FEM','pm_non_FRM/FEM']\n# species_code = ['44201','88101','88502']\n# name = ''\n# num = 3\n# =============================================================================\n\nspecies = ['Winds','Temperature','Pressure','RH']\nspecies_code = ['WIND','TEMP','PRESS','RH_DP']\nname = '_met'\nnum = 4\n\ndef aqs(state,ac):\n AQS={}\n for i in range(0,num):\n print(species[i])\n for j in range(2009,2019):\n dataframename = species[i]+ac+str(j)\n start = time.time()\n print(j)\n temp = pd.read_csv('https://aqs.epa.gov/aqsweb/airdata/hourly_'+species_code[i]+'_'+str(j)+'.zip',header=0,sep=',')\n temp['Date GMT'] = pd.to_datetime(temp['Date GMT'])\n temp = temp[(temp['State Name']==state)] \n AQS[dataframename] = temp\n end = time.time()\n print(round(end-start)) \n dict_AQS = AQS \n \n AQS_df = pd.concat(dict_AQS)\n AQS_df = AQS_df.drop(['Parameter Code','POC','Datum','Date GMT','Time GMT','MDL','Uncertainty',\n 'Qualifier','Method Type','Method Code','Method Name','Date of Last Change'], axis=1)\n \n AQS_df.to_csv(r'E:/Research/AIRPACT_eval/AQS_data/'+state+'_aqs'+name+'.csv')\n print(state + ' Done')\n\naqs('Washington','_WA')\naqs('Oregon','_OR')\naqs('Idaho','_ID')\naqs('Montana','_MT')\naqs('California','_CA')\naqs('Utah','_UT')\naqs('Nevada','_NV')\naqs('Canada','_CC')\n#%%\nif num == 3:\n # =============================================================================\n # Take AQS data and merge with observation data\n # =============================================================================\n \n inputDir = r'E:/Research/AIRPACT_eval/'\n \n # ##############################################################################\n # # Combine hrly model data\n # ##############################################################################\n # \n # df_1 = pd.read_csv('http://lar.wsu.edu/R_apps/2009ap3/data/2009hrly.csv', sep=',')\n # df_2 = pd.read_csv('http://lar.wsu.edu/R_apps/2010ap3/data/2010hrly.csv', sep=',')\n # df_3 = pd.read_csv('http://lar.wsu.edu/R_apps/2011ap3/data/hrly2011ap3.csv', sep=',')\n # df_4 = pd.read_csv('http://lar.wsu.edu/R_apps/2012ap3/data/hrly2012ap3.csv', sep=',') #Whole years data\n # #df_5 = pd.read_csv('http://lar.wsu.edu/R_apps/2012ap4/data/hrly2012.csv', sep=',') #Second half of years data\n # df_5 = pd.read_csv('http://lar.wsu.edu/R_apps/2013ap4/data/hrly2013.csv', sep=',')\n # df_6 = pd.read_csv('http://lar.wsu.edu/R_apps/2014ap4/data/hrly2014.csv', sep=',')\n # df_7 = pd.read_csv('http://lar.wsu.edu/R_apps/2015ap4/data/hrly2015.csv', sep=',') #Full year data\n # #df_8 = pd.read_csv('http://lar.wsu.edu/R_apps/2015ap5/data/hrly2015.csv', sep=',')\n # df_8 = pd.read_csv('http://lar.wsu.edu/R_apps/2016ap5/data/hrly2016.csv', sep=',')\n # df_9 = pd.read_csv('http://lar.wsu.edu/R_apps/2017ap5/data/hrly2017.csv', sep=',')\n # df_10 = pd.read_csv('http://lar.wsu.edu/R_apps/2018ap5/data/hrly2018.csv', sep=',')\n # \n # #Combine data\n # df_list = [df_1,df_2,df_3,df_4,df_5,df_6,df_7,df_8,df_9,df_10]\n # df_mod = pd.concat(df_list)\n # \n # #Drop uneccesary columns\n # df_mod = df_mod.drop(['O3_obs','PM2.5_obs'], axis=1)\n # \n # #df_mod = pd.merge(df_mod,aqsid, on='AQSID', how='outer') \n # \n # # Convert to datetime and adjust to PST\n # print('Converting datetime, this may take a while')\n # df_mod['datetime'] = pd.to_datetime(df_mod['DateTime'], infer_datetime_format=True)\n # df_mod[\"datetime\"] = df_mod[\"datetime\"].apply(lambda x: x - dt.timedelta(hours=8)) #Adjust to PST\n # df_mod = df_mod.drop(['DateTime'], axis=1)\n # \n # df_mod.to_csv(inputDir + '/model_aqs.csv')\n # print('Model data combined')\n # =============================================================================\n \n ##############################################################################\n # Read AQS data. csv's created from 'AQS_grabbing.py' script, and the model data from the previous lines of code\n ##############################################################################\n # Read model data\n df_mod = pd.read_csv(inputDir + '/model_aqs.csv',sep=',')\n df_mod['datetime'] = pd.to_datetime(df_mod['datetime']) #Must convert to date time to merge later\n df_mod = df_mod.drop('Unnamed: 0',axis=1)\n \n #Create AQSID Column form state code, county code, and site num\n aqsid = pd.read_csv(inputDir+'aqs_sites.csv')\n aqsid = aqsid.ix[:,['State Code','County Code','Site Number','Local Site Name','Location Setting']]\n \n aqsid['County Code'] = [\"%03d\" % n for n in aqsid['County Code'] ]\n aqsid['Site Number'] = [\"%04d\" % n for n in aqsid['Site Number'] ]\n \n aqsid['AQSID'] = (aqsid['State Code']).astype(str) + (aqsid['County Code']).astype(str)+(aqsid['Site Number']).astype(str)\n \n # Must force every cell in AQSID to be a string, otherwise lose most of data\n aqsid['AQSID'] = aqsid['AQSID'].astype(str)\n df_mod['AQSID'] = df_mod['AQSID'].astype(str)\n \n df_mod = pd.merge(df_mod,aqsid) # Merge df_mod and aqsid so as to add names and such to the datafram\n \n print('Model data read')\n \n # Read AQS data\n df_wa = pd.read_csv(inputDir + 'AQS_data/Washington_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_or = pd.read_csv(inputDir + 'AQS_data/Oregon_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_id = pd.read_csv(inputDir + 'AQS_data/Idaho_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n #df_cc = pd.read_csv(inputDir + 'Canada_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_mt = pd.read_csv(inputDir + 'AQS_data/Montana_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_ca = pd.read_csv(inputDir + 'AQS_data/California_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_nv = pd.read_csv(inputDir + 'AQS_data/Nevada_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_ut = pd.read_csv(inputDir + 'AQS_data/Utah_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n \n # Combine AQS data\n df_list = [df_wa,df_or,df_id,df_mt,df_ca,df_nv,df_ut]\n df_obs = pd.concat(df_list)\n \n \n #Create AQSID Column form state code, county code, and site num\n df_obs['County Code'] = [\"%03d\" % n for n in df_obs['County Code'] ]\n df_obs['Site Num'] = [\"%04d\" % n for n in df_obs['Site Num'] ]\n \n df_obs['AQSID'] = (df_obs['State Code']).astype(str) + (df_obs['County Code']).astype(str)+(df_obs['Site Num']).astype(str)\n \n # Drop columns of data we are not looking at so as to increase the speed of the script\n df_obs = df_obs.drop(['Unnamed: 0','Unnamed: 1','State Name','County Name','State Code','County Code','Site Num','Units of Measure','Latitude','Longitude'],axis=1)\n df_obs = df_obs.rename(columns={'Date Local_Time Local': 'datetime','Parameter Name':'Parameter_Name'})\n print('Observed data read and combined')\n \n # Only pulls ozone/pm data\n df_obs_o3 = df_obs.loc[df_obs['Parameter_Name']=='Ozone']\n df_obs_pm = df_obs.loc[df_obs['Parameter_Name']=='PM2.5 - Local Conditions']\n df_obs_pm2 = df_obs.loc[df_obs['Parameter_Name']=='Acceptable PM2.5 AQI & Speciation Mass']\n df_obs_pm = pd.concat([df_obs_pm,df_obs_pm2])\n \n df_obs_o3 = df_obs_o3.rename(columns={'Sample Measurement':'O3_obs'})\n df_obs_pm = df_obs_pm.rename(columns={'Sample Measurement':'PM2.5_obs'})\n \n df_obs_o3 = df_obs_o3.drop(['Parameter_Name'],axis=1)\n df_obs_pm = df_obs_pm.drop(['Parameter_Name'],axis=1)\n df_obs = pd.merge(df_obs_o3, df_obs_pm, on =['datetime','AQSID'], how='outer')\n \n df_obs = pd.merge(df_obs,aqsid, how='outer') \n #df_obs = df_obs.drop(['Latitude_x','Latitude_y','Longitude_x','Longitude_y'], axis=1)\n \n ##############################################################################\n # Manipulate obs and mod dataframes to set them up to plot\n ##############################################################################\n #df_com = pd.concat([df_obs,df_mod])\n '''\n # sites which are common between base and Observations\n sites_common = set(df_obs['AQSID']).intersection(set(df_mod['AQSID']))\n \n ## take only the data which is for common sites\n df_obs_new = pd.DataFrame(columns=df_obs.columns)\n df_mod_new = pd.DataFrame(columns=df_mod.columns)\n for sites in sites_common:\n # print sites\n dfa = df_obs.loc[df_obs['AQSID']==sites, df_obs.columns]\n dfb = df_mod.loc[df_mod['AQSID']==sites, df_mod.columns]\n df_obs_new = pd.concat([df_obs_new, dfa], join='outer', ignore_index=True)\n df_mod_new = pd.concat([df_mod_new, dfb], join='outer', ignore_index=True)\n '''\n # merge now\n print('Merging large dataframes, this may take a while')\n #df_com = pd.merge(df_obs_new, df_mod_new, on=['datetime', 'AQSID','long_name'], how='outer')\n df_com = pd.merge(df_obs, df_mod, how='outer')\n \n #df_com = pd.concat([df_obs,df_mod])\n \n \n # Need to convert these to numeric\n df_com.loc[:,'O3_mod'] = pd.to_numeric(df_com.loc[:,'O3_mod'], errors='coerce')\n df_com.loc[:,'PM2.5_mod'] = pd.to_numeric(df_com.loc[:,'PM2.5_mod'], errors='coerce')\n #df_com.loc[:,'AQSID'] = pd.to_numeric(df_com.loc[:,'AQSID'], errors='coerce')\n \n #df_com = df_com.drop(['AQSID_x','AQSID_y'],axis=1)\n df_com['datetime'] = pd.to_datetime(df_com['datetime'], infer_datetime_format=True)\n \n #df_com = pd.merge(df_com,aqsid, on=['AQSID','long_name'], how='outer') \n #df_com = df_com.set_index('datetime')\n \n df_com.loc[:,'O3_mod'] = pd.to_numeric(df_com.loc[:,'O3_mod'], errors='coerce')\n df_com.loc[:,'PM2.5_mod'] = pd.to_numeric(df_com.loc[:,'PM2.5_mod'], errors='coerce')\n df_com.loc[:,'O3_obs'] = pd.to_numeric(df_com.loc[:,'O3_obs'], errors='coerce')\n df_com['O3_obs'] = df_com['O3_obs']*1000 #convert to ppb\n df_obs['O3_obs'] = df_obs['O3_obs']*1000\n df_com.loc[:,'PM2.5_obs'] = pd.to_numeric(df_com.loc[:,'PM2.5_obs'], errors='coerce')\n df_com = df_com.drop(['State Code','County Code','Site Number'],axis=1) # drop unecessary columns\n print('Combined dataframe finished')\n \n df_com.to_csv(inputDir+'AQS_data/df_com_aplong.csv')\n \n \n ","sub_path":"AIRPACT_eval/AQS_grabbing.py","file_name":"AQS_grabbing.py","file_ext":"py","file_size_in_byte":10733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"520333099","text":"import collections\nimport sys\n\nn,m,k,x = map(int,sys.stdin.readline().split())\nroad = collections.defaultdict(list)\nfor _ in range(m):\n s,d = map(int,sys.stdin.readline().split())\n road[s].append(d)\n \nq=collections.deque()\nq.append((0,x))\n\nans=[]\nvisited = [0 for _ in range(n+1)]\nvisited[x] = 1 # 시작점\n\nwhile q:\n dist, ct = q.popleft() \n \n if dist==k: # 거리 k이면 정답 리스트에 넣기\n ans.append(ct)\n \n for c in road[ct]: # 연결된 도시들 중 방문 안 한 도시 방문\n if not visited[c]:\n visited[c]=1\n q.append((dist+1,c)) # 거리 +1 \n \nans.sort() \nif not ans:\n print(-1)\nelse:\n for i in ans:\n print(i)\n","sub_path":"Algorithm/EUNWOO/18352.py","file_name":"18352.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"129776658","text":"import scrapy\nfrom w3lib.html import remove_tags, remove_tags_with_content\nfrom NewsCrawler.items import ArticleItem\n\n\nclass NewsCrawler(scrapy.Spider):\n name = \"NewsCrawler\"\n allowed_domains = ['nba.udn.com']\n start_urls = [\n \"https://nba.udn.com/nba/index?gr=www\",\n ]\n\n def parse(self, response):\n news_list = response.xpath(\n '//*[@id=\"news_body\"]//dl//a/@href').getall()\n for url in news_list:\n yield response.follow(url, callback=self.parse_news)\n\n def parse_news(self, response):\n input = ''.join(response.xpath(\n '//*[@id=\"story_body_content\"]/span/p').extract())\n content = remove_tags(\n remove_tags_with_content(input, ('div', 'figure')), keep=('p',))\n\n item = ArticleItem()\n item['a_title'] = response.css(\n 'h1.story_art_title::text').get()\n item['a_datetime'] = response.css(\n 'div.shareBar__info--author span::text').get()\n item['a_source'] = response.css(\n 'div.shareBar__info--author::text').get()\n item['a_content'] = content\n yield item\n","sub_path":"mysite/NewsCrawler/NewsCrawler/spiders/newsCrawler.py","file_name":"newsCrawler.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"325721985","text":"# -*- coding=utf-8 -*-\n'''\n2020/2/13\n(避免滥用,代码已经废弃,现已不更新,有需要请适量使用exe版本)\n京东抢购商品程序\n通过商品的skuid、地区id抢购\n'''\nimport sys\nimport io\n\nimport schedule\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom config import Config\nfrom jdProgram import *\nfrom message import message\nfrom util import getconfigMd5, _setDNSCache\n\nimport threading\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')\n\nglobal cookies_String, mail, sc_key, messageType, modelType, area, skuidsString, skuids, captchaUrl, eid, fp, payment_pwd\nglobal scheduled_time_start\nglobal scheduled_time_end\nglobal quit_scripts_falg \n\ndef getconfig():\n global cookies_String, mail, sc_key, messageType, modelType, area, skuidsString, skuids, captchaUrl, eid, fp, payment_pwd\n global scheduled_time_start\n global scheduled_time_end\n global quit_scripts_falg \n \n quit_scripts_falg = False\n\n global_config = Config()\n # cookie 网页获取\n cookies_String = global_config.getRaw('config', 'cookies_String')\n # 有货通知 收件邮箱\n mail = global_config.getRaw('config', 'mail')\n # 方糖微信推送的key 不知道的请看http://sc.ftqq.com/3.version\n sc_key = global_config.getRaw('config', 'sc_key')\n # 推送方式 1(mail)或 2(wechat)\n messageType = global_config.getRaw('config', 'messageType')\n # 下单模式\n modelType = global_config.getRaw('V2', 'model')\n # 地区id\n area = global_config.getRaw('config', 'area')\n # 脚本开始检测时间end\n scheduled_time_start = global_config.getRaw('Schedule', 'scheduled_time_start')\n # 脚本开始检测时间\n scheduled_time_end = global_config.getRaw('Schedule', 'scheduled_time_end')\n\n # 商品id\n skuidsString = global_config.getRaw('V2', 'skuids')\n skuids = str(skuidsString).split(',')\n # 验证码服务地址\n captchaUrl = global_config.getRaw('Temporary', 'captchaUrl')\n if not modelType:\n logger.error('请在configDemo.ini文件填写下单model')\n\n if len(skuids[0]) == 0:\n logger.error('请在configDemo.ini文件中输入你的商品id')\n sys.exit(1)\n '''\n 备用\n '''\n # eid\n eid = global_config.getRaw('Temporary', 'eid')\n fp = global_config.getRaw('Temporary', 'fp')\n # 支付密码\n payment_pwd = global_config.getRaw('config', 'payment_pwd')\n\n\n# 初次\nconfigTime = int(time.time())\ngetconfig()\nconfigMd5 = getconfigMd5()\nmessage = message(messageType=messageType, sc_key=sc_key, mail=mail)\n\nis_Submit_captcha = False\nsubmit_captcha_rid = ''\nsubmit_captcha_text = ''\nencryptClientInfo = ''\nsubmit_Time = 0\nsession = requests.session()\nsession.headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Connection\": \"keep-alive\"\n}\nchecksession = requests.session()\nchecksession.headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Connection\": \"keep-alive\"\n}\nmanual_cookies = {}\n\n\ndef get_tag_value(tag, key='', index=0):\n if key:\n value = tag[index].get(key)\n else:\n value = tag[index].text\n return value.strip(' \\t\\r\\n')\n\n\nfor item in cookies_String.split(';'):\n name, value = item.strip().split('=', 1)\n # 用=号分割,分割1次\n manual_cookies[name] = value\n # 为字典cookies添加内容\n\ncookiesJar = requests.utils.cookiejar_from_dict(manual_cookies, cookiejar=None, overwrite=True)\nsession.cookies = cookiesJar\n\n\ndef validate_cookies():\n for flag in range(1, 3):\n try:\n targetURL = 'https://order.jd.com/center/list.action'\n payload = {\n 'rid': str(int(time.time() * 1000)),\n }\n resp = session.get(url=targetURL, params=payload, allow_redirects=False)\n if resp.status_code == requests.codes.OK:\n logger.info('校验是否登录[成功]')\n return True\n else:\n logger.info('校验是否登录[失败]')\n logger.info('请在configDemo.ini文件下更新cookie')\n time.sleep(5)\n continue\n except Exception as e:\n logger.info('第【%s】次请重新获取cookie', flag)\n time.sleep(5)\n continue\n message.sendAny('脚本登录cookie失效了,请重新登录')\n sys.exit(1)\n\n\ndef getUsername():\n userName_Url = 'https://passport.jd.com/new/helloService.ashx?callback=jQuery339448&_=' + str(\n int(time.time() * 1000))\n session.headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Referer\": \"https://order.jd.com/center/list.action\",\n \"Connection\": \"keep-alive\"\n }\n resp = session.get(url=userName_Url, allow_redirects=True)\n resultText = resp.text\n resultText = resultText.replace('jQuery339448(', '')\n resultText = resultText.replace(')', '')\n usernameJson = json.loads(resultText)\n logger.info('登录账号名称[%s]', usernameJson['nick'])\n\n\n'''\n检查是否有货\n'''\n\n\ndef check_item_stock(itemUrl):\n response = session.get(itemUrl)\n if (response.text.find('无货') > 0):\n return True\n \n if (response.text.find('此商品暂时售完') > 0):\n return True\n else:\n return False\n\n\n'''\n取消勾选购物车中的所有商品\n'''\n\n\ndef cancel_select_all_cart_item():\n url = \"https://cart.jd.com/cancelAllItem.action\"\n data = {\n 't': 0,\n 'outSkus': '',\n 'random': random.random()\n }\n resp = session.post(url, data=data)\n if resp.status_code != requests.codes.OK:\n print('Status: %u, Url: %s' % (resp.status_code, resp.url))\n return False\n return True\n\n\n'''\n购物车详情\n'''\n\n\ndef cart_detail():\n url = 'https://cart.jd.com/cart.action'\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Referer\": \"https://order.jd.com/center/list.action\",\n \"Host\": \"cart.jd.com\",\n \"Connection\": \"keep-alive\"\n }\n resp = session.get(url, headers=headers)\n soup = BeautifulSoup(resp.text, \"html.parser\")\n\n cart_detail = dict()\n for item in soup.find_all(class_='item-item'):\n try:\n sku_id = item['skuid'] # 商品id\n except Exception as e:\n logger.info('购物车中有套装商品,跳过')\n continue\n try:\n # 例如:['increment', '8888', '100001071956', '1', '13', '0', '50067652554']\n # ['increment', '8888', '100002404322', '2', '1', '0']\n item_attr_list = item.find(class_='increment')['id'].split('_')\n p_type = item_attr_list[4]\n promo_id = target_id = item_attr_list[-1] if len(item_attr_list) == 7 else 0\n\n cart_detail[sku_id] = {\n 'name': get_tag_value(item.select('div.p-name a')), # 商品名称\n 'verder_id': item['venderid'], # 商家id\n 'count': int(item['num']), # 数量\n 'unit_price': get_tag_value(item.select('div.p-price strong'))[1:], # 单价\n 'total_price': get_tag_value(item.select('div.p-sum strong'))[1:], # 总价\n 'is_selected': 'item-selected' in item['class'], # 商品是否被勾选\n 'p_type': p_type,\n 'target_id': target_id,\n 'promo_id': promo_id\n }\n except Exception as e:\n logger.error(\"商品%s在购物车中的信息无法解析,报错信息: %s,该商品自动忽略\", sku_id, e)\n\n logger.info('购物车信息:%s', cart_detail)\n return cart_detail\n\n\n'''\n修改购物车商品的数量\n'''\n\n\ndef change_item_num_in_cart(sku_id, vender_id, num, p_type, target_id, promo_id):\n url = \"https://cart.jd.com/changeNum.action\"\n data = {\n 't': 0,\n 'venderId': vender_id,\n 'pid': sku_id,\n 'pcount': num,\n 'ptype': p_type,\n 'targetId': target_id,\n 'promoID': promo_id,\n 'outSkus': '',\n 'random': random.random(),\n # 'locationId'\n }\n session.headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Referer\": \"https://cart.jd.com/cart\",\n \"Connection\": \"keep-alive\"\n }\n resp = session.post(url, data=data)\n return json.loads(resp.text)['sortedWebCartResult']['achieveSevenState'] == 2\n\n\n'''\n添加商品到购物车\n'''\n\n\ndef add_item_to_cart(sku_id):\n url = 'https://cart.jd.com/gate.action'\n payload = {\n 'pid': sku_id,\n 'pcount': 1,\n 'ptype': 1,\n }\n resp = session.get(url=url, params=payload)\n if 'https://cart.jd.com/cart.action' in resp.url: # 套装商品加入购物车后直接跳转到购物车页面\n result = True\n else: # 普通商品成功加入购物车后会跳转到提示 \"商品已成功加入购物车!\" 页面\n soup = BeautifulSoup(resp.text, \"html.parser\")\n result = bool(soup.select('h3.ftx-02')) # [商品已成功加入购物车!]\n\n if result:\n logger.info('%s 已成功加入购物车', sku_id)\n else:\n logger.error('%s 添加到购物车失败', sku_id)\n\n\ndef get_checkout_page_detail():\n \"\"\"获取订单结算页面信息\n\n 该方法会返回订单结算页面的详细信息:商品名称、价格、数量、库存状态等。\n\n :return: 结算信息 dict\n \"\"\"\n url = 'http://trade.jd.com/shopping/order/getOrderInfo.action'\n # url = 'https://cart.jd.com/gotoOrder.action'\n payload = {\n 'rid': str(int(time.time() * 1000)),\n }\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Referer\": \"https://cart.jd.com/cart.action\",\n \"Connection\": \"keep-alive\",\n 'Host': 'trade.jd.com',\n }\n try:\n resp = session.get(url=url, params=payload, headers=headers)\n if not response_status(resp):\n logger.error('获取订单结算页信息失败')\n return ''\n if '刷新太频繁了' in resp.text:\n return '刷新太频繁了'\n soup = BeautifulSoup(resp.text, \"html.parser\")\n risk_control = get_tag_value(soup.select('input#riskControl'), 'value')\n showCheckCode = get_tag_value(soup.select('input#showCheckCode'), 'value')\n if not showCheckCode:\n pass\n else:\n if showCheckCode == 'true':\n logger.info('提交订单需要验证码')\n global is_Submit_captcha, encryptClientInfo\n encryptClientInfo = get_tag_value(soup.select('input#encryptClientInfo'), 'value')\n is_Submit_captcha = True\n\n order_detail = {\n 'address': soup.find('span', id='sendAddr').text[5:], # remove '寄送至: ' from the begin\n 'receiver': soup.find('span', id='sendMobile').text[4:], # remove '收件人:' from the begin\n 'total_price': soup.find('span', id='sumPayPriceId').text[1:], # remove '¥' from the begin\n 'items': []\n }\n\n logger.info(\"下单信息:%s\", order_detail)\n return risk_control\n except requests.exceptions.RequestException as e:\n logger.error('订单结算页面获取异常:%s' % e)\n except Exception as e:\n logger.error('下单页面数据解析异常:%s', e)\n return ''\n\n\n'''\n下柜商品检测\n'''\n\n\ndef item_removed(sku_id):\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Referer\": \"http://trade.jd.com/shopping/order/getOrderInfo.action\",\n \"Connection\": \"keep-alive\",\n 'Host': 'item.jd.com',\n }\n url = 'https://item.jd.com/{}.html'.format(sku_id)\n page = requests.get(url=url, headers=headers)\n return '该商品已下柜' not in page.text\n\n\n'''\n购买环节\n测试三次\n'''\n\n\ndef normalModeBuyMask(sku_id):\n cancel_select_all_cart_item()\n cart = cart_detail()\n if sku_id in cart:\n logger.info('%s 已在购物车中,调整数量为 %s', sku_id, 1)\n cart_item = cart.get(sku_id)\n change_item_num_in_cart(\n sku_id=sku_id,\n vender_id=cart_item.get('vender_id'),\n num=1,\n p_type=cart_item.get('p_type'),\n target_id=cart_item.get('target_id'),\n promo_id=cart_item.get('promo_id')\n )\n else:\n add_item_to_cart(sku_id)\n risk_control = get_checkout_page_detail()\n if risk_control == '刷新太频繁了':\n return False\n if len(risk_control) > 0:\n if submit_order(session, risk_control, sku_id, skuids, submit_Time, encryptClientInfo, is_Submit_captcha,\n payment_pwd, submit_captcha_text, submit_captcha_rid):\n return True\n return False\n\n\ndef fastModeBuyMask(sku_id):\n add_item_to_cart(sku_id)\n risk_control = get_checkout_page_detail()\n if risk_control == '刷新太频繁了':\n return False\n if len(risk_control) > 0:\n if submit_order(session, risk_control, sku_id, skuids, submit_Time, encryptClientInfo, is_Submit_captcha,\n payment_pwd, submit_captcha_text, submit_captcha_rid):\n return True\n return False\n\n\n'''\n删除购物车选中商品\n'''\n\n\ndef remove_item():\n url = \"https://cart.jd.com/batchRemoveSkusFromCart.action\"\n data = {\n 't': 0,\n 'null': '',\n 'outSkus': '',\n 'random': random.random(),\n 'locationId': '19-1607-4773-0'\n }\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.37\",\n \"Accept\": \"application/json, text/javascript, */*; q=0.01\",\n \"Referer\": \"https://cart.jd.com/cart.action\",\n \"Host\": \"cart.jd.com\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Accept-Encoding\": \"zh-CN,zh;q=0.9,ja;q=0.8\",\n \"Origin\": \"https://cart.jd.com\",\n \"Connection\": \"keep-alive\"\n }\n resp = session.post(url, data=data, headers=headers)\n logger.info('清空购物车')\n if resp.status_code != requests.codes.OK:\n print('Status: %u, Url: %s' % (resp.status_code, resp.url))\n return False\n return True\n\n\ndef select_all_cart_item():\n url = \"https://cart.jd.com/selectAllItem.action\"\n data = {\n 't': 0,\n 'outSkus': '',\n 'random': random.random()\n }\n resp = session.post(url, data=data)\n if resp.status_code != requests.codes.OK:\n print('Status: %u, Url: %s' % (resp.status_code, resp.url))\n return False\n return True\n\n\ndef normalModeAutoBuy(inStockSkuid):\n for skuId in inStockSkuid:\n if item_removed(skuId):\n global submit_Time\n submit_Time = int(time.time() * 1000)\n logger.info('[%s]类型商品有货啦!马上下单', skuId)\n skuidUrl = 'https://item.jd.com/' + skuId + '.html'\n if normalModeBuyMask(skuId):\n message.send(skuidUrl, True)\n sys.exit(1)\n else:\n message.send(skuidUrl, False)\n else:\n logger.info('[%s]类型商品有货,但已下柜商品', skuId)\n\n\ndef fastModeAutoBuy(inStockSkuid):\n for skuId in inStockSkuid:\n global submit_Time\n submit_Time = int(time.time() * 1000)\n logger.info('[%s]类型商品有货啦!马上下单', skuId)\n skuidUrl = 'https://item.jd.com/' + skuId + '.html'\n if fastModeBuyMask(skuId):\n message.send(skuidUrl, True)\n sys.exit(1)\n else:\n if item_removed(skuId):\n message.send(skuidUrl, False)\n else:\n logger.info('[%s]商品已下柜,商品列表中踢出', skuId)\n skuids.remove(skuId)\n select_all_cart_item()\n remove_item()\n\n\ndef check_Config():\n global configMd5, configTime\n nowMd5 = getconfigMd5()\n configTime = time.time()\n if not nowMd5 == configMd5:\n logger.info('配置文件修改,重新读取文件')\n getconfig()\n configMd5 = nowMd5\n \ndef normalMode():\n global quit_scripts_falg\n flag = 1\n while (1):\n if quit_scripts_falg == True:\n logger.info('退出脚本')\n sys.exit()\n try:\n if flag == 1:\n validate_cookies()\n getUsername()\n # 检测配置文件是否修改\n if int(time.time()) - configTime >= 60:\n check_Config()\n # modelType\n logger.info('第' + str(flag) + '次 ')\n flag += 1\n # 检测库存\n inStockSkuid = check_stock(checksession, skuids, area)\n # 下单任务\n normalModeAutoBuy(inStockSkuid)\n # 休眠模块\n timesleep = random.randint(1, 3) / 10\n time.sleep(timesleep)\n # 校验是否还在登录模块\n if flag % 100 == 0:\n logger.info('校验是否还在登录')\n validate_cookies()\n except Exception as e:\n print(traceback.format_exc())\n time.sleep(10)\n\ndef fastMode():\n global quit_scripts_falg\n flag = 1\n while (1):\n try:\n if flag == 1:\n validate_cookies()\n getUsername()\n select_all_cart_item()\n remove_item()\n # 检测配置文件修改\n if int(time.time()) - configTime >= 600:\n check_Config()\n # modelType\n logger.info('第' + str(flag) + '次 ')\n flag += 1\n # 检测库存\n inStockSkuid = check_stock(checksession, skuids, area)\n #inStockSkuid = [100012043978]\n # 下单任务\n fastModeAutoBuy(inStockSkuid)\n # 休眠模块\n timesleep = random.randint(1, 3) / 10\n time.sleep(timesleep)\n # 校验是否还在登录模块\n if flag % 100 == 0:\n logger.info('校验是否还在登录')\n validate_cookies()\n except Exception as e:\n print(traceback.format_exc())\n time.sleep(10)\n\ndef exitScript():\n global quit_scripts_falg\n quit_scripts_falg = True\n\ndef myMain():\n # _setDNSCache()\n if modelType == '2':\n logger.info('V2版本当前模式[普通模式]')\n normalMode()\n elif modelType == '1':\n logger.info('V2版本当前模式[极速模式]')\n fastMode()\n\ndef normalModeInMultiProcess():\n p1 = threading.Thread(target=normalMode, args=())\n p1.start()\n\ndef fastModeInMultiProcess():\n p2 = threading.Thread(target=fastMode, args=())\n p2.start()\n\ndef exitScriptInMultiProcess():\n p3 = threading.Thread(target=exitScript, args=())\n p3.start()\n \nschedule.every().day.at(scheduled_time_start).do(fastModeInMultiProcess)\nlogger.info('fastMode is scheduled at: ' + scheduled_time_start)\n#schedule.every().day.at(scheduled_time_end).do(exitScriptInMultiProcess)\n#logger.info('exitScript is scheduled at: ' + scheduled_time_end)\n\nwhile True:\n schedule.run_pending()","sub_path":"jdBuyMask-master/jdBuyMask_V2.py","file_name":"jdBuyMask_V2.py","file_ext":"py","file_size_in_byte":20684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"411886794","text":"#!-*- coding:utf-8 -*-\r\n# __author__ : Sora\r\n# ___time___ : 2019/06/24/9:06\r\n\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport random\r\nimport time\r\nimport formula\r\n\r\n# 主程序开始\r\nprint('请输入ER网络的顶点个数:')\r\nNETWORK_SIZE = int(input())\r\nadjacentMatrix = np.zeros((NETWORK_SIZE, NETWORK_SIZE), dtype=int) # 初始化邻接矩阵\r\n\r\n\r\nprint('请输入边数:')\r\nEDGE = float(input())\r\n\r\n\r\n\r\n\r\n# 生成ER网络\r\ndef generateRandomNetwork(EDGE):\r\n while EDGE > 0 :\r\n x, y = np.random.randint(NETWORK_SIZE), np.random.randint(NETWORK_SIZE)\r\n # 随机取边\r\n while x == y or adjacentMatrix[x][y] == 1:\r\n x, y = np.random.randint(NETWORK_SIZE), np.random.randint(NETWORK_SIZE)\r\n adjacentMatrix[x][y] = adjacentMatrix[y][x] = 1\r\n EDGE = EDGE - 1\r\n\r\n\r\n\r\n# 用于绘制ER图\r\ndef showGraph():\r\n G = nx.Graph()\r\n for i in range(len(adjacentMatrix)):\r\n G.add_node(i)\r\n for j in range(len(adjacentMatrix)):\r\n if adjacentMatrix[i][j] == 1:\r\n G.add_edge(i, j)\r\n nx.draw(G,pos=nx.random_layout(G), node_size=3,width=0.05)\r\n print(\"density:\",formula.density(G))\r\n print(\"clustering coefficient:\",formula.clustering_coefficient(G))\r\n a= formula.average_path_length(G)\r\n print('nx.shortest_path_length(G):',a)\r\n plt.savefig(\"ER.png\", dpi=300)\r\n plt.show()\r\n\r\n\r\n\r\n# 将ER网络写入文件中\r\ndef writeRandomNetworkToFile():\r\n ARRS = []\r\n f = open('randomNetwork01.txt', 'w+')\r\n for i in range(NETWORK_SIZE):\r\n t = adjacentMatrix[i]\r\n ARRS.append(t)\r\n for j in range(NETWORK_SIZE):\r\n s = str(t[j])\r\n f.write(s)\r\n f.write(' ')\r\n f.write('\\n')\r\n f.close()\r\n\r\n\r\n# 计算度分布并将其存入文件中\r\ndef calculateDegreeDistribution():\r\n averageDegree = 0.0\r\n identify = 0.0\r\n statistic = np.zeros((NETWORK_SIZE), dtype=float) # statistic将用于存放度分布的数组,数组下标为度的大小,对应数组内容为该度的概率\r\n degree = np.zeros((NETWORK_SIZE), dtype=int) # degree用于存放每个节点的度\r\n for i in range(NETWORK_SIZE):\r\n for j in range(NETWORK_SIZE):\r\n degree[i] = degree[i] + adjacentMatrix[i][j]\r\n for i in range(NETWORK_SIZE):\r\n averageDegree += degree[i]\r\n print('平均度为' + str(averageDegree / NETWORK_SIZE)) # 计算平均度\r\n for i in range(NETWORK_SIZE):\r\n statistic[degree[i]] = statistic[degree[i]] + 1\r\n for i in range(NETWORK_SIZE):\r\n statistic[i] = statistic[i] / NETWORK_SIZE\r\n identify = identify + statistic[i]\r\n identify = int(identify)\r\n print('如果output为1则该算法正确\\toutput=' + str(identify)) # 用于测试算法是否正确\r\n\r\n\r\n\r\n\r\ngenerateRandomNetwork(EDGE) # 生成ER随机网络\r\nrandom.seed(time.time()) # 'random.random()#生成[0,1)之间的随机数\r\n\r\nwriteRandomNetworkToFile() # 将随机网络写入randomNetwork01.txt文件中\r\ncalculateDegreeDistribution() # 计算此ER随机网络的度分布并将结果写入文件degreee01.txt文件中\r\n\r\nprint('您所构造的ER网络如下:')\r\nshowGraph()\r\n\r\n","sub_path":"网络科学导论/网络科学导论作业/ER_NE.py","file_name":"ER_NE.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"529353541","text":"import requests\n\nfrom .exceptions import (ObjectAlreadyExists,\n ObjectNotFound, ObjectUnprocessable,\n RequestMalformed, RequestUnauthorized,\n ServerError, TypesenseClientError)\n\n\nclass ApiCall(object):\n API_KEY_HEADER_NAME = 'X-TYPESENSE-API-KEY'\n\n def __init__(self, config):\n self.config = config\n\n def nodes(self):\n return [self.config.master_node] + self.config.read_replica_nodes\n\n @staticmethod\n def get_exception(http_code):\n if http_code == 400:\n return RequestMalformed\n elif http_code == 401:\n return RequestUnauthorized\n elif http_code == 404:\n return ObjectNotFound\n elif http_code == 409:\n return ObjectAlreadyExists\n elif http_code == 422:\n return ObjectUnprocessable\n elif http_code == 500:\n return ServerError\n else:\n return TypesenseClientError\n\n def get(self, endpoint, params=None, as_json=True):\n params = params or {}\n\n for node in self.nodes():\n url = node.url() + endpoint\n print(url)\n try:\n r = requests.get(url,\n headers={ApiCall.API_KEY_HEADER_NAME: node.api_key},\n params=params,\n timeout=self.config.timeout_seconds)\n print(r)\n if r.status_code != 200:\n error_message = r.json().get('message', 'API error.')\n raise ApiCall.get_exception(r.status_code)(error_message)\n return r.json() if as_json else r.text\n except requests.exceptions.Timeout:\n pass\n except requests.exceptions.ConnectionError:\n pass\n except TypesenseClientError as typesense_client_error:\n raise typesense_client_error\n except Exception as e:\n raise e\n\n raise TypesenseClientError('All hosts are bad.')\n\n def post(self, endpoint, body):\n url = self.config.master_node.url() + endpoint\n api_key = self.config.master_node.api_key\n\n r = requests.post(url, json=body,\n headers={ApiCall.API_KEY_HEADER_NAME: api_key},\n timeout=self.config.timeout_seconds)\n if r.status_code != 201:\n error_message = r.json().get('message', 'API error.')\n print(url)\n raise ApiCall.get_exception(r.status_code)(error_message)\n\n return r.json()\n\n def delete(self, endpoint):\n url = self.config.master_node.url() + endpoint\n api_key = self.config.master_node.api_key\n\n r = requests.delete(url,\n headers={ApiCall.API_KEY_HEADER_NAME: api_key},\n timeout=self.config.timeout_seconds)\n if r.status_code != 200:\n error_message = r.json().get('message', 'API error.')\n raise ApiCall.get_exception(r.status_code)(error_message)\n\n return r.json()\n","sub_path":"typesense/api_call.py","file_name":"api_call.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"356748570","text":"import statistics\nimport math\nimport textwrap\nimport datetime\nimport calendar\nimport collections\n\nblah = dict(\n tracks = 0, landfalls=0, landfall_TC = 0, landfall_TD = 0,\n landfall_TS = 0, landfall_HU = 0, landfall_MHU = 0,\n TSreach = 0, HUreach = 0, MHUreach = 0, track_distance = 0,\n track_distance_TC = 0, track_distance_TS = 0,\n track_distance_HU = 0, track_distance_MHU = 0,\n ACE = 0, HDP = 0, MHDP = 0, cat45reach = 0, cat5reach = 0\n)\n\nclass Hurdat2Calculations:\n\n def rank_seasons(self, quantity, stattr, year1=None, year2=None, descending=True, **kw):\n \"\"\"Rank and compare full tropical cyclone seasons to one another.\n\n Required Arguments:\n quantity: how long of a list of ranks do you want; an integer.\n stattr: the storm attribute that you'd like to rank seasons by.\n \n * Storm Attributes: \n \"tracks\", \"landfall_TC\", \"TSreach\", \"HUreach\", \"MHUreach\",\n \"track_distance_TC\", \"ACE\", \"track_distance_TS\", \"HDP\",\n \"track_distance_HU\", \"MHDP\", \"track_distance_MHU\"\n\n * Note: Though attributes \"track_distance\", \"landfalls\", \n \"landfall_TD\", \"landfall_TS\", \"landfall_HU\",\n \"landfall_MHU\", \"TDonly\", \"TSonly\", \"HUonly\", \"cat45reach\",\n and \"cat5reach\" are valid storm attributes to rank by,\n their quantities will not be visible in the ranking output.\n\n Default Arguments:\n year1 (None): begin year. If included, the indicated year will\n represent the low-end of years to assess. In the absence of\n the end-year, all years from this begin year to the end of the\n record-range will be used in ranking.\n year2 (None): end year. If included, the indicated year will\n represent the upper-end of years to assess. In the absence of\n the begin-year, all years from the start of the record-range\n to this indicated year will be used in ranking.\n descending (True): bool to indicate sorting seasons in descending\n (higher-to-lower) or not. The default of True implies seasons\n will be ranked from higher-to-lower.\n\n Examples:\n ---------\n .rank_seasons(10,\"ACE\"): Retrieve a report of tropical\n cyclone seasons sorted by the top-10 Accumulated Cyclone\n Energy values.\n .rank_seasons(15,\"HDP\",1967): Retrieve a report of tropical\n cyclone seasons sorted by the top-15 Hurricane Destruction\n Potential values occurring since 1967 (the beginning of the\n satellite era).\n .rank_seasons(5,\"track_distance_TS\",1951,2000,True):\n Retrieve a report of the bottom-5 seasons of distance\n traversed by, at-least, tropical storms, all between 1951 and\n 2000.\n .rank_seasons(10,\"HUreach\",year2=2000): Retrieves a report \n of the top-10 seasons with the most Hurricanes prior-to, and\n including the year 2000.\n \"\"\"\n\n # --------------------\n year1 = abs(year1) \\\n if type(year1) == int \\\n and abs(year1) >= self.record_range[0] \\\n else self.record_range[0]\n year2 = abs(year2) \\\n if type(year2) == int \\\n and abs(year2) <= self.record_range[1] \\\n else self.record_range[1]\n\n year1, year2 = [\n min([year1, year2]),\n max([year1, year2])\n ]\n\n if len(range(year1, year2)) == 0:\n raise ValueError(\"The years given must be different!\")\n\n # List seasons sorted by stattr\n sorted_seasons = sorted(\n [s for s in self.season.values() if year1 <= s.year <= year2],\n key=lambda czen: getattr(czen, stattr),\n reverse = descending\n )\n # Values sorted\n ranks = sorted(\n set([\n getattr(s, stattr) for s in sorted_seasons \\\n if descending is False \\\n or (getattr(s, stattr) > 0 and kw.get(\"info\") is None) \\\n or kw.get(\"info\") is not None\n ]),\n reverse = descending\n )[:quantity]\n\n # RETURN if _season_stats (via rank_seasons_thru) method called this method\n if kw.get(\"info\", None) is not None:\n # insert years data if not included in original ranking\n if (year1 <= kw[\"info\"] <= year2) is False:\n ranks = sorted(\n ranks + [getattr(self.season[kw[\"info\"]], stattr)],\n reverse = descending\n )\n return {\n \"seasonvalu\": getattr(self.season[kw[\"info\"]], stattr),\n \"rank\": ranks.index(getattr(self.season[kw[\"info\"]], stattr)) + 1,\n \"tied\": len([\"tie\" for season in sorted_seasons if getattr(season, stattr) == getattr(self.season[kw[\"info\"]], stattr)]) - 1,\n \"outof\": len(ranks)\n }\n # List that holds printed quantities\n printedqty = []\n \n print(\"\")\n print(\"TOP {} SEASONS RANKED BY {}\".format(\n len(ranks),\n stattr.upper()\n ).center(79))\n\n print(\"{}{}\".format(\n str(self.basin()),\n \", {}-{}\".format(year1, year2)\n ).center(79))\n print(\"-\" * 79)\n\n print(\"{:4} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^25}\".format(\n \"\",\"\",\"\",\"LAND\",\"QTY\",\"\",\"\",\"TC DIST\",\n \"STATUS-RELATED TRACK\" if \"track_distance\" in stattr else \"ENERGY INDICES\"\n ))\n print(\"{:4} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^25}\".format(\n \"\",\"\",\"NUM OF\",\"FALL\",\"TRPC\",\"QTY\",\"QTY\",\"TRAVRSD\",\n \"DISTANCES (in nmi)\" if \"track_distance\" in stattr else \"x10^4 kt^2\"\n ))\n print(\"RANK YEAR {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^7} {:^7} {:^7}\".format(\n \"TRACKS\",\"TCs\",\"STRM\",\"HURR\",\"MAJ\",\"(nmi)\",\n \"TRPCSTM\" if \"track_distance\" in stattr else \"ACE\",\n \"HURRICN\" if \"track_distance\" in stattr else \"HDP\",\n \"MAJHURR\" if \"track_distance\" in stattr else \"MHDP\"\n ))\n print(\"{:-^4} {:-^4} {:-^6} {:-^4} {:-^4} {:-^4} {:-^3} {:-^7} {:-^7} {:-^7} {:-^7}\".format(\n \"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"\n ))\n for season in sorted_seasons:\n try:\n current_rank = ranks.index(getattr(season, stattr)) + 1 \\\n if ranks.index(getattr(season, stattr)) + 1 \\\n not in printedqty else None\n except:\n break\n print(\"{:>3}{:1} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:>7.1f} {:>{ACELEN}f} {:>{ACELEN}f} {:>{ACELEN}f}\".format(\n current_rank if current_rank is not None else \"\", \n \".\" if current_rank is not None else \"\",\n season.year,\n season.tracks,\n season.landfall_TC,\n season.TSreach,\n season.HUreach,\n season.MHUreach,\n season.track_distance_TC,\n season.track_distance_TS if \"track_distance\" in stattr \\\n else season.ACE * math.pow(10,-4),\n season.track_distance_HU if \"track_distance\" in stattr \\\n else season.HDP * math.pow(10,-4),\n season.track_distance_MHU if \"track_distance\" in stattr \\\n else season.MHDP * math.pow(10,-4),\n ACELEN = 7.1 if \"track_distance\" in stattr else 7.3\n ))\n if current_rank is not None and current_rank not in printedqty:\n printedqty.append(current_rank)\n print(\"\")\n\n def rank_seasons_thru(self, quantity, stattr, year1=None, year2=None, descending=True, **kw):\n \"\"\"Rank and compare *partial* tropical cyclone seasons to one another.\n\n * Of note, if neither `start` or `thru` keywords are included, this\n function becomes a wrapper for .rank_seasons\n\n Required Arguments:\n quantity: how long of a list of ranks do you want; an integer.\n stattr: the storm attribute that you'd like to rank seasons by.\n \n * Storm Attributes: \n \"tracks\", \"landfall_TC\", \"TSreach\", \"HUreach\", \"MHUreach\",\n \"track_distance_TC\", \"ACE\", \"track_distance_TS\", \"HDP\",\n \"track_distance_HU\", \"MHDP\", \"track_distance_MHU\"\n\n * Note: Though attributes \"track_distance\", \"landfalls\", \n \"landfall_TD\", \"landfall_TS\", \"landfall_HU\",\n \"landfall_MHU\", \"TDonly\", \"TSonly\", \"HUonly\", \"cat45reach\",\n and \"cat5reach\" are valid storm attributes to rank by,\n their quantities will not be visible in the ranking output.\n\n Default Arguments:\n year1 = None: begin year. If included, the indicated year will\n represent the low-end of years to assess. In the absence of\n the end-year, all years from this begin year to the end of the\n record-range will be used in ranking.\n year2 = None: end year. If included, the indicated year will\n represent the upper-end of years to assess. In the absence of\n the begin-year, all years from the start of the record-range\n to this indicated year will be used in ranking.\n descending = True: parallel bool used to determine reverse kw of\n sorted calls; whether results will be printed higher-to-lower\n or not.\n\n Keyword Arguments:\n start = (1, 1): list/tuple given to indicate the starting month and\n day wherein a season's calculations will be made.\n thru = (12,31): list/tuple representing the month and day that you\n want to assess the seasons through. If start != (1,1) but thru\n == (12,31), the stats reported will be through the Season's\n ending.\n\n Examples:\n ---------\n .rank_seasons_thru(10, \"ACE\", thru=[8,31]): Retrieve a report\n of tropical cyclone seasons sorted by the top-10 ACE values through\n August 31.\n .rank_seasons_thru(10, \"TSreach\", 1967, thru=[9,15]): Retrieve\n a report of tropical cyclone seasons sorted by the top-10 totals of\n tropical storms through September 15, since 1967 (the satellite\n era).\n .rank_seasons_thru(20, \"track_distance_TC\", start=[7,1], thru=(10,31)):\n Retrieve a report of the top-20 seasons of total distance traversed\n by storms while being designated as tropical cyclones, between July\n 1st and the end of October.\n \"\"\"\n\n year1 = self.record_range[0] if year1 is None \\\n or year1 < self.record_range[0] else year1\n year2 = self.record_range[1] if year2 is None \\\n or year2 > self.record_range[1] else year2\n\n # Partial-Season Bookened Month, Day Tuples\n start = kw.get(\"start\", (1,1))\n thru = kw.get(\"thru\", (12,31))\n\n # error if thru or start are not list/tuples\n if type(thru) not in [list,tuple]:\n return print(\"OOPS! Ensure thru is a list or tuple of (month,day)\")\n if type(start) not in [list,tuple]:\n return print(\"OOPS! Ensure start is a list or tuple of (month,day)\")\n\n # If the full year is being asked for, this is essentially just a\n # wrapper for the regular rank_seasons method\n if start == (1,1) and thru == (12,31):\n result = self.rank_seasons(\n quantity,\n stattr,\n year1,\n year2,\n descending,\n info=kw.get(\"info\")\n )\n return result\n\n rseason = {}\n for season in [s for s in self.season.values() \\\n if year1 <= s.year <= year2 \\\n or (kw.get(\"info\") is not None \\\n and s.year == kw.get(\"info\"))]:\n yr = season.year\n rseason[yr] = dict(\n tracks = 0, landfalls=0, landfall_TC = 0, landfall_TD = 0,\n landfall_TS = 0, landfall_HU = 0, landfall_MHU = 0,\n TSreach = 0, HUreach = 0, MHUreach = 0, track_distance = 0,\n track_distance_TC = 0, track_distance_TS = 0,\n track_distance_HU = 0, track_distance_MHU = 0,\n ACE = 0, HDP = 0, MHDP = 0, cat45reach = 0, cat5reach = 0\n )\n # account for a non-existant season being requested by stats method\n if kw.get(\"info\") is not None and kw.get(\"info\") not in self.season:\n rseason[kw.get(\"info\")] = dict(\n tracks = 0, landfalls=0, landfall_TC = 0, landfall_TD = 0,\n landfall_TS = 0, landfall_HU = 0, landfall_MHU = 0,\n TSreach = 0, HUreach = 0, MHUreach = 0, track_distance = 0,\n track_distance_TC = 0, track_distance_TS = 0,\n track_distance_HU = 0, track_distance_MHU = 0,\n ACE = 0, HDP = 0, MHDP = 0, cat45reach = 0, cat5reach = 0\n )\n for tc in season.tc.values():\n track_added = False\n lndfls = False; lndfl_TC = False; lndfl_TD = False;\n lndfl_TS = False; lndfl_HU = False; lndfl_MHU = False;\n rTS = False; rHU = False; rMHU = False; r45 = False; r5 = False\n entries = [\n trk for trk in tc.entry #\\\n # if start <= trk.month_day_tuple <= thru\n ]\n for INDX, ENTRY in enumerate(tc.entry):\n # Handle Track Distance related vars;\n # only need to check validity of INDX-1\n # if INDX >= 1 and start <= tc.entry[INDX-1].month_day_tuple <= thru:\n if INDX >= 1 \\\n and ((thru != (12,31) and start <= tc.entry[INDX-1].month_day_tuple <= thru) \\\n or (thru == (12,31) and datetime.date(tc.year, *start) <= tc.entry[INDX-1].entrytime.date())):\n rseason[yr][\"track_distance\"] += haversine(\n tc.entry[INDX-1].location,\n tc.entry[INDX].location\n )\n rseason[yr][\"track_distance_TC\"] += haversine(\n tc.entry[INDX-1].location,\n tc.entry[INDX].location\n ) if tc.entry[INDX-1].status in (\"SD\",\"TD\",\"SS\",\"TS\",\"HU\") else 0\n rseason[yr][\"track_distance_TS\"] += haversine(\n tc.entry[INDX-1].location,\n tc.entry[INDX].location\n ) if tc.entry[INDX-1].status in (\"SS\",\"TS\",\"HU\") else 0\n rseason[yr][\"track_distance_HU\"] += haversine(\n tc.entry[INDX-1].location,\n tc.entry[INDX].location\n ) if tc.entry[INDX-1].status == \"HU\" else 0\n rseason[yr][\"track_distance_MHU\"] += haversine(\n tc.entry[INDX-1].location,\n tc.entry[INDX].location\n ) if tc.entry[INDX-1].status == \"HU\" \\\n and tc.entry[INDX-1].wind >= 96 else 0\n # Handle everything else\n if (thru != (12,31) and start <= ENTRY.month_day_tuple <= thru) \\\n or (thru == (12,31) and datetime.date(tc.year, *start) <= ENTRY.entrytime.date()):\n # if start <= ENTRY.month_day_tuple <= thru:\n rseason[yr][\"ACE\"] += math.pow(ENTRY.wind,2) \\\n if ENTRY.wind >= 34 \\\n and ENTRY.status in (\"SS\",\"TS\",\"HU\") \\\n and ENTRY.is_synoptic \\\n else 0\n rseason[yr][\"HDP\"] += math.pow(ENTRY.wind,2) \\\n if ENTRY.wind >= 64 \\\n and ENTRY.status == \"HU\" \\\n and ENTRY.is_synoptic \\\n else 0\n rseason[yr][\"MHDP\"] += math.pow(ENTRY.wind,2) \\\n if ENTRY.wind >= 96 and ENTRY.status == \"HU\" \\\n and ENTRY.is_synoptic \\\n else 0\n if track_added is False:\n rseason[yr][\"tracks\"] += 1\n track_added = True\n if lndfls is False and ENTRY.record_identifier == \"L\":\n rseason[yr][\"landfalls\"] += 1\n lndfls = True\n if lndfl_TC is False and ENTRY.record_identifier == \"L\" \\\n and ENTRY.is_TC:\n rseason[yr][\"landfall_TC\"] += 1\n lndfl_TC = True\n if lndfl_TD is False and ENTRY.record_identifier == \"L\" \\\n and ENTRY.status in [\"SD\",\"TD\"]:\n rseason[yr][\"landfall_TD\"] += 1\n lndfl_TD = True\n if lndfl_TS is False and ENTRY.record_identifier == \"L\" \\\n and ENTRY.status in [\"SS\",\"TS\",\"HU\"]:\n rseason[yr][\"landfall_TS\"] += 1\n lndfl_TS = True\n if lndfl_HU is False and ENTRY.record_identifier == \"L\" \\\n and ENTRY.status == \"HU\":\n rseason[yr][\"landfall_HU\"] += 1\n lndfl_HU = True\n if lndfl_MHU is False and ENTRY.record_identifier == \"L\" \\\n and ENTRY.status == \"HU\" and ENTRY.wind >= 96:\n rseason[yr][\"landfall_MHU\"] += 1\n lndfl_MHU = True\n if rTS is False and ENTRY.status in [\"SS\",\"TS\",\"HU\"]:\n rseason[yr][\"TSreach\"] += 1\n rTS = True\n if rHU is False and ENTRY.status in [\"HU\"]:\n rseason[yr][\"HUreach\"] += 1\n rHU = True\n if rMHU is False and ENTRY.wind >= 96:\n rseason[yr][\"MHUreach\"] += 1\n rMHU = True\n if r45 is False and ENTRY.wind >= 114:\n rseason[yr][\"cat45reach\"] += 1\n r45 = True\n if r5 is False and ENTRY.wind >= 136:\n rseason[yr][\"cat5reach\"] += 1\n r5 = True\n\n sorted_seasons = sorted(\n [s for s in self.season.values() if year1 <= s.year <= year2],\n key=lambda s: rseason[s.year][stattr],\n reverse = descending\n )\n # Values sorted\n ranks = sorted(\n set([\n rseason[s.year][stattr] for s in sorted_seasons \\\n if descending is False \\\n or (rseason[s.year][stattr] > 0 and kw.get(\"info\") is None) \\\n or kw.get(\"info\") is not None\n ]),\n reverse = descending\n )[:quantity]\n\n # RETURN if info method called this method\n if kw.get(\"info\", None) is not None:\n if (year1 <= kw[\"info\"] <= year2) is False:\n ranks = sorted(\n ranks + [rseason[kw[\"info\"]][stattr]],\n reverse = descending\n )\n return {\n \"seasonvalu\": rseason[kw[\"info\"]][stattr],\n \"rank\": ranks.index(rseason[kw[\"info\"]][stattr]) + 1,\n \"tied\": len([\"tie\" for season in rseason.values() if season[stattr] == rseason[kw[\"info\"]][stattr]]) - 1,\n \"outof\": len(ranks)\n }\n\n # List that holds printed quantities\n printedqty = []\n\n print(\"\")\n print(\"TOP {} SEASONS RANKED BY {}, {}\".format(\n len(ranks),\n stattr.upper(),\n \"{}through {}\".format(\n \"from {} \".format(\n \"{} {}\".format(\n calendar.month_abbr[start[0]], start[1]\n )\n ) if \"start\" in kw else \"\",\n \"{} {}\".format(\n calendar.month_abbr[thru[0]], thru[1]\n ) if thru != (12,31) else \"End of Season\"\n )\n ).center(79)\n )\n\n print(\"{}{}\".format(\n str(self.basin()),\n \", {}-{}\".format(year1, year2)\n ).center(79))\n print(\"-\" * 79)\n\n print(\"{:4} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^25}\".format(\n \"\",\"\",\"\",\"LAND\",\"QTY\",\"\",\"\",\"TC DIST\",\n \"STATUS-RELATED TRACK\" if \"track_distance\" in stattr else \"ENERGY INDICES\"\n ))\n print(\"{:4} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^25}\".format(\n \"\",\"\",\"NUM OF\",\"FALL\",\"TRPC\",\"QTY\",\"QTY\",\"TRAVRSD\",\n \"DISTANCES (nmi)\" if \"track_distance\" in stattr else \"x10^4 kt^2\"\n ))\n print(\"RANK YEAR {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^7} {:^7} {:^7}\".format(\n \"TRACKS\",\"TCs\",\"STRM\",\"HURR\",\"MAJ\",\"(nmi)\",\n \"TRPCSTM\" if \"track_distance\" in stattr else \"ACE\",\n \"HURRICN\" if \"track_distance\" in stattr else \"HDP\",\n \"MAJHURR\" if \"track_distance\" in stattr else \"MHDP\"\n ))\n print(\"{:-^4} {:-^4} {:-^6} {:-^4} {:-^4} {:-^4} {:-^3} {:-^7} {:-^7} {:-^7} {:-^7}\".format(\n \"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"\n ))\n for season in sorted_seasons:\n try:\n current_rank = ranks.index(rseason[season.year][stattr]) + 1 \\\n if ranks.index(rseason[season.year][stattr]) + 1 \\\n not in printedqty else None\n except:\n # indicates bounds beyond quantity asked for exceeded\n break\n print(\"{:>3}{:1} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:>7.1f} {:>{ACELEN}f} {:>{ACELEN}f} {:>{ACELEN}f}\".format(\n current_rank if current_rank is not None else \"\", \n \".\" if current_rank is not None else \"\",\n season.year,\n rseason[season.year][\"tracks\"],\n rseason[season.year][\"landfall_TC\"],\n rseason[season.year][\"TSreach\"],\n rseason[season.year][\"HUreach\"],\n rseason[season.year][\"MHUreach\"],\n rseason[season.year][\"track_distance_TC\"],\n rseason[season.year][\"track_distance_TS\"] if \"track_distance\" in stattr else rseason[season.year][\"ACE\"] * math.pow(10,-4),\n rseason[season.year][\"track_distance_HU\"] if \"track_distance\" in stattr else rseason[season.year][\"HDP\"] * math.pow(10,-4),\n rseason[season.year][\"track_distance_MHU\"] if \"track_distance\" in stattr else rseason[season.year][\"MHDP\"] * math.pow(10,-4),\n ACELEN = 7.1 if \"track_distance\" in stattr else 7.3\n ))\n if current_rank is not None and current_rank not in printedqty:\n printedqty.append(current_rank)\n print(\"\")\n\n def rank_storms(self, quantity, stattr, year1=None, year2=None, coordextent=None, contains_method=\"anywhere\"):\n \"\"\"Rank and compare individual tropical cyclones to one another.\n\n Required Arguments:\n quantity: how long of a list of ranks do you want; an integer.\n stattr: the storm attribute that you'd like to rank seasons by.\n \n * Working Storm Attributes for ranking: \n \"track_distance_TC\", \"landfalls\", \"maxwind\", \"minmslp\",\n \"ACE\", \"track_distance_TS\", \"HDP\", \"track_distance_HU\",\n \"MHDP\", \"track_distance_MHU\"\n\n * The following attributes will not work because at the\n individual storm level these are bools:\n \"landfall_TC\", \"landfall_TD\", \"landfall_TS\", \"landfall_HU\",\n \"landfall_MHU\", \"TSreach\", \"HUreach\", \"MHUreach\",\n \"cat45reach\", \"cat5reach\"\n\n * Other attributes of class TropicalCyclone that are not\n mentioned here will work for ranking too, but their actual\n values will not display on the printed report.\n\n Default Arguments:\n year1 (None): begin year. If included, the indicated year will\n represent the low-end of years to assess. In the absence of\n the end-year, all years from this begin year to the end of the\n record-range will be used to determine ranking.\n year2 (None): end year. If included, the indicated year will\n represent the upper-end of years to assess. In the absence of\n the begin-year, all years from the start of the record-range\n to this indicated year will be used to determine ranking.\n coordextent (None): **EXPERIMENTAL** This accepts 2 tupled latitude\n and longitude coordinates, representing a geographical\n bounding-box. The use of this bounding-box is determined by the\n kwarg, contains_method. See the documentation for determination\n of use. The results from using these two arguments only\n indicates that the track of the storm identified *AT SOME\n POINT* tracked into this bounding-box. It in no way indicates\n that the ranked value occurred within.\n contains_method (\"anywhere\"): if a coordinate extent is included (see\n above), this default argument determines this method's\n strategy. The default of 'anywhere' implies that all matching\n storms will be further discriminated by whether or not any point of their track occurred within the bounding-box (coordextent). A value of \"start\" means if the start of the storm's track occurred in the bounding-box.\n\n Examples:\n ---------\n .rank_storms(10, \"ACE\"): Retrieve a report of tropical\n cyclones sorted by the top-10 values of Accumulated Cyclone\n Energy on record.\n .rank_storms(20, \"HDP\", 1967): Retrieve a report of tropical\n cyclones sorted by the top-20 values of Hurricane Destruction\n Potential since 1967 (the beginning of the satellite era).\n .rank_storms(5, \"minmslp\", 1901, 1940): Retrieve a report of the\n top-5 tropical cyclones with the lowest minimum pressure\n readings between 1901 and 1940.\n .rank_storms(10, \"maxwind\", coordextent=[(31,-98), (18,-80)])\n Retrieve a report of the top 10 storms, ranked by max-wind,\n whose genesis occurred in (roughly) the Gulf of Mexico.\n \"\"\"\n\n year1 = self.record_range[0] if year1 is None \\\n or year1 < self.record_range[0] else year1\n year2 = self.record_range[1] if year2 is None \\\n or year2 > self.record_range[1] else year2\n\n # List of tropical-cyclones sorted by stattr\n sorted_storms = sorted(\n [tc for tc in self.tc.values() if year1 <= tc.year <= year2],\n key=lambda tc: getattr(tc, stattr),\n reverse = False if stattr == \"minmslp\" else True\n )\n # Values sorted\n ranks = sorted(\n set([\n getattr(tc, stattr) for tc in sorted_storms \\\n if stattr == \"minmslp\" \\\n or getattr(tc, stattr) > 0\n ]),\n reverse = False if stattr == \"minmslp\" else True\n )[:quantity]\n\n # If bounding-box coords provided...\n if coordextent is not None:\n contains_method = contains_method.lower() # Ensure lowercase\n # Warning message\n if contains_method not in [\"start\", \"anywhere\"]:\n print(\n \"* Defaulting to 'anywhere' location method. The only \"\n \"valid values for the contains_method keyword argument \"\n \"are 'start' and 'anywhere'.\"\n )\n contains_method = \"anywhere\"\n # Just search starting point\n if contains_method == \"start\":\n sorted_storms = [\n TC for TC in sorted_storms if self.coord_contains(\n TC.entry[0].location,\n coordextent[0],\n coordextent[1]\n )\n ]\n # Any point within the bounding-box\n else:\n sorted_storms = [\n TC for TC in sorted_storms \\\n if any(\n self.coord_contains(\n entry.location,\n *coordextent\n ) for entry in TC.entry\n )\n ]\n ranks = sorted(\n set([\n getattr(TC, stattr) for TC in sorted_storms \\\n if stattr == \"minmslp\" \\\n or getattr(TC, stattr) > 0\n ]),\n reverse = False if stattr == \"minmslp\" else True\n )[:quantity]\n\n # List that holds printed quantities\n printedqty = []\n\n print(\"\")\n print(\"TOP {} STORMS RANKED BY {}\".format(\n len(ranks),\n stattr.upper()\n ).center(79))\n if coordextent is not None:\n print(\"{:^79}\".format(\n \"* Coordinate Bounding-Box: {}; {}\".format(\n \"{}{} {}{}\".format(\n abs(coordextent[0][0]),\n \"N\" if coordextent[1][0] >= 0 else \"S\",\n abs(coordextent[0][1]),\n \"W\" if -180 < coordextent[1][1] <= 0 else \"E\"\n ),\n \"{}{} {}{}\".format(\n abs(coordextent[1][0]),\n \"N\" if coordextent[1][0] >= 0 else \"S\",\n abs(coordextent[1][1]),\n \"W\" if -180 < coordextent[1][1] <= 0 else \"E\"\n )\n )\n ))\n\n print(\"{}{}\".format(\n str(self.basin()),\n \", {}-{}\".format(year1, year2)\n ).center(79))\n print(\"-\" * 79)\n\n print(\"{:^4} {:^10} {:^8} {:^4} {:^4} {:^4} {:^6} {:^22}\".format(\n \"\",\"\",\"\",\"LAND\",\"\",\"\",\"TCDIST\",\n \"STATUS-RELATED TRACK\" if \"track\" in stattr else \"ENERGY INDICES\"\n ))\n print(\"{:^4} {:^10} {:^8} {:^4} {:>4} {:>4} {:^6} {:^22}\".format(\n \"\",\"\",\"\",\"FALL\",\"MIN\",\"MAX\",\"TRVRSD\",\n \"DISTANCES (nmi)\" if \"track\" in stattr else \"x10^4 kt^2\"\n ))\n print(\"{:^4} {:<10} {:^8} {:<4} {:^4} {:^4} {:^6} {:^6} {:^6} {:^6}\".format(\n \"RANK\",\"NAME\",\"ATCFID\",\"QTY\",\"MSLP\",\"WIND\",\"(nmi)\",\n \"TRPCST\" if \"track\" in stattr else \"ACE\",\n \"HURRCN\" if \"track\" in stattr else \"HDP\",\n \"MAJHUR\" if \"track\" in stattr else \"MHDP\"\n ))\n print(\"{:-^4} {:-^10} {:-^8} {:-^4} {:-^4} {:-^4} {:-^6} {:-^6} {:-^6} {:-^6}\".format(\n \"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"\n ))\n\n for TC in sorted_storms:\n try:\n current_rank = ranks.index(getattr(TC, stattr)) + 1 \\\n if ranks.index(getattr(TC, stattr)) + 1 \\\n not in printedqty else None\n except:\n break\n print(\"{:>3}{:1} {:<10} {:8} {:^4} {:>4} {:>4} {:>6.1f} {:>{ACELEN}f} {:>{ACELEN}f} {:>{ACELEN}f}\".format(\n current_rank if current_rank is not None else \"\", \n \".\" if current_rank is not None else \"\",\n TC.name.title(),\n TC.atcfid,\n TC.landfalls,\n TC.minmslp if TC.minmslp is not None else \"N/A\",\n TC.maxwind if TC.maxwind > 0 else \"N/A\",\n TC.track_distance_TC,\n TC.track_distance_TS if \"track\" in stattr else TC.ACE * math.pow(10,-4),\n TC.track_distance_HU if \"track\" in stattr else TC.HDP * math.pow(10,-4),\n TC.track_distance_MHU if \"track\" in stattr else TC.MHDP * math.pow(10,-4),\n ACELEN = 6.1 if \"track\" in stattr else 6.3\n ))\n if current_rank is not None and current_rank not in printedqty:\n printedqty.append(current_rank)\n print(\"\")\n\n def rank_climo(self, quantity, stattr, year1=None, year2=None, descending=True, **climoparam):\n \"\"\"Rank and compare climatological eras to one another.\n\n Required Arguments:\n quantity: how long of a list of ranks do you want; an integer.\n stattr: the storm attribute that you'd like to rank seasons by.\n \n * Working Storm Attributes for ranking: \n \"track_distance_TC\", \"landfalls\", \"maxwind\", \"minmslp\",\n \"ACE\", \"track_distance_TS\", \"HDP\", \"track_distance_HU\",\n \"MHDP\", \"track_distance_MHU\"\n\n * The following attributes will not work because at the\n individual storm level these are bools:\n \"landfall_TC\", \"landfall_TD\", \"landfall_TS\", \"landfall_HU\",\n \"landfall_MHU\", \"TSreach\", \"HUreach\", \"MHUreach\",\n \"cat45reach\", \"cat5reach\"\n\n * Other attributes of class TropicalCyclone that are not\n mentioned here will work for ranking too, but their actual\n values will not display on the printed report.\n\n Default Arguments:\n year1 (None): begin year. If included, the indicated year will\n represent the low-end of years to assess. In the absence of\n the end-year, all years from this begin year to the end of the\n record-range will be used to determine ranking.\n year2 (None): end year. If included, the indicated year will\n represent the upper-end of years to assess. In the absence of\n the begin-year, all years from the start of the record-range\n to this indicated year will be used to determine ranking.\n descending (True): parallel bool used to determine reverse kw of\n sorted calls; whether results will be printed higher-to-lower\n or not.\n \n Optional Keyword Arguments (**climoparam):\n * These control Climatological Spans and Extents *\n climatology (30): the quantity of years that will be assessed per\n climate era.\n increment (5): the time (in years) between one climate era and the\n next (ex. 1981-2010, 1986-2015, etc).\n\n Examples:\n ---------\n .rank_climo(10,\"ACE\"): Retrieve the top 10 climate eras in the\n record that have the largest ACE (30yr climo; 5yr incremented)\n .rank_climo(20,\"track_distance_TC\", climatology=10, increment=1):\n Retrieve the top 20 10-year climatological eras (incremented by 1\n year) of accumulated tropical cyclone track-distance.\n \"\"\"\n climatology = climoparam.get(\"climatology\", 30)\n increment = climoparam.get(\"increment\", 5)\n\n year1 = self.record_range[0] if year1 is None \\\n or year1 < self.record_range[0] else year1\n year2 = self.record_range[1] if year2 is None \\\n or year2 > self.record_range[1] else year2\n\n Era = collections.namedtuple(\"Era\", [\"era\", stattr])\n\n climo = {} # dictionary to hold the climatology data\n\n for yr1, yr2 in [(y, y+climatology-1) \\\n for y in range(1801, year2, increment) \\\n if year1 <= y <= year2 \\\n and year1 <= y+climatology-1 <= year2]:\n climo[yr1, yr2] = Era(\n (yr1, yr2),\n sum(getattr(self.season[s], stattr) for s in range(yr1, yr2+1))\n )\n\n # List of tropical-cyclones sorted by stattr\n sorted_climo = sorted(\n [era for era in climo.values()],\n key=lambda era: getattr(era, stattr),\n reverse = descending\n )\n # Values sorted\n ranks = sorted(\n set([\n getattr(era, stattr) for era in sorted_climo \\\n if descending is False \\\n or getattr(era, stattr) > 0\n ]),\n reverse = descending\n )[:quantity]\n\n # Rank printed list\n printedqty = []\n\n print(\"\")\n print(\"{:^41}\".format(\n \"TOP {} CLIMATOLOGICAL PERIODS\".format(quantity)\n ))\n print(\"{:^41}\".format(\n \"RANKED BY {}\".format(stattr.upper())\n ))\n print(\"{}{}\".format(\n str(self.basin()),\n \", {}-{}\".format(year1, year2)\n ).center(41))\n\n print(\"{:-^41}\".format(\"\"))\n print(\"{:^41}\".format(\n \"{}-Year Climatologies; {}-Year Incremented\".format(\n climatology,\n increment\n )\n ))\n print(\"{:-^41}\".format(\"\"))\n print(\" {:^4} {:^9} {:^12}\".format(\n \"RANK\",\n \"PERIOD\",\n stattr.upper()\n ))\n print(\" {:-^4} {:-^9} {:-^12}\".format(\n \"\",\"\",\"\"\n ))\n for clmt in sorted_climo:\n try:\n current_rank = ranks.index(getattr(clmt, stattr)) + 1 \\\n if ranks.index(getattr(clmt, stattr)) + 1 \\\n not in printedqty else None\n except:\n break\n print(\" {:>4} {:9} {}\".format(\n \"{:>3}{:1}\".format(\n current_rank if current_rank is not None else \"\", \n \".\" if current_rank is not None else \"\"\n ),\n \"{}-{}\".format(*clmt.era),\n getattr(clmt,stattr)\n ))\n if current_rank is not None and current_rank not in printedqty:\n printedqty.append(current_rank)\n print(\"\")\n\n def _season_stats_str(self, seasonreq, year1, year2, rstart, rthru, width, **kw):\n strlist = []\n yr = seasonreq\n strlist.append(\"-\" * width)\n strlist.append(\"Tropical Cyclone Stats for {}\".format(yr).center(width))\n strlist.append(\n \"{}{}\".format(\n self.basin(),\n \"\"\n ).center(width)\n )\n strlist[-1] += \"\\n\"\n\n statyrline = \"Stats calculated for Seasons {}\".format(\n \"{}-{}\".format(\n year1,\n year2\n ) if year2 != self.record_range[1] \\\n else \"since {} ({} total seasons)\".format(\n year1,\n self.record_range[1] - year1 + 1\n )\n ).center(width)\n strlist.append(statyrline)\n\n if rstart != (1,1) or rthru != (12,31):\n strlist.append(\n \"from {} thru {}\".format(\n \"{} {}\".format(\n calendar.month_name[rstart[0]],\n rstart[1],\n ),\n \"{} {}\".format(\n calendar.month_name[rthru[0]],\n rthru[1],\n )\n ).center(width)\n )\n strlist[-1] += \"\\n\"\n for line in textwrap.wrap(\n \"* TS-related Statistics include Hurricanes in their totals\" \\\n \" except for landfall data\",\n width,\n initial_indent=\" \" * 4,\n subsequent_indent=\" \" * 4\n ):\n strlist.append(line.center(width))\n strlist[-1] += \"\\n\"\n if any(1971 <= y <= 1990 for y in range(year1, year2 + 1)):\n for line in textwrap.wrap(\n \"* Hurdat2 Landfall data incomplete for seasons 1971-1990\",\n width,\n initial_indent=\" \" * 4,\n subsequent_indent=\" \" * 4\n ):\n strlist.append(line.center(width))\n strlist.append(\"-\" * width)\n\n for attr, label in [\n (\"tracks\", \"Tropical Cyclones\"),\n (\"track_distance_TC\", \"TC Track Distance\"),\n (\"track_distance_TS\", \"TS Distance\"),\n (\"track_distance_HU\", \"HU Distance\"),\n (\"track_distance_MHU\", \"MHU Distance\"),\n (\"TSreach\", \"Tropical Storms\"),\n (\"ACE\", \"ACE\"),\n (\"HUreach\", \"Hurricanes\"),\n (\"HDP\", \"HDP\"),\n (\"MHUreach\", \"Major Hurricanes\"),\n (\"MHDP\", \"MHDP\"),\n (\"landfall_TC\", \"Total Landfalling TC's\"),\n (\"landfall_TS\", \"TS Landfalls\"),\n (\"landfall_HU\", \"HU Landfalls\")\n ]:\n if \"landfall\" not in attr or (\"landfall\" in attr and all(1971 <= y <= 1990 for y in range(year1, year2)) is False):\n rankinfo = self.rank_seasons_thru(\n 1337,\n attr,\n year1,\n year2,\n start = rstart,\n thru = rthru,\n descending=kw.get(\"descending\", True),\n info=yr\n )\n strlist.append('{:<35}Rank {}/{}{}'.format(\n \"* {}: {}{} \".format(\n label,\n \"{:.1f}\".format(rankinfo[\"seasonvalu\"]) \\\n if \"distance\" in attr \\\n else (\"{:.1f}\".format(rankinfo[\"seasonvalu\"] * 10 ** (-4)) \\\n if attr in [\"ACE\", \"HDP\", \"MHDP\"] \\\n else rankinfo[\"seasonvalu\"]\n ),\n \" nmi\" if \"track_distance\" in attr \\\n else (\" * 10^4 kt^2\" \\\n if attr in [\"ACE\", \"HDP\", \"MHDP\"] else \"\"\n ),\n ),\n rankinfo[\"rank\"],\n rankinfo[\"outof\"],\n \" (tied w/{} other season{})\".format(\n rankinfo[\"tied\"],\n \"s\" if rankinfo[\"tied\"] >= 2 else \"\"\n ) if rankinfo[\"tied\"] > 0 else \"\"\n ))\n strlist.append(\"\\n\")\n return \"\\n\".join(strlist)\n\n def _season_stats(self, seasonreq, year1, year2, rstart, rthru, width, **kw):\n\n yr = seasonreq\n\n print(\"\")\n print(\"-\" * width)\n print(\"Tropical Cyclone Stats for {}\".format(yr).center(width))\n print(\"{}{}\".format(\n self.basin(),\n \"\"\n ).center(width)\n )\n print(\"\")\n for line in textwrap.wrap(\n \"Stats calculated for Seasons {}\".format(\n \"{}-{}\".format(\n year1,\n year2\n ) if year2 != self.record_range[1] \\\n else \"since {} ({} total seasons)\".format(\n year1,\n self.record_range[1] - year1 + 1\n )\n ),\n width,\n initial_indent=\" \" * 4,\n subsequent_indent=\" \" * 4):\n print(line.center(width))\n if rstart != (1,1) or rthru != (12,31):\n print(\n \"from {} thru {}\".format(\n \"{} {}\".format(\n calendar.month_name[rstart[0]],\n rstart[1],\n ),\n \"{} {}\".format(\n calendar.month_name[rthru[0]],\n rthru[1],\n )\n ).center(width)\n )\n print(\"\")\n for line in textwrap.wrap(\n \"* TS-related Statistics include Hurricanes in their totals\" \\\n \" except for landfall data\",\n width,\n initial_indent=\" \" * 4,\n subsequent_indent=\" \" * 4):\n print(line.center(width))\n\n print(\"\")\n # Only print this disclaimer if years in this range overlap\n if any(1971 <= y <= 1990 for y in range(year1, year2 + 1)):\n for line in textwrap.wrap(\n \"* Hurdat2 Landfall data incomplete for seasons 1971-1990\",\n width,\n initial_indent=\" \" * 4,\n subsequent_indent=\" \" * 4):\n print(line.center(width))\n print(\"-\" * width)\n\n for attr, label in [\n (\"tracks\", \"Tropical Cyclones\"),\n (\"track_distance_TC\", \"TC Track Distance\"),\n (\"track_distance_TS\", \"TS Distance\"),\n (\"track_distance_HU\", \"HU Distance\"),\n (\"track_distance_MHU\", \"MHU Distance\"),\n (\"TSreach\", \"Tropical Storms\"),\n (\"ACE\", \"ACE\"),\n (\"HUreach\", \"Hurricanes\"),\n (\"HDP\", \"HDP\"),\n (\"MHUreach\", \"Major Hurricanes\"),\n (\"MHDP\", \"MHDP\"),\n (\"landfall_TC\", \"Total Landfalling TC's\"),\n (\"landfall_TS\", \"TS Landfalls\"),\n (\"landfall_HU\", \"HU Landfalls\")\n ]:\n if \"landfall\" not in attr or (\"landfall\" in attr and all(1971 <= y <= 1990 for y in range(year1, year2)) is False):\n rankinfo = self.rank_seasons_thru(\n 1337,\n attr,\n year1,\n year2,\n start = rstart,\n thru = rthru,\n descending=kw.get(\"descending\", True),\n info=yr\n )\n print('{:<35}Rank {}/{}{}'.format(\n \"* {}: {}{} \".format(\n label,\n \"{:.1f}\".format(rankinfo[\"seasonvalu\"]) \\\n if \"distance\" in attr \\\n else (\"{:.1f}\".format(rankinfo[\"seasonvalu\"] * 10 ** (-4)) \\\n if attr in [\"ACE\", \"HDP\", \"MHDP\"] \\\n else rankinfo[\"seasonvalu\"]\n ),\n \" nmi\" if \"track_distance\" in attr \\\n else (\" * 10^4 kt^2\" \\\n if attr in [\"ACE\", \"HDP\", \"MHDP\"] else \"\"\n ),\n ),\n rankinfo[\"rank\"],\n rankinfo[\"outof\"],\n \" (tied w/{} other season{})\".format(\n rankinfo[\"tied\"],\n \"s\" if rankinfo[\"tied\"] >= 2 else \"\"\n ) if rankinfo[\"tied\"] > 0 else \"\"\n ))\n print(\"\")\n\nclass SeasonCalculations:\n\n @property\n def start_date(self):\n \"\"\"The <> of the start of the season.\"\"\"\n return self.tc_entries[0].entrytime\n\n @property\n def start_ordinal(self):\n \"\"\"The day-number (1-365) of the year that the start of the season took\n place.\n \"\"\"\n return self.start_date.replace(year=1).toordinal()\n\n @property\n def end_date(self):\n \"\"\"The <> of the end of the season.\"\"\"\n last_tc_en = self.tc_entries[-1]\n return last_tc_en.next_entry.entrytime \\\n if last_tc_en.next_entry is not None \\\n else last_tc_en.entrytime\n\n @property\n def end_ordinal(self):\n \"\"\"The day-number (1-365) of the year that the end of the season\n occurred.\n\n In the event that the day number exceeds 365, it generally means that\n the season extended into the following year.\n \"\"\"\n end = self.end_date.replace(year=1).toordinal()\n # protect against seasons that extend into the following year\n if end <= self.start_ordinal:\n return self.end_date.replace(year=2).toordinal()\n else:\n return end\n\n @property\n def duration(self):\n \"\"\"Returns the duration of the season in days.\n\n This is calculated using the .start_date and .end_date for the season\n \"\"\"\n tdelta = self.end_date - self.start_date\n # return all_times[-1] - all_times[0]\n return tdelta.days + tdelta.seconds / 86400\n\n @property\n def track_distance(self):\n \"\"\"Returns the accumulated track distances (in nmi) of all systems\n during the season, regardless of the systems' status.\n \"\"\"\n return sum(tcyc.track_distance for tcyc in self.tc.values())\n\n @property\n def track_distance_TC(self):\n \"\"\"Returns the accumulated track distances (in nmi) of all systems\n during the season, while the systems were designated as tropical\n cyclones (\"SD\",\"SS\",\"TD\",\"TS\",\"HU\").\n \"\"\"\n return sum(tcyc.track_distance_TC for tcyc in self.tc.values())\n\n @property\n def ACE(self):\n \"\"\"Returns the accumulated cyclone energy (ACE) for the entire season,\n being the sum of all individual tropical cyclone ACE's.\n \"\"\"\n return sum(tcyc.ACE for tcyc in self.tc.values())\n\n @property\n def track_distance_TS(self):\n \"\"\"Returns the sum of track distances (in nmi) of all tropical\n cyclones while they were designated as at-least tropical storms (SS,\n TS, or HU).\n \"\"\"\n return sum(tcyc.track_distance_TS for tcyc in self.tc.values())\n\n @property\n def HDP(self):\n \"\"\"Returns the hurricane destruction potential (HDP) for the entire\n season, being the sum of all individual tropical cyclone HDP's.\n \"\"\"\n return sum(tcyc.HDP for tcyc in self.tc.values())\n\n @property\n def track_distance_HU(self):\n \"\"\"Returns the sum of track distances (in nmi) of all tropical\n cyclones while they were of hurricane status.\n \"\"\"\n return sum(tcyc.track_distance_HU for tcyc in self.tc.values())\n\n @property\n def MHDP(self):\n \"\"\"Returns the major hurricane destruction potential (MHDP) for the\n entire season, being the sum of all individual tropical cyclone MHDP's.\n \"\"\"\n return sum(tcyc.MHDP for tcyc in self.tc.values())\n\n @property\n def track_distance_MHU(self):\n \"\"\"Returns the sum of track distances (in nmi) of all tropical\n cyclones when the storms were designated as major hurricanes.\n \"\"\"\n return sum(tcyc.track_distance_MHU for tcyc in self.tc.values())\n\nclass TropicalCycloneCalculations:\n\n @property\n def start_date(self):\n \"\"\"The <> of the birth of the tropical cyclone.\"\"\"\n return self.tc_entries[0].entrytime \\\n if len(self.tc_entries) > 0 else None\n\n @property\n def start_ordinal(self):\n \"\"\"\n The day-number (1-365) of the year that the birth of the tropical\n cyclone took place.\n \"\"\"\n return self.tc_entries[0].entrytime.replace(year=1).toordinal() \\\n if len(self.tc_entries) > 0 else None\n\n @property\n def end_date(self):\n \"\"\"The <> where the storm became post-tropical.\"\"\"\n if len(self.tc_entries) > 0:\n return self.tc_entries[-1].next_entry.entrytime \\\n if self.tc_entries[-1].next_entry is not None \\\n else self.tc_entries[-1].entrytime\n else:\n return None\n\n @property\n def end_ordinal(self):\n \"\"\"\n The day-number (1-365) of the year that the tropical cyclone became\n post-tropical.\n\n In the event that the day number exceeds 365, it generally means that\n the tropical storm didn't become post-tropical until the following\n year.\n \"\"\"\n if len(self.tc_entries) > 0:\n end = self.end_date.replace(year=1).toordinal()\n # protect against seasons that extend into the following year\n if end <= self.start_ordinal:\n return self.end_date.replace(year=2).toordinal()\n else:\n return end\n else:\n return None\n\n @property\n def duration(self):\n \"\"\"\n The track duration in days; simply the end time minus the beginning\n time. In essence, this variable disregards the status of the storm.\n\n For more substantive properties, try duration_ for\n aggregated measurements as storms can lose and regain statuses\n \"\"\"\n\n return (self.entry[-1].entrytime - self.entry[0].entrytime).days \\\n + (self.entry[-1].entrytime - self.entry[0].entrytime).seconds / 86400\n\n @property\n def track_distance(self):\n \"\"\"Returns the distance (in nmi) traversed by the system, regardless of\n status (whether or not the system is designated as a tropical cyclone).\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self.entry\n if en.previous_entry is not None\n )\n\n @property\n def duration_TC(self):\n \"\"\"\n This is the total time that a storm was a designated tropical cyclone.\n\n * Of note * A storm can lose previous tropical cyclone status but\n regain it. For the Atlantic Hurdat2, this occurs in around 2.6% of\n storms, but almost 8% of storms since the year 2000. So if one compares\n track life versus this duration property, it isn't out of the question\n that they'll be different. See Hurricane Ivan (2004) as a prime\n example.\n \"\"\"\n\n totes = sum(\n (en.next_entry.entrytime - en.entrytime).days\n + (en.next_entry.entrytime - en.entrytime).seconds / 86400\n if en.next_entry is not None\n and en.is_TC\n else 0\n for en in self.entry\n )\n\n return totes\n\n @property\n def track_distance_TC(self):\n \"\"\"The distance (in nmi) trekked by the system when a designated\n tropical cyclone (status as a tropical or sub-tropical depression, a\n tropical or sub-tropical storm, or a hurricane).\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self.entry\n if en.previous_entry is not None\n and en.previous_entry.is_TC\n )\n\n @property\n def ACE(self):\n \"\"\"Returns the tropical cyclone's Accumulated Cyclone Energy (ACE).\n\n Using values from required observations (0Z, 6Z, 12Z, and 18Z), this\n variable is \"calculated by summing the squares of the estimated\n 6-hourly maximum sustained surface wind speed in knots for all periods\n while the system is either a tropical storm or hurricane.\" (G. Bell,\n M. Chelliah. Journal of Climate. Vol. 19, Issue 4. pg 593. 15 February\n 2006.). \n\n Because sub-tropical storms (SS) still have some tropical\n characteristics, their values are included as well. Regardless of the\n case for or against, note that it is a very small contribution. Using\n the Atlantic Hurdat2 Database as an example, when included in the\n calculation (using only storms since 1968, as that is when the SS\n designation first appears in the Atlantic HURDAT2), only around 2.5% of ACE\n contribution has occurred from sub-tropical storms.\n \"\"\"\n return sum(\n math.pow(en.wind,2) for en in self.entry\n if en.wind >= 34\n and en.is_synoptic\n and en.status in (\"SS\",\"TS\",\"HU\")\n )\n\n @property\n def perc_ACE(self):\n \"\"\"The percent (decimal form) of total season ACE contributed by this\n storm.\n \"\"\"\n if self._season.ACE > 0:\n return self.ACE / self._season.ACE\n else:\n return 0\n\n @property\n def duration_TS(self):\n \"\"\"\n This is the total time that a storm was designated at least a tropical\n storm.\n \"\"\"\n\n totes = sum(\n (en.next_entry.entrytime - en.entrytime).days\n + (en.next_entry.entrytime - en.entrytime).seconds / 86400\n if en.next_entry is not None\n and en.status in [\"SS\", \"TS\", \"HU\"]\n else 0\n for en in self.entry\n )\n\n return totes\n\n @property\n def track_distance_TS(self):\n \"\"\"The distance (in nmi) trekked by the system while a tropical storm\n or hurricane.\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self.entry\n if en.previous_entry is not None\n and en.previous_entry.status in [\"SS\", \"TS\", \"HU\"]\n )\n\n @property\n def track_TS_perc_TC(self):\n \"\"\"Returns the system's tropical storm track-distance divided by its \n tropical cyclone track-distance.\n\n This value represents the proportional distance of a storm that\n occurred while it was at-least a tropical storm compared to when it was\n a designated tropical cyclone.\n\n None will be returned if track_distance_TC == 0\n \"\"\"\n if self.track_distance_TC != 0:\n return round(self.track_distance_HU / self.track_distance_TC,2)\n else:\n return None\n\n @property\n def ACE_per_nmi(self):\n \"\"\"Returns the Accumulated Cyclone Energy (ACE) divided by the\n systems's track-distance when it was at-least a tropical storm.\n \"\"\"\n return self.ACE / self.track_distance_TS if self.track_distance_TS > 0 else 0\n\n @property\n def ACE_no_landfall(self):\n \"\"\"Returns the ACE of the storm prior to any landfall made (if\n applicable).\n \"\"\"\n\n ace_no_lf = 0\n for en in self.entry:\n if en.record_identifier == \"L\":\n break\n if en.wind >= 34 \\\n and en.is_synoptic \\\n and en.status in (\"SS\",\"TS\",\"HU\"):\n ace_no_lf += math.pow(en.wind, 2)\n return ace_no_lf\n\n @property\n def HDP(self):\n \"\"\"Returns the tropical cyclone's Hurricane Destruction Potential\n (HDP).\n\n Using values from required observations (0Z, 6Z, 12Z, and 18Z), this\n variable is \"calculated by summing the squares of the estimated\n 6-hourly maximum sustained wind speed for all periods in which the\n system is a hurricane.\" (Bell, et. al. Climate Assessment for 1999.\n Bulletin of the American Meteorological Society. Vol 81, No. 6. June\n 2000. S19.)\n \"\"\"\n return sum(\n math.pow(en.wind, 2) for en in self.entry\n if en.wind >= 64\n and en.is_synoptic\n and en.status == \"HU\"\n )\n\n @property\n def perc_HDP(self):\n \"\"\"The percent (decimal form) of total season HDP contributed by this\n storm.\n \"\"\"\n if self._season.HDP > 0:\n return self.HDP / self._season.HDP\n else:\n return 0\n\n @property\n def duration_HU(self):\n \"\"\"\n This is the total time that a storm was designated at a hurricane.\n \"\"\"\n\n totes = sum(\n (en.next_entry.entrytime - en.entrytime).days\n + (en.next_entry.entrytime - en.entrytime).seconds / 86400\n if en.next_entry is not None\n and en.status == \"HU\"\n else 0\n for en in self.entry\n )\n\n return totes\n\n @property\n def track_distance_HU(self):\n \"\"\"The distance (in nmi) trekked by the system while a hurricane.\"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self.entry\n if en.previous_entry is not None\n and en.previous_entry.status == \"HU\"\n )\n\n @property\n def HDP_per_nmi(self):\n \"\"\"Returns the system's Hurricane Destruction Potential (HDP) divided\n by the systems's track-distance when it was a hurricane.\n \"\"\"\n\n return self.HDP / self.track_distance_HU if self.track_distance_HU > 0 else 0\n\n @property\n def HDP_perc_ACE(self):\n \"\"\"Returns the system's HDP divided by its ACE.\n\n This is the value (0 is lowest; 1 highest) representing how much\n contribution to ACE was made while a system was designated as a\n hurricane.\n\n return None will occur if ACE is 0 for the system.\n \"\"\"\n if self.ACE != 0: return round(self.HDP / self.ACE,2)\n else: return None\n\n @property\n def track_HU_perc_TC(self):\n \"\"\"Returns the system's hurricane track-distance divided by its\n tropical cyclone track-distance\n\n This value represents the proportional distance of a storm that\n occurred while it was a hurricane compared to when it was a designated\n tropical cyclone.\n\n None will be returned if track_distance_TC == 0\n \"\"\"\n if self.track_distance_TC != 0:\n return round(self.track_distance_HU / self.track_distance_TC,2)\n else:\n return None\n\n @property\n def track_HU_perc_TS(self):\n \"\"\"Returns the system's hurricane track-distance divided by its\n tropical storm track-distance.\n\n This value represents the proportional distance of a storm that\n occurred while it was a hurricane compared to when it was at-least a\n tropical storm.\n\n None will be returned if track_distance_TS == 0\n \"\"\"\n if self.track_distance_TS != 0:\n return round(self.track_distance_HU / self.track_distance_TS,2)\n else:\n return None\n\n @property\n def MHDP(self):\n \"\"\"Returns the tropical cyclone's Major Hurricane Destruction Potential\n (MHDP).\n\n This inclusion of this variable is merely an extension of the\n definitions of ACE and HDP, which are widely referenced indices. This\n takes the logic of those definitions and applies it only to major-\n hurricanes (max-wind >= 96kts).\n \"\"\"\n return sum(\n math.pow(en.wind, 2) for en in self.entry\n if en.wind >= 96\n and en.is_synoptic\n and en.status == \"HU\"\n )\n\n @property\n def perc_MHDP(self):\n \"\"\"The percent (decimal form) of total season MHDP contributed by this\n storm.\n \"\"\"\n if self._season.MHDP > 0:\n return self.MHDP / self._season.MHDP\n else:\n return 0\n\n @property\n def duration_MHU(self):\n \"\"\"\n This is the total time that a storm was designated at a hurricane.\n \"\"\"\n\n totes = sum(\n (en.next_entry.entrytime - en.entrytime).days\n + (en.next_entry.entrytime - en.entrytime).seconds / 86400\n if en.next_entry is not None\n and en.status == \"HU\" and en.wind >= 96\n else 0\n for en in self.entry\n )\n\n return totes\n\n @property\n def track_distance_MHU(self):\n \"\"\"The distance (in nmi) trekked by the system while a major\n hurricane.\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self.entry\n if en.previous_entry is not None\n and en.previous_entry.wind >= 96\n and en.previous_entry.status == \"HU\"\n )\n\n @property\n def MHDP_per_nmi(self):\n \"\"\"Returns the system's Major Hurricane Destruction Potential (MHDP)\n divided by the systems's track-distance when it was a major hurricane.\n \"\"\"\n return self.MHDP / self.track_distance_MHU if self.track_distance_MHU > 0 else 0\n\n @property\n def MHDP_perc_ACE(self):\n \"\"\"Returns the system's MHDP divided by its ACE.\n\n This is the value (0 is lowest; 1 highest) representing how much\n contribution to ACE was made while a system was designated as a\n major hurricane.\n\n return None will occur if ACE is 0 for the system.\n \"\"\"\n if self.ACE != 0: return round(self.MHDP / self.ACE,2)\n else: return None\n\n @property\n def track_MHU_perc_TC(self):\n \"\"\"Returns the system's major-hurricane track-distance divided by its\n tropical cyclone track-distance.\n\n This value represents the proportional distance of a storm that\n occurred while it was a major-hurricane compared to when it was a\n designated tropical cyclone.\n\n None will be returned if track_distance_TC == 0\n \"\"\"\n if self.track_distance_TC != 0:\n return round(self.track_distance_MHU / self.track_distance_TC,2)\n else:\n return None\n\n @property\n def track_MHU_perc_TS(self):\n \"\"\"Returns the system's major-hurricane track-distance divided by its\n tropical storm track-distance.\n\n This value represents the proportional distance of a storm that\n occurred while it was a major-hurricane compared to when it was at-\n least a tropical storm.\n\n None will be returned if track_distance_TS == 0\n \"\"\"\n if self.track_distance_TS != 0:\n return round(self.track_distance_MHU / self.track_distance_TS,2)\n else:\n return None\n\n @property\n def MHDP_perc_HDP(self):\n \"\"\"Returns the system's MHDP divided by its HDP.\n\n This is the value (0 is lowest; 1 highest) representing how much\n contribution to its HDP was made while a system was designated as a\n major hurricane.\n\n return None will occur if HDP is 0 for the system.\n \"\"\"\n if self.HDP != 0: return round(self.MHDP / self.HDP,2)\n else: return None\n\n @property\n def track_MHU_perc_HU(self):\n \"\"\"Returns the system's major-hurricane track-distance divided by its\n hurricane track-distance.\n\n This value represents the proportional distance of a storm that\n occurred while it was a major-hurricane compared to when it was a\n hurricane.\n\n None will be returned if track_distance_HU == 0\n \"\"\"\n if self.track_distance_HU != 0:\n return round(self.track_distance_MHU / self.track_distance_HU,2)\n else:\n return None\n\n\nclass TCEntryCalculations:\n\n __slots__ = []\n\n @property\n def track_distance(self):\n \"\"\"\n The track distance traversed by the system (regardless of status) from\n the start of the track to the time of this <>\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self._tc.entry\n if self._tc.entry.index(en) <= self._tc.entry.index(self)\n and en.previous_entry is not None\n )\n\n @property\n def track_distance_TC(self):\n \"\"\"\n The track distance traversed by the system while designated a tropical\n cyclone from the start of the track to the time of this\n <>.\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self._tc.entry[:self._tc.entry.index(self)+1]\n if en.previous_entry is not None\n and en.previous_entry.is_TC\n )\n\n @property\n def track_distance_TS(self):\n \"\"\"\n The track distance traversed by the system while a tropical storm or\n stronger, from the start of the track to the time of this\n <>\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self._tc.entry[:self._tc.entry.index(self)+1]\n if en.previous_entry is not None\n and en.previous_entry.status in (\"SS\", \"TS\", \"HU\")\n )\n\n @property\n def track_distance_HU(self):\n \"\"\"\n The track distance traversed by the system while designated a hurricane\n from the start of the track to the time of this <>\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self._tc.entry[:self._tc.entry.index(self)+1]\n if en.previous_entry is not None\n and en.previous_entry.status == \"HU\"\n )\n\n @property\n def track_distance_MHU(self):\n \"\"\"\n The track distance traversed by the system while designated a major-\n hurricane, from the start of the track to the time of this\n <>\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self._tc.entry[:self._tc.entry.index(self)+1]\n if en.previous_entry is not None\n and en.previous_entry.status == \"HU\"\n and en.previous_entry.wind >= 96\n )\n\n def direction(self, cardinal=False):\n \"\"\"Returns the heading (in degrees) of the tropical cyclone at the time\n of the .\n\n This is calculated using this and the previous entry locations.\n\n Default Argument\n ----------------\n cardinal (False): if True, it will return an accurate cardinal\n direction abbreviation (ex: 'NNW' == North-Northwest) instead\n of degrees.\n\n Of note, the first entry (index of 0) of any tropical cyclone will not\n have any associated direction because there is no previous entry to\n compare it with.\n\n For reference:\n Degrees Direction\n ---------- -------------------\n 0 // 45 North // North-east\n 90 // 135 East // South-east\n 180 // 225 South // South-west\n 270 // 315 West // North-west\n \"\"\"\n if self._tc.entry.index(self) != 0:\n dlat = self.latitude - self.previous_entry.latitude\n # account for longitudinal traversals of 180E/-180W\n if abs(self.longitude - self.previous_entry.longitude) < 180:\n dlon = self.longitude - self.previous_entry.longitude\n else:\n dlon = self.longitude + (\n 360 * (1 if self.longitude < 0 else -1)\n ) - self.previous_entry.longitude\n deg_dir = math.degrees(math.atan2(dlon, dlat))\n if cardinal is True:\n return cardinal_direction(\n deg_dir + (360 if deg_dir < 0 else 0)\n )\n else:\n return deg_dir + (360 if deg_dir < 0 else 0)\n else:\n return None\n\n @property\n def speed(self):\n \"\"\"\n Returns the forward lateral speed of the tropical cyclone at the time\n of the in knots (nautical miles per hour).\n\n This is calculated using this and the previous entry locations (gps\n coordinates) and the time of the entry.\n\n Of note, the first entry (index of 0) of any tropical cyclone will not\n have any associated speed because there is no previous entry to compare\n it to.\n \"\"\"\n if self._tc.entry.index(self) != 0:\n dist = haversine(self.location, self.previous_entry.location)\n et = (self.entrytime - self.previous_entry.entrytime).seconds / 60 / 60\n return dist / et\n else:\n return None\n\n @property\n def saffir_simpson(self):\n return saffir_simpson_scale(self.wind)\n\n @property\n def avg_wind_extent_TS(self):\n \"\"\"Returns the average extent of at-least tropical storm winds.\"\"\"\n return statistics.mean(self.extent_TS)\n\n @property\n def areal_extent_TS(self):\n \"\"\"Return the instantaneous maximum tropical-storm-strength wind areal\n expanse (in nmi^2) covered by the storm.\n \n This is calculated by taking each TS-wind quadrant value and summing\n their areal-extents (those extents being considered 1/4 of a circle). \n \"\"\"\n return sum(\n math.pi * math.pow(r, 2) / 4\n for r in self.extent_TS\n if r is not None\n )\n\n @property\n def avg_wind_extent_TS50(self):\n \"\"\"Returns the average extent of at-least gale winds.\"\"\"\n return statistics.mean(self.extent_TS50)\n\n @property\n def areal_extent_TS50(self):\n \"\"\"Return the instantaneous maximum gale-strength wind (TS50; winds >=\n 50kts) areal expanse (in nmi^2) covered by the storm.\n \n This is calculated by taking each TS50-wind quadrant value and summing\n their areal-extents (those extents being considered 1/4 of a circle). \n \"\"\"\n return sum(\n math.pi * math.pow(r, 2) / 4 \\\n for r in self.extent_TS50 \\\n if r is not None\n )\n\n @property\n def avg_wind_extent_HU(self):\n \"\"\"Returns the average extent of hurricane-strength winds.\"\"\"\n return statistics.mean(self.extent_HU)\n\n @property\n def areal_extent_HU(self):\n \"\"\"Return the instantaneous maximum hurricane-strength wind areal\n expanse (in nmi^2) covered by the storm.\n \n This is calculated by taking each HU-wind quadrant value and summing\n their areal-extents (those extents being considered 1/4 of a circle).\n \"\"\"\n\n return sum(\n math.pi * math.pow(r, 2) / 4 \\\n for r in self.extent_HU \\\n if r is not None\n )\n\ndef saffir_simpson_scale(spd):\n \"\"\"Static method that returns the equivalent saffir-simpson scale rating,\n based on wind-speed in knots.\n\n This is the most-common index used to generalize tropical cyclone\n intensity. Tropical storm speeds will return 0; Weaker storms will return\n -1.\n\n Example: saffir_simpson_scale(100) --> 3 (implying category 3).\n \"\"\"\n if 34 <= spd < 64: return 0\n elif 64 <= spd < 83: return 1\n elif 83 <= spd < 96: return 2\n elif 96 <= spd < 114: return 3\n elif 114 <= spd < 136: return 4\n elif spd >= 136: return 5\n else: return -1\n\ndef distance_from_coordinates(lat, lon, distance, direction):\n latr = math.radians(lat)\n lonr = math.radians(lon)\n if distance == None: distance = 0\n r = 3440.065 # mean radius of earth in nmi\n \n if direction in [\"N\", \"S\"]:\n y = (1 if direction == \"N\" else -1) * distance / r + latr\n return (math.degrees(y), lon)\n else:\n # x = (2 if direction == \"E\" else -1) * math.asin(distance / (2 * r * math.pow(math.cos(latr), 2))) + lonr\n # x = (2 if direction == \"E\" else -2) * math.asin(math.sqrt(distance / math.pow(math.cos(latr), 2))) + lonr\n # x = (1 if direction == \"E\" else -1) * math.acos(2 * distance / math.cos(latr)**2) + lonr\n x = (2 if direction == \"E\" else -2) * math.asin(math.sqrt(math.pow(math.sin(distance / (2 * r)), 2) / math.pow(math.cos(latr), 2))) + lonr\n return (lat, math.degrees(x))\n\ndef haversine(startpos, endpos):\n \"\"\"Returns the distance (in nmi) between two tupled GPS coordinates.\n\n Args:\n startpos: the starting gps-coordinate point; in tuple form of \n (latitude, longitude). Both need to be an int or float.\n endpos: the ending gps-coordinate point; in tuple form of (latitude,\n longitude). Both need to be an int or float.\n\n The formula used was found on Wikipedia\n (https://en.wikipedia.org/wiki/Haversine_formula).\n \"\"\"\n lat1 = math.radians(startpos[0])\n lon1 = math.radians(startpos[1])\n lat2 = math.radians(endpos[0])\n lon2 = math.radians(endpos[1])\n r = 3440.065 # mean radius of earth in nmi\n d = 2 * r * math.asin(math.sqrt(math.pow(math.sin((lat2 - lat1)/2),2) + math.cos(lat1) * math.cos(lat2) * math.pow(math.sin((lon2-lon1)/2),2)))\n return d\n\ndef cardinal_direction(deg):\n \"\"\"\n Returns the cardinal direction (an abbreviation) based on a degree-heading.\n\n Examples:\n 10.5 --> 'N'\n 257 --> 'WSW'\n 20.2 --> 'NNE'\n 93 --> 'E'\n 165 --> 'SSE'\n \"\"\"\n if deg <= 11.25: return \"N\"\n elif deg <= 33.75: return \"NNE\"\n elif deg <= 56.25: return \"NE\"\n elif deg <= 78.75: return \"ENE\"\n elif deg <= 101.25: return \"E\"\n elif deg <= 123.75: return \"ESE\"\n elif deg <= 146.25: return \"SE\"\n elif deg <= 168.75: return \"SSE\"\n elif deg <= 191.25: return \"S\"\n elif deg <= 213.75: return \"SSW\"\n elif deg <= 236.25: return \"SW\"\n elif deg <= 258.75: return \"WSW\"\n elif deg <= 281.25: return \"W\"\n elif deg <= 303.75: return \"WNW\"\n elif deg <= 326.25: return \"NW\"\n elif deg <= 348.75: return \"NNW\"\n else: return \"N\"\n\n\ndef direction(lat1, lon1, lat2, lon2, cardinal=False):\n \"\"\"\n This is essentially a mirror function of the\n .direction method. Just included so I could test some\n arbitrary coordinates and revisit later if I choose.\n \"\"\"\n dlat = lat2 - lat1\n # account for longitudinal traversals of 180E/-180W\n if abs(lon2 - lon1) < 180:\n dlon = lon2 - lon1\n else:\n dlon = lon2 + (\n 360 * (1 if lon2 < 0 else -1)\n ) - lon1\n deg_dir = math.degrees(math.atan2(dlon, dlat))\n if cardinal is True:\n return cardinal_direction(\n deg_dir + (360 if deg_dir < 0 else 0)\n )\n else:\n return deg_dir + (360 if deg_dir < 0 else 0)\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":"previous_versions/v2.2.2/hurdat2parser/_calculations.py","file_name":"_calculations.py","file_ext":"py","file_size_in_byte":78056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"120395178","text":"#! /usr/bin/env python3\nimport sys\n\ndef parse_output(fileout,shift):\n #\n skip=True\n read_vkpt=False\n verbosity=False\n lines=[]\n dims={\"vkpt\":[]}\n with open(fileout,\"r\") as fl:\n for line in fl: \n if \"number of Kohn-Sham states\" in line:\n dims[\"nbnd\"]=int(line.split()[-1])\n #\n if \"number of k points\" in line:\n dims[\"nkpts\"]=int(line.split()[4])\n read_vkpt=True\n if \"Crystallographic axes\" in line: verbosity=True\n if ( \"k(\" in line and read_vkpt):\n k=[float(x.strip(\"),\")) for x in line.split()[4:7] ]\n dims[\"vkpt\"].append(k) \n if \"cryst. coord.\" in line: read_vkpt=False\n #\n if \"End of band structure calculation\" in line: skip=False\n if \"Writing output data file\" in line: skip=True\n if (not skip): lines.append(line)\n\n #\n # now parse the list of lines\n #\n lines.pop(0)\n #\n nlines=dims[\"nbnd\"]//8\n if (dims[\"nbnd\"]%8>0): nlines+=1\n #\n bands=[]\n for k in range(dims[\"nkpts\"]):\n #\n # parse eigs for a given kpt\n eigs=[]\n for ind in range(3,3+nlines):\n for x in lines[ind].split(): eigs.append(float(x)-shift)\n #\n # add kpt to previous kpt list\n bands.append(eigs)\n #\n # delete lines\n nlines_to_pop=3+nlines\n if verbosity: nlines_to_pop+= 2+nlines\n #\n for ind in range(nlines_to_pop):\n lines.pop(0)\n \n \n #print(bands)\n return dims,bands\n\n\nif __name__ == \"__main__\":\n\n #\n # get cmd line args\n #\n if (len(sys.argv) < 1): \n print(\"Usage: %s [opts]\",sys.argv[0])\n sys.exit(2)\n #\n filename = sys.argv[1]\n # \n shift=0.0\n if (len(sys.argv) >= 4 and (sys.argv[2]==\"--shift\" or sys.argv[2]==\"-s\")): \n shift=float(sys.argv[3])\n\n #\n # parsing\n #\n dims,bands = parse_output(filename,shift)\n\n #\n # printout\n #\n for ib in range(dims[\"nbnd\"]):\n #\n for ik in range(dims[\"nkpts\"]):\n xk = float(ik)*0.5/float(dims[\"nkpts\"]-1)\n en = bands[ik][ib] \n print(\"%15.9f %15.9f\" % (xk,en) )\n #\n print(\"\")\n\n","sub_path":"tools/plot_bands.py","file_name":"plot_bands.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"486164906","text":"import sys\n\nlist0 = [('0', 'zéro')]\nlist1_9 = [('1', 'un'),\n ('2', 'deux'),\n ('3', 'trois'),\n ('4', 'quatre'),\n ('5', 'cinq'),\n ('6', 'six'),\n ('7', 'sept'),\n ('8', 'huit'),\n ('9', 'neuf')]\nlist10_99 = [('10', 'dix'),\n ('11', 'onze'),\n ('12', 'douze'),\n ('13', 'treize'),\n ('14', 'quatorze'),\n ('15', 'quinze'),\n ('16', 'seize'),\n ('17', 'dix-sept'),\n ('18', 'dix-huit'),\n ('19', 'dix-neuf'),\n ('20', 'vingt'),\n ('21', 'vingt et un'),\n ('22', 'vingt-deux'),\n ('23', 'vingt-trois'),\n ('24', 'vingt-quatre'),\n ('25', 'vingt-cinq'),\n ('26', 'vingt-six'),\n ('27', 'vingt-sept'),\n ('28', 'vingt-huit'),\n ('29', 'vingt-neuf'),\n ('30', 'trente'),\n ('31', 'trente et un'),\n ('32', 'trente-deux'),\n ('33', 'trente-trois'),\n ('34', 'trente-quatre'),\n ('35', 'trente-cinq'),\n ('36', 'trente-six'),\n ('37', 'trente-sept'),\n ('38', 'trente-huit'),\n ('39', 'trente-neuf'),\n ('40', 'quarante'),\n ('41', 'quarante et un'),\n ('42', 'quarante-deux'),\n ('43', 'quarante-trois'),\n ('44', 'quarante-quatre'),\n ('45', 'quarante-cinq'),\n ('46', 'quarante-six'),\n ('47', 'quarante-sept'),\n ('48', 'quarante-huit'),\n ('49', 'quarante-neuf'),\n ('50', 'cinquante'),\n ('51', 'cinquante et un'),\n ('52', 'cinquante-deux'),\n ('53', 'cinquante-trois'),\n ('54', 'cinquante-quatre'),\n ('55', 'cinquante-cinq'),\n ('56', 'cinquante-six'),\n ('57', 'cinquante-sept'),\n ('58', 'cinquante-huit'),\n ('59', 'cinquante-neuf'),\n ('60', 'soixante'),\n ('61', 'soixante et un'),\n ('62', 'soixante-deux'),\n ('63', 'soixante-trois'),\n ('64', 'soixante-quatre'),\n ('65', 'soixante-cinq'),\n ('66', 'soixante-six'),\n ('67', 'soixante-sept'),\n ('68', 'soixante-huit'),\n ('69', 'soixante-neuf'),\n ('70', 'soixante-dix'),\n ('71', 'soixante-et-onze'),\n ('72', 'soixante-douze'),\n ('73', 'soixante-treize'),\n ('74', 'soixante-quatorze'),\n ('75', 'soixante-quinze'),\n ('76', 'soixante-seize'),\n ('77', 'soixante-dix-sept'),\n ('78', 'soixante-dix-huit'),\n ('79', 'soixante-dix-neuf'),\n ('80', 'quatre-vingts'),\n ('81', 'quatre-vingt-un'),\n ('82', 'quatre-vingt-deux'),\n ('83', 'quatre-vingt-trois'),\n ('84', 'quatre-vingt-quatre'),\n ('85', 'quatre-vingt-cinq'),\n ('86', 'quatre-vingt-six'),\n ('87', 'quatre-vingt-sept'),\n ('88', 'quatre-vingt-huit'),\n ('89', 'quatre-vingt-neuf'),\n ('90', 'quatre-vingt-dix'),\n ('91', 'quatre-vingt-onze'),\n ('92', 'quatre-vingt-douze'),\n ('93', 'quatre-vingt-treize'),\n ('94', 'quatre-vingt-quatorze'),\n ('95', 'quatre-vingt-quinze'),\n ('96', 'quatre-vingt-seize'),\n ('97', 'quatre-vingt-dix-sept'),\n ('98', 'quatre-vingt-dix-huit'),\n ('99', 'quatre-vingt-dix-neuf')]\n\n\ndef fr1_9(pref_digit, pref_word, p):\n for (digit, word) in list1_9:\n p(pref_digit + digit, pref_word + word)\n\n\ndef fr10_99(pref_digit, pref_word, p):\n for (digit, word) in list10_99:\n p(pref_digit + digit, pref_word + word)\n\n\ndef fr1_99(pref_digit, pref_word, p):\n fr1_9(pref_digit, pref_word, p)\n fr10_99(pref_digit, pref_word, p)\n\n\ndef fr01_99(pref_digit, pref_word, p):\n fr1_9(pref_digit + '0', pref_word, p)\n fr10_99(pref_digit, pref_word, p)\n\n\ndef fr100_999(pref_digit, pref_word, p):\n p(pref_digit + '100', pref_word + 'cent')\n fr01_99(pref_digit + '1', pref_word + 'cent ', p)\n fr1_9(pref_digit, pref_word, lambda d, w: fr01_99(d, w + ' cent ', p))\n\n\ndef fr1_999(pref_digit, pref_word, p):\n fr1_99(pref_digit, pref_word, p)\n fr100_999(pref_digit, pref_word, p)\n\n\ndef fr001_999(pref_digit, pref_word, p):\n fr01_99(pref_digit + '0', pref_word, p)\n fr100_999(pref_digit, pref_word, p)\n\n\ndef fr1000_999999(pref_digit, pref_word, p):\n p(pref_digit + '1000', pref_word + 'mille')\n fr001_999(pref_digit + '1', pref_word + 'mille ', p)\n fr1_999(pref_digit, pref_word, lambda d, w: fr001_999(d, w + ' mille ', p))\n\n\ndef fr000001_999999(pref_digit, pref_word, p):\n fr001_999(pref_digit + '000', pref_word, p)\n fr1000_999999(pref_digit + '00', pref_word, p)\n\n\ndef fr1_999999(pref_digit, pref_word, p):\n fr1_999(pref_digit, pref_word, p)\n fr1000_999999(pref_digit, pref_word, p)\n\n\ndef fr1000000_999999999(pref_digit, pref_word, p):\n p(pref_digit + '1000000', pref_word + 'million')\n fr001_999(pref_digit + '1', pref_word + 'millions ', p)\n fr1_999(pref_digit, pref_word, lambda d, w: fr001_999(d, w + ' millions ', p))\n\n\nf = fr1_999999\nif len(sys.argv) > 1:\n if sys.argv[1] == '100':\n f = fr1_99\n elif sys.argv[1] == '1000':\n f = fr1_999\n elif sys.argv[1] == '1000000':\n f = fr1_999999\n\nf('', '', lambda d, w: print(w + '\\t' + d))\n","sub_path":"native/cli/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"644715043","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport quandl\nfrom sklearn.linear_model import LinearRegression\n\nquandl.ApiConfig.api_key = 'wPaa4PYkmNxA45kLj7f4'\nstock_data = quandl.get('WIKI/AAPL', start_date='2013-09-03', end_date='2020-12-28')\n# print(stock_data)\n\ndataset = pd.DataFrame(stock_data)\ndataset.head()\ndataset.to_csv('AAPL_stock.csv')\n\nx = dataset.loc[:,'High':'Adj. Volume']\ny = dataset.loc[:,'Open']\n\nimport sklearn.model_selection as model_selection\nx_train,x_test,y_train,y_test = model_selection.train_test_split(x,y,test_size= 0.1,random_state = 0)\nLR = LinearRegression()\nLR.fit(x_train,y_train)\nLR.score(x_test,y_test)\n\ntest_data = x.head(1)\nprediction = LR.predict(test_data)\nprint('Predicted stock price:')\nprint(prediction)\nprint('Actual stock price:',y.head(1))\n\n\n","sub_path":"stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"378618277","text":"import requests\r\n\r\n\r\ndef paisesInfo() -> list:\r\n listadoPaises = []\r\n response = requests.get(\"https://api.covid19api.com/countries\")\r\n if response.status_code == 200:\r\n for pais in response.json():\r\n listadoPaises.append(pais[\"Slug\"])\r\n listadoPaises.sort()\r\n return listadoPaises","sub_path":"TP5/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"461236358","text":"# -*- coding: utf-8 -*-\n\n\nimport common\n\nimport sqlalchemy.orm as orm\n\nimport clusterdb as db\n\n\nclass ListServerInterfaceApp(common.ListApp):\n\n observable = True\n\n CSV_FIELDS = (\n \"server_name\",\n \"name\",\n \"mac\",\n \"port\",\n \"vlan\",\n \"switch_ip\")\n\n @classmethod\n def create_parser(cls, parsers):\n parser = parsers.add_parser(\n \"list-server-interface\", description=\"List server interfaces.\")\n\n parser.add_argument(\n \"-i\", \"--if-name\",\n help=\"The name of the interface to show.\",\n default=None)\n parser.add_argument(\n \"-s\", \"--switch-ip\",\n help=\"IP address of connected switch.\",\n default=None)\n parser.add_argument(\n \"-p\", \"--port\",\n help=\"Port on connected switch.\",\n default=None)\n parser.add_argument(\n \"-m\", \"--mac-address\",\n help=\"MAC address of network interface.\",\n default=None)\n parser.add_argument(\n \"-l\", \"--vlan\",\n help=\"VLAN for network interface.\",\n type=int,\n default=None)\n parser.add_argument(\n \"server_names\",\n metavar=\"SERVER_NAME\",\n nargs=\"*\",\n help=(\n \"Server names to show interfaces for. \"\n \"If nothing is set, then all server interfaces will be \"\n \"listed.\"))\n\n return parser\n\n def __init__(self, options):\n super(ListServerInterfaceApp, self).__init__(options)\n\n self.server_names = sorted(set(options.server_names))\n self.ifname = options.if_name\n self.switch_ip = options.switch_ip\n self.port = options.port\n self.mac_address = options.mac_address\n self.vlan = options.vlan\n\n def get_info(self):\n session = self.session_maker()\n\n query = session.query(db.ServerInterface)\n query = query.options(orm.joinedload(db.ServerInterface.server))\n query = query.join(db.Server)\n\n if self.server_names:\n query = query.filter(db.Server.name.in_(self.server_names))\n if self.ifname:\n query = query.filter(db.ServerInterface.name == self.ifname)\n if self.switch_ip:\n query = query.filter(\n db.ServerInterface.switch_ip == self.switch_ip)\n if self.port:\n query = query.filter(db.ServerInterface.port == self.port)\n if self.mac_address:\n query = query.filter(\n db.ServerInterface.mac_address == self.mac_address)\n if self.vlan:\n query = query.filter(db.ServerInterface.vlan == self.vlan)\n\n interfaces_data = {}\n for interface in query.all():\n data = interfaces_data.setdefault(interface.server.name, {})\n data[interface.name] = {\n \"mac\": interface.mac,\n \"port\": interface.port,\n \"vlan\": interface.vlan,\n \"switch_ip\": interface.switch_ip}\n\n return interfaces_data\n\n def info_to_csv(self, info):\n for server_name, server_data in sorted(info.iteritems()):\n for if_name, if_data in sorted(server_data.iteritems()):\n yield {\n \"server_name\": server_name,\n \"name\": if_name,\n \"mac\": if_data[\"mac\"],\n \"port\": if_data[\"port\"],\n \"vlan\": if_data[\"vlan\"],\n \"switch_ip\": if_data[\"switch_ip\"]}\n","sub_path":"deploy/deploy_cluster/apps/list_server_interface.py","file_name":"list_server_interface.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"478437597","text":"#!/usr/bin/env python\n\nimport config\nimport os\nimport threading\nimport logging\nimport sys\nimport RunCLI\nimport opJson, json, manageBD\n\n\n# Create a custom logger\nlogger = logging.getLogger(__name__)\n\n# Create handlers\nc_handler = logging.FileHandler(config.FILELOG)\nf_handler = logging.FileHandler(config.FILELOG)\n\n\nc_handler.setLevel(logging.WARNING)\nf_handler.setLevel(logging.ERROR)\n\n\n# Create formatters and add it to handlers\nc_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')\nf_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n\nc_handler.setFormatter(c_format)\nf_handler.setFormatter(f_format)\n\n\n# Add handlers to the logger\nlogger.addHandler(c_handler)\nlogger.addHandler(f_handler)\n\n\n \n#Metodo de envio creacion Proyecto a esclavo\n#comando=\"curl -F file=@/home/admred/Documentos/vagrant/andres/Vagranfile http://192.168.19.251:8000/CrearProyecto/andres\"\ndef enviarVM(proyecto,slave):\n comando=\"curl -F file=@\" + config.VAGRANTSERVICEHOME + proyecto + \"/Vagrantfile\" + \" http://\" + slave + \":\" + config.SLAVE1PORT +\"/CrearProyecto/\" + proyecto\n logger.warning('Ingresando a enviarVM')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n\n except Exception as e:\n logger.error(sys.exc_info()[1])\n\n\n#Metodo de envio consulta de estado proyecto al esclavo\n#comando=\"curl http://192.168.19.251:8000/StatusProyecto/andres\" \ndef preguntarEstadoProyecto(proyecto,slave):\n comando=\"curl http://\" + slave + \":\" + config.SLAVE1PORT + \"/StatusProyecto/\" + proyecto\n logger.warning('Ingresando a preguntarEstadoProyecto')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n #del mensaje del slave se saca la info del estado de cada virtual\n data=opJson.abrirArchivo(config.MSGSlave)\n if proyecto in data:\n for VM,atributo in data[proyecto][0][\"VMs\"].items():\n manageBD.modificarVM(proyecto,VM,\"\",atributo[\"Status\"])\n except Exception as e:\n logger.error(sys.exc_info()[1])\n\n\n#Metodo de envio solicitud borrado proyecto al esclavo\n#comando=\"curl http://192.168.19.251:8000/BorrarProyecto/andres\" \ndef enviarBorrarProyecto(proyecto,slave):\n comando=\"curl http://\" + slave + \":\" + config.SLAVE1PORT + \"/BorrarProyecto/\" + proyecto\n logger.warning('Ingresando a enviarBorrarProyecto')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n except Exception as e:\n logger.error(sys.exc_info()[1])\n\n\n\n#Metodo de envio solicitud levantar VM de un proyecto al esclavo\n#comando=\"curl http://192.168.19.251:8000/LevantarVM/andres/VM\" \ndef enviarLevantarVM(proyecto,VM,slave):\n comando=\"curl http://\" + slave + \":\" + config.SLAVE1PORT + \"/LevantarVM/\" + proyecto + \"/\" + VM\n logger.warning('Ingresando a enviarLevantarVM')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n except Exception as e:\n logger.error(sys.exc_info()[1]) \n\n\n\n\n#Metodo de envio solicitud apagar VM de un proyecto al esclavo\n#comando=\"curl http://192.168.19.251:8000/ApagarVM/andres/VM\" \ndef enviarApagarVM(proyecto,VM,slave):\n comando=\"curl http://\" + slave + \":\" + config.SLAVE1PORT + \"/ApagarVM/\" + proyecto + \"/\" + VM\n logger.warning('Ingresando a enviarApagarVM')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n except Exception as e:\n logger.error(sys.exc_info()[1]) \n\n\n#Metodo de envio solicitud borrar VM de un proyecto al esclavo\n#comando=\"curl http://192.168.19.251:8000/ApagarVM/andres/VM\" \ndef enviarBorrarVM(proyecto,VM,slave):\n comando=\"curl http://\" + slave + \":\" + config.SLAVE1PORT + \"/BorrarVM/\" + proyecto + \"/\" + VM\n logger.warning('Ingresando a enviarApagarVM')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n except Exception as e:\n logger.error(sys.exc_info()[1]) ","sub_path":"opSlave.py","file_name":"opSlave.py","file_ext":"py","file_size_in_byte":4448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"259409800","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\n# Copyright (C) 2011 ~ 2012 Deepin, Inc.\n# 2011 ~ 2012 Long Changjin\n# \n# Author: Long Changjin \n# Maintainer: Long Changjin \n# \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nfrom dtk.ui.label import Label\nfrom dtk.ui.utils import color_hex_to_cairo\nfrom dtk.ui.draw import draw_line\nfrom dtk.ui.constant import ALIGN_MIDDLE\nfrom constant import *\nimport gtk\nimport gobject\n\nclass StatusBar(gtk.HBox):\n '''docstring for StatusBar'''\n def __init__(self):\n super(StatusBar, self).__init__(False)\n self.__count = 0\n self.__timeout_id = None\n self.text_label = Label(\"\", text_x_align=ALIGN_MIDDLE,\n label_width=500,\n enable_select=False,\n enable_double_click=False)\n text_align = gtk.Alignment()\n text_align.set(0.0, 0.5, 0.0, 0.0)\n text_align.add(self.text_label)\n\n self.button_hbox = gtk.HBox(False)\n self.button_hbox.set_spacing(WIDGET_SPACING)\n button_align = gtk.Alignment()\n button_align.set(1.0, 0.5, 0.0, 0.0)\n button_align.set_padding(0, 0, 0, 10)\n button_align.add(self.button_hbox)\n\n self.pack_start(text_align)\n self.pack_start(button_align)\n\n self.set_size_request(WINDOW_WIDTH, STATUS_HEIGHT)\n self.connect(\"expose-event\", self.draw_background)\n\n def draw_background(self, widget, event):\n cr = widget.window.cairo_create()\n x, y, w, h = widget.allocation\n cr.set_source_rgb(*color_hex_to_cairo(MODULE_BG_COLOR))\n cr.rectangle(x, y+1, w, h-1)\n cr.fill()\n\n cr.set_source_rgb(*color_hex_to_cairo(TREEVIEW_BORDER_COLOR))\n draw_line(cr, x, y + 1, x + w, y + 1)\n\n def set_text(self, text):\n self.__count += 1\n if self.__timeout_id:\n gtk.timeout_remove(self.__timeout_id)\n self.text_label.set_text(text)\n self.__timeout_id = gobject.timeout_add(3000, self.hide_text)\n\n def hide_text(self):\n self.__count -= 1\n self.__timeout_id = None\n self.text_label.set_text(\"\")\n\n def set_buttons(self, buttons):\n self.clear_button()\n for bt in buttons:\n self.button_hbox.pack_start(bt, False, False)\n self.show_all()\n\n def get_buttons(self):\n return self.button_hbox.get_children()\n\n def clear_button(self):\n self.button_hbox.foreach(self.button_hbox.remove)\n \ngobject.type_register(StatusBar)\n","sub_path":"modules/touchpad/src/statusbar.py","file_name":"statusbar.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"163003361","text":"import shlex\nfrom itertools import chain\n\nfrom .utils import *\nimport pytest\n\nimport scuba.utils\n\n\ndef _parse_cmdline(cmdline):\n # Strip the formatting and whitespace\n lines = [l.rstrip('\\\\').strip() for l in cmdline.splitlines()]\n\n # Split each line, and return a flattened list of arguments\n return chain.from_iterable(map(shlex.split, lines))\n\ndef _test_format_cmdline(args):\n\n # Call the unit-under-test to get the formatted command line\n result = scuba.utils.format_cmdline(args)\n\n # Parse the result back out to a list of arguments\n out_args = _parse_cmdline(result)\n\n # Verify that they match\n assert_seq_equal(out_args, args)\n\n\ndef test_format_cmdline():\n '''format_cmdline works as expected'''\n\n _test_format_cmdline([\n 'something',\n '-a',\n '-b',\n '--long', 'option text',\n '-s', 'hort',\n 'a very long argument here that will end up on its own line because it is so wide and nothing else will fit at the default width',\n 'and now',\n 'some', 'more', 'stuff',\n 'and even more stuff',\n ])\n\n\ndef test_shell_quote_cmd():\n args = ['foo', 'bar pop', '\"tee ball\"']\n\n result = scuba.utils.shell_quote_cmd(args)\n\n out_args = shlex.split(result)\n\n assert_seq_equal(out_args, args)\n\n\ndef test_parse_env_var():\n '''parse_env_var returns a key, value pair'''\n result = scuba.utils.parse_env_var('KEY=value')\n assert result == ('KEY', 'value')\n\ndef test_parse_env_var_more_equals():\n '''parse_env_var handles multiple equals signs'''\n result = scuba.utils.parse_env_var('KEY=anotherkey=value')\n assert result == ('KEY', 'anotherkey=value')\n\ndef test_parse_env_var_no_equals(monkeypatch):\n '''parse_env_var handles no equals and gets value from environment'''\n monkeypatch.setenv('KEY', 'mockedvalue')\n result = scuba.utils.parse_env_var('KEY')\n assert result == ('KEY', 'mockedvalue')\n\ndef test_parse_env_var_not_set(monkeypatch):\n '''parse_env_var returns an empty string if not set'''\n monkeypatch.delenv('NOTSET', raising=False)\n result = scuba.utils.parse_env_var('NOTSET')\n assert result == ('NOTSET', '')\n\ndef test_flatten_list__not_list():\n with pytest.raises(ValueError):\n scuba.utils.flatten_list('abc')\n\ndef test_flatten_list__not_nested():\n sample = [1, 2, 3, 4]\n result = scuba.utils.flatten_list(sample)\n assert result == sample\n\ndef test_flatten_list__nested_1():\n sample = [\n 1,\n [2, 3],\n 4,\n [5, 6, 7],\n ]\n exp = range(1, 7+1)\n result = scuba.utils.flatten_list(sample)\n assert_seq_equal(result, exp)\n\ndef test_flatten_list__nested_many():\n sample = [\n 1,\n [2, 3],\n [4, 5, [6, 7, 8]],\n 9, 10,\n [11, [12, [13, [14, [15, [16, 17, 18]]]]]],\n ]\n exp = range(1, 18+1)\n result = scuba.utils.flatten_list(sample)\n assert_seq_equal(result, exp)\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"569348883","text":"import struct\nimport array\n\nfrom errors import *\n\n\n\ndef AddObjToPayload(payload, obj):\n \"\"\"Adds an object to the payload\n\n Objects come in three flavors: single objects, iterators and iterators nested in iterators. \n Because we cannot extend iterators of iterators, we use this recursive function to break all \n iterators down into single objects and add them that way.\n\n @param payload A payload in the form of a byte array we add the obj to\n @param obj The object we want to add to the payload\n \"\"\"\n try:\n payload.append(obj)\n except:\n for o in obj:\n AddObjToPayload(payload, o)\n\ndef EncodeInt32(number):\n \"\"\"\n Encode a 32-bit signed integer as a 4-byte string\n @param number \n @return byte array of size 4 that represents the integer\n \"\"\"\n return struct.pack(' 8:\n raise TypeError(\"Expecting bitfield of size no greater than 8, got bitfield of size %i\"%(len(bitString)))\n bitList = list(bitString)\n bitList.reverse()\n for i in range(8-len(bitList)):\n bitList.append(0)\n return bitList\n\ndef EncodeAxes(axes):\n \"\"\"\n Encode an array of axes names into an axis bitfield\n @param axes Array of axis names ['x', 'y', ...] \n @return bitfield containing a representation of the axes map\n \"\"\"\n # TODO: Test cases?\n\n axes_map = {\n 'x':0x01,\n 'y':0x02,\n 'z':0x04,\n 'a':0x08,\n 'b':0x10,\n }\n\n bitfield = 0\n\n for axis in axes:\n bitfield |= axes_map[axis]\n\n return bitfield\n\n\ndef UnpackResponse(format, data):\n \"\"\"\n Attempt to unpack the given data using the specified format. Throws a protocol\n error if the unpacking fails.\n \n @param format Format string to use for unpacking\n @param data Data to unpack, including a string if specified\n @return list of values unpacked, if successful.\n \"\"\"\n\n try:\n return struct.unpack(format, buffer(data))\n except struct.error as e:\n raise ProtocolError(\"Unexpected data returned from machine. Expected length=%i, got=%i, error=%s\"%\n (struct.calcsize(format),len(data),str(e)))\n\ndef UnpackResponseWithString(format, data):\n \"\"\"\n Attempt to unpack the given data using the specified format, and with a trailing,\n null-terminated string. Throws a protocol error if the unpacking fails.\n \n @param format Format string to use for unpacking\n @param data Data to unpack, including a string if specified\n @return list of values unpacked, if successful.\n \"\"\"\n if (len(data) < struct.calcsize(format) + 1):\n raise ProtocolError(\"Not enough data received from machine, expected=%i, got=%i\"%\n (struct.calcsize(format)+1,len(data))\n )\n\n output = UnpackResponse(format, data[0:struct.calcsize(format)])\n output += data[struct.calcsize(format):],\n\n return output\n","sub_path":"s3g/coding.py","file_name":"coding.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"130130395","text":"from os import listdir\nfrom os.path import join\nfrom arcpy import ASCIIToRaster_conversion, Resample_management\n\ncurr_asc_directory = \"D:\\PTBPI\\SIXTH SURVEY\\DATA\\ARUS2\"\ncurr_asc_input = \"RESULTOSCARJUL2018\"\ncurr_asc_output = \"RESULTOSCARJUL2018_1\"\ncurr_asc_output2 = \"RESULTOSCARJUL2018_2\"\n\ndef main():\n\tprint(\"\\n\" + \"OSCAR Global Ocean Current Tool\")\n\tprint(\" ASCII to Raster Converter \")\n\tprint(\" Version 1.00a by: MasBoyo \" + \"\\n\")\n\n\t#Convert into low resolution grid\n\tprint(\"\\n\" + \"Process 1 (Convert .asc to grid .adf) - STARTED\" + \"\\n\")\n\n\tlistfiles = []\n\tsearchasc = join(curr_asc_directory,curr_asc_input)\n\tfor f in listdir(searchasc):\n\t\tcurrascii = join(curr_asc_directory,curr_asc_input,f)\n\t\tcurrgrid = join(curr_asc_directory,curr_asc_output,f.replace('.asc',''))\n\t\tcurrproj = join(currgrid,\"prj.adf\")\n\t\tlistfiles.append((currascii,currgrid,currproj))\n\tfor i in range(len(listfiles)):\n\t\tconvASCRAS(listfiles[i][0],listfiles[i][1],listfiles[i][2])\n\n\tprint(\"\\n\" + \"Process 1 (Convert .asc to grid .adf) - FINISHED\" + \"\\n\")\n\n\t#Resample grid data\n\tprint(\"\\n\" + \"Process 2 (Upscale resolution of grid .adf) - STARTED\" + \"\\n\")\n\n\tlistfiles2 = []\n\tsearchasc2 = join(curr_asc_directory,curr_asc_output)\n\tfor f in listdir(searchasc2):\n\t\tif f.endswith(\"dircur\") or f.endswith(\"velcur\") or f.endswith(\"vcurne\"):\n\t\t\tcurrgrid1o = join(curr_asc_directory,curr_asc_output,f)\n\t\t\tcurrgridhi = join(curr_asc_directory,curr_asc_output2,f)\n\t\t\tcurrproj2 = join(currgridhi,\"prj.adf\")\n\t\t\tlistfiles2.append((currgrid1o,currgridhi,currproj2))\n\tfor i in range(len(listfiles2)):\n\t\tgrdResample(listfiles2[i][0],listfiles2[i][1],listfiles2[i][2])\n\n\tprint(\"\\n\" + \"Process 2 (Upscale resolution of grid .adf) - FINISHED\" + \"\\n\")\n\ndef convASCRAS(a,b,c):\n\tprint(\"Working on \" + a)\n\trasterType = \"FLOAT\"\n\tASCIIToRaster_conversion(a, b, rasterType)\n\twith open(c, \"w\") as grdprj:\n\t\tgrdprj.write(\"Projection GEOGRAPHIC\" + \"\\n\" +\\\n\t\t\t\"Datum WGS84\" + \"\\n\" +\\\n\t\t\t\"Spheroid WGS84\" + \"\\n\" +\\\n\t\t\t\"Units DD\" + \"\\n\" +\\\n\t\t\t\"Zunits NO\" + \"\\n\" +\\\n\t\t\t\"Parameters \")\n\tgrdprj.close()\n\tprint(\"Exported as \" + b)\n\ndef grdResample(a,b,c):\n\tprint(\"Working on \" + a)\n\tResample_management(a, b, \"0.125\", \"CUBIC\")\n\twith open(c, \"w\") as grdprj:\n\t\tgrdprj.write(\"Projection GEOGRAPHIC\" + \"\\n\" +\\\n\t\t\t\"Datum WGS84\" + \"\\n\" +\\\n\t\t\t\"Spheroid WGS84\" + \"\\n\" +\\\n\t\t\t\"Units DD\" + \"\\n\" +\\\n\t\t\t\"Zunits NO\" + \"\\n\" +\\\n\t\t\t\"Parameters \")\n\tgrdprj.close()\n\tprint(\"Exported as \" + b)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"tools/OSCAR_CURRENT_ASC2RAS.py","file_name":"OSCAR_CURRENT_ASC2RAS.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"560626796","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nfrom azure.cli.core.commands.validators import get_default_location_from_resource_group\n\nfrom azure.cli.core.commands.parameters import zone_type\n\nfrom ._validators import (validate_public_ip_addresses, validate_public_ip_prefixes)\n# pylint: disable=line-too-long\n\n\ndef load_arguments(self, _):\n with self.argument_context('network nat gateway') as c:\n c.argument('nat_gateway_name', id_part='name', options_list=['--name', '-n'], help='Name of the NAT gateway.')\n c.argument('location', validator=get_default_location_from_resource_group)\n c.argument('public_ip_addresses', nargs='+', help='Space-separated list of public IP addresses (names or IDs).', validator=validate_public_ip_addresses)\n c.argument('public_ip_prefixes', nargs='+', help='Space-separated list of public IP prefixes (names or IDs).', validator=validate_public_ip_prefixes)\n c.argument('idle_timeout', help='Idle timeout in minutes.')\n c.argument('zone', zone_type)\n c.ignore('expand')\n","sub_path":"src/azure-cli/azure/cli/command_modules/natgateway/_params.py","file_name":"_params.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"280971916","text":"# This file has been developed by Arastoo Khjehee as an automation tool for the camtasia2ffmpeg.py scritpt\r\n# developed by Ramy Aydarous and Jose Luis Garcia del Castillo for lossless video editting without re-encoding \r\n# or re-rendering\r\n# \r\n# https://github.com/Arastookhajehee \r\n# https://github.com/garciadelcastillo\r\n# https://github.com/RamyAydarous\r\n\r\nimport os\r\nimport glob\r\nimport subprocess\r\n\r\nprint(\"Would you like to run the camtasia2ffmpeg.py file automatically?\")\r\nrunMode = input(\"(y):Automatic Mode (n):Input file name manually \")\r\n\r\nif (runMode == \"y\"):\r\n print(\"\")\r\n print(\"Make sure none of the .tscproj files have the same name as the .mp4 files!!!\")\r\n print(\"Due to the replacement of the original file with the same name, This might\")\r\n print(\"result in unexpected errors, or unwanted trimmings.\")\r\n continueOper = input(\"Would you like to continue? (y):Yes (n):No \")\r\n if (continueOper == \"y\"):\r\n tscprojFiles = glob.glob(\"*.tscproj\")\r\n fileCount = len(tscprojFiles)\r\n for i in range(0,fileCount):\r\n tscprojFile = str(tscprojFiles[i])\r\n subprocess.call(\"python .\\camtasia2ffmpeg.py \\\"\" + tscprojFile)\r\nelse:\r\n print(\"Manual Mode selected.\")\r\n print(\"What is the name of the .tscproj file that you would like to use?\")\r\n manualtscprojFile = input(\"(write only name without the .tscproj) \")\r\n tscprojFile = manualtscprojFile + \".tscproj\"\r\n subprocess.call(\"python .\\camtasia2ffmpeg.py \\\"\" + tscprojFile)","sub_path":"RunCamtasiaToFFmpegAutomatically.py","file_name":"RunCamtasiaToFFmpegAutomatically.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"175581162","text":"import numpy as np\nimport pandas as pd\nfrom . import missing_value_pred as mvp\nimport d3m.metadata.base as mbase\nfrom d3m.primitive_interfaces.unsupervised_learning import UnsupervisedLearnerPrimitiveBase\nfrom d3m.primitive_interfaces.base import CallResult\nimport stopit\nimport math\nimport typing\n\nfrom d3m import container\nfrom d3m.metadata import hyperparams, params\nfrom d3m.metadata.hyperparams import UniformBool\nimport common_primitives.utils as utils\n\nimport typing\n\nfrom . import config\n\nInput = container.DataFrame\nOutput = container.DataFrame\n\n# store the regression models for each missing-value column in training data\n\n\nclass IR_Params(params.Params):\n fitted : typing.Union[typing.Any, None]\n verbose : typing.Union[typing.Any, None]\n iterations_done : typing.Union[typing.Any, None]\n has_finished : typing.Union[typing.Any, None]\n best_imputation : typing.Union[typing.Any, None]\n\nclass IterativeRegressionHyperparameter(hyperparams.Hyperparams):\n verbose = UniformBool(default=False,\n semantic_types=['http://schema.org/Boolean',\n 'https://metadata.datadrivendiscovery.org/types/ControlParameter'])\n use_columns = hyperparams.Set(\n elements=hyperparams.Hyperparameter[int](-1),\n default=(),\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"A set of column indices to force primitive to operate on. If any specified column cannot be parsed, it is skipped.\",\n )\n exclude_columns = hyperparams.Set(\n elements=hyperparams.Hyperparameter[int](-1),\n default=(),\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"A set of column indices to not operate on. Applicable only if \\\"use_columns\\\" is not provided.\",\n )\n return_result = hyperparams.Enumeration(\n values=['append', 'replace', 'new'],\n default='replace',\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"Should parsed columns be appended, should they replace original columns, or should only parsed columns be returned? This hyperparam is ignored if use_semantic_types is set to false.\",\n )\n use_semantic_types = hyperparams.UniformBool(\n default=False,\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"Controls whether semantic_types metadata will be used for filtering columns in input dataframe. Setting this to false makes the code ignore return_result and will produce only the output dataframe\"\n )\n add_index_columns = hyperparams.UniformBool(\n default=True,\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"Also include primary index columns if input data has them. Applicable only if \\\"return_result\\\" is set to \\\"new\\\".\",\n )\n\nclass IterativeRegressionImputation(UnsupervisedLearnerPrimitiveBase[Input, Output, IR_Params, IterativeRegressionHyperparameter]):\n \"\"\"\n Impute the missing value by iteratively regress using other attributes.\n It will fit and fill the missing value in the training set, and store the learned models.\n In the `produce` phase, it will use the learned models to iteratively regress on the\n testing data again, and return the imputed testing data.\n\n Parameters:\n ----------\n verbose: bool\n Control the verbosity\n\n Attributes:\n ----------\n best_imputation: dict. key: column name; value: trained imputation method (parameters)\n could be sklearn regression model, or \"mean\" (which means the regression failed)\n\n \"\"\"\n metadata = hyperparams.base.PrimitiveMetadata({\n # Required\n \"id\": \"f70b2324-1102-35f7-aaf6-7cd8e860acc4\",\n \"version\": config.VERSION,\n \"name\": \"DSBox Iterative Regression Imputer\",\n \"description\": \"Impute missing values using iterative regression\",\n \"python_path\": \"d3m.primitives.data_preprocessing.IterativeRegressionImputation.DSBOX\",\n \"primitive_family\": \"DATA_PREPROCESSING\",\n \"algorithm_types\": [\"IMPUTATION\"],\n \"source\": {\n \"name\": config.D3M_PERFORMER_TEAM,\n \"contact\": config.D3M_CONTACT,\n \"uris\": [config.REPOSITORY]\n },\n # Automatically generated\n # \"primitive_code\"\n # \"original_python_path\"\n # \"schema\"\n # \"structural_type\"\n # Optional\n \"keywords\": [\"preprocessing\", \"imputation\"],\n \"installation\": [config.INSTALLATION],\n \"location_uris\": [],\n \"precondition\": [hyperparams.base.PrimitivePrecondition.NO_CATEGORICAL_VALUES],\n # \"effects\": [hyperparams.base.PrimitiveEffects.NO_MISSING_VALUES],\n \"hyperparms_to_tune\": []\n })\n\n def __init__(self, *, hyperparams: IterativeRegressionHyperparameter) -> None:\n super().__init__(hyperparams=hyperparams)\n\n # All primitives must define these attributes\n self.hyperparams = hyperparams\n\n # All other attributes must be private with leading underscore\n self._best_imputation: typing.Dict = {} # in params.regression_models\n self._train_x: Input = None\n self._is_fitted = True\n self._has_finished = True\n self._iterations_done = True\n self._verbose = hyperparams['verbose'] if hyperparams else False\n\n def set_params(self, *, params: IR_Params) -> None:\n self._is_fitted = params['fitted']\n self._verbose = params['verbose']\n self._iterations_done = params['iterations_done']\n self._has_finished = params['has_finished']\n self._best_imputation = params['best_imputation']\n\n def get_params(self) -> IR_Params:\n return IR_Params(\n fitted = self._is_fitted,\n verbose = self._verbose,\n iterations_done = self._iterations_done,\n has_finished = self._has_finished,\n best_imputation = self._best_imputation\n )\n\n def set_training_data(self, *, inputs: Input) -> None:\n \"\"\"\n Sets training data of this primitive.\n\n Parameters\n ----------\n inputs : Input\n The inputs.\n \"\"\"\n if (pd.isnull(inputs).sum().sum() == 0): # no missing value exists\n if self._verbose:\n print(\"Warning: no missing value in train dataset\")\n\n self._train_x = inputs\n self._is_fitted = False\n\n def fit(self, *, timeout: float = None, iterations: int = None) -> CallResult[None]:\n \"\"\"\n train imputation parameters. Now support:\n -> greedySearch\n\n for the method that not trainable, do nothing:\n -> interatively regression\n -> other\n\n Parameters:\n ----------\n data: pandas dataframe\n label: pandas series, used for the trainable methods\n \"\"\"\n\n # if already fitted on current dataset, do nothing\n if self._is_fitted:\n return CallResult(None, self._has_finished, self._iterations_done)\n\n if (timeout is None):\n timeout = 2**31 - 1\n if (iterations is None):\n self._iterations_done = True\n iterations = 30\n # import pdb\n # pdb.set_trace()\n # setup the timeout\n with stopit.ThreadingTimeout(timeout) as to_ctx_mrg:\n assert to_ctx_mrg.state == to_ctx_mrg.EXECUTING\n\n data = self._train_x.copy()\n\n # start fitting\n if self._verbose:\n print(\"=========> iteratively regress method:\")\n data_clean, self._best_imputation = self.__iterativeRegress(data, iterations)\n\n # self._train_x, self._best_imputation = self.__iterativeRegress(data, iterations)\n if to_ctx_mrg.state == to_ctx_mrg.EXECUTED:\n self._is_fitted = True\n self._iterations_done = True\n self._has_finished = True\n elif to_ctx_mrg.state == to_ctx_mrg.TIMED_OUT:\n self._is_fitted = False\n self._iterations_done = False\n self._has_finished = False\n return CallResult(None, self._has_finished, self._iterations_done)\n\n def produce(self, *, inputs: Input, timeout: float = None, iterations: int = None) -> CallResult[Output]:\n \"\"\"\n precond: run fit() before\n\n to complete the data, based on the learned parameters, support:\n -> greedy search\n\n also support the untrainable methods:\n -> iteratively regression\n -> other\n\n Parameters:\n ----------\n data: pandas dataframe\n label: pandas series, used for the evaluation of imputation\n\n TODO:\n ----------\n 1. add evaluation part for __simpleImpute()\n\n \"\"\"\n\n # inputs = inputs.convert_objects(convert_numeric=True)\n attribute = utils.list_columns_with_semantic_types(\n inputs.metadata, ['https://metadata.datadrivendiscovery.org/types/Attribute'])\n numeric = utils.list_columns_with_semantic_types(\n inputs.metadata, ['http://schema.org/Integer', 'http://schema.org/Float'])\n numeric = [x for x in numeric if x in attribute]\n\n # keys = data.keys()\n # missing_col_id = []\n\n inputs = inputs.iloc[:, numeric].apply(\n lambda col: pd.to_numeric(col, errors='coerce'))\n # data = mvp.df2np(numeric_data, missing_col_id, self._verbose)\n\n for i in numeric:\n old_metadata = dict(inputs.metadata.query((mbase.ALL_ELEMENTS, i)))\n old_metadata[\"structural_type\"] = inputs.iloc[:, i].values.dtype.type\n inputs.metadata = inputs.metadata.update((mbase.ALL_ELEMENTS, i), old_metadata)\n\n # Impute numerical attributes only\n\n if (not self._is_fitted):\n # todo: specify a NotFittedError, like in sklearn\n raise ValueError(\"Calling produce before fitting.\")\n\n if (pd.isnull(inputs).sum().sum() == 0): # no missing value exists\n if self._verbose:\n print(\"Warning: no missing value in test dataset\")\n self._has_finished = True\n return CallResult(inputs, self._has_finished, self._iterations_done)\n\n if (timeout is None):\n timeout = 2**31 - 1\n if (iterations is None):\n self._iterations_done = True\n iterations = 30 # only works for iteratively_regre method\n\n data = inputs.copy()\n # record keys:\n keys = data.keys()\n index = data.index\n\n # setup the timeout\n with stopit.ThreadingTimeout(timeout) as to_ctx_mrg:\n assert to_ctx_mrg.state == to_ctx_mrg.EXECUTING\n\n # start completing data...\n if self._verbose:\n print(\"=========> iteratively regress method:\")\n data_clean = self.__regressImpute(data, self._best_imputation, iterations)\n value = None\n if to_ctx_mrg.state == to_ctx_mrg.EXECUTED:\n self._is_fitted = True\n self._has_finished = True\n value = pd.DataFrame(data_clean, index, keys)\n value = container.DataFrame(value)\n value.metadata = data.metadata\n elif to_ctx_mrg.state == to_ctx_mrg.TIMED_OUT:\n print(\"Timed Out...\")\n self._is_fitted = False\n self._has_finished = False\n self._iterations_done = False\n return CallResult(value, self._has_finished, self._iterations_done)\n\n\n @classmethod\n def _get_columns_to_fit(cls, inputs: Input, hyperparams: IterativeRegressionHyperparameter):\n if not hyperparams['use_semantic_types']:\n return inputs, list(range(len(inputs.columns)))\n\n inputs_metadata = inputs.metadata\n\n def can_produce_column(column_index: int) -> bool:\n return cls._can_produce_column(inputs_metadata, column_index, hyperparams)\n\n columns_to_produce, columns_not_to_produce = common_utils.get_columns_to_use(inputs_metadata,\n use_columns=hyperparams['use_columns'],\n exclude_columns=hyperparams['exclude_columns'],\n can_use_column=can_produce_column)\n return inputs.iloc[:, columns_to_produce], columns_to_produce\n\n\n @classmethod\n def _can_produce_column(cls, inputs_metadata: mbase.DataMetadata, column_index: int, hyperparams: IterativeRegressionHyperparameter) -> bool:\n column_metadata = inputs_metadata.query((mbase.ALL_ELEMENTS, column_index))\n\n semantic_types = column_metadata.get('semantic_types', [])\n if len(semantic_types) == 0:\n cls.logger.warning(\"No semantic types found in column metadata\")\n return False\n if \"https://metadata.datadrivendiscovery.org/types/Attribute\" in semantic_types:\n return True\n\n return False\n\n\n #============================================ helper functions ============================================\n def __iterativeRegress(self, data, iterations):\n '''\n init with simple imputation, then apply regression to impute iteratively\n '''\n # for now, cancel the evaluation part for iterativeRegress\n # is_eval = False\n # if (label_col_name==None or len(label_col_name)==0):\n # is_eval = False\n # else:\n # is_eval = True\n\n # indices for numeric attribute columns only\n attribute = utils.list_columns_with_semantic_types(\n data.metadata, ['https://metadata.datadrivendiscovery.org/types/Attribute'])\n numeric = utils.list_columns_with_semantic_types(\n data.metadata, ['http://schema.org/Integer', 'http://schema.org/Float'])\n numeric = [x for x in numeric if x in attribute]\n\n keys = data.keys()\n missing_col_id = []\n numeric_data = data.iloc[:, numeric].apply(\n lambda col: pd.to_numeric(col, errors='coerce'))\n data = mvp.df2np(numeric_data, missing_col_id, self._verbose)\n\n # Impute numerical attributes only\n missing_col_id = [x for x in missing_col_id if x in numeric]\n missing_col_data = data[:, missing_col_id]\n\n # If all values in a column are missing, set that column to zero\n all_missing = np.sum(np.isnan(missing_col_data), axis=0) == missing_col_data.shape[0]\n for col, col_missing in enumerate(all_missing):\n if col_missing:\n missing_col_data[:, col] = 0\n\n imputed_data = np.zeros([data.shape[0], len(missing_col_id)])\n imputed_data_lastIter = missing_col_data\n # coeff_matrix = np.zeros([len(missing_col_id), data.shape[1]-1]) #coefficient vector for each missing value column\n model_list = [None] * len(missing_col_id) # store the regression model\n epoch = iterations\n counter = 0\n # mean init all missing-value columns\n init_imputation = [\"mean\"] * len(missing_col_id)\n next_data = mvp.imputeData(data, missing_col_id, init_imputation, self._verbose)\n\n while (counter < epoch):\n for i in range(len(missing_col_id)):\n target_col = missing_col_id[i]\n next_data[:, target_col] = missing_col_data[:, i] # recover the column that to be imputed\n\n data_clean, model_list[i] = mvp.bayeImpute(next_data, target_col, self._verbose)\n next_data[:, target_col] = data_clean[:, target_col] # update bayesian imputed column\n imputed_data[:, i] = data_clean[:, target_col] # add the imputed data\n\n # if (is_eval):\n # self.__evaluation(data_clean, label)\n\n # if (counter > 0):\n # distance = np.square(imputed_data - imputed_data_lastIter).sum()\n # if self._verbose: print(\"changed distance: {}\".format(distance))\n imputed_data_lastIter = np.copy(imputed_data)\n counter += 1\n data[:, missing_col_id] = imputed_data_lastIter\n # convert model_list to dict\n model_dict = {}\n for i in range(len(model_list)):\n model_dict[keys[missing_col_id[i]]] = model_list[i]\n\n return data, model_dict\n\n def __regressImpute(self, data, model_dict, iterations):\n \"\"\"\n \"\"\"\n col_names = data.keys()\n # 1. convert to np array and get missing value column id\n missing_col_id = []\n data = mvp.df2np(data, missing_col_id, self._verbose)\n\n model_list = [] # the model list\n new_missing_col_id = [] # the columns that have correspoding model\n # mask = np.ones((data.shape[1]), dtype=bool) # false means: this column cannot be bring into impute\n # offset = 0 # offset from missing_col_id to new_missing_col_id\n\n for i in range(len(missing_col_id)):\n name = col_names[missing_col_id[i]]\n # if there is a column that not appears in trained model, impute it as \"mean\"\n if (name not in model_dict.keys()):\n data = mvp.imputeData(data, [missing_col_id[i]], [\"mean\"], self._verbose)\n # mask[missing_col_id[i]] = False\n print(\"fill\" + name + \"with mean\")\n # offset += 1\n else:\n model_list.append(model_dict[name])\n new_missing_col_id.append(missing_col_id[i])\n\n # now, impute the left missing columns using the model from model_list (ignore the extra columns)\n to_impute_data = data # just change a name..\n missing_col_data = to_impute_data[:, new_missing_col_id]\n epoch = iterations\n counter = 0\n # mean init all missing-value columns\n init_imputation = [\"mean\"] * len(new_missing_col_id)\n next_data = mvp.imputeData(to_impute_data, new_missing_col_id, init_imputation, self._verbose)\n\n while (counter < epoch):\n for i in range(len(new_missing_col_id)):\n target_col = new_missing_col_id[i]\n next_data[:, target_col] = missing_col_data[:, i] # recover the column that to be imputed\n\n next_data = mvp.transform(next_data, target_col, model_list[i], self._verbose)\n\n counter += 1\n\n # put back to data\n # data[:, mask] = next_data\n return next_data\n","sub_path":"dsbox/datapreprocessing/cleaner/iterative_regression.py","file_name":"iterative_regression.py","file_ext":"py","file_size_in_byte":18531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"381700066","text":"# coding=utf-8\r\nr\"\"\"\r\nVQE with parallel QPUs on Rigetti Forest\r\n========================================\r\n\r\n.. meta::\r\n :property=\"og:description\": This demonstration showcases how parallel QPUs can\r\n speed up the calculation of the potential energy surface of molecular Hamiltonian.\r\n :property=\"og:image\": https://pennylane.ai/qml/_images/vqe_diagram.png\r\n\r\nThis tutorial showcases how using asynchronously-evaluated parallel QPUs can speed up the\r\ncalculation of the potential energy surface of molecular hydrogen (:math:`H_2`).\r\n\r\nUsing a VQE setup, we task two devices from the\r\n`PennyLane-Forest `__ plugin with evaluating\r\nseparate terms in the qubit Hamiltonian of :math:`H_2`. As these devices are allowed to operate\r\nasynchronously, i.e., at the same time and without having to wait for each other,\r\nthe calculation can be performed in roughly half the time.\r\n\r\nWe begin by importing the prerequisite libraries:\r\n\"\"\"\r\n\r\nimport time\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pennylane as qml\r\nfrom pennylane import qchem\r\n\r\n##############################################################################\r\n# This tutorial requires the ``pennylane-qchem``, ``pennylane-forest`` and ``dask``\r\n# packages, which are installed separately using:\r\n#\r\n# .. code-block:: bash\r\n#\r\n# pip install pennylane-qchem\r\n# pip install pennylane-forest\r\n# pip install \"dask[delayed]\"\r\n#\r\n# Finding the qubit Hamiltonians of :math:`H_{2}`\r\n# -----------------------------------------------\r\n#\r\n# The objective of this tutorial is to evaluate the potential energy surface of molecular\r\n# hydrogen. This is achieved by finding the ground state energy of :math:`H_{2}` as we increase\r\n# the bond length between the hydrogen atoms.\r\n#\r\n# Each inter-atomic distance results in a different qubit Hamiltonian. To find the corresponding\r\n# Hamiltonian, we use the :func:`~.pennylane_qchem.qchem.generate_hamiltonian` function of the\r\n# :mod:`~.pennylane_qchem.qchem` package. Further details on the mapping from the electronic\r\n# Hamiltonian of a molecule to a qubit Hamiltonian can be found in the\r\n# :doc:`tutorial_quantum_chemistry` and :doc:`tutorial_vqe`\r\n# tutorials.\r\n#\r\n# We begin by creating a dictionary containing a selection of bond lengths and corresponding data\r\n# files saved in `XYZ `__ format. These files\r\n# follow a standard format for specifying the geometry of a molecule and can be downloaded as a\r\n# Zip from :download:`here <../demonstrations/vqe_parallel/vqe_parallel.zip>`.\r\n\r\ndata = { # keys: atomic separations (in Angstroms), values: corresponding files\r\n 0.3: \"vqe_parallel/h2_0.30.xyz\",\r\n 0.5: \"vqe_parallel/h2_0.50.xyz\",\r\n 0.7: \"vqe_parallel/h2_0.70.xyz\",\r\n 0.9: \"vqe_parallel/h2_0.90.xyz\",\r\n 1.1: \"vqe_parallel/h2_1.10.xyz\",\r\n 1.3: \"vqe_parallel/h2_1.30.xyz\",\r\n 1.5: \"vqe_parallel/h2_1.50.xyz\",\r\n 1.7: \"vqe_parallel/h2_1.70.xyz\",\r\n 1.9: \"vqe_parallel/h2_1.90.xyz\",\r\n 2.1: \"vqe_parallel/h2_2.10.xyz\",\r\n}\r\n\r\n##############################################################################\r\n# The next step is to create the qubit Hamiltonians for each value of the inter-atomic distance.\r\n\r\nhamiltonians = []\r\n\r\nfor separation, file in data.items():\r\n h, nr_qubits = qchem.generate_hamiltonian(\r\n mol_name=str(separation),\r\n mol_geo_file=file,\r\n mol_charge=0,\r\n multiplicity=1,\r\n basis_set=\"sto-3g\",\r\n )\r\n\r\n hamiltonians.append(h)\r\n\r\n##############################################################################\r\n# Each Hamiltonian can be written as a linear combination of fifteen tensor products of Pauli\r\n# matrices. Let's take a look more closely at one of the Hamiltonians:\r\n\r\nh = hamiltonians[0]\r\n\r\nprint(\"Number of terms: {}\\n\".format(len(h.ops)))\r\nfor op in h.ops:\r\n print(\"Measurement {} on wires {}\".format(op.name, op.wires))\r\n\r\n##############################################################################\r\n# Defining the energy function\r\n# ----------------------------\r\n#\r\n# The fifteen Pauli terms comprising each Hamiltonian can conventionally be evaluated in a\r\n# sequential manner: we evaluate one expectation value at a time before moving on to the next.\r\n# However, this task is highly suited to parallelization. With access to multiple QPUs,\r\n# we can split up evaluating the terms between the QPUs and gain an increase in processing speed.\r\n#\r\n#\r\n# .. note::\r\n# Some of the Pauli terms commute, and so they can be evaluated in practice with fewer than\r\n# fifteen quantum circuit runs. Nevertheless, these quantum circuit runs can still be\r\n# parallelized to multiple QPUs.\r\n#\r\n# Let's suppose we have access to two quantum devices. In this tutorial we consider two\r\n# simulators from Rigetti: ``4q-qvm`` and ``9q-square-qvm``, but we could also run on hardware\r\n# devices from Rigetti or other providers.\r\n#\r\n# We can evaluate the expectation value of each Hamiltonian with eight terms run on\r\n# one device and seven terms run on the other, as summarized by the diagram below:\r\n#\r\n# .. figure:: /demonstrations/vqe_parallel/vqe_diagram.png\r\n# :width: 65%\r\n# :align: center\r\n#\r\n# To do this, start by instantiating a device for each term:\r\n\r\ndev1 = [qml.device(\"forest.qvm\", device=\"4q-qvm\") for _ in range(8)]\r\ndev2 = [qml.device(\"forest.qvm\", device=\"9q-square-qvm\") for _ in range(7)]\r\ndevs = dev1 + dev2\r\n\r\n##############################################################################\r\n# .. note::\r\n#\r\n# For the purposes of this demonstration, we are simulating the QPUs using the\r\n# ``forest.qvm`` simulator. To run this demonstration on hardware, simply\r\n# swap ``forest.qvm`` for ``forest.qpu`` and specify the hardware device to run on.\r\n#\r\n# Please refer to the `Rigetti website `__ for an up-to-date\r\n# list on available QPUs.\r\n#\r\n# .. warning::\r\n# Rigetti's QVM and Quil Compiler services must be running for this tutorial to execute. They\r\n# can be installed by consulting the `Rigetti documentation\r\n# `__ or, for users with Docker, by running:\r\n#\r\n# .. code-block:: bash\r\n#\r\n# docker run -d -p 5555:5555 rigetti/quilc -R -p 5555\r\n# docker run -d -p 5000:5000 rigetti/qvm -S -p 5000\r\n#\r\n# We must also define a circuit to prepare the ground state, which is a superposition of the\r\n# Hartree-Fock (:math:`|1100\\rangle`) and doubly-excited (:math:`|0011\\rangle`) configurations.\r\n# The simple circuit below is able to prepare states of the form :math:`\\alpha |1100\\rangle +\r\n# \\beta |0011\\rangle` and hence encode the ground state wave function of the hydrogen molecule. The\r\n# circuit has a single free parameter, which controls a Y-rotation on the third qubit.\r\n\r\n\r\ndef circuit(param, wires):\r\n qml.BasisState(np.array([1, 1, 0, 0]), wires=[0, 1, 2, 3])\r\n qml.RY(param, wires=2)\r\n qml.CNOT(wires=[2, 3])\r\n qml.CNOT(wires=[2, 0])\r\n qml.CNOT(wires=[3, 1])\r\n\r\n\r\n##############################################################################\r\n# The ground state for each inter-atomic distance is characterized by a different Y-rotation angle.\r\n# The values of these Y-rotations can be found by minimizing the ground state energy as outlined in\r\n# :doc:`tutorial_vqe`. In this tutorial, we load pre-optimized rotations and focus on\r\n# comparing the speed of evaluating the potential energy surface with sequential and parallel\r\n# evaluation. These parameters can be downloaded by clicking :download:`here\r\n# <../demonstrations/vqe_parallel/RY_params.npy>`.\r\n\r\nparams = np.load(\"vqe_parallel/RY_params.npy\")\r\n\r\n##############################################################################\r\n# Finally, the energies as functions of rotation angle can be given using\r\n# :class:`~.pennylane.VQECost`.\r\n\r\nenergies = [qml.VQECost(circuit, h, devs) for h in hamiltonians]\r\n\r\n##############################################################################\r\n# Calculating the potential energy surface\r\n# ----------------------------------------\r\n#\r\n# :class:`~.pennylane.VQECost` returns a :class:`~.pennylane.QNodeCollection` which can be\r\n# evaluated using the input parameters to the ansatz circuit. The\r\n# :class:`~.pennylane.QNodeCollection` can be evaluated asynchronously by passing the keyword\r\n# argument ``parallel=True``. When ``parallel=False`` (the default behaviour), the QNodes are\r\n# instead evaluated sequentially.\r\n#\r\n# We can use this feature to compare the sequential and parallel times required to calculate the\r\n# potential energy surface. The following function calculates the surface:\r\n\r\n\r\ndef calculate_surface(parallel=True):\r\n s = []\r\n t0 = time.time()\r\n\r\n for i, e in enumerate(energies):\r\n print(\"Running for inter-atomic distance {} Å\".format(list(data.keys())[i]))\r\n s.append(e(params[i], parallel=parallel))\r\n\r\n t1 = time.time()\r\n\r\n print(\"Evaluation time: {0:.2f} s\".format(t1 - t0))\r\n return s, t1 - t0\r\n\r\n\r\nprint(\"Evaluating the potential energy surface sequentially\")\r\nsurface_seq, t_seq = calculate_surface(parallel=False)\r\n\r\nprint(\"\\nEvaluating the potential energy surface in parallel\")\r\nsurface_par, t_par = calculate_surface(parallel=True)\r\n\r\n##############################################################################\r\n# We have seen how a :class:`~.pennylane.QNodeCollection` can be evaluated in parallel. This results\r\n# in a speed up in processing:\r\n\r\nprint(\"Speed up: {0:.2f}\".format(t_seq / t_par))\r\n\r\n##############################################################################\r\n# Can you think of other ways to combine multiple QPUs to improve the\r\n# performance of quantum algorithms? To conclude the tutorial, let's plot the calculated\r\n# potential energy surfaces:\r\n\r\nplt.plot(surface_seq, linewidth=2.2, marker=\"o\", color=\"red\")\r\nplt.plot(surface_par, linewidth=2.2, marker=\"d\", color=\"blue\")\r\nplt.title(\"Potential energy surface for molecular hydrogen\", fontsize=12)\r\nplt.xlabel(\"Atomic separation (Å)\", fontsize=16)\r\nplt.ylabel(\"Ground state energy (Ha)\", fontsize=16)\r\nplt.grid(True)\r\n\r\n##############################################################################\r\n# These surfaces overlap, with any variation due to the limited number of shots used to evaluate the\r\n# expectation values in the ``forest.qvm`` device (we are using the default value of\r\n# ``shots=1024``).\r\n","sub_path":"demonstrations/tutorial_vqe_parallel.py","file_name":"tutorial_vqe_parallel.py","file_ext":"py","file_size_in_byte":10452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"615727712","text":"from appium.webdriver.common.mobileby import MobileBy\nimport time\nfrom library.core.BasePage import BasePage\nfrom library.core.TestLogger import TestLogger\nfrom pages import *\n\n\nclass GroupChatApprovalDetail(BasePage):\n \"\"\"群聊--审批-审批内容页面 \"\"\"\n ACTIVITY = 'com.cmcc.cmrcs.android.ui.activities.EditGroupPageActivity'\n\n __locators = {\n '返回': (MobileBy.ACCESSIBILITY_ID, 'back'),\n '关闭': (MobileBy.ACCESSIBILITY_ID, 'cc h5 ic close'),\n '请输入申请内容': (MobileBy.IOS_PREDICATE, 'value == \"请输入申请内容\"'),\n '添加审批人': (MobileBy.XPATH, '//XCUIElementTypeOther[@name=\"审批\"]/XCUIElementTypeOther[4]/XCUIElementTypeOther[3]/XCUIElementTypeOther'),\n '添加抄送人': (MobileBy.XPATH, '//XCUIElementTypeOther[@name=\"审批\"]/XCUIElementTypeOther[7]/XCUIElementTypeOther/XCUIElementTypeOther'),\n '审批转聊天': (MobileBy.XPATH, '//XCUIElementTypeOther[@name=\"审批\"]/XCUIElementTypeOther[9]'),\n '分享至当前群': (MobileBy.XPATH, '//XCUIElementTypeOther[@name=\"审批\"]/XCUIElementTypeOther[10]'),\n '提交': (MobileBy.ACCESSIBILITY_ID, '提交'),\n\n }\n\n @TestLogger.log()\n def is_on_this_page(self):\n \"\"\"当前页面是否在审批\"\"\"\n\n try:\n self.wait_until(\n timeout=15,\n auto_accept_permission_alert=True,\n condition=lambda d: self.is_text_present('我的通用审批')\n )\n return True\n except:\n return False\n\n @TestLogger.log()\n def wait_for_page_load(self, timeout=15, auto_accept_alerts=True):\n \"\"\"等待审��详情页面加载 \"\"\"\n try:\n self.wait_until(\n timeout=timeout,\n auto_accept_permission_alert=auto_accept_alerts,\n condition=lambda d: self._is_element_present(self.__class__.__locators[\"请输入申请内容\"])\n )\n except:\n message = \"页面在{}s内,没有加载成功\".format(timeout)\n raise AssertionError(\n message\n )\n return self\n\n @TestLogger.log('判断页面存在元素')\n def is_exist_element(self, locator='关闭'):\n if self._is_element_present(self.__locators[locator]):\n return True\n else:\n return False\n\n @TestLogger.log()\n def click_back(self, element='返回'):\n \"\"\"点击返回\"\"\"\n self.click_element(self.__class__.__locators[element])\n\n\n @TestLogger.log()\n def click_close_h5(self, element='关闭'):\n \"\"\"点击关闭h5页面按钮\"\"\"\n self.click_element(self.__class__.__locators[element])\n\n @TestLogger.log()\n def click_input_application_detail(self, element='请输入申请内容'):\n \"\"\"点击请输入申请内容\"\"\"\n self.click_element(self.__class__.__locators[element])\n\n @TestLogger.log()\n def input_application_detail(self, text):\n \"\"\"输入申请内容\"\"\"\n self.input_text(self.__class__.__locators['请输入申请内容'], text)\n\n @TestLogger.log()\n def click_add_approver(self, element='添加审批人'):\n \"\"\"点击添加审批人\"\"\"\n self.click_element(self.__class__.__locators[element])\n\n @TestLogger.log()\n def add_approver(self, name='大佬1'):\n \"\"\"添加审批人\"\"\"\n self.click_add_approver()\n time.sleep(2)\n SelectHeContactsDetailPage().select_one_he_contact_by_name(name)\n SelectHeContactsDetailPage().click_sure_icon()\n time.sleep(2)\n\n @TestLogger.log()\n def click_approval_change_to_chat(self):\n \"\"\"点击审批转聊天\"\"\"\n self.click_element((MobileBy.IOS_PREDICATE, 'name CONTAINS \"审批转聊天\"'))\n # self.click_element(self.__class__.__locators[element])\n time.sleep(3)\n\n @TestLogger.log()\n def click_share_to_group(self):\n \"\"\"点击分享至当前群\"\"\"\n self.click_element((MobileBy.IOS_PREDICATE, 'name CONTAINS \"分享至当前群\"'))\n # self.click_element(self.__class__.__locators[element])\n time.sleep(3)\n\n @TestLogger.log()\n def click_submit(self, element='提交'):\n \"\"\"点击提交\"\"\"\n self.click_element(self.__class__.__locators[element])\n","sub_path":"pages/groupset/GroupApprovalDetail.py","file_name":"GroupApprovalDetail.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"581382599","text":"\"\"\"connectus URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include,re_path\nfrom django.contrib.auth import views as auth_views\nfrom . import views\n\n\napp_name_ = 'accounts'\n\nurlpatterns = [\n\n \n path('', auth_views.login, {'template_name':'accounts/starter.html'}, name=\"login\"),\n path('logout/', auth_views.logout, {'template_name':'accounts/logout.html'}, name=\"logout\"),\n path('register/', views.register, name=\"register\"),\n path('searchjobs/', views.jobsfinder, name=\"jobs-search\"),\n path('profile/', views.profile, name=\"profile\"),\n path('update/', views.update_profile, name=\"update-profile\"),\n re_path(r'^connect/(?P.+)/(?P\\d+)/$', views.change_friends, name='change_friends'),\n re_path(r'^users/$', views.view_profile, name='view_profile'),\n re_path(r'^profile/(?P\\d+)/$', views.view_profile, name='view_profile_with_pk'),\n \n]\n","sub_path":"connectus/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"598342369","text":"from discord.ext import commands\r\n\r\nimport random\r\nimport time\r\nfrom typing import Union\r\nimport asyncio\r\nimport json\r\n\r\nimport Chess_Bot.util.Data as data\r\nimport Chess_Bot.util.Utility as util\r\nfrom Chess_Bot.util.CPP_IO import *\r\nfrom Chess_Bot.cogs.Profiles import Profile, ProfileNames\r\nfrom Chess_Bot import constants\r\n\r\n\r\nclass Engine(commands.Cog):\r\n\r\n def __init__(self, client):\r\n self.client = client\r\n\r\n @commands.command(aliases=['play', 'm'])\r\n @commands.cooldown(1, 3, commands.BucketType.user)\r\n async def move(self, ctx, move):\r\n '''\r\n {\r\n \"name\": \"move\",\r\n \"description\": \"Plays a move against the computer.\\\\nPlease enter the move in algebraic notation.\\\\nFor example, Nxe4, Nge5, c4, Ke2, etc.\\\\nMore about algebraic notation [here](https://www.chess.com/article/view/chess-notation#algebraic-notation).\\\\nYou can also enter it in UCI (universal chess interface) notation.\",\r\n \"aliases\": [\r\n \"play\",\r\n \"m\"\r\n ],\r\n \"usage\": \"$move \",\r\n \"examples\": [\r\n \"$move e4\",\r\n \"$move e7e5\",\r\n \"$move Ke2\"\r\n ],\r\n \"cooldown\": 3\r\n }\r\n '''\r\n\r\n person = ctx.author.id\r\n game = data.data_manager.get_game(person)\r\n\r\n if game == None:\r\n await ctx.send('You do not have a game in progress.')\r\n return\r\n if 'resign' in move.lower():\r\n data.data_manager.delete_game(ctx.author.id, False)\r\n\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 0, game.bot)\r\n if ctx.author.id in util.thonking:\r\n util.thonking.remove(ctx.author.id)\r\n await ctx.send(f'Game resigned. Your new rating is {round(new_rating)} ({round(old_rating)} + {round(new_rating - old_rating, 2)}).\\n'\r\n 'Tip: Trying to resign? You can also use the `$resign` command.')\r\n return\r\n\r\n if isinstance(game, data.Game):\r\n if person in util.thonking:\r\n await ctx.send('Chess Bot is already thinking')\r\n return\r\n\r\n board = chess.Board(game.fen)\r\n try:\r\n board.push_san(move)\r\n except ValueError:\r\n try:\r\n board.push_uci(move)\r\n except ValueError:\r\n await ctx.send('Illegal move played. Make sure your move is in SAN or UCI notation.\\nUse `$help move` for more info.')\r\n return\r\n if board.is_checkmate():\r\n if board.turn == chess.WHITE and game.color == 0 or board.turn == chess.BLACK and game.color == 1:\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 1, game.bot)\r\n data.data_manager.delete_game(person, True)\r\n await ctx.send('You won!')\r\n elif board.turn == chess.WHITE and game.color == 1 or board.turn == chess.BLACK and game.color == 0:\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 0, game.bot)\r\n data.data_manager.delete_game(person, False)\r\n await ctx.send('You lost.')\r\n\r\n await ctx.send(f'Your new rating is {round(new_rating)} ({round(old_rating)} + {round(new_rating - old_rating, 2)})')\r\n return\r\n elif board.can_claim_draw():\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 1/2, game.bot)\r\n await ctx.send('Draw')\r\n data.data_manager.delete_game(person, None)\r\n\r\n await ctx.send(f'Your new rating is {round(new_rating)} ({round(old_rating)} + {round(new_rating - old_rating, 2)})')\r\n return\r\n\r\n game.fen = board.fen()\r\n data.data_manager.change_game(person, game)\r\n\r\n thonk = self.client.get_emoji(constants.THONK_EMOJI_ID)\r\n await ctx.message.add_reaction(thonk)\r\n util.thonking.append(person)\r\n\r\n move, game = await run_engine(person)\r\n # If person resigned while bot was thinking\r\n if data.data_manager.get_game(person) is None:\r\n return\r\n game.last_moved = time.time()\r\n game.warned = False\r\n data.data_manager.change_game(person, game)\r\n\r\n await output_move(ctx, person, move)\r\n await log(person, self.client, ctx)\r\n if person in util.thonking:\r\n util.thonking.remove(person)\r\n\r\n board = chess.Board(game.fen)\r\n if board.is_game_over(claim_draw=True) or move == 'RESIGN':\r\n if move == 'RESIGN':\r\n await ctx.send('Chess Bot resigned')\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 1, game.bot)\r\n data.data_manager.delete_game(person, True)\r\n elif board.is_checkmate():\r\n if board.turn == chess.WHITE and game.color == 0 or board.turn == chess.BLACK and game.color == 1:\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 1, game.bot)\r\n data.data_manager.delete_game(person, True)\r\n await ctx.send('You won!')\r\n elif board.turn == chess.WHITE and game.color == 1 or board.turn == chess.BLACK and game.color == 0:\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 0, game.bot)\r\n data.data_manager.delete_game(person, False)\r\n await ctx.send('You lost.')\r\n else:\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 1/2, game.bot)\r\n await ctx.send('Draw')\r\n data.data_manager.delete_game(person, None)\r\n\r\n await ctx.send(f'Your new rating is {round(new_rating)} ({round(old_rating)} + {round(new_rating - old_rating, 2)})')\r\n elif isinstance(game, data.Game2):\r\n board = chess.Board(game.fen)\r\n color = chess.WHITE if person == game.white else chess.BLACK\r\n util2 = self.client.get_cog('Util')\r\n\r\n if board.turn != color:\r\n await ctx.send(f'It is not your turn!')\r\n return\r\n try:\r\n board.push_san(move)\r\n except ValueError:\r\n try:\r\n board.push_uci(move)\r\n except ValueError:\r\n await ctx.send('Illegal move played. Make sure your move is in SAN or UCI notation.\\nUse `$help move` for more info.')\r\n return\r\n if color == chess.WHITE:\r\n game.white_last_moved = time.time()\r\n game.white_warned = False\r\n else:\r\n game.black_last_moved = time.time()\r\n game.black_warned = False\r\n game.fen = board.fen()\r\n data.data_manager.change_game(person, game)\r\n if board.is_checkmate():\r\n white_delta, black_delta = util.update_rating2(\r\n game.white, game.black, 1 if board.turn == chess.BLACK else 0)\r\n embed = discord.Embed(\r\n title=f'{ctx.author}\\'s game', description=f'{whiteblack[not board.turn].capitalize()} won by checkmate.')\r\n path = get_image2(person, color)\r\n file = discord.File(path, filename='board.png')\r\n embed.set_image(url='attachment://board.png')\r\n await ctx.send(embed=embed, file=file)\r\n\r\n file1, embed1 = util2.make_embed(\r\n game.white, title='Your game has ended', description=f'{whiteblack[not board.turn].capitalize()} won by checkmate.\\nYour new rating is {round(data.data_manager.get_rating(game.white))} ({white_delta})')\r\n file2, embed2 = util2.make_embed(\r\n game.black, title='Your game has ended', description=f'{whiteblack[not board.turn].capitalize()} won by checkmate.\\nYour new rating is {round(data.data_manager.get_rating(game.black))} ({black_delta})')\r\n\r\n await util2.send_notif(game.white, file=file1, embed=embed1)\r\n await util2.send_notif(game.black, file=file2, embed=embed2)\r\n\r\n data.data_manager.delete_game(game.white, not board.turn)\r\n return\r\n elif board.can_claim_draw():\r\n white_delta, black_delta = util.update_rating2(\r\n game.white, game.black, 1/2)\r\n embed = discord.Embed(\r\n title=f'{ctx.author}\\'s game', description=f'Draw.')\r\n path = get_image2(person, color)\r\n file = discord.File(path, filename='board.png')\r\n embed.set_image(url='attachment://board.png')\r\n await ctx.send(embed=embed, file=file)\r\n\r\n file1, embed1 = util2.make_embed(\r\n title=f'Your game has ended', description=f'Draw.\\nYour new rating is {round(data.data_manager.get_rating(game.white))} ({white_delta})')\r\n file2, embed2 = util2.make_embed(\r\n title=f'Your game has ended', description=f'Draw.\\nYour new rating is {round(data.data_manager.get_rating(game.black))} ({black_delta})')\r\n await util2.send_notif(game.white, file=file1, embed=embed1)\r\n await util2.send_notif(game.black, file=file2, embed=embed2)\r\n\r\n data.data_manager.delete_game(game.white, 69)\r\n return\r\n\r\n game.fen = board.fen()\r\n if color == chess.WHITE:\r\n game.white_last_moved = time.time()\r\n game.white_warned = False\r\n data.data_manager.change_game(person, game)\r\n file, embed = util2.make_embed(game.white, title=f'Your game with {await util2.get_name(game.black)}', description='You have moved.')\r\n await ctx.message.reply(file=file, embed=embed)\r\n\r\n file, embed = util2.make_embed(game.black, title=f'Your game with {await util2.get_name(game.white)}', description='It is your turn')\r\n await util2.send_notif(game.black, embed=embed, file=file)\r\n else:\r\n game.black_last_moved = time.time()\r\n game.black_warned = False\r\n data.data_manager.change_game(person, game)\r\n\r\n file, embed = util2.make_embed(game.black, title=f'Your game with {await util2.get_name(game.white)}', description='You have moved.')\r\n await ctx.message.reply(file=file, embed=embed)\r\n\r\n file, embed = util2.make_embed(game.white, title=f'Your game with {await util2.get_name(game.black)}', description='It is your turn')\r\n await util2.send_notif(game.white, embed=embed, file=file)\r\n\r\n @commands.group(invoke_without_command=True)\r\n @commands.cooldown(1, 3, commands.BucketType.user)\r\n async def challenge(self, ctx):\r\n '''\r\n {\r\n \"name\": \"challenge\",\r\n \"description\": \"Challenges somebody to a game of chess. Use `$challenge bot` to challenge a bot, or `$challenge user` to challenge another person.\",\r\n \"usage\": \"$challenge\",\r\n \"examples\": [\r\n \"$challenge bot cb1\",\r\n \"$challenge bot sf3\",\r\n \"$challenge user <@person>\"\r\n ],\r\n \"cooldown\": 3,\r\n \"subcommands\": [\r\n \"bot\",\r\n \"user\"\r\n ]\r\n }\r\n '''\r\n helpcog = self.client.get_cog('Help')\r\n docstr = self.client.get_command('challenge').help\r\n kwargs = json.loads(docstr)\r\n await ctx.send(embed=helpcog.make_help_embed(**kwargs))\r\n\r\n @challenge.command()\r\n async def bot(self, ctx, bot):\r\n '''\r\n {\r\n \"name\": \"challenge bot\",\r\n \"description\": \"Challenges the bot to a game of chess.\\\\nUse `$profiles to see which bots you can challenge.\\\\nYour color is assigned randomly.\",\r\n \"usage\": \"$challenge bot \",\r\n \"examples\": [\r\n \"$challenge bot cb1\",\r\n \"$challenge bot sf3\" \r\n ],\r\n \"cooldown\": 3\r\n }\r\n '''\r\n person = ctx.author.id\r\n\r\n game = data.data_manager.get_game(person)\r\n if game is not None:\r\n await ctx.send('You already have a game in progress')\r\n return\r\n\r\n if isinstance(bot, str):\r\n try:\r\n botid = Profile[bot].value\r\n except KeyError:\r\n await ctx.send(f'\"{bot}\" is not the valid tag of a bot. Use `$profiles` to see which bots you can challenge.')\r\n return\r\n\r\n game = data.Game()\r\n game.color = random.randint(0, 1)\r\n game.bot = botid\r\n\r\n data.data_manager.change_game(person, game)\r\n\r\n await ctx.send(f'Game started with {ProfileNames[bot].value}\\nYou play the {whiteblack[game.color]} pieces.')\r\n\r\n move = None\r\n if game.color == 0:\r\n thonk = self.client.get_emoji(constants.THONK_EMOJI_ID)\r\n await ctx.message.add_reaction(thonk)\r\n util.thonking.append(person)\r\n\r\n move, game = await run_engine(person)\r\n await log(person, self.client, ctx)\r\n if person in util.thonking:\r\n util.thonking.remove(person)\r\n data.data_manager.change_game(person, game)\r\n\r\n await output_move(ctx, person, move)\r\n game.last_moved = time.time()\r\n game.warned = False\r\n data.data_manager.change_game(person, game)\r\n\r\n @challenge.command(aliases=['person'])\r\n async def user(self, ctx, person: Union[discord.Member, discord.User]):\r\n '''\r\n {\r\n \"name\": \"challenge user\",\r\n \"description\": \"Challenges another user to a game of chess.\\\\nReact with a check mark to accept a challenge, and react with an X mark to decline\\\\nThe challenge will expire in 10 minutes.\",\r\n \"usage\": \"$challenge user \",\r\n \"examples\": [\r\n \"$challenge user <@person>\" \r\n ],\r\n \"cooldown\": 3,\r\n \"aliases\": [\r\n \"person\"\r\n ]\r\n }\r\n '''\r\n\r\n if data.data_manager.get_game(ctx.author.id) is not None:\r\n await ctx.send('You already have a game in progress.')\r\n return\r\n if data.data_manager.get_game(person.id) is not None:\r\n await ctx.send(f'{person} already has a game in progress.')\r\n return\r\n if ctx.author.id == person.id:\r\n await ctx.send(f'You cannot challenge yourself.')\r\n return\r\n\r\n util2 = self.client.get_cog('Util')\r\n\r\n challenge_msg = await ctx.send((f'{person.mention}, {ctx.author} has challenged you to a game of chess.\\n'\r\n 'React with :white_check_mark: to accept.\\n'\r\n 'React with :x: to decline or withdraw your challenge.'))\r\n await challenge_msg.add_reaction('✅')\r\n await challenge_msg.add_reaction('❌')\r\n\r\n def check(reaction, user):\r\n return ((user.id == person.id and str(reaction.emoji) == '✅') or\r\n ((user.id == person.id or user.id == ctx.author.id) and str(reaction.emoji) == '❌'))\r\n\r\n try:\r\n reaction, user = await self.client.wait_for('reaction_add', timeout=600.0, check=check)\r\n except asyncio.TimeoutError:\r\n await challenge_msg.reply('Challenge timed out!')\r\n else:\r\n if str(reaction.emoji) == '❌':\r\n await challenge_msg.reply('Challenge declined / withdrawn')\r\n return\r\n \r\n if data.data_manager.get_game(ctx.author.id) is not None or data.data_manager.get_game(person.id) is not None:\r\n await challenge_msg.reply('Challenge failed. One of the people already has a game in progress.')\r\n \r\n game = data.Game2()\r\n if random.randint(0, 1) == 0:\r\n game.white = ctx.author.id\r\n game.black = person.id\r\n else:\r\n game.white = person.id\r\n game.black = ctx.author.id\r\n data.data_manager.change_game(None, game)\r\n path = get_image2(ctx.author.id)\r\n file = discord.File(path, filename='board.png')\r\n embed = discord.Embed(\r\n title='Game started!', description=f'White: {await util2.get_name(game.white)}\\nBlack: {await util2.get_name(game.black)}')\r\n embed.set_image(url='attachment://board.png')\r\n await challenge_msg.reply(f'<@{game.white}> <@{game.black}>', file=file, embed=embed)\r\n\r\n @commands.command()\r\n @commands.cooldown(1, 3, commands.BucketType.user)\r\n async def resign(self, ctx):\r\n '''\r\n {\r\n \"name\": \"resign\",\r\n \"description\": \"Resigns your current game.\",\r\n \"usage\": \"$resign\",\r\n \"examples\": [\r\n \"$resign\"\r\n ],\r\n \"cooldown\": 3\r\n }\r\n '''\r\n\r\n game = data.data_manager.get_game(ctx.author.id)\r\n\r\n if game is None:\r\n await ctx.send('You do not have a game in progress')\r\n return\r\n\r\n if isinstance(game, data.Game):\r\n data.data_manager.delete_game(ctx.author.id, False)\r\n if ctx.author.id in util.thonking:\r\n util.thonking.remove(ctx.author.id)\r\n\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 0, game.bot)\r\n\r\n await ctx.send(f'Game resigned. Your new rating is {round(new_rating)} ({round(old_rating)} + {round(new_rating - old_rating, 2)})')\r\n elif isinstance(game, data.Game2):\r\n util2 = self.client.get_cog('Util')\r\n white_delta, black_delta = util.update_rating2(game.white, game.black,\r\n 0 if ctx.author.id == game.black else 1)\r\n if ctx.author.id == game.white:\r\n await ctx.send(f'Game resigned. Your new rating is {round(data.data_manager.get_rating(ctx.author.id), 3)} ({round(white_delta, 3)})')\r\n file, embed = util2.make_embed(\r\n game.black, title='Your game has ended', description=f'Your apponent has resigned. Your new rating is {round(data.data_manager.get_rating(game.black), 3)} ({round(black_delta, 3)})')\r\n await util2.send_notif(game.black, file=file, embed=embed)\r\n else:\r\n await ctx.send(f'Game resigned. Your new rating is {round(data.data_manager.get_rating(ctx.author.id), 3)} ({round(black_delta, 3)})')\r\n file, embed = util2.make_embed(\r\n game.white, title='Your game has ended', description=f'Your apponent has resigned. Your new rating is {round(data.data_manager.get_rating(game.white), 3)} ({round(white_delta, 3)})')\r\n await util2.send_notif(game.white, file=file, embed=embed)\r\n data.data_manager.delete_game(\r\n ctx.author.id, chess.WHITE if ctx.author.id == game.black else chess.BLACK)\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(Engine(bot))\r\n","sub_path":"Chess_Bot/cogs/Engine.py","file_name":"Engine.py","file_ext":"py","file_size_in_byte":19754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"638034480","text":"# _*_ coding: utf_8 _*_\n\"\"\"\n@author: Eddie\n\nThis example problem is meant to be a demonstration of how ``pyshgp`` could be\nused to perform simple regression tasks. \n\nThe problem consists of using integer instructions and integer constants to fit\nthe following polynomial: \n\n.. literalinclude:: /../examples/integer_regression.py\n :pyobject: target_function\n\nThe training set for this problem consists of only 20 data points.\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport random\n\nimport pyshgp.gp.gp as gp\nimport pyshgp.push.interpreter as interp\nimport pyshgp.push.instructions.registered_instructions as ri\nimport pyshgp.push.instruction as instr\n\ndef target_function(x):\n return x**3 - (2*(x**2)) - x\n\ndef error_func(program):\n errors = []\n\n for x in range(20):\n # Create the push interpreter and run program\n interpreter = interp.PushInterpreter(inputs=[x])\n interpreter.run_push(program)\n # Get output\n top_int = interpreter.state.stacks[\"_integer\"].ref(0)\n\n if type(top_int) == int:\n # compare to target output\n target_int = target_function(x)\n # calculate error\n errors.append(abs(top_int - target_int))\n else:\n errors.append(1000)\n\n return errors\n\nproblem_params = {\n \"atom_generators\" : [ri.get_instruction('_integer_div'),\n ri.get_instruction('_integer_mult'),\n ri.get_instruction('_integer_add'),\n ri.get_instruction('_integer_sub'),\n lambda: random.randint(0, 10),\n instr.PyshInputInstruction(0)],\n \"epigenetic_markers\" : [],\n \"selection_method\" : \"epsilon_lexicase\",\n \"genetic_operator_probabilities\" : {\"alternation\" : 0.5,\n \"uniform_mutation\" : 0.5},\n \"alternation_rate\" : 0.1,\n \"uniform_mutation_rate\" : 0.1\n}\n\n\nif __name__ == \"__main__\":\n gp.evolution(error_func, problem_params)\n\n","sub_path":"examples/integer_regression.py","file_name":"integer_regression.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"344347096","text":"import pygame\npygame.init()\n\nDisplay_Width = 1200\nDisplay_Height = 675\nDisplay = pygame.display.set_mode((Display_Width,Display_Height))\n\nclass Platform(pygame.sprite.Sprite):\n def __init__(self,x,y,type=\"platform\"):\n pygame.sprite.Sprite.__init__(self)\n self.type = type\n if self.type == \"platform\":\n plat = pygame.image.load(\"images/platform.png\").convert_alpha()\n elif self.type == \"trampoline\":\n plat = pygame.image.load(\"images/trampoline.png\").convert_alpha()\n width, height = plat.get_rect().size\n plat = pygame.transform.scale(plat,(int(width*0.84),int(height*0.84)))\n width, height = plat.get_rect().size\n hitbox = pygame.transform.scale(plat,(int(width),int(height*0.5)))\n h_width, h_height = hitbox.get_rect().size\n self.rect = hitbox.get_rect()\n self.rect.move(0,height-h_height)\n self.rect.x = x\n self.rect.y = y\n self.image = plat\n","sub_path":"Classes/Platform.py","file_name":"Platform.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"297960232","text":"import requests\nimport json\n\ndef insert(username,note):\n data = {\"username\":username, \"note\":note}\n json_data = json.dumps(data)\n res = requests.post(\"http://127.0.0.1:8000/create/\", data=json_data)\n print(res.status_code)\n print(res.json())\n\ninsert(\"jitu\",\"hey there i am jitu...\")","sub_path":"provider/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"287869708","text":"#!/usr/bin/python3\n#-*- coding=utf-8 -*-\n\nimport urllib.request, os, sys\nimport time\n\nwget_temp_file = \"wget_{}.html\".format(time.time())\n\ndef getHttp(url, data = \"\"):\n \"\"\"get the url from web\"\"\"\n i = 0\n print(url)\n #while i < 2:\n # try:\n f = None\n if data:\n f = urllib.request.urlopen(url, data)\n else:\n f = urllib.request.urlopen(url)\n d = f.read()\n f.close()\n return d\n # except:\n # i += 1\n # print(\"网络错误 %d\" % i)\n #return \"\"\n\ndef addToHtml(filename, content):\n try:\n if (os.path.isfile(filename) == True):\n f = open(filename, \"w\")\n else:\n f = open(filename, \"a\")\n f.write(content)\n f.close()\n except:\n print(filename, \"write Error\")\n\ndef removeHtmlContent(a):\n r = [\n (\" \", \"\\n\"),\n (\" \", \" \"),\n ]\n for e in r:\n a = a.replace(e[0], e[1])\n\n f1 = \"<\"\n f2 = \">\"\n t1 = a.find(f1)\n while t1 != -1:\n t2 = a.find(f2, t1)\n a = a[:t1] + a[t2+len(f2):]\n t1 = a.find(f1)\n return a\n\ndef getIndex(url):\n ret = []\n f1 = ' \" + f)\n\n t1 = a.find(f1)\n while t1 != -1:\n t2 = a.find(f2, t1+len(f1))\n ret.append(a[t1+len(f1):t2])\n t1 = a.find(f1, t2)\n\n return ret\n\ndef getContent(url):\n d = \"/tmp/\"\n e = url.split(\"/\")[-1]\n f = d+e\n a = \"\"\n if os.path.exists(f):\n a = open(f).read()\n if len(a) == 0:\n a = getHttp(url)\n open(f, \"wb\").write(a)\n else:\n a = getHttp(url)\n open(f, \"wb\").write(a)\n\n try:\n a = a.decode(\"gbk\")\n except UnicodeDecodeError:\n # correct the ill chars\n import checkIllegalChar\n a = checkIllegalChar.correctChars(a, \"gbk\", \"utf-8\")\n open(f, \"w\").write(a)\n a = a.decode(\"gbk\").encode(\"utf-8\")\n\n f3 = ''\n f4 = ''\n t3 = a.find(f3)\n t4 = a.find(f4, t3+len(f3))\n f1 = 'div id=\"content\">'\n f2 = ''\n t1 = a.find(f1)\n t2 = a.find(f2, t1+len(f1))\n\n title = a[t3+len(f3):t4].replace(\"正文 \", \"\")\n title = title.split(\"_\")[0]\n content = a[t1+len(f1):t2]\n print(e, \"title : {}\".format(len(title)), \"content: {}\".format(len(content)))\n if t2-t1-len(f1) < 0:\n return \"\"\n\n return \"==> \" + title + \"\\n\"*3 + removeHtmlContent(content) + \"\\n\"*3\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 2:\n f = \"/tmp/novel_{}.txt\".format(time.time())\n s = \"\"\n\n base = sys.argv[1].strip()\n index = getIndex(base)\n\n i = 0\n for e in index:\n b = getContent(base+e)\n if b == \"\":\n break\n s = s + b\n #i += 1\n #if i == 10:\n # break\n addToHtml(f, s)\n print(\"save to {}\".format(f))\n else:\n print(\"python3 getNovelsiluke.py url\")\n\n","sub_path":"py/getNovelsiluke3.py","file_name":"getNovelsiluke3.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"160084996","text":"#!/usr/bin/env python\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nFetch values from the Ska engineering telemetry archive.\n\"\"\"\nimport collections\nimport contextlib\nimport fnmatch\nimport logging\nimport operator\nimport os\nimport pickle\nimport re\nimport sys\nimport time\nimport warnings\nfrom pathlib import Path\n\nimport numpy as np\nimport pyyaks.context\nfrom astropy.io import ascii\nfrom Chandra.Time import DateTime\nfrom ska_helpers.utils import lru_cache_timed\n\nfrom . import __version__ # noqa\nfrom . import cache, file_defs, remote_access\nfrom .derived.comps import ComputedMsid\nfrom .lazy import LazyDict\nfrom .remote_access import ENG_ARCHIVE\nfrom .units import Units\n\n# Module-level units, defaults to CXC units (e.g. Kelvins etc)\nUNITS = Units(system=\"cxc\")\n\n# Module-level control of whether MSID.fetch will cache the last 30 results\nCACHE = False\n\nIGNORE_COLNAMES = (\"TIME\", \"MJF\", \"MNF\", \"TLM_FMT\")\nDIR_PATH = os.path.dirname(os.path.abspath(__file__))\n\n# Dates near the start of 2000 that demarcates the split between the 1999 data\n# and post-2000 data. The 1999 data goes out to at least 2000:005:13:00:00,\n# while post-2000 data starts as late as 2000:001:11:58:59. Dates between LO\n# and HI get taken from either 1999 or post-2000. The times are 4 millisec before\n# a minor frame boundary to avoid collisions.\nDATE2000_LO = DateTime(\"2000:001:00:00:00.090\").date\nDATE2000_HI = DateTime(\"2000:003:00:00:00.234\").date\n\n# Launch date (earliest possible date for telemetry)\nLAUNCH_DATE = \"1999:204\"\n\n# Maximum number of MSIDs that should ever match an input MSID spec\n# (to prevent accidentally selecting a very large number of MSIDs)\nMAX_GLOB_MATCHES = 10\n\n# Special-case state codes that override those in the TDB\nSTATE_CODES = {\n # SIMDIAG\n \"3SDSWELF\": [(0, \"F\"), (1, \"T\")],\n \"3SDSYRS\": [(0, \"F\"), (1, \"T\")],\n \"3SDWMRS\": [(0, \"F\"), (1, \"T\")],\n # SIM_MRG\n \"3TSCMOVE\": [(0, \"F\"), (1, \"T\")],\n \"3FAMOVE\": [(0, \"F\"), (1, \"T\")],\n \"3SEAID\": [(0, \"SEA-A\"), (1, \"SEA-B\")],\n \"3SEARSET\": [(0, \"F\"), (1, \"T\")],\n \"3SEAROMF\": [(0, \"F\"), (1, \"T\")],\n \"3SEAINCM\": [(0, \"F\"), (1, \"T\")],\n \"3STAB2EN\": [(0, \"DISABLE\"), (1, \"ENABLE\")],\n \"3SMOTPEN\": [(0, \"ENABLE\"), (1, \"DISABLE\")],\n \"3SMOTSEL\": [(0, \"TSC\"), (1, \"FA\")],\n \"3SHTREN\": [(0, \"DISABLE\"), (1, \"ENABLE\")],\n \"3SEARAMF\": [(0, \"F\"), (1, \"T\")],\n}\n\n# Cached version (by content type) of first and last available times in archive\nCONTENT_TIME_RANGES = {}\n\n# Default source of data.\nDEFAULT_DATA_SOURCE = \"cxc\"\n\n\nclass _DataSource(object):\n \"\"\"\n Context manager and quasi-singleton configuration object for managing the\n data_source(s) used for fetching telemetry.\n \"\"\"\n\n _data_sources = (DEFAULT_DATA_SOURCE,)\n _allowed = (\"cxc\", \"maude\", \"test-drop-half\")\n\n def __init__(self, *data_sources):\n self._new_data_sources = data_sources\n\n def __enter__(self):\n self._orig_data_sources = self.__class__._data_sources\n self.set(*self._new_data_sources)\n\n def __exit__(self, type, value, traceback):\n self.__class__._data_sources = self._orig_data_sources\n\n @classmethod\n def set(cls, *data_sources):\n \"\"\"\n Set current data sources.\n\n :param *data_sources: one or more sources (str)\n \"\"\"\n if any(\n data_source.split()[0] not in cls._allowed for data_source in data_sources\n ):\n raise ValueError(\n \"data_sources {} not in allowed set {}\".format(\n data_sources, cls._allowed\n )\n )\n\n if len(data_sources) == 0:\n raise ValueError(\n \"must select at least one data source in {}\".format(cls._allowed)\n )\n\n cls._data_sources = data_sources\n\n @classmethod\n def sources(cls, include_test=True):\n \"\"\"\n Get tuple of current data sources names.\n\n :param include_test: include sources that start with 'test'\n :returns: tuple of data source names\n \"\"\"\n if include_test:\n sources = cls._data_sources\n else:\n sources = [x for x in cls._data_sources if not x.startswith(\"test\")]\n\n return tuple(source.split()[0] for source in sources)\n\n @classmethod\n def get_msids(cls, source):\n \"\"\"\n Get the set of MSID names corresponding to ``source`` (e.g. 'cxc' or 'maude')\n\n :param source: str\n :returns: set of MSIDs\n \"\"\"\n source = source.split()[0]\n\n if source == \"cxc\":\n out = list(content.keys())\n elif source == \"maude\":\n import maude\n\n out = list(maude.MSIDS.keys())\n else:\n raise ValueError('source must be \"cxc\" or \"msid\"')\n\n return set(out)\n\n @classmethod\n def options(cls):\n \"\"\"\n Get the data sources and corresponding options as a dict.\n\n Example::\n\n >>> data_source.set('cxc', 'maude allow_subset=False')\n >>> data_source.options()\n {'cxc': {}, 'maude': {'allow_subset': False}}\n\n :returns: dict of data source options\n \"\"\"\n import ast\n\n out = {}\n for source in cls._data_sources:\n vals = source.split()\n name, opts = vals[0], vals[1:]\n out[name] = {}\n for opt in opts:\n key, val = opt.split(\"=\")\n val = ast.literal_eval(val)\n out[name][key] = val\n\n return out\n\n\n# Public interface is a \"data_source\" module attribute\ndata_source = _DataSource\n\n\ndef local_or_remote_function(remote_print_output):\n \"\"\"\n Decorator maker so that a function gets run either locally or remotely\n depending on the state of remote_access.access_remotely. This decorator\n maker takes an optional remote_print_output argument that will be\n be printed (locally) if the function is executed remotely,\n\n For functions that are decorated using this wrapper:\n\n Every path that may be generated locally but used remotely should be\n split with _split_path(). Conversely the functions that use\n the resultant path should re-join them with os.path.join. In the\n remote case the join will happen using the remote rules.\n \"\"\"\n\n def the_decorator(func):\n def wrapper(*args, **kwargs):\n if remote_access.access_remotely:\n # If accessing a remote archive, establish the connection (if\n # necessary)\n if not remote_access.connection_is_established():\n try:\n if not remote_access.establish_connection():\n raise remote_access.RemoteConnectionError(\n \"Unable to establish connection for remote fetch.\"\n )\n except EOFError:\n # An EOF error can be raised if the python interpreter is being\n # called in such a way that input cannot be received from the\n # user (e.g. when the python interpreter is called from MATLAB)\n # If that is the case (and remote access is enabled), then\n # raise an import error\n raise ImportError(\n \"Unable to interactively get remote access info from user.\"\n )\n # Print the output, if specified\n if remote_access.show_print_output and remote_print_output is not None:\n print(remote_print_output)\n sys.stdout.flush()\n # Execute the function remotely and return the result\n return remote_access.execute_remotely(func, *args, **kwargs)\n else:\n return func(*args, **kwargs)\n\n return wrapper\n\n return the_decorator\n\n\ndef _split_path(path):\n \"\"\"\n Return a tuple of the components for ``path``. Strip off the drive if\n it exists AND access is remote. This works correctly for the local OS\n (linux / windows).\n \"\"\"\n path = Path(path)\n parts = path.parts\n if remote_access.access_remotely and path.drive:\n parts = (\"/\",) + parts[1:]\n return parts\n\n\ndef _get_start_stop_dates(times):\n if len(times) == 0:\n return {}\n else:\n return {\"start\": DateTime(times[0]).date, \"stop\": DateTime(times[-1]).date}\n\n\n# Context dictionary to provide context for msid_files\nft = pyyaks.context.ContextDict(\"ft\")\n\n# Global (eng_archive) definition of file names\nmsid_files = pyyaks.context.ContextDict(\"msid_files\", basedir=ENG_ARCHIVE)\nmsid_files.update(file_defs.msid_files)\n\n# Module-level values defining available content types and column (MSID) names.\n# Then convert from astropy Table to recarray for API stability.\n# Note that filetypes.as_array().view(np.recarray) does not quite work...\nfiletypes = ascii.read(os.path.join(DIR_PATH, \"filetypes.dat\"))\nfiletypes_arr = filetypes.as_array()\nfiletypes = np.recarray(len(filetypes_arr), dtype=filetypes_arr.dtype)\nfiletypes[()] = filetypes_arr\n\n# Get the list of filenames (an array is built to pass all the filenames at\n# once to the remote machine since passing them one at a time is rather slow)\nall_msid_names_files = dict()\nfor filetype in filetypes:\n ft[\"content\"] = filetype[\"content\"].lower()\n all_msid_names_files[str(ft[\"content\"])] = _split_path(msid_files[\"colnames\"].abs)\n\n\n# Function to load MSID names from the files (executed remotely, if necessary)\n@local_or_remote_function(\"Loading MSID names from Ska eng archive server...\")\ndef load_msid_names(all_msid_names_files):\n import pickle\n\n all_colnames = dict()\n for k, msid_names_file in all_msid_names_files.items():\n try:\n all_colnames[k] = pickle.load(open(os.path.join(*msid_names_file), \"rb\"))\n except IOError:\n pass\n return all_colnames\n\n\ndef load_content(all_colnames):\n out = {}\n # Save the names\n for content_type, msid_names in all_colnames.items():\n out.update(\n (name, content_type)\n for name in sorted(msid_names)\n if name not in IGNORE_COLNAMES\n )\n return out\n\n\n# Define MSID names as a dict of content_type: [MSID_names_for_content_type].\n# This is a LazyDict so nothing happens until a value is requested.\nall_colnames = LazyDict(load_msid_names, all_msid_names_files)\n\n# Define MSID content definition as dict of MSID_name: content_type\ncontent = LazyDict(load_content, all_colnames)\n\n\n# Cache of the most-recently used TIME array and associated bad values mask.\n# The key is (content_type, tstart, tstop).\ntimes_cache = dict(key=None)\n\n\n# Set up logging.\nclass NullHandler(logging.Handler):\n def emit(self, record):\n pass\n\n\nlogger = logging.getLogger(\"Ska.engarchive.fetch\")\nlogger.addHandler(NullHandler())\nlogger.propagate = False\n\n\ndef get_units():\n \"\"\"Get the unit system currently being used for conversions.\"\"\"\n return UNITS[\"system\"]\n\n\ndef set_units(unit_system):\n \"\"\"Set the unit system used for output telemetry values. The default\n is \"cxc\". Allowed values for ``unit_system`` are:\n\n ==== ==============================================================\n cxc FITS standard units used in CXC archive files (basically MKS)\n sci Same as \"cxc\" but with temperatures in degC instead of Kelvins\n eng OCC engineering units (TDB P009, e.g. degF, ft-lb-sec, PSI)\n ==== ==============================================================\n\n :param unit_system: system of units (cxc, sci, eng)\n \"\"\"\n UNITS.set_units(unit_system)\n\n\ndef read_bad_times(table):\n \"\"\"Include a list of bad times from ``table`` in the fetch module\n ``bad_times`` registry. This routine can be called multiple times with\n different tables and the bad times will be appended to the registry. The\n table can include any number of bad time interval specifications, one per\n line. A bad time interval line has three columns separated by whitespace,\n e.g.::\n\n aogbias1 2008:292:00:00:00 2008:297:00:00:00\n\n The MSID name is not case sensitive and the time values can be in any\n ``DateTime`` format. Blank lines and any line starting with the #\n character are ignored.\n \"\"\"\n bad_times = ascii.read(table, format=\"no_header\", names=[\"msid\", \"start\", \"stop\"])\n\n for msid, start, stop in bad_times:\n msid_bad_times.setdefault(msid.upper(), []).append((start, stop))\n\n\n# Set up bad times dict\nmsid_bad_times = dict()\nread_bad_times(os.path.join(DIR_PATH, \"msid_bad_times.dat\"))\n\n\ndef msid_glob(msid):\n \"\"\"Get the archive MSIDs matching ``msid``.\n\n The function returns a tuple of (msids, MSIDs) where ``msids`` is a list of\n MSIDs that is all lower case and (where possible) matches the input\n ``msid``. The output ``MSIDs`` is all upper case and corresponds to the\n exact MSID names stored in the archive HDF5 files.\n\n :param msid: input MSID glob\n :returns: tuple (msids, MSIDs)\n \"\"\"\n msids = {}\n MSIDS = {}\n\n # First check if `msid` matches a computed class. This does not allow\n # for globs, and here the output MSIDs is the single computed class.\n if ComputedMsid.get_matching_comp_cls(msid) is not None:\n return [msid], [msid.upper()]\n\n sources = data_source.sources(include_test=False)\n for source in sources:\n ms, MS = _msid_glob(msid, source)\n msids.update((m, None) for m in ms)\n MSIDS.update((m, None) for m in MS)\n\n if not msids:\n raise ValueError(\n \"MSID {!r} is not in {} data source(s)\".format(\n msid, \" or \".join(x.upper() for x in sources)\n )\n )\n\n return list(msids), list(MSIDS)\n\n\ndef _msid_glob(msid, source):\n \"\"\"Get the archive MSIDs matching ``msid``.\n\n The function returns a tuple of (msids, MSIDs) where ``msids`` is a list of\n MSIDs that is all lower case and (where possible) matches the input\n ``msid``. The output ``MSIDs`` is all upper case and corresponds to the\n exact MSID names stored in the archive HDF5 files.\n\n :param msid: input MSID glob\n :returns: tuple (msids, MSIDs)\n \"\"\"\n source_msids = data_source.get_msids(source)\n\n # MSID is the upper-case version of the MSID name that is actually used in\n # backend queries. ``msid`` is the user-supplied version.\n MSID = msid.upper()\n\n # CALC_ is a synonym for DP_ which works in both CXC and MAUDE archives, so\n # swap to DP_ if CALC_ is found. These are calculated pseudo-MSIDs.\n if MSID.startswith(\"CALC_\"):\n MSID = \"DP_\" + MSID[5:]\n\n # matches_msid is a list of MSIDs that match the input MSID. Providing the\n # initial DP_ is optional so we try both if the MSID doesn't already start\n # with DP_ (i.e. PITCH or DP_PITCH).\n matches_msid = (MSID,)\n if not MSID.startswith(\"DP_\"):\n matches_msid += (\"DP_\" + MSID,)\n\n # If one of matches_msid is in the source then return the upper\n # case version and whatever the user supplied (could be any case).\n for match in matches_msid:\n if match in source_msids:\n return [msid], [match]\n\n # Next try as a file glob. If there is a match then return a\n # list of matches, all lower case and all upper case. Since the\n # input was a glob the returned msids are just lower case versions\n # of the matched upper case MSIDs.\n for match in matches_msid:\n matches = fnmatch.filter(source_msids, match)\n if matches:\n if len(matches) > MAX_GLOB_MATCHES:\n raise ValueError(\n \"MSID spec {} matches more than {} MSIDs. \"\n \"Refine the spec or increase fetch.MAX_GLOB_MATCHES\".format(\n msid, MAX_GLOB_MATCHES\n )\n )\n return [x.lower() for x in matches], matches\n\n # msid not found for this data source\n return [], []\n\n\ndef _get_table_intervals_as_list(table, check_overlaps=True):\n \"\"\"\n Determine if the input ``table`` looks like a table of intervals. This can either be\n a structured array / Table with datestart / datestop or tstart / tstop columns,\n OR a list of lists.\n\n If so, return a list of corresponding start/stop tuples, otherwise return None.\n\n If ``check_overlaps`` is True then a check is made to assure that the supplied\n intervals do not overlap. This is needed when reading multiple intervals with\n a single call to fetch, but not for bad times filtering.\n \"\"\"\n intervals = None\n\n if isinstance(table, (list, tuple)):\n try:\n intervals = [\n (DateTime(row[0]).secs, DateTime(row[1]).secs) for row in table\n ]\n except Exception:\n pass\n else:\n for prefix in (\"date\", \"t\"):\n start = prefix + \"start\"\n stop = prefix + \"stop\"\n try:\n intervals = [\n (DateTime(row[start]).secs, DateTime(row[stop]).secs)\n for row in table\n ]\n except Exception:\n pass\n else:\n break\n\n # Got an intervals list, now sort\n if check_overlaps and intervals is not None:\n\n intervals = sorted(intervals, key=lambda x: x[0])\n\n # Check for overlaps\n if any(i0[1] > i1[0] for i0, i1 in zip(intervals[:-1], intervals[1:])):\n raise ValueError(\"Input intervals overlap\")\n\n return intervals\n\n\nclass MSID(object):\n \"\"\"Fetch data from the engineering telemetry archive into an MSID object.\n\n The input ``msid`` is case-insensitive and can include linux file \"glob\"\n patterns, for instance ``orb*1*_x`` (ORBITEPHEM1_X) or ``*pcadmd``\n (AOPCADMD). For derived parameters the initial ``DP_`` is optional, for\n instance ``dpa_pow*`` (DP_DPA_POWER).\n\n :param msid: name of MSID (case-insensitive)\n :param start: start date of telemetry (Chandra.Time compatible)\n :param stop: stop date of telemetry (current time if not supplied)\n :param filter_bad: automatically filter out bad values\n :param stat: return 5-minute or daily statistics ('5min' or 'daily')\n\n :returns: MSID instance\n \"\"\"\n\n units = UNITS\n fetch = sys.modules[__name__]\n\n def __init__(self, msid, start=LAUNCH_DATE, stop=None, filter_bad=False, stat=None):\n msids, MSIDs = msid_glob(msid)\n if len(MSIDs) > 1:\n raise ValueError(\"Multiple matches for {} in Eng Archive\".format(msid))\n else:\n self.msid = msids[0]\n self.MSID = MSIDs[0]\n\n # Capture the current module units\n self.units = Units(self.units[\"system\"])\n self.unit = self.units.get_msid_unit(self.MSID)\n self.stat = stat\n if stat:\n self.dt = {\"5min\": 328, \"daily\": 86400}[stat]\n\n # If ``start`` is actually a table of intervals then fetch\n # each interval separately and concatenate the results\n intervals = _get_table_intervals_as_list(start, check_overlaps=True)\n if intervals is not None:\n start, stop = intervals[0][0], intervals[-1][1]\n\n self.tstart = DateTime(start).secs\n self.tstop = (\n DateTime(stop).secs if stop else DateTime(time.time(), format=\"unix\").secs\n )\n self.datestart = DateTime(self.tstart).date\n self.datestop = DateTime(self.tstop).date\n self.data_source = {}\n self.content = content.get(self.MSID)\n\n if self.datestart < DATE2000_LO and self.datestop > DATE2000_HI:\n intervals = [(self.datestart, DATE2000_HI), (DATE2000_HI, self.datestop)]\n\n # Get the times, values, bad values mask from the HDF5 files archive\n if intervals is None:\n self._get_data()\n else:\n self._get_data_over_intervals(intervals)\n\n # If requested filter out bad values and set self.bad = None\n if filter_bad:\n self.filter_bad()\n\n if \"CHETA_FETCH_DATA_GAP\" in os.environ:\n create_msid_data_gap(self, os.environ[\"CHETA_FETCH_DATA_GAP\"])\n\n def __len__(self):\n return len(self.vals)\n\n @property\n def dtype(self):\n return self.vals.dtype\n\n def __repr__(self):\n attrs = [self.__class__.__name__, self.MSID]\n for name, val in (\n (\"start\", self.datestart),\n (\"stop\", self.datestop),\n (\"len\", len(self)),\n (\"dtype\", self.dtype.name),\n (\"unit\", self.unit),\n (\"stat\", self.stat),\n ):\n if val is not None:\n attrs.append(\"{}={}\".format(name, val))\n\n return \"<\" + \" \".join(attrs) + \">\"\n\n def _get_data_over_intervals(self, intervals):\n \"\"\"\n Fetch intervals separately and concatenate the results.\n \"\"\"\n msids = []\n for start, stop in intervals:\n msids.append(\n self.fetch.MSID(\n self.msid, start, stop, filter_bad=False, stat=self.stat\n )\n )\n\n # No bad values column for stat='5min' or 'daily', but still need this attribute.\n if self.stat:\n self.bads = None\n\n self.colnames = msids[0].colnames\n for attr in self.colnames:\n vals = np.concatenate([getattr(msid, attr) for msid in msids])\n setattr(self, attr, vals)\n\n def _get_data(self):\n \"\"\"Get data from the Eng archive\"\"\"\n logger.info(\n \"Getting data for %s between %s to %s\",\n self.msid,\n self.datestart,\n self.datestop,\n )\n\n comp_cls = ComputedMsid.get_matching_comp_cls(self.msid)\n if comp_cls:\n self._get_comp_data(comp_cls)\n return\n\n # Avoid stomping on caller's filetype 'ft' values with _cache_ft()\n with _cache_ft():\n ft[\"content\"] = self.content\n ft[\"msid\"] = self.MSID\n\n with _set_msid_files_basedir(self.datestart):\n if self.stat:\n if \"maude\" in data_source.sources():\n raise ValueError(\n \"MAUDE data source does not support telemetry statistics\"\n )\n ft[\"interval\"] = self.stat\n self._get_stat_data()\n else:\n self.colnames = [\"vals\", \"times\", \"bads\"]\n args = (\n self.content,\n self.tstart,\n self.tstop,\n self.MSID,\n self.units[\"system\"],\n )\n\n if (\n \"cxc\" in data_source.sources()\n and self.MSID in data_source.get_msids(\"cxc\")\n ):\n # CACHE is normally True only when doing ingest processing. Note\n # also that to support caching the get_msid_data_from_cxc_cached\n # method must be static.\n get_msid_data = (\n self._get_msid_data_from_cxc_cached\n if CACHE\n else self._get_msid_data_from_cxc\n )\n self.vals, self.times, self.bads = get_msid_data(*args)\n self.data_source[\"cxc\"] = _get_start_stop_dates(self.times)\n\n if \"test-drop-half\" in data_source.sources() and hasattr(\n self, \"vals\"\n ):\n # For testing purposes drop half the data off the end. This assumes another\n # data_source like 'cxc' has been selected.\n idx = len(self.vals) // 2\n self.vals = self.vals[:idx]\n self.times = self.times[:idx]\n self.bads = self.bads[:idx]\n # Following assumes only one prior data source but ok for controlled testing\n for source in self.data_source:\n self.data_source[source] = _get_start_stop_dates(self.times)\n\n if (\n \"maude\" in data_source.sources()\n and self.MSID in data_source.get_msids(\"maude\")\n ):\n # Update self.vals, times, bads in place. This might concatenate MAUDE\n # telemetry to existing CXC values.\n self._get_msid_data_from_maude(*args)\n\n def _get_comp_data(self, comp_cls):\n logger.info(f\"Getting computed values for {self.msid}\")\n\n # Do computation. This returns a dict of MSID attribute values.\n attrs = comp_cls(self.units[\"system\"])(\n self.tstart, self.tstop, self.msid, self.stat\n )\n\n # Allow upstream class to be a bit sloppy on times and include samples\n # outside the time range. This can happen with classes that inherit\n # from DerivedParameter.\n ok = (attrs[\"times\"] >= self.tstart) & (attrs[\"times\"] <= self.tstop)\n all_ok = np.all(ok)\n\n # List of \"colnames\", which is the ndarray attributes. There can be\n # non-ndarray attributes that get returned, including typically 'unit'.\n self.colnames = [\n attr\n for attr, val in attrs.items()\n if (isinstance(val, np.ndarray) and len(val) == len(attrs[\"times\"]))\n ]\n\n # Apply attributes to self\n for attr, val in attrs.items():\n if (\n not all_ok\n and isinstance(val, np.ndarray)\n and len(val) == len(attrs[\"times\"])\n ):\n val = val[ok]\n setattr(self, attr, val)\n\n def _get_stat_data(self):\n \"\"\"Do the actual work of getting stats values for an MSID from HDF5\n files\"\"\"\n filename = msid_files[\"stats\"].abs\n logger.info(\"Opening %s\", filename)\n\n @local_or_remote_function(\n \"Getting stat data for \" + self.MSID + \" from Ska eng archive server...\"\n )\n def get_stat_data_from_server(filename, dt, tstart, tstop):\n import tables\n\n open_file = getattr(tables, \"open_file\", None) or tables.openFile\n h5 = open_file(os.path.join(*filename))\n table = h5.root.data\n times = (table.col(\"index\") + 0.5) * dt\n row0, row1 = np.searchsorted(times, [tstart, tstop])\n table_rows = table[row0:row1] # returns np.ndarray (structured array)\n h5.close()\n return (times[row0:row1], table_rows, row0, row1)\n\n times, table_rows, row0, row1 = get_stat_data_from_server(\n _split_path(filename), self.dt, self.tstart, self.tstop\n )\n logger.info(\"Closed %s\", filename)\n\n self.bads = None\n self.times = times\n self.colnames = [\"times\"]\n for colname in table_rows.dtype.names:\n # Don't like the way columns were named in the stats tables.\n # Fix that here.\n colname_out = _plural(colname) if colname != \"n\" else \"samples\"\n\n if colname_out in (\n \"vals\",\n \"mins\",\n \"maxes\",\n \"means\",\n \"p01s\",\n \"p05s\",\n \"p16s\",\n \"p50s\",\n \"p84s\",\n \"p95s\",\n \"p99s\",\n ):\n vals = self.units.convert(self.MSID, table_rows[colname])\n elif colname_out == \"stds\":\n vals = self.units.convert(\n self.MSID, table_rows[colname], delta_val=True\n )\n else:\n vals = table_rows[colname]\n\n setattr(self, colname_out, vals)\n self.colnames.append(colname_out)\n\n # Redefine the 'vals' attribute to be 'means' if it exists. This is a\n # more consistent use of the 'vals' attribute and there is little use\n # for the original sampled version.\n if hasattr(self, \"means\"):\n # Create new attribute midvals and add as a column (fixes kadi#17)\n self.colnames.append(\"midvals\")\n self.midvals = self.vals\n self.vals = self.means\n\n # Convert vals to unicode for Python 3+. If this MSID is a\n # state-valued MSID (with string value) then `vals` is the only possible\n # string attribute. None of the others like mins/maxes etc will exist.\n for colname in self.colnames:\n vals = getattr(self, colname)\n if vals.dtype.kind == \"S\":\n setattr(self, colname, vals.astype(\"U\"))\n\n @staticmethod\n @cache.lru_cache(30)\n def _get_msid_data_from_cxc_cached(content, tstart, tstop, msid, unit_system):\n \"\"\"Do the actual work of getting time and values for an MSID from HDF5\n files and cache recent results. Caching is very beneficial for derived\n parameter updates but not desirable for normal fetch usage.\"\"\"\n return MSID._get_msid_data_from_cxc(content, tstart, tstop, msid, unit_system)\n\n @staticmethod\n def _get_msid_data_from_cxc(content, tstart, tstop, msid, unit_system):\n \"\"\"Do the actual work of getting time and values for an MSID from HDF5\n files\"\"\"\n\n # Get a row slice into HDF5 file for this content type that picks out\n # the required time range plus a little padding on each end.\n h5_slice = get_interval(content, tstart, tstop)\n\n # Cache the last set of TIME values so repeated queries from within a\n # content type use the already-available times. Use the content, start\n # row and stop row as key. This guarantees that the times array matches\n # the subsequent values.\n cache_key = (content, h5_slice.start, h5_slice.stop)\n\n # Read the TIME values either from cache or from disk.\n if times_cache[\"key\"] == cache_key:\n logger.info(\"Using times_cache for %s %s to %s\", content, tstart, tstop)\n times = times_cache[\"val\"] # Already filtered on times_ok\n times_ok = times_cache[\"ok\"] # For filtering MSID.val and MSID.bad\n times_all_ok = times_cache[\"all_ok\"]\n else:\n ft[\"msid\"] = \"time\"\n filename = msid_files[\"msid\"].abs\n logger.info(\"Reading %s\", filename)\n\n @local_or_remote_function(\n \"Getting time data from Ska eng archive server...\"\n )\n def get_time_data_from_server(h5_slice, filename):\n import tables\n\n open_file = getattr(tables, \"open_file\", None) or tables.openFile\n h5 = open_file(os.path.join(*filename))\n times_ok = ~h5.root.quality[h5_slice]\n times = h5.root.data[h5_slice]\n h5.close()\n return (times_ok, times)\n\n times_ok, times = get_time_data_from_server(h5_slice, _split_path(filename))\n\n # Filter bad times. Last instance of bad times in archive is 2004\n # so don't do this unless needed. Creating a new 'times' array is\n # much more expensive than checking for np.all(times_ok).\n times_all_ok = np.all(times_ok)\n if not times_all_ok:\n times = times[times_ok]\n\n times_cache.update(\n dict(key=cache_key, val=times, ok=times_ok, all_ok=times_all_ok)\n )\n\n # Extract the actual MSID values and bad values mask\n ft[\"msid\"] = msid\n filename = msid_files[\"msid\"].abs\n logger.info(\"Reading %s\", filename)\n\n @local_or_remote_function(\n \"Getting msid data for \" + msid + \" from Ska eng archive server...\"\n )\n def get_msid_data_from_server(h5_slice, filename):\n import tables\n\n open_file = getattr(tables, \"open_file\", None) or tables.openFile\n h5 = open_file(os.path.join(*filename))\n vals = h5.root.data[h5_slice]\n bads = h5.root.quality[h5_slice]\n h5.close()\n return (vals, bads)\n\n vals, bads = get_msid_data_from_server(h5_slice, _split_path(filename))\n\n # Remote access will return arrays that don't own their data, see #150.\n # For an explanation see:\n # https://ipyparallel.readthedocs.io/en/latest/details.html#non-copying-sends-and-numpy-arrays\n try:\n bads.flags.writeable = True\n vals.flags.writeable = True\n except ValueError:\n bads = bads.copy()\n vals = vals.copy()\n\n # Filter bad times rows if needed\n if not times_all_ok:\n logger.info(\"Filtering bad times values for %s\", msid)\n bads = bads[times_ok]\n vals = vals[times_ok]\n\n # Slice down to exact requested time range\n row0, row1 = np.searchsorted(times, [tstart, tstop])\n logger.info(\"Slicing %s arrays [%d:%d]\", msid, row0, row1)\n vals = Units(unit_system).convert(msid.upper(), vals[row0:row1])\n times = times[row0:row1]\n bads = bads[row0:row1]\n\n # Possibly expand the bads list for a set of about 30 MSIDs which\n # have incorrect values in CXCDS telemetry\n bads = _fix_ctu_dwell_mode_bads(msid, bads)\n\n # Change bytestring to (unicode) string\n if vals.dtype.kind == \"S\":\n vals = vals.astype(\"U\")\n\n return (vals, times, bads)\n\n def _get_msid_data_from_maude(self, content, tstart, tstop, msid, unit_system):\n \"\"\"\n Get time and values for an MSID from MAUDE.\n Returned values are (for now) all assumed to be good.\n \"\"\"\n import maude\n\n # Telemetry values from another data_source may already be available. If\n # so then only query MAUDE from after the last available point.\n telem_already = hasattr(self, \"times\") and len(self.times) > 2\n\n if telem_already:\n tstart = self.times[-1] + 0.001 # Don't fetch the last point again\n dt = self.times[-1] - self.times[-2]\n if tstop - tstart < dt * 2:\n # Already got enough data from the original query, no need to hit MAUDE\n return\n\n # Actually query MAUDE\n options = data_source.options()[\"maude\"]\n try:\n out = maude.get_msids(msids=msid, start=tstart, stop=tstop, **options)\n except Exception as e:\n raise Exception(\"MAUDE query failed: {}\".format(e))\n\n # Only one MSID is queried from MAUDE but maude.get_msids() already returns\n # a list of results, so select the first element.\n out = out[\"data\"][0]\n\n vals = Units(unit_system).convert(\n msid.upper(), out[\"values\"], from_system=\"eng\"\n )\n times = out[\"times\"]\n bads = np.zeros(len(vals), dtype=bool) # No 'bad' values from MAUDE\n\n self.data_source[\"maude\"] = _get_start_stop_dates(times)\n self.data_source[\"maude\"][\"flags\"] = out[\"flags\"]\n\n if telem_already:\n vals = np.concatenate([self.vals, vals])\n times = np.concatenate([self.times, times])\n bads = np.concatenate([self.bads, bads])\n\n self.vals = vals\n self.times = times\n self.bads = bads\n\n @property\n def state_codes(self):\n \"\"\"List of state codes tuples (raw_count, state_code) for state-valued\n MSIDs\n \"\"\"\n if self.vals.dtype.kind not in (\"S\", \"U\"):\n self._state_codes = None\n\n if self.MSID in STATE_CODES:\n self._state_codes = STATE_CODES[self.MSID]\n\n if not hasattr(self, \"_state_codes\"):\n import Ska.tdb\n\n try:\n states = Ska.tdb.msids[self.MSID].Tsc\n except Exception:\n self._state_codes = None\n else:\n if states is None or len(set(states[\"CALIBRATION_SET_NUM\"])) != 1:\n warnings.warn(\n \"MSID {} has string vals but no state codes \"\n \"or multiple calibration sets\".format(self.msid)\n )\n self._state_codes = None\n else:\n states = np.sort(states.data, order=\"LOW_RAW_COUNT\")\n self._state_codes = [\n (state[\"LOW_RAW_COUNT\"], state[\"STATE_CODE\"])\n for state in states\n ]\n return self._state_codes\n\n @property\n def raw_vals(self):\n \"\"\"Raw counts corresponding to the string state-code values that are\n stored in ``self.vals``\n \"\"\"\n # If this is not a string-type value then there are no raw values\n if self.vals.dtype.kind not in (\"S\", \"U\") or self.state_codes is None:\n self._raw_vals = None\n\n if not hasattr(self, \"_raw_vals\"):\n self._raw_vals = np.zeros(len(self.vals), dtype=\"int8\") - 1\n # CXC state code telem all has same length with trailing spaces\n # so find max length for formatting below.\n max_len = max(len(x[1]) for x in self.state_codes)\n fmtstr = \"{:\" + str(max_len) + \"s}\"\n for raw_val, state_code in self.state_codes:\n ok = self.vals == fmtstr.format(state_code)\n self._raw_vals[ok] = raw_val\n\n return self._raw_vals\n\n @property\n def tdb(self):\n \"\"\"Access the Telemetry database entries for this MSID\"\"\"\n import Ska.tdb\n\n return Ska.tdb.msids[self.MSID]\n\n def interpolate(self, dt=None, start=None, stop=None, times=None):\n \"\"\"Perform nearest-neighbor interpolation of the MSID to the specified\n time sequence.\n\n The time sequence steps uniformly by ``dt`` seconds starting at the\n ``start`` time and ending at the ``stop`` time. If not provided the\n times default to the first and last times for the MSID.\n\n The MSID ``times`` attribute is set to the common time sequence. In\n addition a new attribute ``times0`` is defined that stores the nearest\n neighbor interpolated time, providing the *original* timestamps of each\n new interpolated value for that MSID.\n\n If ``times`` is provided then this gets used instead of the default linear\n progression from ``start`` and ``dt``.\n\n :param dt: time step (sec, default=328.0)\n :param start: start of interpolation period (DateTime format)\n :param stop: end of interpolation period (DateTime format)\n :param times: array of times for interpolation (default=None)\n \"\"\"\n import Ska.Numpy\n\n if times is not None:\n if any(kwarg is not None for kwarg in (dt, start, stop)):\n raise ValueError(\n 'If \"times\" keyword is set then \"dt\", \"start\", '\n 'and \"stop\" cannot be set'\n )\n # Use user-supplied times that are within the range of telemetry.\n ok = (times >= self.times[0]) & (times <= self.times[-1])\n times = times[ok]\n else:\n dt = 328.0 if dt is None else dt\n tstart = DateTime(start).secs if start else self.times[0]\n tstop = DateTime(stop).secs if stop else self.times[-1]\n\n # Legacy method for backward compatibility. Note that the np.arange()\n # call accrues floating point error.\n tstart = max(tstart, self.times[0])\n tstop = min(tstop, self.times[-1])\n times = np.arange(tstart, tstop, dt)\n\n logger.info(\"Interpolating index for %s\", self.msid)\n indexes = Ska.Numpy.interpolate(\n np.arange(len(self.times)), self.times, times, method=\"nearest\", sorted=True\n )\n logger.info(\"Slicing on indexes\")\n for colname in self.colnames:\n colvals = getattr(self, colname)\n if colvals is not None:\n setattr(self, colname, colvals[indexes])\n\n # Make a new attribute times0 that stores the nearest neighbor\n # interpolated times. Then set the MSID times to be the common\n # interpolation times.\n self.times0 = self.times\n self.times = times\n\n def copy(self):\n from copy import deepcopy\n\n return deepcopy(self)\n\n def filter_bad(self, bads=None, copy=False):\n \"\"\"Filter out any bad values.\n\n After applying this method the \"bads\" column will be set to None to\n indicate that there are no bad values.\n\n :param bads: Bad values mask. If not supplied then self.bads is used.\n :param copy: return a copy of MSID object with bad values filtered\n \"\"\"\n obj = self.copy() if copy else self\n\n # If bad mask is provided then override any existing bad mask for MSID\n if bads is not None:\n obj.bads = bads\n\n # Nothing to do if bads is None (i.e. bad values already filtered)\n if obj.bads is None:\n return\n\n if np.any(obj.bads):\n logger.info(\"Filtering bad values for %s\", obj.msid)\n ok = ~obj.bads\n colnames = (x for x in obj.colnames if x != \"bads\")\n for colname in colnames:\n setattr(obj, colname, getattr(obj, colname)[ok])\n\n obj.bads = None\n\n if copy:\n return obj\n\n def filter_bad_times(self, start=None, stop=None, table=None, copy=False):\n \"\"\"Filter out intervals of bad data in the MSID object.\n\n There are three usage options:\n\n - Supply no arguments. This will use the global list of bad times read\n in with fetch.read_bad_times().\n - Supply both ``start`` and ``stop`` values where each is a single\n value in a valid DateTime format.\n - Supply an ``table`` parameter in the form of a 2-column table of\n start and stop dates (space-delimited) or the name of a file with\n data in the same format.\n\n The ``table`` parameter must be supplied as a table or the name of a\n table file, for example::\n\n bad_times = ['2008:292:00:00:00 2008:297:00:00:00',\n '2008:305:00:12:00 2008:305:00:12:03',\n '2010:101:00:01:12 2010:101:00:01:25']\n msid.filter_bad_times(table=bad_times)\n msid.filter_bad_times(table='msid_bad_times.dat')\n\n :param start: Start of time interval to exclude (any DateTime format)\n :param stop: End of time interval to exclude (any DateTime format)\n :param table: Two-column table (start, stop) of bad time intervals\n :param copy: return a copy of MSID object with bad times filtered\n \"\"\"\n if table is not None:\n bad_times = ascii.read(table, format=\"no_header\", names=[\"start\", \"stop\"])\n elif start is None and stop is None:\n bad_times = []\n for msid_glob, times in msid_bad_times.items():\n if fnmatch.fnmatch(self.MSID, msid_glob):\n bad_times.extend(times)\n elif start is None or stop is None:\n raise ValueError(\n \"filter_times requires either 2 args (start, stop) or no args\"\n )\n else:\n bad_times = [(start, stop)]\n\n obj = self.copy() if copy else self\n obj._filter_times(bad_times, exclude=True)\n if copy:\n return obj\n\n def remove_intervals(self, intervals, copy=False):\n \"\"\"\n Remove telemetry points that occur within the specified ``intervals``\n\n This method is the converse of select_intervals().\n\n The ``intervals`` argument can be either a list of (start, stop) tuples\n or an EventQuery object from kadi.\n\n If ``copy`` is set to True then a copy of the MSID object is made prior\n to removing intervals, and that copy is returned. The default is to\n remove intervals in place.\n\n This example shows fetching the pitch component of the spacecraft rate.\n After examining the rates, the samples during maneuvers are then removed\n and the standard deviation is recomputed. This filters out the large\n rates during maneuvers::\n\n >>> aorate2 = fetch.Msid('aorate2', '2011:001', '2011:002')\n >>> aorate2.vals.mean() * 3600 * 180 / np.pi # rate in arcsec/sec\n 3.9969393528801782\n >>> figure(1)\n >>> aorate2.plot(',')\n\n >>> from kadi import events\n >>> aorate2.remove_intervals(events.manvrs)\n >>> aorate2.vals.mean() * 3600 * 180 / np.pi # rate in arcsec/sec\n -0.0003688639491030978\n >>> figure(2)\n >>> aorate2.plot(',')\n\n :param intervals: EventQuery or iterable (N x 2) with start, stop dates/times\n :param copy: return a copy of MSID object with intervals removed\n \"\"\"\n obj = self.copy() if copy else self\n obj._filter_times(intervals, exclude=True)\n if copy:\n return obj\n\n def select_intervals(self, intervals, copy=False):\n \"\"\"\n Select telemetry points that occur within the specified ``intervals``\n\n This method is the converse of remove_intervals().\n\n The ``intervals`` argument can be either a list of (start, stop) tuples\n or an EventQuery object from kadi.\n\n If ``copy`` is set to True then a copy of the MSID object is made prior\n to selecting intervals, and that copy is returned. The default is to\n selecte intervals in place.\n\n This example shows fetching the pitch component of the spacecraft rate.\n After examining the rates, the samples during maneuvers are then selected\n and the mean is recomputed. This highlights the large rates during\n maneuvers::\n\n >>> aorate2 = fetch.Msid('aorate2', '2011:001', '2011:002')\n >>> aorate2.vals.mean() * 3600 * 180 / np.pi # rate in arcsec/sec\n 3.9969393528801782\n >>> figure(1)\n >>> aorate2.plot(',')\n\n >>> from kadi import events\n >>> aorate2.select_intervals(events.manvrs)\n >>> aorate2.vals.mean() * 3600 * 180 / np.pi # rate in arcsec/sec\n 24.764309542605481\n >>> figure(2)\n >>> aorate2.plot(',')\n\n :param intervals: EventQuery or iterable (N x 2) with start, stop dates/times\n :param copy: return a copy of MSID object with intervals selected\n \"\"\"\n obj = self.copy() if copy else self\n obj._filter_times(intervals, exclude=False)\n if copy:\n return obj\n\n def _filter_times(self, intervals, exclude=True):\n \"\"\"\n Filter the times of self based on ``intervals``.\n\n :param intervals: iterable (N x 2) with tstart, tstop in seconds\n :param exclude: exclude intervals if True, else include intervals\n \"\"\"\n # Make an initial acceptance mask. If exclude is True then initially\n # all values are allowed (ok=True). If exclude is False (i.e. only\n # include the interval times) then ok=False everywhere.\n ok = np.empty(len(self.times), dtype=bool)\n ok[:] = exclude\n\n # See if the input intervals is actually a table of intervals\n intervals_list = _get_table_intervals_as_list(intervals, check_overlaps=False)\n if intervals_list is not None:\n intervals = intervals_list\n\n # Check if this is an EventQuery. Would rather not import EventQuery\n # because this is expensive (django), so just look at the names in\n # object MRO.\n if \"EventQuery\" in (cls.__name__ for cls in intervals.__class__.__mro__):\n intervals = intervals.intervals(self.datestart, self.datestop)\n\n intervals = [\n (DateTime(start).secs, DateTime(stop).secs) for start, stop in intervals\n ]\n\n for tstart, tstop in intervals:\n if tstart > tstop:\n raise ValueError(\n \"Start time %s must be less than stop time %s\" % (tstart, tstop)\n )\n\n if tstop < self.times[0] or tstart > self.times[-1]:\n continue\n\n # Find the indexes of bad data. Using side=left,right respectively\n # will exclude points exactly equal to the bad_times values\n # (though in reality an exact tie is extremely unlikely).\n i0 = np.searchsorted(self.times, tstart, side=\"left\")\n i1 = np.searchsorted(self.times, tstop, side=\"right\")\n ok[i0:i1] = not exclude\n\n colnames = (x for x in self.colnames)\n for colname in colnames:\n attr = getattr(self, colname)\n if isinstance(attr, np.ndarray):\n setattr(self, colname, attr[ok])\n\n def write_zip(self, filename, append=False):\n \"\"\"Write MSID to a zip file named ``filename``\n\n Within the zip archive the data for this MSID will be stored in csv\n format with the name .csv.\n\n :param filename: output zipfile name\n :param append: append to an existing zipfile\n \"\"\"\n import zipfile\n\n colnames = self.colnames[:]\n if self.bads is None and \"bads\" in colnames:\n colnames.remove(\"bads\")\n\n if self.state_codes:\n colnames.append(\"raw_vals\")\n\n # Indexes value is not interesting for output\n if \"indexes\" in colnames:\n colnames.remove(\"indexes\")\n\n colvals = tuple(getattr(self, x) for x in colnames)\n fmt = \",\".join(\"%s\" for x in colnames)\n\n f = zipfile.ZipFile(\n filename, (\"a\" if append and os.path.exists(filename) else \"w\")\n )\n info = zipfile.ZipInfo(self.msid + \".csv\")\n info.external_attr = 0o664 << 16 # Set permissions\n info.date_time = time.localtime()[:7]\n info.compress_type = zipfile.ZIP_DEFLATED\n f.writestr(\n info,\n \",\".join(colnames)\n + \"\\n\"\n + \"\\n\".join(fmt % x for x in zip(*colvals))\n + \"\\n\",\n )\n f.close()\n\n def logical_intervals(self, op, val, complete_intervals=False, max_gap=None):\n \"\"\"Determine contiguous intervals during which the logical comparison\n expression \"MSID.vals op val\" is True. Allowed values for ``op``\n are::\n\n == != > < >= <=\n\n If ``complete_intervals`` is True (default is False) then the intervals\n are guaranteed to be complete so that the all reported intervals had a\n transition before and after within the telemetry interval.\n\n If ``max_gap`` is specified then any time gaps longer than ``max_gap`` are\n filled with a fictitious False value to create an artificial interval\n boundary at ``max_gap / 2`` seconds from the nearest data value.\n\n Returns a structured array table with a row for each interval.\n Columns are:\n\n * datestart: date of interval start\n * datestop: date of interval stop\n * duration: duration of interval (sec)\n * tstart: time of interval start (CXC sec)\n * tstop: time of interval stop (CXC sec)\n\n Examples::\n\n >>> dat = fetch.MSID('aomanend', '2010:001', '2010:005')\n >>> manvs = dat.logical_intervals('==', 'NEND', complete_intervals=True)\n\n >>> dat = fetch.MSID('61PSTS02', '1999:200', '2000:001')\n >>> safe_suns = dat.logical_intervals('==', 'SSM', max_gap=66)\n\n :param op: logical operator, one of == != > < >= <=\n :param val: comparison value\n :param complete_intervals: return only complete intervals (default=True)\n :param max_gap: max allowed gap between time stamps (sec, default=None)\n :returns: structured array table of intervals\n \"\"\"\n from . import utils\n\n ops = {\n \"==\": operator.eq,\n \"!=\": operator.ne,\n \">\": operator.gt,\n \"<\": operator.lt,\n \">=\": operator.ge,\n \"<=\": operator.le,\n }\n try:\n op = ops[op]\n except KeyError:\n raise ValueError(\n 'op = \"{}\" is not in allowed values: {}'.format(op, sorted(ops.keys()))\n )\n\n # Do local version of bad value filtering\n if self.bads is not None and np.any(self.bads):\n ok = ~self.bads\n vals = self.vals[ok]\n times = self.times[ok]\n else:\n vals = self.vals\n times = self.times\n\n bools = op(vals, val)\n return utils.logical_intervals(times, bools, complete_intervals, max_gap)\n\n def state_intervals(self):\n \"\"\"Determine contiguous intervals during which the MSID value\n is unchanged.\n\n Returns a structured array table with a row for each interval.\n Columns are:\n\n * datestart: date of interval start\n * datestop: date of interval stop\n * duration: duration of interval (sec)\n * tstart: time of interval start (CXC sec)\n * tstop: time of interval stop (CXC sec)\n * val: MSID value during the interval\n\n Example::\n\n dat = fetch.MSID('cobsrqid', '2010:001', '2010:005')\n obsids = dat.state_intervals()\n\n :param val: state value for which intervals are returned.\n :returns: structured array table of intervals\n \"\"\"\n from . import utils\n\n # Do local version of bad value filtering\n if self.bads is not None and np.any(self.bads):\n ok = ~self.bads\n vals = self.vals[ok]\n times = self.times[ok]\n else:\n vals = self.vals\n times = self.times\n\n if len(self.vals) < 2:\n raise ValueError(\"Filtered data length must be at least 2\")\n\n return utils.state_intervals(times, vals)\n\n def iplot(self, fmt=\"-b\", fmt_minmax=\"-c\", **plot_kwargs):\n \"\"\"Make an interactive plot for exploring the MSID data.\n\n This method opens a new plot figure (or clears the current figure) and\n plots the MSID ``vals`` versus ``times``. This plot can be panned or\n zoomed arbitrarily and the data values will be fetched from the archive\n as needed. Depending on the time scale, ``iplot`` displays either full\n resolution, 5-minute, or daily values. For 5-minute and daily values\n the min and max values are also plotted.\n\n Once the plot is displayed and the window is selected by clicking in\n it, the following key commands are recognized::\n\n a: autoscale for full data range in x and y\n m: toggle plotting of min/max values\n p: pan at cursor x\n y: toggle autoscaling of y-axis\n z: zoom at cursor x\n ?: print help\n\n Example::\n\n dat = fetch.Msid('aoattqt1', '2011:001', '2012:001', stat='5min')\n dat.iplot()\n dat.iplot('.b', '.c', markersize=0.5)\n\n Caveat: the ``iplot()`` method is not meant for use within scripts, and\n may give unexpected results if used in combination with other plotting\n commands directed at the same plot figure.\n\n :param fmt: plot format for values (default=\"-b\")\n :param fmt_minmax: plot format for mins and maxes (default=\"-c\")\n :param plot_kwargs: additional plotting keyword args\n\n \"\"\"\n\n from .plot import MsidPlot\n\n self._iplot = MsidPlot(self, fmt, fmt_minmax, **plot_kwargs)\n\n def plot(self, *args, **kwargs):\n \"\"\"Plot the MSID ``vals`` using Ska.Matplotlib.plot_cxctime()\n\n This is a convenience function for plotting the MSID values. It\n is equivalent to::\n\n plot_cxctime(self.times, self.vals, *args, **kwargs)\n\n where ``*args`` are additional arguments and ``**kwargs`` are\n additional keyword arguments that are accepted by ``plot_cxctime()``.\n\n Example::\n\n dat = fetch.Msid('tephin', '2011:001', '2012:001', stat='5min')\n dat.plot('-r', linewidth=2)\n\n \"\"\"\n\n import matplotlib.pyplot as plt\n from Ska.Matplotlib import plot_cxctime\n\n vals = self.raw_vals if self.state_codes else self.vals\n plot_cxctime(self.times, vals, *args, state_codes=self.state_codes, **kwargs)\n plt.margins(0.02, 0.05)\n # Upper-cased version of msid name from user\n title = self.msid.upper()\n if self.stat:\n title = f\"{title} ({self.stat})\"\n plt.title(title)\n if self.unit:\n plt.ylabel(self.unit)\n\n\nclass MSIDset(collections.OrderedDict):\n \"\"\"Fetch a set of MSIDs from the engineering telemetry archive.\n\n Each input ``msid`` is case-insensitive and can include linux file \"glob\"\n patterns, for instance ``orb*1*_?`` (ORBITEPHEM1_X, Y and Z) or\n ``aoattqt[1234]`` (AOATTQT1, 2, 3, and 4). For derived parameters the\n initial ``DP_`` is optional, for instance ``dpa_pow*`` (DP_DPA_POWER).\n\n :param msids: list of MSID names (case-insensitive)\n :param start: start date of telemetry (Chandra.Time compatible)\n :param stop: stop date of telemetry (current time if not supplied)\n :param filter_bad: automatically filter out bad values\n :param stat: return 5-minute or daily statistics ('5min' or 'daily')\n\n :returns: Dict-like object containing MSID instances keyed by MSID name\n \"\"\"\n\n MSID = MSID\n\n def __init__(\n self, msids=None, start=LAUNCH_DATE, stop=None, filter_bad=False, stat=None\n ):\n if msids is None:\n msids = []\n\n super(MSIDset, self).__init__()\n\n intervals = _get_table_intervals_as_list(start, check_overlaps=True)\n if intervals is not None:\n start, stop = intervals[0][0], intervals[-1][1]\n\n self.tstart = DateTime(start).secs\n self.tstop = DateTime(stop).secs if stop else DateTime().secs\n self.datestart = DateTime(self.tstart).date\n self.datestop = DateTime(self.tstop).date\n\n # Input ``msids`` may contain globs, so expand each and add to new list\n new_msids = []\n for msid in msids:\n new_msids.extend(msid_glob(msid)[0])\n for msid in new_msids:\n if intervals is None:\n self[msid] = self.MSID(\n msid, self.tstart, self.tstop, filter_bad=False, stat=stat\n )\n else:\n self[msid] = self.MSID(msid, intervals, filter_bad=False, stat=stat)\n\n if filter_bad:\n self.filter_bad()\n\n def __deepcopy__(self, memo=None):\n out = self.__class__([], None)\n for attr in (\"tstart\", \"tstop\", \"datestart\", \"datestop\"):\n setattr(out, attr, getattr(self, attr))\n for msid in self:\n out[msid] = self[msid].copy()\n\n return out\n\n def copy(self):\n return self.__deepcopy__()\n\n def filter_bad(self, copy=False, union=False):\n \"\"\"Filter bad values for the MSID set.\n\n By default (``union=False``) the bad values are filtered individually for\n each MSID.\n\n If ``union=True`` this method applies the union (logical-OR) of bad value\n masks for all MSIDs in the set with the same content type. The result\n is that the filtered MSID samples are valid for *all* MSIDs within the\n content type and the arrays all match up.\n\n For example::\n\n msids = fetch.MSIDset(['aorate1', 'aorate2', 'aogyrct1', 'aogyrct2'],\n '2009:001', '2009:002')\n msids.filter_bad()\n\n Since ``aorate1`` and ``aorate2`` both have content type of\n ``pcad3eng`` they will be filtered as a group and will remain with the\n same sampling. This will allow something like::\n\n plot(msids['aorate1'].vals, msids['aorate2'].vals)\n\n Likewise the two gyro count MSIDs would be filtered as a group. If\n this group-filtering is not the desired behavior one can always call\n the individual MSID.filter_bad() function for each MSID in the set::\n\n for msid in msids.values():\n msid.filter_bad()\n\n :param copy: return a copy of MSID object with intervals selected\n \"\"\"\n obj = self.copy() if copy else self\n\n if not union:\n # Filter bad values individually for each MSID\n for msid in obj.values():\n msid.filter_bad()\n # Maintain existing function API to return None for copy=False\n return obj if copy else None\n\n # Union of bad value masks for all MSIDs in the set with the same\n # content type.\n for content in set(x.content for x in obj.values()):\n bads = None\n\n msids = [\n x for x in obj.values() if x.content == content and x.bads is not None\n ]\n for msid in msids:\n if bads is None:\n bads = msid.bads.copy()\n else:\n bads |= msid.bads\n\n for msid in msids:\n msid.filter_bad(bads)\n\n if copy:\n return obj\n\n def filter_bad_times(self, start=None, stop=None, table=None, copy=False):\n \"\"\"Filter out intervals of bad data in the MSIDset object.\n\n There are three usage options:\n\n - Supply no arguments. This will use the global list of bad times read\n in with fetch.read_bad_times().\n - Supply both ``start`` and ``stop`` values where each is a single\n value in a valid DateTime format.\n - Supply an ``table`` parameter in the form of a 2-column table of\n start and stop dates (space-delimited) or the name of a file with\n data in the same format.\n\n The ``table`` parameter must be supplied as a table or the name of a\n table file, for example::\n\n msidset.filter_bad_times()\n bad_times = ['2008:292:00:00:00 2008:297:00:00:00',\n '2008:305:00:12:00 2008:305:00:12:03',\n '2010:101:00:01:12 2010:101:00:01:25']\n msidset.filter_bad_times(table=bad_times)\n msidset.filter_bad_times(table='msid_bad_times.dat')\n\n :param start: Start of time interval to exclude (any DateTime format)\n :param stop: End of time interval to exclude (any DateTime format)\n :param table: Two-column table (start, stop) of bad time intervals\n :param copy: return a copy of MSID object with intervals selected\n \"\"\"\n obj = self.copy() if copy else self\n\n for msid in obj.values():\n msid.filter_bad_times(start, stop, table)\n\n if copy:\n return obj\n\n def interpolate(\n self,\n dt=None,\n start=None,\n stop=None,\n filter_bad=True,\n times=None,\n bad_union=False,\n copy=False,\n ):\n \"\"\"\n Perform nearest-neighbor interpolation of all MSID values in the set\n to a common time sequence. The values are updated in-place.\n\n **Times**\n\n The time sequence steps uniformly by ``dt`` seconds starting at the\n ``start`` time and ending at the ``stop`` time. If not provided the\n times default to the ``start`` and ``stop`` times for the MSID set.\n\n If ``times`` is provided then this gets used instead of the default linear\n progression from ``start`` and ``dt``.\n\n For each MSID in the set the ``times`` attribute is set to the common\n time sequence. In addition a new attribute ``times0`` is defined that\n stores the nearest neighbor interpolated time, providing the *original*\n timestamps of each new interpolated value for that MSID.\n\n **Filtering and bad values**\n\n If ``filter_bad`` is True (default) then bad values are filtered from\n the interpolated MSID set. There are two strategies for doing this:\n\n 1) ``bad_union = False``\n\n Remove the bad values in each MSID prior to interpolating the set to\n a common time series. This essentially says to use all the available\n data individually. Each MSID has bad data filtered individually\n *before* interpolation so that the nearest neighbor interpolation only\n finds good data. This strategy is done when ``filter_union = False``,\n which is the default setting.\n\n 2) ``bad_union = True``\n\n Mark every MSID in the set as bad at the interpolated time if *any*\n of them are bad at that time. This stricter version is required when it\n is important that the MSIDs be truly correlated in time. For instance\n this is needed for attitude quaternions since all four values must be\n from the exact same telemetry sample. If you are not sure, this is the\n safer option.\n\n :param dt: time step (sec, default=328.0)\n :param start: start of interpolation period (DateTime format)\n :param stop: end of interpolation period (DateTime format)\n :param filter_bad: filter bad values\n :param times: array of times for interpolation (default=None)\n :param bad_union: filter union of bad values after interpolating\n :param copy: return a new copy instead of in-place update (default=False)\n \"\"\"\n import Ska.Numpy\n\n obj = self.copy() if copy else self\n\n msids = list(obj.values()) # MSID objects in the MSIDset\n\n # Ensure that tstart / tstop is entirely within the range of available\n # data fetched from the archive.\n max_fetch_tstart = max(msid.times[0] for msid in msids)\n min_fetch_tstop = min(msid.times[-1] for msid in msids)\n\n if times is not None:\n if any(kwarg is not None for kwarg in (dt, start, stop)):\n raise ValueError(\n 'If \"times\" keyword is set then \"dt\", \"start\", '\n 'and \"stop\" cannot be set'\n )\n # Use user-supplied times that are within the range of telemetry.\n ok = (times >= max_fetch_tstart) & (times <= min_fetch_tstop)\n obj.times = times[ok]\n else:\n # Get the nominal tstart / tstop range\n dt = 328.0 if dt is None else dt\n tstart = DateTime(start).secs if start else obj.tstart\n tstop = DateTime(stop).secs if stop else obj.tstop\n\n tstart = max(tstart, max_fetch_tstart)\n tstop = min(tstop, min_fetch_tstop)\n obj.times = np.arange((tstop - tstart) // dt + 1) * dt + tstart\n\n for msid in msids:\n if filter_bad and not bad_union:\n msid.filter_bad()\n logger.info(\"Interpolating index for %s\", msid.msid)\n indexes = Ska.Numpy.interpolate(\n np.arange(len(msid.times)),\n msid.times,\n obj.times,\n method=\"nearest\",\n sorted=True,\n )\n logger.info(\"Slicing on indexes\")\n for colname in msid.colnames:\n colvals = getattr(msid, colname)\n if colvals is not None:\n setattr(msid, colname, colvals[indexes])\n\n # Make a new attribute times0 that stores the nearest neighbor\n # interpolated times. Then set the MSID times to be the common\n # interpolation times.\n msid.times0 = msid.times\n msid.times = obj.times\n\n if bad_union:\n common_bads = np.zeros(len(obj.times), dtype=bool)\n for msid in msids:\n if msid.stat is None and msid.bads is None:\n warnings.warn(\n \"WARNING: {!r} MSID has bad values already filtered.\\n\"\n \"This prevents `filter_bad_union` from working as expected.\\n\"\n \"Use MSIDset (not Msidset) with filter_bad=False.\\n\"\n )\n if msid.bads is not None: # 5min and daily stats have no bad values\n common_bads |= msid.bads\n\n # Apply the common bads array and optional filter out these bad values\n for msid in msids:\n msid.bads = common_bads\n if filter_bad:\n msid.filter_bad()\n\n # Filter MSIDset-level times attr to match invididual MSIDs if filter_bad is True\n if filter_bad:\n obj.times = obj.times[~common_bads]\n\n if copy:\n return obj\n\n def write_zip(self, filename):\n \"\"\"Write MSIDset to a zip file named ``filename``\n\n Within the zip archive the data for each MSID in the set will be stored\n in csv format with the name .csv.\n\n :param filename: output zipfile name\n \"\"\"\n append = False\n for msid in self.values():\n msid.write_zip(filename, append=append)\n append = True\n\n\nclass Msid(MSID):\n \"\"\"\n Fetch data from the engineering telemetry archive into an MSID object.\n Same as MSID class but with filter_bad=True by default.\n\n :param msid: name of MSID (case-insensitive)\n :param start: start date of telemetry (Chandra.Time compatible)\n :param stop: stop date of telemetry (current time if not supplied)\n :param filter_bad: automatically filter out bad values\n :param stat: return 5-minute or daily statistics ('5min' or 'daily')\n :param unit_system: Unit system (cxc|eng|sci, default=current units)\n\n :returns: MSID instance\n \"\"\"\n\n units = UNITS\n\n def __init__(self, msid, start=LAUNCH_DATE, stop=None, filter_bad=True, stat=None):\n super(Msid, self).__init__(\n msid, start=start, stop=stop, filter_bad=filter_bad, stat=stat\n )\n\n\nclass Msidset(MSIDset):\n \"\"\"Fetch a set of MSIDs from the engineering telemetry archive.\n Same as MSIDset class but with filter_bad=True by default.\n\n :param msids: list of MSID names (case-insensitive)\n :param start: start date of telemetry (Chandra.Time compatible)\n :param stop: stop date of telemetry (current time if not supplied)\n :param filter_bad: automatically filter out bad values\n :param stat: return 5-minute or daily statistics ('5min' or 'daily')\n :param unit_system: Unit system (cxc|eng|sci, default=current units)\n\n :returns: Dict-like object containing MSID instances keyed by MSID name\n \"\"\"\n\n MSID = MSID\n\n def __init__(self, msids, start=LAUNCH_DATE, stop=None, filter_bad=True, stat=None):\n super(Msidset, self).__init__(\n msids, start=start, stop=stop, filter_bad=filter_bad, stat=stat\n )\n\n\nclass HrcSsMsid(Msid):\n \"\"\"\n Fetch data from the engineering telemetry archive into an MSID object.\n Same as MSID class but with filter_bad=True by default.\n\n :param msid: name of MSID (case-insensitive)\n :param start: start date of telemetry (Chandra.Time compatible)\n :param stop: stop date of telemetry (current time if not supplied)\n :param filter_bad: automatically filter out bad values\n :param stat: return 5-minute or daily statistics ('5min' or 'daily')\n :param unit_system: Unit system (cxc|eng|sci, default=current units)\n\n :returns: MSID instance\n\n \"\"\"\n\n units = UNITS\n\n def __new__(self, msid, start=LAUNCH_DATE, stop=None, stat=None):\n ss_msids = \"2TLEV1RT 2VLEV1RT 2SHEV1RT 2TLEV2RT 2VLEV2RT 2SHEV2RT\"\n if msid.upper() not in ss_msids.split():\n raise ValueError(\n \"MSID {} is not in HRC secondary science ({})\".format(msid, ss_msids)\n )\n\n # If this is not full-resolution then add boolean bads mask to individual MSIDs\n msids = [msid, \"HRC_SS_HK_BAD\"]\n out = MSIDset(msids, start=start, stop=stop, stat=stat)\n if stat is not None:\n for m in msids:\n out[m].bads = np.zeros(len(out[m].vals), dtype=np.bool)\n\n # Set bad mask\n i_bads = np.flatnonzero(out[\"HRC_SS_HK_BAD\"].vals > 0)\n out[\"HRC_SS_HK_BAD\"].bads[i_bads] = True\n\n # For full-resolution smear the bad mask out by +/- 5 samples\n if stat is None:\n for i_bad in i_bads:\n i0 = max(0, i_bad - 5)\n i1 = i_bad + 5\n out[\"HRC_SS_HK_BAD\"].bads[i0:i1] = True\n\n # Finally interpolate and filter out bad values\n out.interpolate(times=out[msid].times, bad_union=True, filter_bad=True)\n return out[msid]\n\n\nclass memoized(object):\n \"\"\"Decorator that caches a function's return value each time it is called.\n If called later with the same arguments, the cached value is returned, and\n not re-evaluated.\n \"\"\"\n\n def __init__(self, func):\n self.func = func\n self.cache = {}\n\n def __call__(self, *args):\n try:\n return self.cache[args]\n except KeyError:\n self.cache[args] = value = self.func(*args)\n return value\n except TypeError:\n # uncachable -- for instance, passing a list as an argument.\n # Better to not cache than to blow up entirely.\n return self.func(*args)\n\n def __repr__(self):\n \"\"\"Return the function's docstring.\"\"\"\n return self.func.__doc__\n\n\ndef get_time_range(msid, format=None):\n \"\"\"\n Get the time range for the given ``msid``.\n\n :param msid: MSID name\n :param format: Output format (DateTime format, e.g. 'secs', 'date', 'greta')\n :returns: (tstart, tstop) in CXC seconds\n \"\"\"\n MSID = msid.upper()\n with _cache_ft():\n ft[\"content\"] = content[MSID]\n ft[\"msid\"] = \"time\"\n filename = msid_files[\"msid\"].abs\n logger.info(\"Reading %s\", filename)\n\n @local_or_remote_function(\"Getting time range from Ska eng archive server...\")\n def get_time_data_from_server(filename):\n import tables\n\n open_file = getattr(tables, \"open_file\", None) or tables.openFile\n h5 = open_file(os.path.join(*filename))\n tstart = h5.root.data[0]\n tstop = h5.root.data[-1]\n h5.close()\n return tstart, tstop\n\n if filename in CONTENT_TIME_RANGES:\n tstart, tstop = CONTENT_TIME_RANGES[filename]\n else:\n tstart, tstop = get_time_data_from_server(_split_path(filename))\n CONTENT_TIME_RANGES[filename] = (tstart, tstop)\n\n if format is not None:\n tstart = getattr(DateTime(tstart), format)\n tstop = getattr(DateTime(tstop), format)\n return tstart, tstop\n\n\ndef get_telem(\n msids,\n start=None,\n stop=None,\n sampling=\"full\",\n unit_system=\"eng\",\n interpolate_dt=None,\n remove_events=None,\n select_events=None,\n time_format=None,\n outfile=None,\n quiet=False,\n max_fetch_Mb=1000,\n max_output_Mb=100,\n):\n \"\"\"\n High-level routine to get telemetry for one or more MSIDs and perform\n common processing functions:\n\n - Fetch a set of MSIDs over a time range, specifying the sampling as\n either full-resolution, 5-minute, or daily data.\n - Filter out bad or missing data.\n - Interpolate (resample) all MSID values to a common uniformly-spaced time sequence.\n - Remove or select time intervals corresponding to specified Kadi event types.\n - Change the time format from CXC seconds (seconds since 1998.0) to something more\n convenient like GRETA time.\n - Write the MSID telemetry data to a zipfile.\n\n :param msids: MSID(s) to fetch (string or list of strings)')\n :param start: Start time for data fetch (default= - 30 days)\n :param stop: Stop time for data fetch (default=NOW)\n :param sampling: Data sampling (full | 5min | daily) (default=full)\n :param unit_system: Unit system for data (eng | sci | cxc) (default=eng)\n :param interpolate_dt: Interpolate to uniform time steps (secs, default=None)\n :param remove_events: Remove kadi events expression (default=None)\n :param select_events: Select kadi events expression (default=None)\n :param time_format: Output time format (secs|date|greta|jd|..., default=secs)\n :param outfile: Output file name (default=None)\n :param quiet: Suppress run-time logging output (default=False)\n :param max_fetch_Mb: Max allowed memory (Mb) for fetching (default=1000)\n :param max_output_Mb: Max allowed memory (Mb) for file output (default=100)\n\n :returns: MSIDset object\n \"\"\"\n from .get_telem import get_telem\n\n return get_telem(\n msids,\n start,\n stop,\n sampling,\n unit_system,\n interpolate_dt,\n remove_events,\n select_events,\n time_format,\n outfile,\n quiet,\n max_fetch_Mb,\n max_output_Mb,\n )\n\n\n@lru_cache_timed(maxsize=1000, timeout=600)\ndef get_interval(content, tstart, tstop):\n \"\"\"\n Get the approximate row intervals that enclose the specified ``tstart`` and\n ``tstop`` times for the ``content`` type.\n\n The output of this function is cached with an LRU cache of the most recent\n 1000 results. The cache expires every 10 minutes to ensure that a persistent\n session will get new data if the archive gets updated.\n\n :param content: content type (e.g. 'pcad3eng', 'thm1eng')\n :param tstart: start time (CXC seconds)\n :param tstop: stop time (CXC seconds)\n\n :returns: rowslice\n \"\"\"\n\n ft[\"content\"] = content\n\n @local_or_remote_function(\n \"Getting interval data from \" + \"DB on Ska eng archive server...\"\n )\n def get_interval_from_db(tstart, tstop, server):\n\n import Ska.DBI\n\n db = Ska.DBI.DBI(dbi=\"sqlite\", server=os.path.join(*server))\n\n query_row = db.fetchone(\n \"SELECT tstart, rowstart FROM archfiles \"\n \"WHERE filetime < ? order by filetime desc\",\n (tstart,),\n )\n if not query_row:\n query_row = db.fetchone(\n \"SELECT tstart, rowstart FROM archfiles order by filetime asc\"\n )\n\n rowstart = query_row[\"rowstart\"]\n\n query_row = db.fetchone(\n \"SELECT tstop, rowstop FROM archfiles \"\n \"WHERE filetime > ? order by filetime asc\",\n (tstop,),\n )\n if not query_row:\n query_row = db.fetchone(\n \"SELECT tstop, rowstop FROM archfiles order by filetime desc\"\n )\n\n rowstop = query_row[\"rowstop\"]\n\n return slice(rowstart, rowstop)\n\n return get_interval_from_db(tstart, tstop, _split_path(msid_files[\"archfiles\"].abs))\n\n\n@contextlib.contextmanager\ndef _cache_ft():\n \"\"\"\n Cache the global filetype ``ft`` context variable so that fetch operations\n do not corrupt user values of ``ft``.\n \"\"\"\n ft_cache_pickle = pickle.dumps(ft)\n try:\n yield\n finally:\n ft_cache = pickle.loads(ft_cache_pickle)\n ft.update(ft_cache)\n delkeys = [x for x in ft if x not in ft_cache]\n for key in delkeys:\n del ft[key]\n\n\n@contextlib.contextmanager\ndef _set_msid_files_basedir(datestart, msid_files=msid_files):\n \"\"\"\n If datestart is before 2000:001:00:00:00 then use the 1999 archive files.\n \"\"\"\n try:\n cache_basedir = msid_files.basedir\n if datestart < DATE2000_LO:\n # Note: don't use os.path.join because ENG_ARCHIVE and basedir must\n # use linux '/' convention but this might be running on Windows.\n dirs = msid_files.basedir.split(os.pathsep)\n msid_files.basedir = os.pathsep.join(dir_ + \"/1999\" for dir_ in dirs)\n yield\n finally:\n msid_files.basedir = cache_basedir\n\n\ndef _fix_ctu_dwell_mode_bads(msid, bads):\n \"\"\"\n Because of an issue related to the placement of the dwell mode flag, MSIDs that get\n stepped on in dwell mode get a bad value at the beginning of a dwell mode, while the\n dwell mode values (DWELLnn) get a bad value at the end. This does a simple\n brute-force fix of expanding any section of bad values by ones sample in the\n appropriate direction.\n \"\"\"\n MSID = msid.upper()\n stepped_on_msids = (\n \"4PRT5BT\",\n \"4RT585T\",\n \"AFLCA3BI\",\n \"AIRU1BT\",\n \"CSITB5V\",\n \"CUSOAOVN\",\n \"ECNV3V\",\n \"PLAED4ET\",\n \"PR1TV01T\",\n \"TCYLFMZM\",\n \"TOXTSUPN\",\n \"ES1P5CV\",\n \"ES2P5CV\",\n )\n\n if MSID in stepped_on_msids or re.match(r\"DWELL\\d\\d\", MSID):\n # Find transitions from good value to bad value. Turn that\n # good value to bad to extend the badness by one sample.\n ok = (bads[:-1] == False) & (bads[1:] == True) # noqa\n bads[:-1][ok] = True\n\n return bads\n\n\ndef add_logging_handler(level=logging.INFO, formatter=None, handler=None):\n \"\"\"Configure logging for fetch module.\n\n :param level: logging level (logging.DEBUG, logging.INFO, etc)\n :param formatter: logging.Formatter (default: Formatter('%(funcName)s: %(message)s'))\n :param handler: logging.Handler (default: StreamHandler())\n \"\"\"\n\n if formatter is None:\n formatter = logging.Formatter(\"%(funcName)s: %(message)s\")\n\n if handler is None:\n handler = logging.StreamHandler()\n\n handler.setFormatter(formatter)\n logger.setLevel(level)\n logger.addHandler(handler)\n\n\ndef _plural(x):\n \"\"\"Return English plural of ``x``. Super-simple and only valid for the\n known small set of cases within fetch where it will get applied.\n \"\"\"\n return x + \"es\" if (x.endswith(\"x\") or x.endswith(\"s\")) else x + \"s\"\n\n\ndef get_data_gap_spec_parser():\n \"\"\"\n Get parser for fetch data gap specification.\n\n This env var is in the form of a command line argument string with the following\n command line options::\n\n --include INCLUDE Include MSIDs matching glob (default=\"*\", can be repeated)\n --exclude EXCLUDE Exclude MSIDs matching glob (default=None, can be repeated)\n --start START Gap start (relative seconds or abs time)\n --stop STOP Gap stop (relative seconds or abs time)\n\n For example::\n\n \"--exclude=*EPHEM* --start=-25000 --stop=-2000\"\n\n \"\"\"\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--include\",\n default=[],\n action=\"append\",\n help=\"Include MSIDs matching glob (default='*', can be repeated)\",\n )\n parser.add_argument(\n \"--exclude\",\n default=[],\n action=\"append\",\n help=\"Exclude MSIDs matching glob (default=None, can be repeated)\",\n )\n parser.add_argument(\n \"--start\", default=-30000, help=\"Gap start (relative seconds or abs time)\"\n )\n parser.add_argument(\n \"--stop\", default=-3000, help=\"Gap stop (relative seconds or abs time)\"\n )\n return parser\n\n\ndef msid_matches_data_gap_spec(msid, includes, excludes):\n from fnmatch import fnmatch\n\n msid = msid.upper()\n includes = includes or [\"*\"]\n match = any(fnmatch(msid, include.upper()) for include in includes) and not any(\n fnmatch(msid, exclude.upper()) for exclude in excludes\n )\n return match\n\n\ndef create_msid_data_gap(msid_obj: MSID, data_gap_spec: str):\n \"\"\"\n Make a data gap in the ``msid_obj`` (in-place) by removing data points.\n\n This is mostly useful for testing via setting the ``CHETA_FETCH_DATA_GAP``\n environment variable.\n\n The ``data_gap_spec`` string corresponds to a command line argument string with the\n following options::\n\n --include INCLUDE Include MSIDs matching glob (default=\"*\", can be repeated)\n --exclude EXCLUDE Exclude MSIDs matching glob (default=None, can be repeated)\n --start START Gap start (CxoTimeLike)\n --stop STOP Gap stop (CxoTimeLike)\n\n For example::\n\n >>> dat = fetch.MSID('aopcadmd', '2010:001', '2010:002')\n >>> gap_spec = \"--start=-2010:001:12:00:00 --stop=2010:001:12:30:00\"\n >>> fetch.create_msid_data_gap(dat, gap_spec)\n\n :param msid_obj: MSID object\n :param data_gap_spec: data gap specification\n \"\"\"\n import shlex\n\n from cxotime import CxoTime\n\n parser = get_data_gap_spec_parser()\n args = parser.parse_args(shlex.split(data_gap_spec))\n\n if msid_matches_data_gap_spec(msid_obj.MSID, args.include, args.exclude):\n start = CxoTime(args.start)\n stop = CxoTime(args.stop)\n logger.info(\n f\"Creating data gap for {msid_obj.MSID} \"\n f\"from {start.date} to {stop.date}\"\n )\n i0, i1 = np.searchsorted(msid_obj.times, [start.secs, stop.secs])\n for attr in msid_obj.colnames:\n val = getattr(msid_obj, attr)\n if val is not None:\n val_new = np.concatenate([val[:i0], val[i1:]])\n setattr(msid_obj, attr, val_new)\n","sub_path":"Ska/engarchive/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":84731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"177610431","text":"import os\nimport shutil\nimport subprocess\nfrom pathlib import Path\n\nfrom setuptools import setup\nfrom setuptools.command.build_clib import build_clib as _build_clib\n\n\nclass build_clib(_build_clib):\n def build_libraries(self, libraries):\n cc = os.environ.get('CC')\n build_static = os.environ.get('BUILD_STATIC', 'n') == 'y'\n include_dirs = None\n library_dirs = None\n if cc is None:\n if self.compiler.compiler_type == 'msvc':\n self.compiler.initialize()\n cc = self.compiler.cc\n include_dirs = self.compiler.include_dirs\n library_dirs = self.compiler.library_dirs\n elif self.compiler.compiler_type == 'bcpp':\n cc = 'bcpp'\n elif hasattr(self.compiler, 'compiler_so') and self.compiler.compiler_so:\n # looks like ['gcc', '-pthread', '-Wl,--sysroot=/', ...]\n cc = self.compiler.compiler_so[0]\n if not cc:\n cc = find_c_compiler()\n output_dir = Path('build/lib/hatanaka/bin')\n output_dir.mkdir(parents=True, exist_ok=True)\n for executable, build_info in libraries:\n output = output_dir / executable\n build(build_info['sources'], output, cc, build_static, include_dirs, library_dirs)\n\n # copy to source dir as well for easier testing\n for f in list(output_dir.glob('rnx2crx*')) + list(output_dir.glob('crx2rnx*')):\n shutil.copy(f, 'hatanaka/bin/')\n\n\ndef build(sources, output, cc, build_static=False, include_dirs=None, library_dirs=None):\n if not all(Path(src).is_file() for src in sources):\n raise FileNotFoundError(sources)\n output = str(output)\n\n if cc.replace('.exe', '').endswith('cl'): # msvc-like\n cmd = [cc, *sources, '/nologo', '/O2', '/Fe:' + output]\n if include_dirs:\n cmd += ['/I' + inc_dir for inc_dir in include_dirs]\n if library_dirs:\n cmd += ['/link']\n cmd += ['/LIBPATH:' + library_dir for library_dir in library_dirs]\n else:\n cmd = [cc, *sources, '-O3', '-Wno-unused-result', '-o', output]\n if include_dirs:\n cmd += ['-I' + inc_dir for inc_dir in include_dirs]\n if library_dirs:\n cmd += ['-L' + library_dir for library_dir in library_dirs]\n if build_static:\n cmd.append('-static')\n\n print(' '.join(cmd))\n subprocess.check_call(cmd)\n\n\ndef find_c_compiler(cc=None):\n compilers = ['cc', 'gcc', 'clang', 'icc', 'icl', 'cl', 'clang-cl']\n if cc is not None:\n compilers = [cc] + compilers\n available = list(filter(shutil.which, compilers))\n if not available:\n raise FileNotFoundError('No C compiler found on PATH')\n return available[0]\n\n\ncmdclass = {'build_clib': build_clib}\n\ntry:\n from wheel.bdist_wheel import bdist_wheel as _bdist_wheel\n\n\n class bdist_wheel(_bdist_wheel):\n def get_tag(self):\n impl, abi_tag, plat_name = super().get_tag()\n impl = 'py3'\n abi_tag = 'none'\n plat_name = plat_name.replace('linux', 'manylinux1')\n return impl, abi_tag, plat_name\n\n\n cmdclass['bdist_wheel'] = bdist_wheel\nexcept ImportError:\n pass\n\nsetup(\n libraries=[\n ('rnx2crx', {'sources': ['rnxcmp/source/rnx2crx.c']}),\n ('crx2rnx', {'sources': ['rnxcmp/source/crx2rnx.c']})\n ],\n cmdclass=cmdclass,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"429346872","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('auth', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Board',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('board_name', models.CharField(max_length=30)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('text', models.CharField(max_length=500)),\n ('date', models.DateTimeField(auto_now_add=True, verbose_name='%Y-%m-%d %H:%M:%S')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Event',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('start_time', models.DateTimeField(verbose_name='Start time:')),\n ('end_time', models.DateTimeField(verbose_name='End time:')),\n ('picture', models.ImageField(verbose_name='Pic', blank=True, upload_to='.')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Place',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('latitude', models.FloatField(verbose_name='Latitude:')),\n ('altitude', models.FloatField(verbose_name='Altitude:')),\n ('event_id', models.OneToOneField(to='Events.Event')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Post',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('author', models.CharField(max_length=30)),\n ('board_id', models.ForeignKey(to='Events.Board')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('password', models.CharField(verbose_name='password', max_length=128)),\n ('last_login', models.DateTimeField(verbose_name='last login', default=django.utils.timezone.now)),\n ('is_superuser', models.BooleanField(verbose_name='superuser status', default=False, help_text='Designates that this user has all permissions without explicitly assigning them.')),\n ('username', models.CharField(max_length=30, unique=True)),\n ('email', models.EmailField(verbose_name='Email', max_length=40, unique=True)),\n ('is_admin', models.BooleanField(verbose_name='Admin status', default=False)),\n ('is_active', models.BooleanField(verbose_name='Active', default=True)),\n ('date_joined', models.DateTimeField(verbose_name='Date joined', default=django.utils.timezone.now)),\n ('groups', models.ManyToManyField(verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of his/her group.', to='auth.Group', related_query_name='user', blank=True, related_name='user_set')),\n ('user_permissions', models.ManyToManyField(verbose_name='user permissions', help_text='Specific permissions for this user.', to='auth.Permission', related_query_name='user', blank=True, related_name='user_set')),\n ],\n options={\n 'verbose_name': 'User',\n 'verbose_name_plural': 'Users',\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='post',\n name='user_id',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='event',\n name='owner',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='comment',\n name='post',\n field=models.ForeignKey(to='Events.Post', default=1),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='board',\n name='event_id',\n field=models.ForeignKey(to='Events.Event'),\n preserve_default=True,\n ),\n ]\n","sub_path":"wsgi/myproject/Events/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"563974305","text":"from flask import Flask, request, render_template, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nimport random\nimport itertools\nfrom flask import Markup\n\napp = Flask(__name__)\n\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///quiz.db'\nquiz = SQLAlchemy(app)\n\n\nclass Questionclass(quiz.Model):\n id = quiz.Column(quiz.Integer, primary_key=True)\n Question = quiz.Column(quiz.String)\n Option1 = quiz.Column(quiz.String)\n Option2 = quiz.Column(quiz.String)\n Option3 = quiz.Column(quiz.String)\n Answer = quiz.Column(quiz.String)\n\n def __init__(self, Question, Option1, Option2, Option3, Answer):\n self.Question = Question\n self.Option1 = Option1\n self.Option2 = Option2\n self.Option3 = Option3\n self.Answer = Answer\n\n\n@app.route('/')\ndef Quizzes():\n return render_template('Quizzes.html')\n\n\ndef addInquiz(Question, Option1, Option2, Option3, Answer):\n quiz.create_all()\n allUsers = Questionclass.query.all()\n new_item = Questionclass(Question, Option1, Option2, Option3, Answer)\n quiz.session.add(new_item)\n quiz.session.commit()\n\n def __repr__(self):\n return '' % self.Question\n\n\n@app.route(\"/view\")\ndef userFetch():\n quiz.create_all()\n allUsers = Questionclass.query.all()\n diction = {\"Questions\": []}\n for x in allUsers:\n diction[\"Questions\"].append({\"Question\": x.Question,\n \"Option1\": x.Option1,\n \"Option2\": x.Option2,\n \"Option3\": x.Option3,\n \"Answer\": x.Answer})\n return jsonify(diction)\n\n\naddInquiz(\n \"A hash function guarantees integrity of a message. It guarantees that message has not be\", \"Replaced\",\"Over view\",\"Changed\",3)\naddInquiz(\n \"Digest created by a hash function is normally called a\",\"Modification detection code (MDC)\",\"Modify authentication connection\",\"Message authentication control\", 1)\naddInquiz(\n \"If a MAC tag is K-bits long, how much work is needed to find a collision to that specific value.\",\"2^{k/2}\", \"K^2\", \"K!\",3)\naddInquiz(\n\"Best way to achieve both privacy and message integrity\",\"Encrypt and Authenticate\",\"Authenticate then Encrypt\",\"Encrypt then Authenticate\", 2)\naddInquiz(\n \" The out put length of SHA - I is _____________ bits\",\"128\",\"160\",\"64\",3)\n\n\nif __name__ == '__main__':\n app.run(port='8080')\n","sub_path":"cbc-mac/app/create_quiz_database.py","file_name":"create_quiz_database.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"127710947","text":"# Imports\nfrom tensorflow.keras.preprocessing.image import img_to_array, load_img\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.utils import get_file\nimport os\nimport numpy as np\nimport cv2 as cv\n\n# Initializing\nmodel = load_model('assets/preTrainedModel.h5')\nface_cascade = cv.CascadeClassifier('assets/haarcascade_frontalface_alt.xml')\n\nImagefactor = 0.5\npoweredImageFactor = 0.7\n\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom PIL import ImageTk, Image\n\nroot = Tk()\nroot.geometry(\"800x600\")\nroot.title('Gender Classifier')\n\n\n# Functions\n# Open Camera\ndef openCamera(event):\n global model\n global face_cascade\n genderWindow = \"Gender Classification\"\n # Fullscreen - Disabled\n # cv.namedWindow(genderWindow, cv.WND_PROP_FULLSCREEN)\n # cv.setWindowProperty(genderWindow, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)\n webcam = cv.VideoCapture(0)\n while webcam.isOpened():\n status, frame = webcam.read()\n if not status:\n print(\"Could not read frame\")\n exit()\n img = frame\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in faces:\n rectangleColor = (0, 255, 0)\n cv.rectangle(img, (x, y), (x + w, y + h), rectangleColor, 2)\n roi_gray = gray[y: y + h, x: x + w]\n roi_color = img[y: y + h, x: x + w]\n extractedImage = np.copy(img[y: y + h, x: x + w])\n if (extractedImage.shape[0]) < 10 or (extractedImage.shape[1]) < 10:\n continue\n extractedImage = cv.resize(extractedImage, (96, 96))\n extractedImage = extractedImage.astype(\"float\") / 255.0\n extractedImage = img_to_array(extractedImage)\n extractedImage = np.expand_dims(extractedImage, axis=0)\n pred = model.predict(extractedImage)\n if pred[0][0] > 0.5:\n label = \"Male\"\n textColor = (255, 0, 0)\n else:\n label = \"Female\"\n textColor = (0, 0, 255)\n cv.putText(img, label, (x, y), cv.FONT_HERSHEY_SIMPLEX, 0.7, textColor, 2)\n titleColor = (0, 0, 255)\n (widthh, heightt), baseline = cv.getTextSize(\"Press Q to Quit\", cv.FONT_HERSHEY_SIMPLEX, 0.7, 2)\n # cv.rectangle(img, (0, 30), (0 + widthh + 10, 30 + heightt + 10), (0, 0, 0), 2)\n recPts = np.array(\n [[[0, 30], [0 + widthh + 10, 30], [0 + widthh + 10, 30 + heightt + 10], [0, 30 + heightt + 10]]],\n dtype=np.int32)\n cv.fillPoly(img, recPts, (0, 0, 0))\n cv.putText(img, \"Press Q to Quit\", (0, 50), cv.FONT_HERSHEY_SIMPLEX, 0.7, titleColor, 2)\n cv.imshow(genderWindow, img)\n if cv.waitKey(10) & 0xFF == ord('q'):\n break\n\n webcam.release()\n cv.destroyAllWindows()\n\n\n# Image Input Window\ndef openImageWindow(event):\n global model\n path = filedialog.askopenfilename()\n img = cv.imread(path)\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n print(path)\n face_cascade = cv.CascadeClassifier('assets/haarcascade_frontalface_default.xml')\n currFaces = face_cascade.detectMultiScale(gray, 1.3, 5)\n faces = currFaces\n maxLength = len(faces)\n\n haarcascades = ['assets/haarcascade_frontalface_alt.xml', 'assets/haarcascade_frontalface_alt2.xml',\n 'assets/haarcascade_frontalface_alt_tree.xml']\n for i in range(0, 3):\n face_cascade = cv.CascadeClassifier(haarcascades[i])\n currFaces = face_cascade.detectMultiScale(gray, 1.3, 5)\n if len(currFaces) > maxLength:\n faces = currFaces\n maxLength = len(currFaces)\n out = []\n for (x, y, w, h) in faces:\n rectangleColor = (255, 0, 0)\n cv.rectangle(img, (x, y), (x + w, y + h), rectangleColor, 2)\n roi_gray = gray[y: y + h, x: x + w]\n roi_color = img[y: y + h, x: x + w]\n extractedImage = np.copy(img[y: y + h, x: x + w])\n if (extractedImage.shape[0]) < 10 or (extractedImage.shape[1]) < 10:\n continue\n extractedImage = cv.resize(extractedImage, (96, 96))\n extractedImage = extractedImage.astype(\"float\") / 255.0\n extractedImage = img_to_array(extractedImage)\n extractedImage = np.expand_dims(extractedImage, axis=0)\n pred = model.predict(extractedImage)\n if pred[0][0] > 0.5:\n label = \"Male : \"\n percentage = pred[0][0] * 100.0\n label += str(round(percentage, 2))\n label += \"%\"\n textColor = (0, 255, 0)\n else:\n label = \"Female : \"\n percentage = pred[0][1] * 100.0\n label += str(round(percentage, 2))\n label += \"%\"\n textColor = (255, 255, 0)\n ok = False\n fontScale = 2.1\n while ok == False:\n fontScale -= 0.1\n if fontScale <= 0.5:\n break\n (widthh, heightt), baseline = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, fontScale, 2)\n if widthh <= w:\n ok = True\n cv.putText(img, label, (x, y), cv.FONT_HERSHEY_SIMPLEX, fontScale, textColor, 2)\n # cv.imshow(\"gender detection\", img)\n\n outputImg = img\n (imgWidth, imgHeight, imgDepth) = outputImg.shape\n outputWindow = 'Output Image'\n # Fullscreen - Disabled\n # cv.namedWindow(outputWindow, cv.WND_PROP_FULLSCREEN)\n # cv.setWindowProperty(outputWindow, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)\n cv.imshow(outputWindow, outputImg)\n cv.imwrite('output.jpg', outputImg)\n videoBtn.place_forget()\n videoBtn.place(x=(800 - 247) / 2, y=370)\n\n\n# Loading Images\nlogo = Image.open(\"assets/Logo.png\")\nlogo = ImageTk.PhotoImage(logo)\n\npoweredImage = Image.open(\"assets/powered.png\")\npoweredImage = ImageTk.PhotoImage(poweredImage.resize((int(495 * poweredImageFactor), int(90 * poweredImageFactor))))\n\nvideoImage = Image.open(\"assets/video.png\")\nvideoImage = ImageTk.PhotoImage(videoImage.resize((int(495 * Imagefactor), int(90 * Imagefactor))))\n\ninputImage = Image.open(\"assets/cam.png\")\ninputImage = ImageTk.PhotoImage(inputImage.resize((int(495 * Imagefactor), int(90 * Imagefactor))))\n\n# Logo Label\nlogoLbl = Label(root, image=logo)\nlogoLbl.place(x=(800 - 500) / 2 - 30, y=10)\n\npoweredLabel = Label(root, image=poweredImage)\npoweredLabel.place(x=(800 - int(495 * poweredImageFactor)) / 2, y=500)\n\n# Buttons\ninputImageBtn = Button(root)\ninputImageBtn.config(image=inputImage)\ninputImageBtn.place(x=(800 - 247) / 2, y=300)\ninputImageBtn.bind('', openImageWindow)\n\nvideoBtn = Button(root)\nvideoBtn.config(image=videoImage)\nvideoBtn.place(x=(800 - 247) / 2, y=370)\nvideoBtn.bind('', openCamera)\n\n# btn.place_forget()\n\nroot.mainloop()","sub_path":"mainMenu.py","file_name":"mainMenu.py","file_ext":"py","file_size_in_byte":6776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"322364075","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.core.urlresolvers import reverse\nfrom wagtail.wagtailadmin import widgets\nfrom wagtail.wagtailadmin.menu import MenuItem\nfrom wagtail.wagtailcore import hooks\n\nfrom wagtailtrans.models import Language\nfrom wagtailtrans.urls import languages, translations\n\n\n@hooks.register('register_admin_urls')\ndef register_admin_urls():\n return [\n url(r'^language/',\n include(languages, namespace='wagtailtrans_languages')),\n url(r'^translate/',\n include(translations, namespace='wagtailtrans_translations')),\n ]\n\n\n@hooks.register('register_settings_menu_item')\ndef register_language_menu_item():\n return MenuItem(\n 'Languages',\n reverse('wagtailtrans_languages:index'),\n classnames='icon icon-snippet',\n order=1000,\n )\n\n\nif not settings.WAGTAILTRANS_SYNC_TREE:\n \"\"\"Only load hooks when WAGTAILTRANS_SYNC_TREE is disabled\"\"\"\n\n @hooks.register('register_page_listing_buttons')\n def page_translations_menu(page, page_perms, is_parent=False):\n if not hasattr(page, 'language'):\n return\n\n if hasattr(page, 'canonical_page') and page.canonical_page:\n return\n\n yield widgets.ButtonWithDropdownFromHook(\n 'Translate into',\n hook_name='wagtailtrans_dropdown_hook',\n page=page,\n page_perms=page_perms,\n is_parent=is_parent,\n priority=10)\n\n @hooks.register('wagtailtrans_dropdown_hook')\n def page_translations_menu_items(page, page_perms, is_parent=False):\n prio = 1\n exclude_lang = None\n\n if hasattr(page, 'language') and page.language:\n exclude_lang = page.language\n\n other_languages = set(\n Language.objects\n .live()\n .exclude(pk=exclude_lang.pk)\n .order_by('position'))\n\n translations = (\n page.get_translations(only_live=False).select_related('language'))\n taken_languages = set(translations.values_list('language', flat=True))\n\n translation_targets = other_languages - taken_languages\n for language in translation_targets:\n yield widgets.Button(\n language.get_code_display(),\n reverse('wagtailtrans_translations:add', kwargs={\n 'page_pk': page.pk,\n 'language_code': language.code,\n }),\n priority=prio)\n\n prio += 1\n","sub_path":"src/wagtailtrans/wagtail_hooks.py","file_name":"wagtail_hooks.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"480655271","text":"#test.py\n#!/usr/bin/env python3\n\n\"\"\" test neuron network performace\nprint top1 and top5 err on test dataset\nof a model\n\nauthor baiyu\n\"\"\"\n\nimport argparse\n\nfrom matplotlib import pyplot as plt\n\nimport torch\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nfrom torchsummary import summary\n\nfrom conf import settings\nfrom utils import get_network, get_test_dataloader\n\ndef evaluate(model,net, classes):\n net.load_state_dict(torch.load(model))\n #print(net)\n net.eval()\n\n correct_1 = 0.0\n correct_5 = 0.0\n total = 0\n \n ground_truth = 0\n with torch.no_grad():\n print(len(cifar100_test_loader.dataset))\n for n_iter, (image, label) in enumerate(cifar100_test_loader):\n #print(\"iteration: {}\\ttotal {} iterations\".format(n_iter + 1, len(cifar100_test_loader)))\n total+=1\n if args.gpu:\n image = image.cuda()\n label = label.cuda()\n print('GPU INFO.....')\n print(torch.cuda.memory_summary(), end='')\n\n #print(label,total)\n output = net(image)\n _, pred = output.topk(5, 1, largest=True, sorted=True)\n correct_label = classes[label[0]]\n label = label.view(label.size(0), -1).expand_as(pred)\n correct = pred.eq(label).float()\n _,predicted = torch.max(output.data,1)\n if classes[predicted[0]] == correct_label:\n ground_truth+=1\n #print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(1)))\n #print(output,\"\\n******\\n\",predicted,\"\\n******\\n\",pred,\"\\n******\\n\",label)\n #compute top 5\n #if label == predicted:\n #correctness += (predicted == label).sum().item()\n #print(label[0])\n #print(\"matched\",' '.join('%5s' % classes[label[0][j]] for j in range(4)))\n #print(label)\n correct_5 += correct[:, :5].sum()\n\n #compute top1\n correct_1 += correct[:, :1].sum()\n #print(Correct_1)\n\n if args.gpu:\n print('GPU INFO.....')\n print(torch.cuda.memory_summary(), end='')\n\n print()\n print(\"Top 1 accuracy: \", correct_1 / len(cifar100_test_loader.dataset))\n print(\"Top 5 accuracy: \", correct_5 / len(cifar100_test_loader.dataset))\n print(\"Parameter numbers: {}\".format(sum(p.numel() for p in net.parameters())))\n print(\"Ground truth \", ground_truth)\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-net', type=str, required=True, help='net type')\n parser.add_argument('-weights', type=str, required=True, help='the weights file you want to test')\n parser.add_argument('-gpu', action='store_true', default=False, help='use gpu or not')\n parser.add_argument('-b', type=int, default=16, help='batch size for dataloader')\n args = parser.parse_args()\n\n\n cifar100_test_loader,classes = get_test_dataloader(\n settings.CIFAR100_TRAIN_MEAN,\n settings.CIFAR100_TRAIN_STD,\n #settings.CIFAR100_PATH,\n num_workers=1,\n batch_size=1,\n )\n models = args.weights.split(\" \")\n networks = args.net.split(\" \")\n print(models, networks, classes)\n for i in range(len(models)):\n args.net = networks[i]\n net = get_network(args)\n #print(net)\n #print(summary(net,batch_size=-1, device='cuda'))\n model = models[i]\n evaluate(model,net,classes)\n\n\n","sub_path":"pytorch-cifar100/evaluate-all.py","file_name":"evaluate-all.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"136075191","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2021, Quantum Bit Core and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\nfrom restaurant_management.setup import install\nfrom erpnext.stock.get_item_details import get_pos_profile\n\n\nclass RestaurantSettings(Document):\n def on_update(self):\n frappe.publish_realtime(\"update_settings\")\n\n def settings_data(self):\n profile = frappe.db.get_value(\"User\", frappe.session.user, \"role_profile_name\")\n restaurant_settings = frappe.get_single(\"Restaurant Settings\")\n\n return dict(\n pos=self.pos_profile_data(),\n permissions=dict(\n invoice=frappe.permissions.get_doc_permissions(frappe.new_doc(\"Sales Invoice\")),\n order=frappe.permissions.get_doc_permissions(frappe.new_doc(\"Table Order\")),\n restaurant_object=frappe.permissions.get_doc_permissions(frappe.new_doc(\"Restaurant Object\")),\n ),\n restrictions=restaurant_settings,\n exceptions=[item for item in restaurant_settings.restaurant_permissions if item.role_profile == profile],\n lang=frappe.session.data.lang\n )\n\n @staticmethod\n def pos_profile_data():\n pos_profile = get_pos_profile(frappe.defaults.get_user_default('company'))\n\n return dict(\n has_pos=pos_profile is not None,\n pos=None if pos_profile is None else frappe.get_doc(\"POS Profile\", pos_profile.name)\n )\n\n\n@frappe.whitelist()\ndef reinstall():\n install.after_install()\n","sub_path":"restaurant_management/restaurant_management/doctype/restaurant_settings/restaurant_settings.py","file_name":"restaurant_settings.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"167718881","text":"VERSION_MAJOR = 0\nVERSION_MINOR = 0\nVERSION_BUILD = 1\nVERSION_INFO = (VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD)\nVERSION_STRING = \"%d.%d.%d\" % VERSION_INFO\nAUTHOR_NAME = \"Thibault Le Meur\"\nDESCRIPTION = \"Collection of widgets for Flask-Appbuilder\"\nAUTHOR_EMAIL = \"t.lemeur@gmail.com\"\n\n__version__ = VERSION_INFO\n\n","sub_path":"build/lib/fab_addon_turbowidgets/version.py","file_name":"version.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"500325546","text":"#!/usr/bin/python\n\nimport time\nimport datetime\n#import Settings\nimport threading\nimport logging\n\nlog = logging.getLogger('root')\n\n#import RPi.GPIO as GPIO\n\n#GPIO.setmode(GPIO.BCM)\n#pin =\n#GPIO.setup(pin, GPIO.OUT)\n\n\nclass Alarm(threading.Thread):\n\n def __init__(self):\n threading.Thread.__init__(self)\n self.stopping = False\n self.nextAlarm = None\n\n\n def stop(self):\n log.info(\"Alarm is stopping\")\n self.stopping = True\n\n\n def soundAlarm(self):\n log.info(\"Alarm triggered\")\n\t #self.media.soundAlarm()\n\t #timeout = 10 #\n\t #self.alarmTimeout = timeout\n\n def run(self):\n while(not self.stopping):\n\t now = datetime.datetime.now()\n\n if(self.nextAlarm is not None and self.nextAlarm < now):\n\t\t self.soundAlarm()","sub_path":"Alarm.py","file_name":"Alarm.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"593302809","text":"from django.db import models\n\n\n# Create your models here.\nfrom django.contrib.auth.models import User\nfrom django.contrib import admin\n\n\n# Used for displaying the barchart of daily MKS num \nclass DailyProgress(models.Model):\n remaining_MKS = models.IntegerField(null=False)\n reporting_date = models.DateField(unique=True, null=False)\n \n def __unicode__(self):\n return self.reporting_date.isoformat()\n\n# Customized the Django Admin Frontend\nclass DailyProgressAdmin(admin.ModelAdmin):\n date_hierarchy = 'reporting_date'\n list_display = ('reporting_date', 'remaining_MKS')\n","sub_path":"mysite/main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"91129730","text":"import random\nimport pygame\n\n\nclass Zombie(pygame.sprite.Sprite):\n def __init__(self):\n super(Zombie, self).__init__()\n self.image = pygame.image.load(\"../pvz/png/Zombie/pt/Zombie_000.png\").convert_alpha()\n self.images = [pygame.image.load(\"../pvz/png/Zombie/pt/Zombie_0{:02d}.png\".format(i)).convert_alpha() for i\n in range(0, 47)]\n self.dieimages = [pygame.image.load(\"../pvz/png/Zombie/die/Zombie_{:03d}.png\".format(i)).convert_alpha() for i\n in range(134, 172)]\n self.attack_images = [pygame.image.load(\"../pvz/png/Zombie/pt/Zombie_{:03d}.png\".format(i)).convert_alpha() for\n i\n in range(94, 133)]\n self.rect = self.images[0].get_rect()\n self.rect.top = 50 + random.randrange(0, 5) * 96\n self.energy = 10\n self.rect.left = 820\n self.speed = 1\n self.dietimes = 0\n self.GOGO = False\n self.Alive = True\n\n def update(self, *args, **kwargs) -> None:\n if self.energy > 0:\n if self.GOGO:\n self.image = self.attack_images[args[0] % len(self.attack_images)]\n else:\n self.image = self.images[args[0] % len(self.images)]\n if self.rect.left > -120 and not self.GOGO:\n self.rect.left -= self.speed\n else:\n if self.dietimes < 38:\n self.image = self.dieimages[self.dietimes]\n self.dietimes += 1\n else:\n if self.dietimes == 38:\n self.Alive = False\n self.kill()\n","sub_path":"pvz/zombie/Zombie.py","file_name":"Zombie.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"31827964","text":"def commons(universal_set, set):\n num_of_commons = 0\n for univ_el in universal_set:\n for el in set:\n if univ_el == el:\n num_of_commons += 1\n return num_of_commons\n\n\ndef set_diff(a, b):\n diff = []\n for a_el in a:\n has_common = False\n for b_el in b:\n if a_el == b_el:\n has_common = True\n break\n if not has_common:\n diff.append(a_el)\n return diff\n\n\ndef set_cover(universal_set, set_of_sets):\n solution_sets = []\n while len(universal_set) != 0:\n best_set = set_of_sets[0]\n best_commons_num = commons(universal_set, set_of_sets[0])\n for i in range(1, len(set_of_sets)):\n set = set_of_sets[i]\n num_of_commons = commons(universal_set, set)\n if num_of_commons > best_commons_num:\n best_set = set\n best_commons_num = num_of_commons\n universal_set = set_diff(universal_set, best_set)\n solution_sets.append(best_set)\n print(solution_sets)\n\n\nuniversal_set = [1, 2, 3, 4, 5, 6, 7, 8]\nset_of_sets = [[1, 2], [7, 8], [2, 3, 4, 5, 6, 7], [1, 2, 3, 4], [5, 6, 7, 8], [5, 6, 7]]\nset_cover(universal_set, set_of_sets)\n\n# time complexity: O(Σ of all S ∈ F: |S|) where F is a family of subsets of X,\n# such that every element of X belongs to at least one subset in F, where X is\n# a finite set referred to as the universal set\n","sub_path":"set-cover.py","file_name":"set-cover.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"130278680","text":"#Module commands: tools to import all modules from specific path, command engine and event engine\nimport importlib, os, utils, discord, difflib\nevents = {}\ncommands = {}\nmodules = {}\nbanned = ['__pycache__']\n\nclass ImportTools():\n def __init__(self, path=\"commands/\"):\n self.path = path\n def ImportFromPath(self):\n for pl in os.listdir(self.path):\n if pl not in banned:\n path = pl.replace(\".py\", \"\")\n spec = importlib.util.spec_from_file_location(path, \"{}{}\".format(self.path, pl))\n foo = importlib.util.module_from_spec(spec)\n modules.update({path:foo})\n spec.loader.exec_module(foo)\n def dynamic_reload(self, module):\n for k, v in modules.items():\n if k == module:\n modules.update({k:importlib.reload(v)})\n def reload_all(self, ):\n for k, v in modules.items():\n modules.update({k:importlib.reload(v)})\n def dynamic_import(self, module):\n spec = importlib.util.spec_from_file_location(module, \"{}{}.py\".format(self.path, module))\n foo = importlib.util.module_from_spec(spec)\n modules.update({module:foo})\n spec.loader.exec_module(foo)\nclass Event(object):\n def SetEvent(self, event, s, *args):\n if events.get(event) == None:\n return\n for d in events.get(event):\n for func, types in d.items():\n req = types[\"require\"]\n typeof = types[\"type\"]\n if typeof == \"sync\":\n if req == \"default\":\n func(*args)\n elif req == \"self\":\n func(s, *args)\n elif typeof == \"async\":\n if req == \"default\":\n utils.awaiter(func(*args))\n elif req == \"self\":\n utils.awaiter(func(s, *args))\n def event(self, event, require=\"default\", type=\"sync\"):\n def func_wrap(func):\n if event not in events.keys():\n events.update({event:[{func:{\"require\":require, \"type\":type}}]})\n else:\n events.get(event).append({func:{\"require\":require, \"type\":type}})\n return func_wrap\nclass Command(object):\n def event(self, command, require=\"default\", type=\"sync\", aliases=[]):\n def func_wrap(func):\n if command not in commands.keys():\n commands.update({command:[{func:{\"require\":require, \"type\":type}}]})\n for alias in aliases:\n commands.update({alias:[{func:{\"require\":require, \"type\":type}}]})\n else:\n commands.get(command).append({func:{\"require\":require, \"type\":type}})\n return func_wrap\ndef SetCommand(command, args, s):\n cmds = commands.keys()\n if command in cmds:\n msg = s[Locals.message]\n for d in commands.get(command):\n for func, types in d.items():\n typ = types[\"type\"]\n req = types[\"require\"]\n # Check if LS flag in message\n if args != None and args[-1] == \"!ls\":\n del args[-1]\n ls_flag = True\n # Then set args to None back\n if len(args) == 0:\n args = None\n else:\n ls_flag = False\n if typ == \"sync\":\n if req == \"dafault\":\n result = func(args)\n elif req == \"self\":\n result = func(s, args)\n elif req == \"message\":\n result = func(s[\"message\"], args)\n elif req == \"client\":\n result = func(s[\"client\"], args)\n else:\n result = func(args)\n utils.syncsender(command, msg, result, ls_flag=ls_flag)\n elif typ == \"async\":\n if req == \"dafault\":\n utils.awaiter(func(args))\n elif req == \"self\":\n utils.awaiter(func(s, args))\n elif req == \"messgae\":\n utils.awaiter(func(s[\"message\"], args))\n elif req == \"client\":\n utils.awaiter(func(s[\"client\"], args))\n else:\n SimillarList = difflib.get_close_matches(command, cmds)\n if len(SimillarList) >= 1:\n return SetCommand(SimillarList[0], args, s) \n return\n# Function to compare that all modules are descriped in packages.json at runtime\ndef compare():\n import settings\n settings = settings.settings(\"packages.json\")\n print(settings)\n for key in commands.keys():\n if key not in settings.keys():\n print(key)\nclass Locals:\n client = \"client\"\n message = \"message\"","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"373103142","text":"''' Configuration file for the program '''\n\nREGION = 'EUW'\nLOCALE = 'en_GB'\n\nRIOT_CLIENT_SERVICES_PATH = 'E:/Riot Games/Riot Client/RiotClientServices.exe'\nLEAGUE_CLIENT_PATH = 'E:/Riot Games/League of Legends/LeagueClient.exe'\nLEAGUE_CLIENT_PROCESS = 'LeagueClient.exe'\nRIOT_CLIENT_PROCESS = 'RiotClientServices.exe'\nRIOT_CLIENT_CONFIG = '~/AppData/Local/Riot Games/Riot Client/Config'\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"379076633","text":"import pygame\n\nclass Button:\n DARK_GREY = (29,29,29)\n\n def __init__(self, screen, x, y, width, height, text=\"\", color=(DARK_GREY), hover=()):\n self.screen = screen \n self.clicked = False\n\n self.height = height\n self.width = width\n self.text = text \n self.color = color\n\n self.hover = (color[0] + 10, color[1] + 10, color[2] + 10)\n\n self.x = x\n self.y = y\n \n self.font = pygame.font.SysFont(\"Arial\", 30)\n self.rect = pygame.Rect(x, y, width, height)\n self.rect.topleft = (x, y)\n \n def collides(self, pos):\n return self.rect.collidepoint(pos)\n\n def draw(self):\n color = self.color\n if self.collides(pygame.mouse.get_pos()):\n color = self.hover\n pygame.draw.rect(self.screen, color, self.rect)\n\n if len(self.text):\n text_img = self.font.render(self.text, True, (255,255,255))\n text_rect = text_img.get_rect(center=(self.rect.topleft[0] + (self.width // 2), self.rect.topleft[1] + (self.height // 2)))\n\n self.screen.blit(text_img, text_rect)\n","sub_path":"tictactoe/src/buttons/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"138312783","text":"from CRABClient.UserUtilities import config, getUsernameFromSiteDB\nconfig = config()\n\nconfig.General.requestName = 'NMSSM_XYH_bbbb_MX_300_MY_60_RECO_Run2016_v1'\nconfig.General.workArea = 'crab_projects_NMSSM_XYH_bbbb_MCproduction_RECO_Run2016_v1'\nconfig.General.transferOutputs = True\nconfig.General.transferLogs = False\nconfig.JobType.maxMemoryMB = 8000\n\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.psetName = 'NMSSM_XYH_bbbb_RECO_cfg.py'\n\nconfig.Data.inputDBS = 'phys03'\nconfig.Data.inputDataset = '/NMSSM_XYH_bbbb_MX_300_MY_60_madgraph242/fravera-crab_NMSSM_XYH_bbbb_MX_300_MY_60_DIGI_Run2016_v2-16ca0fac1b892ff3c3d45d801745cbbf/USER'\nconfig.Data.splitting = 'FileBased'\nconfig.Data.publication = True\nconfig.Data.unitsPerJob = 1\nconfig.Data.outLFNDirBase = '/store/user/%s/NMSSM_XYH_bbbb_RECO/' % (getUsernameFromSiteDB())\nconfig.Data.outputDatasetTag = 'crab_NMSSM_XYH_bbbb_MX_300_MY_60_RECO_Run2016_v1'\n\nconfig.Site.storageSite = 'T3_US_FNALLPC'\nconfig.JobType.numCores = 4\n\n","sub_path":"NMSSM/bbbb_Files/crab_NMSSM_XYH_bbbb_MX_300_MY_60_RECO_cfg.py","file_name":"crab_NMSSM_XYH_bbbb_MX_300_MY_60_RECO_cfg.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"642346872","text":"from django.conf.urls import url\nfrom django_cas_ng.views import login, logout\nfrom pages.views import *\n\nurlpatterns = [\n url(r'^$', home_page, name='home'),\n url(r'^home$', home_page),\n url(r'^events$', events_page, name='events'),\n url(r'^minecraft$', minecraft_page, name='minecraft'),\n url(r'^contact$', contact_page, name='contact'),\n url(r'^auth$', auth_page),\n url(r'^login$', login, name='login'),\n url(r'^logout$', logout, name='logout'), \n]\n","sub_path":"pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"526075722","text":"import struct\nimport sys\n\nregistroCEP = struct.Struct(\"72s72s72s72s2s8s2s\")\ncepColumn = 5\nf = open(\"cep_ordenado.dat\",\"rb\")\nf.seek(0, 2)\ntamanhoBytes = f.tell()\ninicio = 0\nfim = tamanhoBytes//registroCEP.size\ncepProc = b'22725031'\ncounter = 0\n\nwhile( inicio < fim):\n\tcounter+=1\n\tmeio = (inicio+fim)//2\n\tf.seek(meio,0)\n\tline = f.read(registroCEP.size)\n\trecord = registroCEP.unpack(line)\n\tprint(record[cepColumn])\n\tif record[cepColumn] < cepProc:\n\t\tinicio = meio + 1\n\telif record[cepColumn] > cepProc:\n\t\tfim = meio - 1\n\telse:\n\t\tprint(record[0])\n\t\tbreak\n\nf.close()\nprint(counter)\n\n","sub_path":"buscabi.py","file_name":"buscabi.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"528667098","text":"import os\nimport yaml\nimport keras\nimport builtin_models.utils as utils\n\nFLAVOR_NAME = \"keras\"\nMODEL_FILE_NAME = \"model.h5\"\n\n\ndef _get_default_conda_env():\n import tensorflow as tf\n return utils.generate_conda_env(\n additional_pip_deps=[\n \"keras=={}\".format(keras.__version__),\n \"tensorflow=={}\".format(tf.__version__),\n ])\n\n\ndef load_model_from_local_file(path):\n from keras.models import load_model\n return load_model(path)\n\n\ndef save_model(keras_model, path='./model/', conda_env=None):\n \"\"\"\n Save a Keras model to a path on the local file system.\n\n :param keras_model: Keras model to be saved. \n\n :param path: Path to a directory containing model data.\n \n :param conda_env: Either a dictionary representation of a Conda environment or the path to a conda environment yaml file. \n \"\"\"\n if(not path.endswith('/')):\n path += '/'\n if not os.path.exists(path):\n os.makedirs(path)\n\n keras_model.save(os.path.join(path, MODEL_FILE_NAME)) \n\n if conda_env is None:\n conda_env = _get_default_conda_env()\n utils.save_conda_env(path, conda_env)\n\n utils.save_model_spec(path, FLAVOR_NAME, MODEL_FILE_NAME)\n utils.generate_ilearner_files(path) # temp solution, to remove later\n\n ","sub_path":"builtin-models/builtin_models/keras.py","file_name":"keras.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"18094961","text":"from pico2d import * # C:\\Users\\enjcat\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages\\pico2d\nimport game_framework\nimport random\nimport game_world\nimport random\nimport Wepon\n\n\ndicts = {0:Wepon.stick,1:Wepon.sword,2:Wepon.ice,3:Wepon.fire,4:Wepon.wand,5:Wepon.heal}\n\nclass Tower:\n def __init__(self):\n print(\"Creating..\")\n self.image = load_image('./res/popmap.png')\n self.x = 150\n self.y = 150\n self.frame = 0\n self.speed = 3\n self.on = 0\n def draw(self):\n self.image.clip_draw(int(self.frame) * 200, 0, 200, 200, get_canvas_width()/2, get_canvas_height()/2)\n def update(self):\n if(self.on == 1):\n self.frame = self.frame + 0.2\n if self.frame >= 4:\n self.on = 0\n rand = random.randint(0,100)\n if(rand < 40):\n game_world.add_object(dicts[5](),game_world.layer_obstacle)\n elif(rand < 65):\n game_world.add_object(dicts[0](),game_world.layer_obstacle)\n elif(rand < 85):\n game_world.add_object(dicts[1](),game_world.layer_obstacle)\n elif(rand < 92):\n game_world.add_object(dicts[2](),game_world.layer_obstacle)\n elif(rand < 99):\n game_world.add_object(dicts[3](),game_world.layer_obstacle)\n elif(rand < 100):\n game_world.add_object(dicts[4](),game_world.layer_obstacle)\n if(self.on == 0 and self.frame > 0):\n self.frame -= 0.2\n\n def pop(self):\n self.on = 1\n\n\n \n\n\n\n\n","sub_path":"3-2/2D게임프로그래밍/2Dgame/term/Holy.py","file_name":"Holy.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"60732540","text":"import threading\nimport wget\nimport os\nimport re\nfrom urllib import request\n\n\ndef down_data(url, fname):\n html = request.urlopen(url)\n with open(fname, 'wb') as fobj:\n while True:\n data = html.read(1024)\n if not data:\n break\n fobj.write(data)\n\n\ndef url_list(fname, patt, encoding=None):\n urls = []\n cpatt = re.compile(patt)\n with open(fname) as fobj:\n for line in fobj:\n\n for m in cpatt.finditer(line):\n urls.append(m.group())\n return urls\n\n\ndef wget_data(url, dest):\n wget.download(url, dest)\n\n\nif __name__ == '__main__':\n url = 'http://www.ifeng.com'\n fname = '/tmp/ifeng.html'\n patt = '(http|https)://[-\\w./_]+\\.(png|jpg|jpeg|gif)'\n encode = ''\n # down_data(url, fname)\n urls = url_list(fname, patt, None)\n print(len(urls))\n dest = '/tmp/ifeng/'\n if not os.path.exists(dest):\n os.mkdir(dest)\n for u in urls:\n print(u)\n t = threading.Thread(wget_data(u, dest))\n t.start()\n","sub_path":"devops/day3/thread_wget.py","file_name":"thread_wget.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"462573471","text":"from tkinter import *\nfrom psgsql import *\nfrom tkinter import messagebox\nimport random\nimport time\nimport config\nimport difftexts as diff\nimport datetime\nfrom itertools import chain\n\n# ================= Interface parameters =======================\ntitle_string = \"Anecdotes\"\nwin_geometry = \"900x600+10+10\"\nbg_of_view_area = \"powder blue\"\nfg_of_view_area = \"Steel Blue\"\ntitle_font = (\"arial\", 30, \"bold\")\ninfo_font = (\"arial\", 10)\ntext_font = (\"arial\", 14)\nbg_of_edit_area = \"pink\"\nfg_of_edit_area = \"Steel Blue\"\n\n# ================= Functions ==================================\n\n\ndef close(event=None):\n root.destroy()\n print(\" Exiting...\")\n exit()\n\n\ndef tick(lbl):\n \"\"\"\n Display current time in lbl\n :param lbl:\n :return:\n \"\"\"\n # get the current local time\n localtime = time.strftime(\"%a, %d %b %Y %H:%M:%S %z\", time.localtime(time.time()))\n lbl.config(text=localtime)\n # calls itself every 200 milliseconds\n # to update the time display as needed\n # could use >200 ms, but display gets jerky\n lbl.after(200, tick, lbl)\n\n# ==================== Classes ================================\n\nclass ListBoxChoice(object):\n def __init__(self, parent_window, data):\n self.master = parent_window\n self.data = data\n self.view_bg = \"powder blue\"\n self.edit_bg = \"pink\"\n self.fg = \"Steel Blue\"\n self.listfg = \"black\"\n self.text_font = (\"arial\", 14)\n self.list_font = (\"arial\", 15, \"bold\")\n self.qtywin = qtyInfo\n self.new = False\n self.key = 0\n self.after_check = False\n self.oldkey = 0\n self.listframe = Frame(self.master)\n self.listframe.pack(side=LEFT, fill=Y)\n self.listframe.tk_focusFollowsMouse()\n self.listscrollbar = Scrollbar(self.listframe)\n self.listscrollbar.pack(side=RIGHT, fill=Y)\n self.listbox = Listbox(self.listframe, font=self.list_font, fg=self.listfg, bg=self.view_bg, bd=5, width=5)\n self.listbox.pack(side=LEFT, fill=Y)\n self.listscrollbar.config(command=self.listbox.yview)\n self.listbox.config(yscrollcommand=self.listscrollbar.set)\n self.textframe = Frame(self.master)\n self.textframe.pack(side=RIGHT, fill=Y)\n self.textbox = Text(self.textframe, font=self.text_font, wrap='word', bg=self.edit_bg, bd=5, width=72)\n self.textbox.pack(side=LEFT, fill=Y, padx=0, pady=0)\n self.textscrollbar = Scrollbar(self.textframe)\n self.textscrollbar.pack(side=RIGHT, fill=Y)\n self.textscrollbar.config(command=self.textbox.yview)\n self.textbox.config(yscrollcommand=self.textscrollbar.set)\n self._qty(self.qtywin)\n self._build_listbox()\n self.master.bind(\"\", self._view)\n self.master.bind(\"\", self._view)\n self.master.bind(\"\", self._view)\n self.master.bind(\"\", self._view)\n self.master.bind(\"\", self._view)\n self.listbox.bind('', self._delete)\n # viewBtn.config(command=self._view)\n newBtn.config(command=self._add)\n editBtn.config(command=self._edit)\n deleteBtn.config(command=self._delete)\n searchBtn.config(command=self._search)\n checkDbBtn.config(command=self._checkDB)\n AllBtn.config(command=self._all)\n\n\n def _qty(self, lbl):\n \"\"\"\n How much items selected from the DataBase\n :param lbl:\n :return:\n \"\"\"\n self.qty_string = f\"There are {self.data.len()} items in the DataBase\"\n lbl.config(text=self.qty_string)\n\n def _build_listbox(self):\n # print(\"Building listbox!...\\n keys = \", self.key, self.oldkey)\n self.listbox.delete(0, END) # Очистка списка анекдотов\n self.fltr = searchWin.get()\n if self.fltr:\n self.fltr = [('anecdote', self.fltr)] # Считывание подстроки из окна searchWin\n if not self.after_check:\n self.lst = sorted(self.data.keys(self.fltr)) # Получение списка ключей для отображениея\n self.len = len(self.lst)\n #print(self.lst)\n if self.len > 0:\n # Словарь, где ключ - id отобранных анекдотов, а значение - порядковый номер\n self.dct = {self.lst[i]: i for i in range(self.len)}\n #\n for item in self.lst:\n self.listbox.insert(END, item)\n if self.new:\n self.dct = {self.lst[i]: i for i in range(self.len)}\n self.new = False\n else:\n self.key = random.choice(self.lst)\n print(self.key)\n self._sel()\n self._view()\n else:\n # Если список пуст, ничего не делаем\n self.key = 0\n self._qty(self.qtywin)\n\n def _add(self):\n print(\"_add: key=\", self.key)\n self.new = True\n self.oldkey = self.key\n self.key = 0\n self._edit()\n\n def _edit(self):\n # print(\"_edit: key=\", self.key)\n self.Edit = Toplevel(self.master)\n self.master.attributes('-disabled', 1)\n self.Edit.transient(self.master)\n self.Edit.title(\"Editing.....\")\n self.tmp_panel = Frame(self.Edit, height=50, width=800, bg=self.view_bg)\n self.tmp_panel.pack(side='top', fill='x')\n self.tmp_textbox = Text(self.Edit, font=self.text_font, wrap='word', bg=self.edit_bg,\n bd=5, width=72)\n self.tmp_textbox.pack(side=LEFT, fill=Y, padx=0, pady=0)\n self.saveBtn = Button(self.tmp_panel, text='Save', command=self._save)\n self.saveBtn.place(x=10, y=10, width=40, height=40)\n self.cancelBtn = Button(self.tmp_panel, text='Cancel', command=self._cancel)\n self.cancelBtn.place(x=50, y=10, width=40, height=40)\n self.tmp_textbox.configure(state=\"normal\")\n self.tmp_textbox.delete('1.0', 'end')\n if self.key > 0:\n self.value = self.data.get(self.key)\n self.tmp_textbox.insert('1.0', self.value['anecdote'])\n\n\n def _cancel(self):\n # print(\"_cancel: key=\", self.key)\n if messagebox.askyesno(\"Edit\", \"All changes will be lost Are you sure?\", default=\"no\"):\n self.new = False\n self.Edit.destroy()\n self.master.attributes('-disabled', 0)\n if self.key == 0 and self.oldkey != 0:\n self.key = self.oldkey\n self.oldkey = 0\n self._view()\n\n def _save(self):\n # print(\"_save: key=\", self.key)\n if messagebox.askyesno(\"Edit\", \"All changes will be saved Are you sure?\", default=\"no\"):\n edited = self.tmp_textbox.get('1.0', 'end')\n if self.key == 0:\n record = Record({config.anecdot_params['value_column']: edited})\n self.key = self.data.add(record)\n\n else:\n record = Record({config.anecdot_params['key_column']: self.key,\n config.anecdot_params['value_column']: edited})\n self.key = self.data.update(record)\n # print(\"_save: key=\", self.key)\n self.oldkey = 0\n if self.new:\n self._build_listbox()\n # self.tmp_textbox.destroy()\n self.Edit.destroy()\n self.master.attributes('-disabled', 0)\n self.listbox.focus_force()\n self._view()\n return\n\n def _delete(self, event=None):\n # print(\"_delete: key=\", self.key)\n if messagebox.askyesno(\"Delete\", \"Are you sure?\", default=\"no\"):\n self.idx = self.listbox.curselection()[0]\n self.key = self.lst[int(self.idx)]\n # print(\"Delete: \", self.key)\n self.data.delete(self.key)\n self.textbox.configure(state=\"normal\")\n self.textbox.delete('1.0', 'end')\n self.textbox.configure(state=\"disabled\")\n self._build_listbox()\n\n def _view(self, event=None):\n # print(\"_view: key= \", self.key, self.new)\n if not self.new:\n selection = self.listbox.curselection()\n if self.len > 0 and len(selection) > 0:\n self.idx = selection[0]\n self.key = self.lst[int(self.idx)]\n\n self.value = self.data.get(self.key)\n self.textbox.configure(state=\"normal\")\n self.textbox.delete('1.0', 'end')\n if self.value is not None:\n creation_date = self.value['creationdate'] if self.value['creationdate'] is not None else None\n CreationTime.config(text=f\"Creation Date: {creation_date}\")\n Votes.config(text=f\"Votes: {self.value['votes']}\")\n Rating.config(text=f\"Rating: {self.value['rating']}\")\n self.textbox.insert('1.0', self.value['anecdote'])\n self.textbox.configure(state=\"disabled\")\n self.new = False\n\n def _sel(self):\n \"\"\"\n Установка курсора на элементе, соответствующем self.key при запуске программы\n :return:\n \"\"\"\n self.ind = self.dct.get(self.key)\n print(\"_sel: \", self.key, self.ind)\n self.listbox.see(self.ind)\n self.listbox.activate(self.ind)\n # self.listbox.selection_anchor(self.ind)\n self.listbox.selection_set(self.ind)\n self.listbox.focus_set()\n\n def _search(self):\n self.textbox.configure(state=\"normal\")\n self.textbox.delete('1.0', 'end')\n self.textbox.configure(state=\"disable\")\n self._build_listbox()\n\n def _checkDB(self):\n #\n # Looking for dublicates\n #\n all = self.data.getall()\n dublicates = [(i['id'], k['id']) for i in all for k in all if i['id'] > k['id']\n and diff.compareText(i['anecdote'], k['anecdote'])]\n if len(dublicates) > 0:\n self.after_check = True\n print(dublicates)\n self.lst = list(chain.from_iterable(dublicates))\n self._build_listbox()\n\n def _all(self):\n self.after_check = False\n searchWin.delete(0, 'end')\n self._build_listbox()\n\n\n# ================================== Main ===============================================\n\nif __name__ == '__main__':\n with OpenDB(config.db_params) as a:\n anecdotes = SqlDBTable(a, config.anecdot_params)\n root = Tk()\n root.protocol(\"WM_DELETE_WINDOW\", close)\n root.geometry(win_geometry)\n root.title(title_string)\n root.resizable(False, False)\n\n # ===================================== Title ===============================================\n\n Tops = Frame(root, width=800, height=50, bg=bg_of_view_area, borderwidth=5)\n Tops.pack(side=TOP)\n lblInfo = Label(Tops, font=title_font, text=title_string, fg=fg_of_view_area)\n lblInfo.grid(row=0, column=0, columnspan=2)\n\n # ===================================== Status =============================================\n\n Status = Frame(root, width=800, height=40, bg=bg_of_view_area, borderwidth=5)\n Status.pack(side=BOTTOM)\n CreationTime = Label(Status, font=info_font, text=\"CreationTime:\", fg=fg_of_view_area)\n CreationTime.grid(row=0, column=700, columnspan=100)\n Votes = Label(Status, font=info_font, text=\"Votes:\", fg=fg_of_view_area)\n Votes.grid(row=0, column=400, columnspan=100)\n Rating = Label(Status, font=info_font, text=\"Rating:\", fg=fg_of_view_area)\n Rating.grid(row=0, column=0, columnspan=100)\n\n # ====================== Clock in the title ===========================================\n\n clock = Label(Tops, font=info_font, fg=fg_of_view_area)\n clock.grid(row=1, column=1)\n tick(clock)\n\n # =================Number of anecdotes in the DB in the title ==============================\n\n qtyInfo = Label(Tops, font=info_font, fg=fg_of_view_area)\n qtyInfo.grid(row=1, column=0, pady=0, padx=1)\n\n # ===================== Menu ============================================================\n panelFrame = Frame(root, height=50, width=800, bg=bg_of_view_area)\n panelFrame.pack(side='top', fill='x')\n editBtn = Button(panelFrame, text='Edit')\n editBtn.place(x=10, y=10, width=40, height=40)\n deleteBtn = Button(panelFrame, text='Delete')\n deleteBtn.place(x=50, y=10, width=40, height=40)\n newBtn = Button(panelFrame, text='New')\n newBtn.place(x=90, y=10, width=40, height=40)\n quitBtn = Button(panelFrame, text='Quit', command=close)\n quitBtn.place(x=130, y=10, width=40, height=40)\n searchWin = Entry(panelFrame, justify=CENTER)\n searchWin.place(x=650, y=10, width=150, height=40)\n searchBtn = Button(panelFrame, text='Search')\n searchBtn.place(x=800, y=10, width=40, height=40)\n checkDbBtn = Button(panelFrame, text='CheckDB')\n checkDbBtn.place(x=550, y=10, width=70, height=40)\n AllBtn = Button(panelFrame, text='All')\n AllBtn.place(x=500, y=10, width=40, height=40)\n root.bind('', close)\n\n # ===================== View area =======================================================\n\n ListBoxChoice(root, anecdotes)\n\n root.mainloop()\n","sub_path":"anecdotes.py","file_name":"anecdotes.py","file_ext":"py","file_size_in_byte":13531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"628597573","text":"# -*- coding:utf-8\n\nimport sys, os\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\n\nclass fileInfo():\n def __init__(self,o_id,name,size, c_time,m_time,owner):\n self.id = o_id\n self.name = name\n self.size = size\n self.c_time = c_time\n self.m_time = m_time\n self.owner = owner\n\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super(MainWindow, self).__init__()\n self.drawlayout()\n self.setCentralWidget(self.fileList)\n\n\n\n def drawlayout(self):\n self.fileList = QTableWidget(0,5)\n self.fileList.setHorizontalHeaderLabels(QStringList([u\"名称\",u\"大小\",u\"创建时间\",u\"最后修改时间\",u\"创建者\"]))\n self.fileList.setShowGrid(True)\n self.fileList.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.fileList.setSelectionBehavior(QAbstractItemView.SelectRows)\n hHeader = self.fileList.horizontalHeader()\n hHeader.setHighlightSections(False)\n self.fileList.verticalHeader().hide()\n\n def insertmyrow(self,fileinfo):\n row = self.fileList.rowCount()\n self.fileList.insertRow(row)\n self.fileList.setItem(row,0,QTableWidgetItem(fileinfo.name))\n self.fileList.setItem(row,1,QTableWidgetItem(fileinfo.size))\n self.fileList.setItem(row,2,QTableWidgetItem(fileinfo.c_time))\n self.fileList.setItem(row,3,QTableWidgetItem(fileinfo.m_time))\n self.fileList.setItem(row,4,QTableWidgetItem(fileinfo.owner))\n\n\ndef main():\n app = QApplication(sys.argv)\n win = MainWindow()\n win.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"110819444","text":"def dychoose(string:str,List:list):\n print(\"after op: {}\".format(string))\n if len(string)==m: return \n temp0 = string[-num+1:]+'0'\n if temp0 in lists:\n print(\"operate: {}\".format(temp0))\n temp_0 = List.copy()\n temp_0.remove(temp0)\n dychoose(string+'0',temp_0)\n temp1 = string[-num+1:]+'1'\n if temp1 in lists:\n print(\"operate:{}\".format(temp1))\n temp_1 = List.copy()\n temp_1.remove(temp1)\n dychoose(string+'1',temp_1)\n\nnum = int(input())\nm = 2**num\nlists = [bin(i).replace('0b','0'*num)[-num:] for i in range(m)]\nstrs = ''\npossible = list()\nstrs = strs +lists[0]\nlists.pop(0)\ndychoose(strs,lists)\npossible.sort()\nprint(\"{} {}\".format(m,possible[0]))","sub_path":"Code/CodeRecords/2303/60716/286415.py","file_name":"286415.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"580124411","text":"\"\"\"\nContactless Characterisation of Oscillating 2D Material Membranes through\nNon-linear Transduction in Fabry-Perot Interferometry\n\nNumerical Implementation of Calibration Method\n\nWritten by Alex Nunn\n\"\"\"\n\nimport numpy as np\nfrom numpy import *\nfrom scipy.special import jv\nfrom scipy.optimize import minimize, least_squares\nfrom scipy.fftpack import fft\n\n\n\"\"\"Refractive Index Definitions\"\"\"\nn0 = 1\nn1 = 2.6 - 1.3j\nn2 = 1\nn3 = 5.6 - 0.4j\n\n\"\"\"\nIntensity Function Definitions\n\nThe following functions compute complex constants of the intensity function,\nthe intensity function itself and derivatives of the intensity function with\nrespect to the quantities 'p1' and 'p2' which correspond to the symbolic\nquantities $d_1 / \\lambda$ and $d_2 / \\lambda$, respectively.\n\"\"\"\nrform = lambda a, b: (a - b)/(a + b)\nr1, r2, r3 = rform(n0, n1), rform(n1,n2), rform(n2, n3)\n\nc = 2 * pi * n1\nc2 = 2 * pi * n2\n\na1 = lambda d: r1 * exp(1j * c * d) + r2 * exp(-1j * c * d)\na2 = lambda d: r1 * r2 * r3 * exp(1j * c * d) + r3 * exp(-1j * c * d)\na3 = lambda d: exp(1j * c * d) + r1 * r2 * exp(-1j * c * d)\na4 = lambda d: r2 * r3 * exp(1j * c * d) + r1 * r3 * exp(-1j * c * d)\n\na1d = lambda d: 1j * c * (r1 * exp(1j * c * d) - r2 * exp(-1j * c * d))\na2d = lambda d: 1j * c * (r1 * r2 * r3 * exp(1j * c * d) - r3 * exp(-1j * c * d))\na3d = lambda d: 1j * c * (exp(1j * c * d) - r1 * r2 * exp(-1j * c * d))\na4d = lambda d: 1j * c * (r2 * r3 * exp(1j * c * d) - r1 * r3 * exp(-1j * c * d))\n\ndef form(p1, p2, a1, a2):\n \"\"\"Returns a useful algebraic form for computing the intensity function\"\"\"\n return abs(a1(p1)) ** 2 + abs(a2(p1)) ** 2 + 2 * real(a1(p1) * conj(a2(p1)) * exp(2j * c2 * p2))\n\ndef form_deriv_p1(p1, p2, a, ad, b, bd):\n \"\"\"Return symbolic derivative of 'form' with respect to p1\"\"\"\n return 2 * real(conj(a(p1)) * ad(p1) + conj(b(p1)) * bd(p1) + (ad(p1) * conj(b(p1)) + a(p1) * conj(bd(p1))) * exp(2j * c2 * p2))\n\ndef form_deriv_p2(p1, p2, a, b):\n \"\"\"Return symbolic derivative of 'form' with respect to p2\"\"\"\n return 2 * real(2j * c2 * a(p1) * conj(b(p1)) * exp(2j * c2 * p2))\n\ndef f(p1, p2):\n \"\"\"\n Return intensity function of reflected light\n\n The arguments 'p1' and 'p2' correspond to $d_1 /\\lambda$ and $d_2 /\\lambda$\n \"\"\"\n return form(p1, p2, a1, a2) / form(p1, p2, a3, a4)\n\ndef f_deriv_p1(p1, p2):\n \"\"\"Derivative of intensity function with respect to p1\"\"\"\n return (form_deriv_p1(p1, p2, a1, a1d, a2, a2d) * form(p1, p2, a3, a4) - form(p1, p2, a1, a2) * form_deriv_p1(p1, p2, a3, a3d, a4, a4d)) / form(p1, p2, a3, a4) ** 2\n\ndef f_deriv_p2(p1, p2):\n \"\"\"Derivative of intensity function with respect to p2\"\"\"\n return (form_deriv_p2(p1, p2, a1, a2) * form(p1, p2, a3, a4) - form(p1, p2, a1, a2) * form_deriv_p2(p1, p2, a3, a4)) / form(p1, p2, a3, a4) ** 2\n\n\"\"\"\nExact Fourier Series Functions\n\nThe following functions are used to compute the Fourier coefficients in the\nFourier series for the intensity function in terms of $\\phi_2$.\n\"\"\"\ndef series_parameters(p1):\n \"\"\"Return series parameters (c, sigma, d)\"\"\"\n c = (a1(p1) * np.conj(a2(p1)))/ (a3(p1) * np.conj(a4(p1)))\n sigma1 = - np.conj(a3(p1)) / np.conj(a4(p1))\n sigma2 = - a4(p1) / a3(p1)\n d1 = (a2(p1) * np.conj(a1(p1)) + a1(p1) * np.conj(a2(p1)) * sigma1 ** 2 + sigma1 * (np.abs(a1(p1)) ** 2 + np.abs(a2(p1)) ** 2 )) / (np.abs(a4(p1)) ** 2 - np.abs(a3(p1)) ** 2)\n d2 = -(a2(p1) * np.conj(a1(p1)) + a1(p1) * np.conj(a2(p1)) * sigma2 ** 2 + sigma2 * (np.abs(a1(p1)) ** 2 + np.abs(a2(p1)) ** 2 )) / (np.abs(a4(p1)) ** 2 - np.abs(a3(p1)) ** 2)\n\n if np.abs(sigma1) > 1:\n return (c, sigma1, d1)\n else:\n return (c, sigma2, d2)\n\n\ndef fourier_coeff_mag(p1, n):\n \"\"\"\n Return fourier coefficient magnitude\n\n :param p1: parameter $d_1/\\lambda$\n :param n: index of Fourier coefficient magnitude\n \"\"\"\n c, sigma, d = series_parameters(p1)\n if n == 0:\n return np.real(c - d/sigma)\n else:\n return np.abs(2 * d / sigma ** (n+1))\n\n\ndef fourier_coeff_phase(p1, n):\n \"\"\"\n Return fourier coefficient phase\n\n :param p1: paramter $d_1/\\lambda$\n :param n: index of Fourier coefficient magnitude\n \"\"\"\n if n == 0:\n return 0\n else:\n c, sigma, d = series_parameters(p1)\n return np.angle(-d / sigma ** (n + 1))\n\n\"\"\"Analytic Predictors\"\"\"\ndef predictor_delta(p1, a):\n def f(z, b1, b2, a):\n d1 = jv(1, 2 * z) * jv(3, z) - jv(1, z) * jv(3, 2 * z)\n d2 = jv(2, 2 * z) * jv(4, z) - jv(2, z) * jv(4, 2 * z)\n\n term1 = (a[2]* jv(1, z) / a[0] - jv(3, z)) ** 2 + (a[3] * jv(2, z) / a[0] - a[1] * jv(4, z) / a[0]) **2 * (d1 / d2)**2\n term2 = (b2 / b1) ** 2 * ((a[2] * jv(1, 2*z) / a[0] - jv(3, 2*z)) ** 2 + (a[3] * jv(2, 2 * z) / a[0] - a[1] * jv(4, 2 * z) / a[0]) ** 2 * (d1 / d2)**2)\n return term1 / term2 - 1\n\n b1 = fourier_coeff_mag(p1, 1)\n b2 = fourier_coeff_mag(p1, 2)\n\n x0s = [1, 2, 3]\n x_least = np.inf\n for x0 in x0s:\n sol = minimize(f, x0=x0, args=(b1, b2, a,), method='BFGS', options=dict(gtol=1e-8))\n if sol.x[0] > 2e-2 and x_least > sol.x[0]:\n x_least = sol.x[0]\n\n return x_least\n\n\ndef predictor_alpha_delta(p1, a):\n \"\"\"Return prediction of alpha, delta, g using extended analytic method\"\"\"\n # Fourier Series Form Parameters\n phase1 = fourier_coeff_phase(p1, 1)\n phase2 = fourier_coeff_phase(p1, 2)\n b1 = fourier_coeff_mag(p1, 1)\n\n # Predict delta Value\n z = predictor_delta(p1, a)\n delta = z / (4 * np.pi)\n\n # Recurring Forms\n d1 = jv(1, 2 * z) * jv(3, z) - jv(1, z) * jv(3, 2 * z)\n d2 = jv(2, 2 * z) * jv(4, z) - jv(2, z) * jv(4, 2 * z)\n\n alpha = np.abs(np.sqrt(((a[2] / a[0] * jv(1, 2 * z) - jv(3, 2 * z)) / d1)**2 + ((a[3] / a[0] * jv(2, 2 * z) - a[1] / a[0] * jv(4, 2 * z))/ d2) **2) * a[0] / (2* b1))\n\n return alpha, delta\n\n\n\"\"\"Fitting Methods\"\"\"\ndef inverse_scenario1(amps):\n \"\"\"\n Numerical fitting method for unknown thickness\n\n From calibration problem amplitudes the unknown parameters of\n - membrane thickness p1,\n - average position g,\n - oscillation amplitude delta\n - apparatus constant $\\alpha$\n are inferred.\n\n IMPLEMENTATION DETAILS:\n Using the scipy implementation of non-linear least square fitting method\n 'Trust Region Reflective algorithm' we fit the parameter vector x where\n\n x[0] : g\n x[1] : delta\n x[2] : d1\n x[3] : alpha\n \"\"\"\n\n n = 2 ** 5 # number of collocation points for FFT\n m = len(amps) # number of amplitudes used in fitting method\n pts = linspace(0, 2*pi, n, endpoint=False) # collocation points\n cpts = cos(pts) # cosine value at collocation points\n\n mat = np.exp(-2 * np.pi * 1j * np.arange(1, m + 1)[:, np.newaxis] * np.arange(n)/n)\n\n def h(x):\n \"\"\"Returns FFT amplitudes {c_n} for parameter values x\"\"\"\n return 2 / n * x[3] * np.abs(mat @ f(x[2], x[0] + x[1] * cpts))\n\n def h_jac(x):\n \"\"\"Returns jacobian derivative matrix of FFT amplitudes {c_n} w.r.t parameter values x\"\"\"\n jac = np.zeros((len(amps), 4))\n\n v = f(x[2], x[0] + x[1] * cpts)\n v_h = f_deriv_p2(x[2], x[0] + x[1] * cpts)\n v_delta = v_h * cpts\n v_d1 = f_deriv_p1(x[2], x[0] + x[1] * cpts)\n\n c = 2 / n * mat @ v\n c_h = 2 / n * mat @ v_h\n c_delta = 2 / n * mat @ v_delta\n c_d1 = 2 / n * mat @ v_d1\n\n jac[:,0] = x[3] * np.real(c_h * np.conj(c)) / np.abs(c)\n jac[:,1] = x[3] * np.real(c_delta * np.conj(c)) / np.abs(c)\n jac[:,2] = x[3] * np.real(c_d1 * np.conj(c)) / np.abs(c)\n jac[:,3] = np.abs(c)\n return jac\n\n # Definition of cost functions with scaling\n fac = 10 ** 3 * 4 ** np.arange(len(amps))\n cost_mod = lambda x: fac * (h(x) - np.abs(amps))\n h_jac_mod = lambda x: h_jac(x) * fac[:, np.newaxis]\n\n # Non-linear least squares fit\n p1_values = [0.001, 0.003, 0.005, 0.007]\n sols = []\n\n # Find a rough solution\n for p1 in p1_values:\n # Predictors (based on analytic formulae)\n alpha, delta = predictor_alpha_delta(p1, amps)\n\n for g in np.linspace(0, 0.5, 20):\n sol = least_squares(\n cost_mod,\n [g, delta, p1, alpha],\n jac=h_jac_mod,\n bounds=(0, np.inf),\n method='trf',\n max_nfev=200\n )\n sols.append(sol)\n\n # Check similar function points\n best_sol = sorted(sols, key=lambda x: x.cost)[0]\n g_similar = (0.25 - fourier_coeff_phase(p1, 1) / (2 * pi) - best_sol.x[0]) % 0.5\n sol = least_squares(\n cost_mod,\n [g_similar, delta, p1, alpha],\n jac=h_jac_mod,\n bounds=(0, np.inf),\n method='trf',\n max_nfev=200\n )\n sols.append(sol)\n\n # Take best of the solutions\n best_sol_rough = sorted(sols, key=lambda x: x.cost)[0]\n\n # Refine best solution\n best_sol = least_squares(\n cost_mod,\n best_sol_rough.x,\n jac=h_jac_mod,\n bounds=(0, np.inf),\n method='trf',\n gtol=1e-12,\n ftol=1e-12,\n xtol=1e-12\n )\n\n return best_sol\n\n\ndef inverse_scenario2(amps):\n pass\n\n\n\"\"\"Convenience Functions\"\"\"\ndef compute_amps(p1, p2_func):\n \"\"\"\n Returns FFT amplitudes for the time series of intensity function with time varying p2 value\n\n The value of 'p1' is fixed and the time series of 'f(p1, p2_func(t))' is\n computed over the interval t = 0, ..., 2 \\pi. The FFT of the time series is\n then taken and the first 10 amplitudes are returned.\n\n :param p1: value of parameter $d_1 /\\lambda$\n :param p2_func: time varying function of 'p2' parameter value\n\n :return nd.array: length 10, real values\n \"\"\"\n N = 2 ** 8 # number of points in time-series (fixed constant)\n x = np.linspace(0, 2*pi, N, endpoint=False)\n data = 2 / N * fft(f(p1, p2_func(x)))\n amps = np.real( 1/2 *(data[1:11] + data[-1:-11:-1]))\n amps[np.abs(amps) < 1e-12] = 0 # chop small amplitudes\n return np.abs(amps)\n\n\ndef compute_amps_simple_osc(p1, g, delta):\n \"\"\"\n Return FFT amplitudes for the times series of intensity function with simple oscillation in p2 value\n\n :param p1: symbolic parameter $d_1 /\\lambda$\n :param g: average position (corresponds to $g / \\lambda$)\n :param delta: amplitudeo of oscillation (corresponds to $\\delta /\\lambda$)\n\n :return nd.array: length 10, real values\n \"\"\"\n p2_func = lambda x: g + delta * np.cos(x)\n return compute_amps(p1, p2_func)\n\n\ndef rel_error(x, y):\n \"\"\"Return relative error in 'y' if 'x' is the correct value\"\"\"\n try:\n # Cast to numpy arrays\n x_a = np.array(x)\n y_a = np.array(y)\n errors = np.zeros_like(x_a, dtype='float')\n\n # True value is zero\n m = x_a == 0\n errors[m] = np.abs(y_a[m])\n\n # True value is non-zero\n m = x_a != 0\n errors[m] = np.abs((y_a[m] - x_a[m])/ x_a[m])\n return errors\n except IndexError:\n if x == 0:\n return abs(y)\n else:\n return abs((y - x)/ x)\n\n\ndef rel_error_modulo(x, y, mod):\n \"\"\"Return relative error in 'y' if 'x' is the correct value modulo 'mod'\"\"\"\n try:\n cases = np.zeros((2, len(x)))\n cases[0, :] = rel_error(x % mod, y % mod)\n cases[1, :] = rel_error(x % mod, y % mod - mod)\n return np.min(cases, axis=0)\n except TypeError:\n return min(\n rel_error(x % mod, y % mod),\n rel_error(x % mod, y % mod - mod)\n )\n","sub_path":"jupyter_notebooks/calibration/calib.py","file_name":"calib.py","file_ext":"py","file_size_in_byte":11577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"260875279","text":"from django import forms\nfrom apps.solicitud.models import Solicitud, Practica\nfrom datetime import datetime, date\n\nTIPOS_USO = (\n ('Practica', 'Practica'),\n ('Proyecto', 'Proyecto'),\n ('Clase', 'Clase'),\n ('Curso', 'Curso'),\n)\nTIPOS_USO2 = (\n ('Practica', 'Practica'),\n ('Proyecto', 'Proyecto'),\n)\nHORAS_INICIO = (\n ('7:00','7:00'),('8:00','8:00'),('9:00','9:00'),('10:00','10:00'),\n ('11:00','11:00'),('12:00','12:00'),('13:00','13:00'),\n ('14:00','14:00'),('15:00','15:00'),('16:00','16:00'),\n ('17:00','17:00'),('18:00','18:00'),('19:00','19:00'),\n ('20:00','20:00'),\n)\nHORAS_FIN = (\n ('8:00','8:00'),('9:00','9:00'),('10:00','10:00'),\n ('11:00','11:00'),('12:00','12:00'),('13:00','13:00'),\n ('14:00','14:00'),('15:00','15:00'),('16:00','16:00'),\n ('17:00','17:00'),('18:00','18:00'),('19:00','19:00'),\n ('20:00','20:00'),('21:00','21:00'),\n)\nclass SolicitudEvaluarForm(forms.ModelForm):\n class Meta:\n model = Solicitud\n fields = ['observaciones']\n labels = {\n 'observaciones':'Comentarios',\n }\n widgets = {\n 'observaciones' : forms.Textarea(attrs={'class':'form-control form-control-sm textS'}),\n }\n\nclass SolicitudForm(forms.ModelForm):\n def clean_date(self):\n date = self.cleaned_data['fecha_requerida']\n if date < date.today():\n raise forms.ValidationError((\"Error: la fecha no puede ser pasada\"), code='fecha_pasado')\n return date\n\n def clean_time(self):\n cleaned_data = super().clean()\n fecha = cleaned_data.get('fecha_requerida')\n hora_ini = cleaned_data.get('hora_inicio')\n hora_fn = cleaned_data.get('hora_fin')\n ahora = datetime.now()\n print(\" hora inicio \" + str(hora_ini) + \"hora fin: \" + str(hora_fn))\n if hora_ini > hora_fn:\n raise forms.ValidationError((\"Error: La hora de fin debe ser posterior a la de inicio\"), code='fecha_pasado')\n #si para ese dia,y se pide una hora ya atrasada\n if hora_ini < ahora.time() and fecha == date.today():\n raise forms.ValidationError((\"Error: La hora seleccionada ya pasó\"), code='fecha_pasado')\n\n\n class Meta:\n model = Solicitud\n\n fields = [\n 'fecha_requerida',\n 'hora_inicio',\n 'hora_fin',\n 'uso',\n 'observaciones',\n ]\n\n labels = {\n 'fecha_requerida': 'Fecha:',\n 'hora_inicio' : 'Hora de inicio:',\n 'hora_fin' : 'Hora de fin:',\n 'uso' : 'Descripción de uso',\n 'observaciones':'Comentarios',\n }\n\n widgets = {\n 'fecha_requerida' : forms.DateInput(attrs={'class':'form-control form-control-sm textS', 'type':'date', 'format':'%d-%m-%Y'}),\n 'hora_inicio' : forms.Select(choices=HORAS_INICIO,attrs={'class':'form-control form-control-sm textS','format':'%H:%M'}),\n 'hora_fin' : forms.Select(choices=HORAS_FIN,attrs={'class':'form-control form-control-sm textS','format':'%H:%M'}),\n 'uso': forms.Select(choices=TIPOS_USO, attrs={'class':'form-control form-control-sm textS'}),\n 'observaciones' : forms.Textarea(attrs={'class':'form-control form-control-sm textS', 'style':'height:12em;'}),\n }\n\nclass SolicitudForm2(SolicitudForm):\n class Meta(SolicitudForm.Meta):\n widgets = {\n 'fecha_requerida' : forms.DateInput(attrs={'class':'form-control form-control-sm textS', 'type':'date', 'format':'%d-%m-%Y'}),\n 'hora_inicio' : forms.Select(choices=HORAS_INICIO,attrs={'class':'form-control form-control-sm textS','format':'%H:%M'}),\n 'hora_fin' : forms.Select(choices=HORAS_FIN,attrs={'class':'form-control form-control-sm textS','format':'%H:%M'}),\n 'uso': forms.Select(choices=TIPOS_USO2, attrs={'class':'form-control form-control-sm textS'}),\n 'observaciones' : forms.Textarea(attrs={'class':'form-control form-control-sm textS', 'style':'height:12em;'}),\n }\n\nclass PracticaForm(forms.ModelForm):\n class Meta:\n fields = '__all__'\n model = Practica\n labels = {\n 'nombre':'Nombre de la practica',\n 'lista_material':'Material necesario',\n }\n widgets = {\n 'nombre' : forms.TextInput(attrs={'class':'form-control form-control-sm textS'}),\n 'lista_material' : forms.Textarea(attrs={'class':'form-control form-control-sm textS'}),\n }\n","sub_path":"apps/solicitud/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"64035748","text":"from xml.dom import minidom\nimport re\nimport urllib.request\n\n# get XML RSS feed\nresponse = urllib.request.urlopen(\"http://www.dhs.sg/rss/what%2527s-new%3F-19.xml\")\nxml = response.read()\n\n# get all XML as a string\nxml_data = minidom.parseString(xml).getElementsByTagName('channel')\n\n# get all items\nparts = xml_data[0].getElementsByTagName('item')\n\n# loop all items\nfor part in parts:\n # get title\n title = part.getElementsByTagName('title')[0].firstChild.nodeValue.strip()\n # get link\n link = part.getElementsByTagName('link')[0].firstChild.nodeValue.strip()\n # get description\n description = part.getElementsByTagName('description')[0].firstChild.wholeText.strip()\n description = re.sub(\"<[^>]*>\", \"\", description)\n description = description[:-10]\n # display info\n print(\"\\n\".join([title, link, description, \"\"]))\n","sub_path":"demopy3_xmlrssurllib.py","file_name":"demopy3_xmlrssurllib.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"71165795","text":"# coding=utf-8\nimport os\nimport ConfigParser\n\ncf = ConfigParser.ConfigParser()\n\n#基础设置\ndeep =10 #探索的深度\nfilename_filter=[]\ndef getallfile(path,f,level,high):\n\thigh=high-1\n\tif high<0:\n\t\treturn\n\tallfilelist=os.listdir(path)\n\n\tfilelist=[]\n\tdirlist=[]\n\tpathlist=[]\n\tlen_dirlist=0\n\t# 遍历该文件夹下的所有目录或者文件\n\tfor file in allfilelist:\n\t\tfilepath=os.path.join(path,file)\n\t\tif os.path.isdir(filepath):\n\t\t\tif file in filename_filter:\n\t\t\t\tcontinue\n\t\t\tlen_dirlist=len_dirlist+1\n\t\t\tdirlist.append(level+file+'\\n')\n\t\t\tpathlist.append(filepath)\n\t\telse:\n\t\t\tif(os.path.splitext(file)[-1]!=''):\n\t\t\t\tfilelist.append(file+\" : \\n\")\n\tfor filename in filelist:\n\t\tf.write(filename.encode('utf-8'))\n\tfor i in range(len_dirlist):\n\t\tf.write(dirlist[i].encode('utf-8'))\n\t\tf.write('`文件夹说明` : \\n')\n\t\tgetallfile(pathlist[i],f,level+\"#\",high)\n\nif __name__ == \"__main__\":\n\t# java工程分析\n \troot_path=os.path.dirname(os.path.abspath(__file__)) # 表示当前所处的文件夹的绝对路径\n \t# 读取配置属性\n \tcf.read(root_path+'/config.conf')\n \trootdir=cf.get(\"base\",\"rootdir\").decode('utf-8')\n \tresultdir=cf.get(\"base\",\"result\")\n \tdeep=cf.getint(\"base\",\"deep\")\n \tfilename_filter=cf.get(\"base\",\"filter\").split(',')\n \tfirst_level=cf.getint(\"base\",\"first_level\")\n\n \t# 开始工作\n \tf=open(root_path+resultdir, 'a')\n \tf.seek(0)\n \tf.truncate() #清空文件\n \tgetallfile(rootdir,f,first_level*'#',deep)\n \tf.close()","sub_path":"python/filesstomd/FilesToMD.py","file_name":"FilesToMD.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"596457452","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# geometry.py\n# \n# Copyright 2015 farminf \n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n# \n\nimport numpy as np\nimport math\n\ndef rotation_matrix(axis, theta):\n \"\"\"\n Return the rotation matrix associated with counterclockwise rotation \n about\n the given axis by theta radians.\n \"\"\"\n axis = np.asarray(axis)\n theta = np.asarray(theta)\n axis = axis/math.sqrt(np.dot(axis, axis))\n a = math.cos(theta/2)\n b, c, d = -axis*math.sin(theta/2)\n aa, bb, cc, dd = a*a, b*b, c*c, d*d\n bc, ad, ac, ab, bd, cd = b*c, a*d, a*c, a*b, b*d, c*d\n return np.array([[aa+bb-cc-dd, 2*(bc+ad), 2*(bd-ac)],\n [2*(bc-ad), aa+cc-bb-dd, 2*(cd+ab)],\n [2*(bd+ac), 2*(cd-ab), aa+dd-bb-cc]])\n\n\n\n\ndef move_fragment (molecule, delta, window):\n\t\"\"\" Function doc \"\"\"\n\t\n\tfor residue in molecule.residues[window[0]:window[1]]:\n\t\tfor atom in residue.atoms:\n\t\t\tatom.coordinates += delta\n\t\n\t\n\ndef rotate_Calpha_dihedral (molecule, axis, theta, window):\n\t\"\"\" Function doc \"\"\"\n\t#v = [3, 5, 0]\n\t#axis = [4, 4, 1]\n\t#theta = 1.2 \n\n\t#print(np.dot(rotation_matrix(axis,theta), v)) \n\tfor residue in molecule.residues[window[0]:window[1]]:\n\t\tfor atom in residue.atoms:\n\t\t\tatom.coordinates = np.dot(\n\t\t\t\trotation_matrix(axis,theta), \n\t\t\t\tatom.coordinates\n\t\t\t)\n\t\t\t\n\t\t\t\ndef main():\n\t\n\treturn 0\n\nif __name__ == '__main__':\n\tmain()\n\n","sub_path":"mcarlo/structure/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"161681608","text":"# Copyright (c) 2018 Manfred Moitzi\n# License: MIT License\nimport pytest\nimport ezdxf\n\n\n@pytest.fixture(scope='module')\ndef dwg():\n return ezdxf.new('R2007')\n\n\ndef test_is_registered():\n from ezdxf.lldxf import loader\n assert loader.is_registered('FIELDLIST', legacy=False)\n\n\ndef test_generic_field_list(dwg):\n field_list = dwg.objects.create_new_dxf_entity('FIELDLIST', {})\n assert field_list.dxftype() == 'FIELDLIST'\n assert len(field_list.handles) == 0\n\n\ndef test_set_get_field_list(dwg):\n field_list = dwg.objects.create_new_dxf_entity('FIELDLIST', {})\n assert field_list.dxftype() == 'FIELDLIST'\n field_list.handles = ['FF', 'EE', 'DD']\n handles = field_list.handles\n assert len(handles) == 3\n assert handles == ['FF', 'EE', 'DD']\n\n handles.append('FFFF')\n assert handles[-1] == 'FFFF'\n\n\ndef test_magic_methods(dwg):\n field_list = dwg.objects.create_new_dxf_entity('FIELDLIST', {})\n field_list.handles = ['FF', 'EE', 'DD', 'CC']\n handles = field_list.handles\n assert len(handles) == 4\n assert handles[1] == 'EE'\n\n handles[1] = 'ABCD'\n assert handles[1] == 'ABCD'\n\n del handles[1:3]\n assert handles[:] == ['FF', 'CC']\n\n handles[1:1] = ['EE', 'DD']\n assert handles == ['FF', 'EE', 'DD', 'CC']\n assert handles[1:3] == ['EE', 'DD']\n","sub_path":"tests/test_modern_structures/test_fieldlist.py","file_name":"test_fieldlist.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"481324358","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 20 22:41:12 2018\n\n@author: allen\n\"\"\"\n\nfrom collections import Counter\n\nclass ProbReader(): \n 'the class to read the raw data of the test case data, including the test case coverage, fault information, etc.'\n \n testToFaultcaseMap={}\n testToStmtcaseMap={}\n testSuiteSize = 0\n fauktSetSize = 0\n stmtSetSize = 0\n testCaseNameList=[]\n \n def __init__(self,path): \n self.covFile = open(path+\"/cov.info\", \"r\")\n self.faultFile = open(path+\"/fault.info\", \"r\")\n self.rtimeFile = open(path+\"/rtime.info\", \"r\")\n \n self.featureNames = {}\n \n self.testCaseNames=[]\n self.faultNames=[]\n self.timeofTestcase={}\n \n \"\"\"\n each sparse map is to represent one constraint in inequation, and use the list to store all the inequation constraints\n \"\"\"\n self.sparseInequationsMapList = [] \n \n \"\"\"\n each sparse map is to represent one constraint in equation, and use the list to store all the equation constraints\n \"\"\"\n self.sparseEquationsMapList = []\n \n \"\"\"\n This map stores the relation between a fault and the set of test cases that cover this fault. The key is the fault, and the value is the test cases\n \"\"\"\n self.faultToTestcaseMap={}\n \n \"\"\"\n This map stores the relation between a stmt and the set of test cases that cover this stmt. The key is the fault, and the value is the test cases\n \"\"\"\n self.stmtsofTestcaseMap={}\n \n ProbReader.testToFaultcaseMap.clear()\n ProbReader.testToStmtcaseMap.clear()\n ProbReader.testCaseNameList.clear() \n return \n \n def displayFeatureNum(self):\n print (\"Total feature size: \",len(self.featureNames))\n \n def displayTestCaseNum(self):\n print (\"Total testcase size: \",len(self.testCaseNames))\n \n def displayStmtNum(self):\n print (\"Total statement size: \",len(self.stmtsofTestcaseMap))\n \n def displayFaultNum(self):\n print (\"Total fault size: \",len(self.faultToTestcaseMap))\n \n def displayConstraintInequationNum(self):\n print (\"Total constrained inequations size: \",len(self.sparseInequationsMapList))\n \n def displayConstraintEquationNum(self):\n print (\"Total constrained equations size: \",len(self.sparseEquationsMapList))\n \n def load(self):\n 'first read all the test case names'\n self.loadRtimeFile()\n self.loadCovFile()\n self.loadFaultFile()\n \n self.buildFeatures()\n ProbReader.testSuiteSize = len(self.testCaseNames) \n ProbReader.stmtSetSize = len(self.stmtsofTestcaseMap)\n ProbReader.fauktSetSize = len(self.faultToTestcaseMap)\n ProbReader.testCaseNameList.extend(self.testCaseNames)\n assert len(ProbReader.testToFaultcaseMap) == len(ProbReader.testCaseNameList)\n assert len(ProbReader.testToStmtcaseMap) == len(ProbReader.testCaseNameList)\n #print (self.timeofTestcase)\n #print (self.stmtsofTestcaseMap)\n #print (self.faultToTestcaseMap)\n return \n \n def buildFeatures(self):\n faultIDs = map(lambda x: int(x[1:]), self.faultToTestcaseMap.keys())\n sortedFaultIDs = sorted(faultIDs) \n totalFeatures= len(self.testCaseNames) + len(sortedFaultIDs)\n for i in range(0,totalFeatures):\n if i < len(self.testCaseNames) :\n key = self.testCaseNames[i]\n self.featureNames[key] = i\n else:\n key = 'f'+str(sortedFaultIDs[i-len(self.testCaseNames)])\n self.featureNames[key] = i \n return\n \n def loadFaultFile(self):\n line = self.faultFile.readline() # 调用文件的 readline()方法\n while line:\n #for testing purpose\n #print(line, end = '')\n parts = line.split(':')\n #example: t2:2 3\n testCaseName= parts[0].strip()\n faults = parts[1].split(' ')\n 'bug fixed here, for case: [\"t329\", \"\\n\"]'\n if( parts[1].strip() == '\\n' or parts[1].strip() == '' ):\n faultList = []\n ProbReader.testToFaultcaseMap[testCaseName]=faultList \n line = self.faultFile.readline()\n continue\n for fault in faults:\n faultName= 'f'+fault.strip()\n if faultName in self.faultToTestcaseMap:\n testcaseList= self.faultToTestcaseMap[faultName]\n testcaseList.append(testCaseName)\n else: \n testcaseList = []\n testcaseList.append(testCaseName)\n self.faultToTestcaseMap[faultName]=testcaseList \n 'adding again for the test to fault map'\n for fault in faults:\n faultName= 'f'+fault.strip()\n if testCaseName in ProbReader.testToFaultcaseMap:\n faultList= ProbReader.testToFaultcaseMap[testCaseName]\n faultList.append(faultName)\n else: \n faultList = []\n faultList.append(faultName)\n ProbReader.testToFaultcaseMap[testCaseName]=faultList \n line = self.faultFile.readline()\n self.faultFile.close()\n 'check there exist no duplication in the map'\n for faultName in self.faultToTestcaseMap:\n testcaseList= self.faultToTestcaseMap[faultName]\n cou=Counter(testcaseList)\n first=cou.most_common(1)\n if first[0][1]>1:\n print ('input have duplicates!!!')\n exit(-1) \n return \n \n def loadCovFile(self):\n line = self.covFile.readline() # 调用文件的 readline()方法\n while line:\n #for testing purpose\n #print(line, end = '')\n parts = line.split(':')\n #example: t2:2 3\n testCaseName= parts[0].strip()\n stmts = parts[1].split(' ')\n if( parts[1].strip() == '\\n' or parts[1].strip() == '' ):\n stmtList = []\n ProbReader.testToStmtcaseMap[testCaseName]=stmtList \n line = self.covFile.readline()\n continue\n \n for stmt in stmts:\n stmtName= 's'+stmt.strip()\n if stmtName in self.stmtsofTestcaseMap:\n testcaseList= self.stmtsofTestcaseMap[stmtName]\n testcaseList.append(testCaseName)\n else: \n testcaseList = []\n testcaseList.append(testCaseName)\n self.stmtsofTestcaseMap[stmtName]=testcaseList\n 'adding again for the test to stmt map'\n for stmt in stmts:\n stmtName= 's'+stmt.strip()\n if testCaseName in ProbReader.testToStmtcaseMap:\n stmtList= ProbReader.testToStmtcaseMap[testCaseName]\n stmtList.append(stmtName)\n else: \n stmtList = []\n stmtList.append(stmtName)\n ProbReader.testToStmtcaseMap[testCaseName]=stmtList \n line = self.covFile.readline()\n self.covFile.close()\n 'check there exist no duplication in the map'\n for stmtName in self.stmtsofTestcaseMap:\n testcaseList= self.stmtsofTestcaseMap[stmtName]\n cou=Counter(testcaseList)\n first=cou.most_common(1)\n if first[0][1]>1:\n print ('input have duplicates!!!')\n exit(-1) \n return \n \n def loadRtimeFile(self):\n line = self.rtimeFile.readline() # 调用文件的 readline()方法\n while line:\n #for testing purpose\n #print(line, end = '')\n parts = line.split(':')\n testCaseName= parts[0].strip()\n time= float(parts[1].strip())\n self.testCaseNames.append(testCaseName)\n self.timeofTestcase[testCaseName] = time\n line = self.rtimeFile.readline()\n self.rtimeFile.close()\n return \n \nif __name__ == \"__main__\":\n #reader = ProbReader('../../../Nemo/subject_programs/make_v5')\n reader = ProbReader('../../../Nemo/example')\n reader.load()\n reader.displayFeatureNum()\n reader.displayTestCaseNum()\n reader.displayStmtNum()\n reader.displayFaultNum()\n print (reader.testCaseNames)\n print (ProbReader.testToFaultcaseMap)\n print (ProbReader.testToStmtcaseMap)\nelse:\n print(\"probReader.py is being imported into another module\")","sub_path":"code/moea/probReader.py","file_name":"probReader.py","file_ext":"py","file_size_in_byte":8763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"12017279","text":"\"\"\"Contains a collection of utility functions for training and evaluating\"\"\"\nfrom __future__ import absolute_import, division, print_function\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import logging\nfrom tensorflow.python.ops import array_ops, variable_scope\nfrom tensorflow import gfile\n\ndef _shape(tensor):\n return tensor.get_shape().as_list()\n\ndef task_as_string(task):\n return \"/job:{}/task:{}\".format(task.type, task.index)\n\n\ndef makeSummary(name, value):\n \"\"\"Creates a tf.Summary prototype with given name and value\"\"\"\n summary = tf.Summary()\n val = summary.value.add()\n val.tag = str(name)\n val.simple_value = float(value)\n return summary\n\ndef getListOfFeatureNamesAndSizes(feature_names, feature_sizes):\n \"\"\"Extract the list of feature names and the dimensionality of each\n feature from string of comma separated values\n\n Args:\n feature_names: string containing comma separated list of features names\n feature_sizes: string containing comma separated list of feature sizes\n\n Returns:\n List of the feature names and list of the dimensionality of each feature.\n elements in the first/second list are strings/integers\n \"\"\"\n\n list_of_feature_names = [\n feature_names.strip() for feature_names in feature_names.split(',')\n ]\n list_of_feature_sizes = [\n int(feature_sizes) for feature_sizes in feature_sizes.split(',')\n ]\n if len(list_of_feature_names) != len(list_of_feature_sizes):\n logging.error(\"Length of feature names (={}) != Length of feature sizes (={})\".format(\n len(list_of_feature_names), len(list_of_feature_sizes)\n ))\n return list_of_feature_names, list_of_feature_sizes\n\ndef get_blocks(images, kernel_size=(1, 1)):\n \"\"\"Splits images into blocks\n Args:\n images: (num_images, height, width, channels) tensor\n kernel_size: A list of length 2 holding the window shape\n\n \"\"\"\n with variable_scope.variable_scope(\"image_subsampling\"):\n batch_size, height, width, channels = _shape(images)\n\n if height % kernel_size[0] != 0:\n offset = array_ops.zeros([batch_size,\n kernel_size[0] - (height % kernel_size[0]),\n width,\n channels])\n images = array_ops.concat([images, offset], 1)\n batch_size, height, width, channels = _shape(images)\n\n if width % kernel_size[1] != 0:\n offset = array_ops.zeros([batch_size,\n height,\n kernel_size[1] - (width % kernel_size[1]),\n channels])\n images = array_ops.concat([images, offset], 2)\n batch_size, height, width, channels = _shape(images)\n new_h, new_w = int(height / kernel_size[0]), int(width / kernel_size[1])\n features = kernel_size[0]*kernel_size[1]*channels\n\n lines = array_ops.split(images, new_h, axis=1)\n line_blocks = []\n for line in lines:\n line = array_ops.transpose(line, [0, 2, 3, 1])\n line = array_ops.reshape(line, [batch_size, new_w, features])\n line_blocks.append(line)\n return array_ops.stack(line_blocks, axis=1)\n","sub_path":"MDLSTM/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"443156148","text":"#Autor: Daniela Estrella Tovar\r\n# Descripción: Dadas las horas trabajadas, las horas extra, y el pago por hora, calcular el pago normal, el pago extra y el pago total.\r\n\r\ndef calcularPagoNormal(horasTrabajo, pago):\r\n pagoNormal= horasTrabajo*pago\r\n return pagoNormal\r\n\r\ndef calcularPagoExtra(horasExtra,pago):\r\n pagoExtra= horasExtra* pago *1.85\r\n return pagoExtra\r\n\r\ndef calcularPagoTotal(horasExtra,horasTrabajo,pago):\r\n pagoExtra=calcularPagoExtra(horasExtra, pago)\r\n pagoNormal=calcularPagoNormal(horasTrabajo, pago)\r\n pagoTotal= pagoNormal + pagoExtra\r\n return pagoTotal\r\n\r\ndef main():\r\n horasTrabajo= int(input(\"Teclea las horas normales trabajadas: \"))\r\n horasExtra= int(input(\"Teclea las horas extra trabajadas: \"))\r\n pago= int(input(\"Teclea el pago por hora: \"))\r\n pagoNormal= calcularPagoNormal(horasTrabajo, pago)\r\n print(\"\"\" \r\nPago Normal: $%.2f\"\"\" % (pagoNormal))\r\n pagoExtra= calcularPagoExtra(horasExtra,pago)\r\n print(\"\"\"Pago Extra: $%.2f\"\"\" % (pagoExtra))\r\n pagoTotal= calcularPagoTotal(horasExtra,horasTrabajo,pago)\r\n print(\"\"\"\r\nPago Total= $%.2f \"\"\" % (pagoTotal))\r\n\r\nmain()","sub_path":"Pago.py","file_name":"Pago.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"374539901","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\nimport os\n\nSTAGE = os.environ.get(\"STAGE\", \"dev\")\n\nAUTHOR = \"Rick Henry\"\nSITENAME = \"Baseball Blog\"\nSITESUBTITLE = \"A companion blog to a non-existent baseball team\"\nSITEURL = os.environ.get(\"SITEURL\", \"\")\nTHEME = \"themes/future-imperfect\"\n\nSHORT_DESCRIPTION = (\n \"This is a static site generated with pelican hosted on netlify. \"\n \"It will use netlify cms to get all the speed and ease of a static site, \"\n \"but with some of the flexibility and dynamic content of a cms.\"\n)\n\nFEATURED_CATEGORY1 = \"Weird Rules\"\nFEATURED_CATEGORY2 = \"Recaps\"\n\nPATH = \"content\"\n\nTIMEZONE = \"America/New_York\"\nDEFAULT_DATE_FORMAT = \"%B %d, %Y\"\n\nDEFAULT_LANG = \"en\"\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\n# Blogroll\nLINKS = (\n (\"Pelican\", \"http://getpelican.com/\"),\n (\"Python.org\", \"http://python.org/\"),\n (\"Jinja2\", \"http://jinja.pocoo.org/\"),\n (\"You can modify those links in your config file\", \"#\"),\n)\n\n# Social widget\nSOCIAL = ((\"You can add links in your config file\", \"#\"), (\"Another social link\", \"#\"))\n\nDEFAULT_PAGINATION = False\n\n# Uncomment following line if you want document-relative URLs when developing\nRELATIVE_URLS = False\n\nPLUGIN_PATHS = [\"plugins\"]\nPLUGINS = [\"sitemap\", \"assets\", \"tipue_search.tipue_search\"]\nSITEMAP = {\"format\": \"xml\"}\n\nsass_style = \"expanded\" if STAGE == \"dev\" else \"compressed\"\n\nASSET_CONFIG = (\n)\n\nSTATIC_PATHS = ['admin', 'images']\n\nPAGE_EXCLUDES = ['admin']\nARTICLE_EXCLUDES = ['admin']\n\nARTICLE_URL = '{date:%Y-%m-%d}-{slug}'\nARTICLE_SAVE_AS = '{date:%Y-%m-%d}-{slug}.html'\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"284940907","text":"#!/usr/bin/env python3\nfrom bs4 import BeautifulSoup\nimport pandas as p\nimport traceback\nfrom obj import yahoo_obj as y\nfrom src.helpers import commons as cm\n\ndef getRisk(html, ticker):\n soup = BeautifulSoup(html, 'html.parser')\n test = lambda x: x!=\"VGT\"\n empty = lambda x: len(x)>0\n print(\"Risk data for {0}:\".format(ticker))\n dict = {\"Type\": [i.text for i in soup.select(y.risk(str(2))) if test(i.text)]}\n data = []\n for x in range(3,20):\n try:\n data = [i.text for i in soup.select(y.risk(str(x))) if empty(i.text)]\n dict[data[0]] = [float(i) for i in data[1:]]\n except:\n pass\n print(dict)\n return dict\n\ndef risk(tickers, metadata):\n code = 0\n for i in tickers:\n try:\n resp = cm.getHtml(\"risk\", i)\n code = resp[0]\n return getRisk(resp[1], i)\n except:\n print(\"Exception occured, this is the status code {0}, and this is the ticker\".format(i))\n traceback.print_exc()\n return None\n\nif __name__ == \"__main__\":\n risk(\"aapl\",\"\")\n","sub_path":"src/risk.py","file_name":"risk.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"134387082","text":"import sys\nfrom logging import INFO, basicConfig, getLogger\n\nfrom echo_bot.database import Database\nfrom echo_bot.echo_handler import EchoHandler\nfrom echo_bot.loader import Loader\nfrom echo_bot.settings import Settings\nfrom telethon import TelegramClient\nfrom telethon.errors.rpcerrorlist import PhoneNumberInvalidError\nfrom telethon.network.connection.tcpabridged import \\\n ConnectionTcpAbridged as CTA\n\nfrom .command_handler import CommandHandler\n\n\nclass EchoChamberBot:\n settings = Settings()\n database = Database()\n\n def __init__(self):\n basicConfig(format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=INFO)\n self.logger = getLogger(__name__)\n self.command_handler = CommandHandler(self.database, self.logger, self.settings)\n self.echo_handler = EchoHandler(self.settings, self.logger, self.database, self.command_handler)\n self._start_client()\n self.loader = Loader(self.client, self.logger, self.settings, self.database, self.command_handler)\n\n def run_until_done(self):\n self.loader.load_all_modules()\n self.logger.info(\"Client successfully started.\")\n self.echo_handler.start_handler(self.client)\n self.logger.info(\"Echo handler successfully started.\")\n self.client.run_until_disconnected()\n\n def _check_config(self):\n api_key = self.settings.get_config(\"api_key\")\n api_hash = self.settings.get_config(\"api_hash\")\n bot_token = self.settings.get_config(\"bot_token\")\n\n while not api_key:\n api_key = input(\"Enter your API key: \")\n\n self.settings.set_config(\"api_key\", api_key)\n\n while not api_hash:\n api_hash = input(\"Enter your API hash: \")\n\n self.settings.set_config(\"api_hash\", api_hash)\n\n while not bot_token:\n bot_token = input(\"Enter your bot token: \")\n\n self.settings.set_config(\"bot_token\", bot_token)\n\n return api_key, api_hash, bot_token\n\n def _start_client(self):\n api_key, api_hash, bot_token = self._check_config()\n self.client = TelegramClient(\"echo_bot\", api_key, api_hash, connection=CTA)\n\n try:\n self.client.start(bot_token=bot_token)\n except PhoneNumberInvalidError:\n print(\"The bot token provided is invalid, exiting.\")\n sys.exit(2)\n\n async def stop_client(self):\n await self.client.disconnect()\n\n\necho_bot = EchoChamberBot()\nldr = echo_bot.loader\n\ntry:\n echo_bot.run_until_done()\nexcept:\n echo_bot.client.loop.run_until_complete(echo_bot.stop_client())\n","sub_path":"echo_bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"230825802","text":"import pygame\nfrom pygame.locals import *\nfrom sys import exit\n\nbackground_image_filename = 'background.jpg'\nSCREEN_SIZE = (800, 450)\n\npygame.init()\n\nscreen = pygame.display.set_mode(SCREEN_SIZE, RESIZABLE, 32)\npygame.display.set_caption(\"Hello, World!\")\n\nbackground = pygame.image.load(background_image_filename).convert()\n\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n exit(0)\n if event.type == VIDEORESIZE:\n SCREEN_SIZE = event.size\n screen = pygame.display.set_mode(SCREEN_SIZE, RESIZABLE, 32)\n pygame.display.set_caption(\"Window resized to \" + str(event.size))\n\n screen.blit(background, (0,0))\n\n x, y = pygame.mouse.get_pos()\n print(x, \" \", y)\n\n pygame.display.update()\n","sub_path":"resizeable.py","file_name":"resizeable.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"61697743","text":"import random\nclass Person():\n def __init__(self,name):\n self.name=name\n self.score=0\n\n def fingerPlay(self):\n game=['石头','剪刀','布']\n index=random.randint(0,2)\n #random.choice(game)\n return game[index]\n\nclass Game():\n def __init__(self,number,aname,bname):\n self.number = number\n self.a = person()\n self.b = person()\n\n def playGame(self):\n for i in range(self.number):\n a_out=self.a.fingerPlay()\n b_Out=self.b.fingerPlay()\n if a_out == b_out:\n print('平局,出的是{}'.format(a_out))\n elif (a_out == '石头'and b_out == '剪刀')or(a_out == '布'and b_out == '石头')or(a__out == '剪刀'and b_out == '布'):\n print('{}获胜,出的是{},{}出的是{}'.format(self.a.name,a_out,self.b.name,b_out))\n else:\n print('{}获胜,出的是{},{}出的是{}'.format(self.b.name,b_out,self.a.name,a_out))\none = Game(5,'JYP','pupppy')\none.playGame() ","sub_path":"1906101028-游雯雯/day0310/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"216222067","text":"import torch.utils.data\r\nimport torchvision.transforms as transforms\r\nimport os.path as osp\r\nimport pickle as pkl\r\nimport re\r\nimport numpy as np\r\nfrom utils.transforms import crop\r\nfrom utils.preprocessing import load_img\r\nfrom utils.geometry import batch_rodrigues, rotation_matrix_to_angle_axis\r\nfrom utils.transforms import normalize_and_concat_72, normalize_screen_coordinates, normalize_and_concat, bbox_from_json\r\nimport config\r\nimport os\r\nfrom smplpytorch.pytorch.smpl_layer import SMPL_Layer\r\nfrom config import joint_set\r\nfrom models.smpl import H36M_TO_J14, SMPL\r\nimport cv2\r\n\r\ncam_param = {\"R\": [[0.9228353966173104, -0.37440015452287667, 0.09055029013436408],\r\n [-0.01498208436370467, -0.269786590656035, -0.9628035794752281],\r\n [0.38490306298896904, 0.8871525910436372, -0.25457791009093983]],\r\n \"t\": [25.76853374383657, 431.05581759025813, 4461.872981411145],\r\n \"f\": [1145.51133842318, 1144.77392807652],\r\n \"c\": [514.968197319863, 501.882018537695]}\r\n\r\n\r\nclass H36MDataset(torch.utils.data.Dataset):\r\n def __init__(self, is_train, img_res=224, window_size=16):\r\n super(H36MDataset, self).__init__()\r\n self.is_train = is_train\r\n self.img_res = img_res\r\n self.window_size = window_size\r\n self.img_path = os.path.join(config.BASE_DATA_DIR, 'h36m')\r\n # self.data_path_imu = os.path.join(self.img_path, \"imu\")\r\n self.data_path_imu = os.path.join(config.BASE_DATA_DIR, 'h36m', \"imu_3d\")\r\n\r\n self.data_path_pkl = os.path.join(self.img_path, \"h36m\")\r\n\r\n self.transform = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\r\n ])\r\n\r\n self.smpl_layer = SMPL(\r\n config.SMPL_MODEL_DIR,\r\n batch_size=64,\r\n create_transl=False,\r\n ).cpu()\r\n # self.h36m_joint_regressor = np.load(\r\n # '/home/data/Paper-Project/connect_features/dataset/J_regressor_h36m_correct.npy')\r\n self.h36m_joint_regressor = np.load('E:/Paper-Project/connect_features/dataset/J_regressor_h36m_correct.npy')\r\n self.data_train, self.data_val, self.data_test = self.load_data()\r\n if self.is_train == 'train':\r\n self.data_all = self.data_train\r\n elif self.is_train == 'val':\r\n self.data_all = self.data_val\r\n else:\r\n self.data_all = self.data_test\r\n\r\n print('load data len=', len(self.data_all))\r\n\r\n def load_data(self):\r\n data_list_train = []\r\n data_list_val = []\r\n data_list_test = []\r\n\r\n if self.is_train == 'train':\r\n subjects = [1, 5, 6, 7, 8]\r\n for s in subjects:\r\n for ac in range(2, 17):\r\n for sb in range(1, 3):\r\n pkl_path = f'h36m_s{s}_action{ac}_subaction{sb}_imu_3d.pkl'\r\n pkl_path = os.path.join(self.data_path_imu, pkl_path)\r\n with open(pkl_path, 'rb') as f:\r\n data_imu = pkl.load(f, encoding='latin1')\r\n data_path = f'h36m_s{s}_action{ac}_subaction{sb}.pkl'\r\n pkl_data = os.path.join(self.data_path_pkl, data_path)\r\n with open(pkl_data, 'rb') as f:\r\n data_data = pkl.load(f, encoding='latin1')\r\n data_data = data_data[1:-1]\r\n for i in range(len(data_imu) - self.window_size):\r\n if i % 5 != 0:\r\n continue\r\n data = {'img': data_data[i + self.window_size - 1],\r\n 'imu': data_imu[i: i + self.window_size]}\r\n data_list_train.append(data)\r\n\r\n if self.is_train == 'val':\r\n subjects = [9, 11]\r\n for s in subjects:\r\n # ac = 2\r\n for ac in range(2, 17):\r\n for sb in range(1, 3):\r\n pkl_path = f'h36m_s{s}_action{ac}_subaction{sb}_imu_3d.pkl'\r\n pkl_path = os.path.join(self.data_path_imu, pkl_path)\r\n with open(pkl_path, 'rb') as f:\r\n data_imu = pkl.load(f, encoding='latin1')\r\n data_path = f'h36m_s{s}_action{ac}_subaction{sb}.pkl'\r\n pkl_data = os.path.join(self.data_path_pkl, data_path)\r\n with open(pkl_data, 'rb') as f:\r\n data_data = pkl.load(f, encoding='latin1')\r\n data_data = data_data[1:-1]\r\n for i in range(len(data_imu) - self.window_size):\r\n if i % 64 != 0:\r\n continue\r\n data = {'img': data_data[i + self.window_size - 1],\r\n 'imu': data_imu[i: i + self.window_size]}\r\n data_list_val.append(data)\r\n\r\n if self.is_train == 'test':\r\n\r\n # s_11_act_16_subact_02_ca_04\r\n s = 11\r\n a = 16\r\n sb = 2\r\n pkl_path = f'h36m_s{s}_action{a}_subaction{sb}_imu_3d.pkl'\r\n pkl_path = os.path.join(self.data_path_imu, pkl_path)\r\n with open(pkl_path, 'rb') as f:\r\n data_imu = pkl.load(f, encoding='latin1')\r\n data_path = f'h36m_s{s}_action{a}_subaction{sb}.pkl'\r\n pkl_data = os.path.join(self.data_path_pkl, data_path)\r\n with open(pkl_data, 'rb') as f:\r\n data_data = pkl.load(f, encoding='latin1')\r\n data_data = data_data[1:-1]\r\n for i in range(len(data_imu) - self.window_size):\r\n if i % 2 != 0:\r\n continue\r\n data = {'img': data_data[i + self.window_size - 1],\r\n 'imu': data_imu[i: i + self.window_size]}\r\n data_list_test.append(data)\r\n\r\n # subjects = [9,11]\r\n # for s in subjects:\r\n # for ac in range(2, 17):\r\n # for sb in range(1, 3):\r\n # pkl_path = f'h36m_s{s}_action{ac}_subaction{sb}_imu_3d.pkl'\r\n # pkl_path = os.path.join(self.data_path_imu, pkl_path)\r\n # with open(pkl_path, 'rb') as f:\r\n # data_imu = pkl.load(f, encoding='latin1')\r\n # data_path = f'h36m_s{s}_action{ac}_subaction{sb}.pkl'\r\n # pkl_data = os.path.join(self.data_path_pkl, data_path)\r\n # with open(pkl_data, 'rb') as f:\r\n # data_data = pkl.load(f, encoding='latin1')\r\n # data_data = data_data[1:-1]\r\n #\r\n # for i in range(len(data_imu) - self.window_size):\r\n # if i % 64 != 0:\r\n # continue\r\n # data = {'img': data_data[i + self.window_size - 1],\r\n # 'imu': data_imu[i: i + self.window_size]}\r\n # data_list_test.append(data)\r\n\r\n return data_list_train, data_list_val, data_list_test\r\n\r\n def get_smpl_coord(self, smpl_param, cam_param):\r\n\r\n pose, shape, trans = smpl_param['pose'], smpl_param['shape'], smpl_param['trans']\r\n smpl_pose = torch.FloatTensor(pose).view(-1, 3)\r\n smpl_shape = torch.FloatTensor(shape).view(1, -1) # smpl parameters (pose: 72 dimension, shape: 10 dimension)\r\n R, t = np.array(cam_param['R'], dtype=np.float32).reshape(3, 3), np.array(cam_param['t'],\r\n type=np.float32).reshape(\r\n 3) # camera rotation and translation\r\n\r\n # merge root pose and camera rotation\r\n root_pose = smpl_pose[0, :].numpy()\r\n root_pose, _ = cv2.Rodrigues(root_pose)\r\n root_pose, _ = cv2.Rodrigues(np.dot(R, root_pose))\r\n smpl_pose[0] = torch.from_numpy(root_pose).view(3)\r\n pose = batch_rodrigues(smpl_pose.view(-1, 3)).reshape(-1, 24, 3, 3)\r\n\r\n # get mesh and joint coordinates\r\n # smpl_poses = smpl_pose.view(24, 3).numpy()\r\n # rotation = []\r\n # for p in smpl_poses:\r\n # rotation.append(cv2.Rodrigues(p)[0])\r\n # rotation = np.array(rotation)\r\n # rotation = torch.tensor(rotation, dtype=torch.float32).view(-1, 24, 3, 3)\r\n # smplout = self.smpl(global_orient=rotation[:, 0].unsqueeze(1), body_pose=rotation[:, 1:], betas=smpl_shape,\r\n # pose2rot=False)\r\n smplout = self.smpl_layer(\r\n betas=smpl_shape,\r\n body_pose=pose[:, 1:],\r\n global_orient=pose[:, 0].unsqueeze(1),\r\n pose2rot=False\r\n )\r\n\r\n # smplout = self.smpl(global_orient=rotation[:, 0].unsqueeze(1), body_pose=rotation[:, 1:], betas=smpl_shape,\r\n # transl=trans, pose2rot=False)\r\n\r\n smpl_mesh_coord = smplout.vertices\r\n smpl_joint_coord = smplout.joints\r\n # incorporate face keypoints\r\n smpl_mesh_coord = smpl_mesh_coord.detach().numpy().astype(np.float32).reshape(-1, 3)\r\n smpl_joint_coord = smpl_joint_coord.detach().numpy().astype(np.float32).reshape(-1, 3)\r\n\r\n # compenstate rotation (translation from origin to root joint was not cancled)\r\n # smpl_trans = np.array(trans, dtype=np.float32).reshape(\r\n # 3) # translation vector from smpl coordinate to h36m world coordinate\r\n # smpl_trans = np.dot(R, smpl_trans[:, None]).reshape(1, 3) + t.reshape(1, 3) / 1000\r\n # root_joint_coord = smpl_joint_coord[0].reshape(1, 3)\r\n # smpl_trans = smpl_trans - root_joint_coord + np.dot(R, root_joint_coord.transpose(1, 0)).transpose(1, 0)\r\n #\r\n # smpl_mesh_coord = smpl_mesh_coord + smpl_trans\r\n # smpl_joint_coord = smpl_joint_coord + smpl_trans\r\n\r\n # change to mean shape if beta is too far from it\r\n smpl_shape[(smpl_shape.abs() > 3).any(dim=1)] = 0.\r\n\r\n # meter -> milimeter\r\n smpl_mesh_coord *= 1000\r\n smpl_joint_coord *= 1000\r\n return smpl_mesh_coord\r\n\r\n def get_fitting_error(self, h36m_joint, smpl_mesh):\r\n\r\n h36m_joint = h36m_joint - h36m_joint[0, None, :] # root-relative\r\n h36m_from_smpl = np.dot(self.h36m_joint_regressor, smpl_mesh)\r\n h36m_from_smpl = h36m_from_smpl - np.mean(h36m_from_smpl, 0)[None, :] + np.mean(h36m_joint, 0)[None,\r\n :] # translation alignment\r\n\r\n # h36m_from_smpl = h36m_from_smpl - h36m_from_smpl[self.h36m_root_joint_idx, None, :]\r\n\r\n error = np.sqrt(np.sum((h36m_joint - h36m_from_smpl) ** 2, 1)).mean()\r\n return error\r\n\r\n def gaussian(self, imu, mean, sigma):\r\n noise = np.random.normal()\r\n gaussian_out = imu + noise\r\n gaussian_out = np.clip(gaussian_out, -1, 1)\r\n return gaussian_out\r\n\r\n def __len__(self):\r\n return len(self.data_all)\r\n\r\n def __getitem__(self, index):\r\n\r\n gasis = np.random.rand()\r\n data_list = self.data_all[index]\r\n data = data_list['img']\r\n data_imus = data_list['imu']\r\n center, scale = bbox_from_json(data['bbox'])\r\n\r\n img_path = data['img_path']\r\n img_path = os.path.join(self.img_path, 'images', img_path)\r\n img = load_img(img_path)\r\n img_test, width, w, h = crop(img, center, scale, (self.img_res, self.img_res))\r\n\r\n \"\"\"get_error\"\"\"\r\n smpl_param = data['smpl_param']\r\n # smpl_mesh_cam = self.get_smpl_coord(smpl_param, cam_param)\r\n # error = self.get_fitting_error(data['joint_cam'], smpl_mesh_cam)\r\n # print(error)\r\n # print(error)\r\n if self.transform:\r\n img = self.transform(img_test)\r\n\r\n imu_rotations = []\r\n imu_accs = []\r\n left_Jtrs = []\r\n relative_Jtrs = []\r\n\r\n for data_imu in data_imus:\r\n imu_rotation = data_imu['imu_ori']\r\n imu_acc = torch.FloatTensor(data_imu['imu_acc'])\r\n left_Jtr = torch.FloatTensor(data_imu['left_keypoints'])\r\n relative_Jtr = torch.FloatTensor(data_imu['relative_keypoints'])\r\n\r\n left_Jtrs.append(left_Jtr)\r\n relative_Jtrs.append(relative_Jtr)\r\n imu_rotations.append(imu_rotation)\r\n imu_accs.append(imu_acc)\r\n\r\n imu_accs = torch.stack(imu_accs)\r\n imu_rotations = np.stack(imu_rotations)\r\n if gasis < 0.3:\r\n imu_rotations = self.gaussian(imu_rotations, 0, 0.2)\r\n\r\n imu_rotations = torch.FloatTensor(imu_rotations)\r\n left_Jtrs = torch.stack(left_Jtrs)\r\n relative_Jtrs = torch.stack(relative_Jtrs)\r\n\r\n imu_data = normalize_and_concat_72(imu_accs, imu_rotations)\r\n pose_aa = torch.FloatTensor(data_imus[-1]['pose']).view(-1, 72)\r\n pose = batch_rodrigues(pose_aa.view(-1, 3)).reshape(-1, 24, 3, 3)\r\n\r\n smpl_shape = torch.FloatTensor(smpl_param['shape'])\r\n\r\n # pred_shape_zero = torch.zeros(10).to(smpl_shape.device).expand_as(smpl_shape)\r\n\r\n smpl_output = self.smpl_layer(\r\n betas=smpl_shape.unsqueeze(0),\r\n body_pose=pose[:, 1:],\r\n global_orient=pose[:, 0].unsqueeze(1),\r\n pose2rot=False\r\n )\r\n pred_joints = smpl_output.joints[0][25:39]\r\n pred_vertices = smpl_output.vertices\r\n\r\n inputs = {'img': img, 'imu_data': imu_data}\r\n targets = {\r\n 'theta': pose_aa.view(-1, 3),\r\n 'smpl_shape': smpl_shape,\r\n 'smpl_pose': pose[0],\r\n 'kp_3d': pred_joints, # 14*3\r\n 'verts': pred_vertices[0],\r\n 'leaf_keypoints': left_Jtrs,\r\n 'relative_keypoints': relative_Jtrs,\r\n\r\n }\r\n metor = {'root': imu_rotations[-1, -1], 'cam_joint': data['joint_cam'],\r\n 'smpl_image': torch.FloatTensor(smpl_param['pose']),\r\n 'smpl_trans': torch.FloatTensor(smpl_param['trans']), }\r\n\r\n info = {'img_path': img_path, 'smpl_param': smpl_param, 'cam_param': data['cam_param'], 'center': center,\r\n 'scale': scale}\r\n\r\n return inputs, targets, metor, info\r\n","sub_path":"Human36M.py","file_name":"Human36M.py","file_ext":"py","file_size_in_byte":14452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"608113653","text":"import requests\n\nfrom datetime import date, timedelta, datetime\nfrom decimal import Decimal\n\nfrom bs4 import BeautifulSoup\nfrom dateutil.relativedelta import relativedelta\nfrom dateutil import parser as date_parser\n\nfrom django.views.generic import View, TemplateView\nfrom django.http import JsonResponse\nfrom django.urls import reverse\nfrom django.db.models import Sum, Avg, Count, F, DecimalField\nfrom django.template.defaultfilters import date as _date\n\nfrom KlimaKar.functions import remove_suffixes, remove_suffix\nfrom KlimaKar.mixins import StaffOnlyMixin\nfrom KlimaKar.templatetags.slugify import slugify\nfrom apps.settings.models import InvoiceDownloadSettings\nfrom apps.warehouse.models import Invoice, Ware, WarePriceChange, Supplier\nfrom apps.invoicing.models import SaleInvoice, Contractor, RefrigerantWeights\nfrom apps.commission.models import Commission\nfrom apps.stats.models import ReceiptPTU, Round\nfrom apps.stats.mixins import ChartDataMixin, BigChartHistoryMixin\nfrom apps.stats.dictionaries import COLORS\n\n\nclass DashboardView(StaffOnlyMixin, TemplateView):\n template_name = \"stats/dashboard.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n context[\"stats\"] = {\n \"purchase\": {\n \"group\": \"purchase\",\n \"metrics\": self._get_purchase_metrics(),\n \"charts\": self._get_purchase_charts(),\n },\n \"sale\": {\"group\": \"sale\", \"metrics\": self._get_sale_metrics(), \"charts\": self._get_sale_charts()},\n }\n return context\n\n def _get_purchase_charts(self):\n charts = []\n if self.request.user.is_staff:\n charts.append(\n {\n \"title\": \"Historia faktur zakupowych\",\n \"url\": reverse(\"stats:purchase_invoices_history\"),\n \"big\": True,\n \"select_date\": {\"extra\": True},\n \"custom_select\": [(\"Sum\", \"Suma\"), (\"Avg\", \"Średnia\"), (\"Count\", \"Ilość\")],\n }\n )\n charts.append(\n {\n \"title\": \"Historia zakupów u dostawców\",\n \"select_date\": True,\n \"custom_select\": [(\"Sum\", \"Suma\"), (\"Avg\", \"Średnia\"), (\"Count\", \"Ilość\")],\n \"url\": reverse(\"stats:supplier_purchase_history\"),\n }\n )\n charts.append(\n {\n \"title\": \"Historia zakupów towarów\",\n \"select_date\": True,\n \"custom_select\": [(\"Count\", \"Ilość\"), (\"Sum\", \"Suma\")],\n \"url\": reverse(\"stats:ware_purchase_history\"),\n }\n )\n return charts\n\n def _get_purchase_metrics(self):\n metrics = []\n metrics.append(\n {\"icon\": \"fa-tags\", \"color\": \"#E21E00\", \"title\": \"Liczba dodanych towarów\", \"class\": \"ware_count\"}\n )\n metrics.append(\n {\"icon\": \"fa-truck\", \"color\": \"#C1456E\", \"title\": \"Liczba dodanych dostawców\", \"class\": \"supplier_count\"}\n )\n metrics.append(\n {\"icon\": \"fa-file-alt\", \"color\": \"#8355C5\", \"title\": \"Liczba dodanych faktur\", \"class\": \"invoice_count\"}\n )\n if self.request.user.is_staff:\n metrics.append(\n {\n \"icon\": \"fa-file-alt\",\n \"color\": \"#8355C5\",\n \"title\": \"Kwota netto dodanych faktur\",\n \"class\": \"invoice_sum\",\n }\n )\n return metrics\n\n def _get_sale_charts(self):\n charts = []\n if self.request.user.is_staff:\n charts.append(\n {\n \"title\": \"Historia faktur sprzedażowych\",\n \"url\": reverse(\"stats:sale_invoices_history\"),\n \"big\": True,\n \"select_date\": {\"extra\": True},\n \"custom_select\": [\n (\"SumNetto\", \"Suma netto\"),\n (\"SumBrutto\", \"Suma brutto\"),\n (\"AvgNetto\", \"Średnia netto\"),\n (\"AvgBrutto\", \"Średnia brutto\"),\n (\"Count\", \"Ilość\"),\n ],\n }\n )\n charts.append(\n {\n \"title\": \"Historia zleceń\",\n \"url\": reverse(\"stats:commission_history\"),\n \"big\": True,\n \"select_date\": {\"extra\": True},\n \"custom_select\": [(\"Sum\", \"Suma\"), (\"Avg\", \"Średnia\"), (\"Count\", \"Ilość\")],\n }\n )\n charts.append(\n {\n \"title\": \"Historia sprzedaży czynników\",\n \"url\": reverse(\"stats:refrigerant_history\"),\n \"big\": True,\n \"select_date\": {\"extra\": True},\n \"custom_select\": [(\"r134a\", \"R134a\"), (\"r1234yf\", \"R1234yf\"), (\"r12\", \"R12\"), (\"r404\", \"R404\")],\n }\n )\n return charts\n\n def _get_sale_metrics(self):\n metrics = []\n metrics.append(\n {\"icon\": \"fa-book\", \"color\": \"#89D23A\", \"title\": \"Liczba dodanych faktur\", \"class\": \"sale_invoice_count\"}\n )\n if self.request.user.is_staff:\n metrics.append(\n {\n \"icon\": \"fa-book\",\n \"color\": \"#89D23A\",\n \"title\": \"Kwota netto dodanych faktur\",\n \"class\": \"sale_invoice_sum\",\n }\n )\n metrics.append(\n {\n \"icon\": \"fa-book\",\n \"color\": \"#89D23A\",\n \"title\": \"Kwota brutto dodanych faktur\",\n \"class\": \"sale_invoice_sum_brutto\",\n }\n )\n metrics.append({\"icon\": \"fa-percentage\", \"color\": \"#E21E00\", \"title\": \"Podatek VAT\", \"class\": \"vat_sum\"})\n metrics.append(\n {\n \"icon\": \"fa-percentage\",\n \"color\": \"#E21E00\",\n \"title\": \"Podatek VAT od firm\",\n \"class\": \"company_vat_sum\",\n }\n )\n metrics.append(\n {\n \"icon\": \"fa-percentage\",\n \"color\": \"#E21E00\",\n \"title\": \"Podatek VAT od osób fizycznych\",\n \"class\": \"person_vat_sum\",\n }\n )\n metrics.append(\n {\"icon\": \"fa-hand-holding-usd\", \"color\": \"#E21E00\", \"title\": \"Kwota PTU\", \"class\": \"ptu_sum\"}\n )\n\n metrics.append(\n {\"icon\": \"fa-tasks\", \"color\": \"#427BD2\", \"title\": \"Liczba zakończonych zleceń\", \"class\": \"commission_count\"}\n )\n if self.request.user.is_staff:\n metrics.append(\n {\n \"icon\": \"fa-tasks\",\n \"color\": \"#427BD2\",\n \"title\": \"Kwota zakończonych zleceń\",\n \"class\": \"commission_sum\",\n }\n )\n\n metrics.append(\n {\n \"icon\": \"fa-users\",\n \"color\": \"#00A0DF\",\n \"title\": \"Liczba dodanych kontrahentów\",\n \"class\": \"contractor_count\",\n }\n )\n metrics.append(\n {\"icon\": \"fa-flask\", \"color\": \"#F8640B\", \"title\": \"Sprzedaż czynnika R134a\", \"class\": \"r134a_sum\"}\n )\n metrics.append(\n {\"icon\": \"fa-flask\", \"color\": \"#F8640B\", \"title\": \"Sprzedaż czynnika R1234yf\", \"class\": \"r1234yf_sum\"}\n )\n metrics.append({\"icon\": \"fa-flask\", \"color\": \"#F8640B\", \"title\": \"Sprzedaż czynnika R12\", \"class\": \"r12_sum\"})\n metrics.append({\"icon\": \"fa-flask\", \"color\": \"#F8640B\", \"title\": \"Sprzedaż czynnika R404\", \"class\": \"r404_sum\"})\n return metrics\n\n\nclass SupplierPurchaseHistory(StaffOnlyMixin, ChartDataMixin, View):\n max_positions = 8\n\n def get(self, *args, **kwargs):\n self.date_option = self.request.GET.get(\"date_select\", \"week\")\n self.metric = self.request.GET.get(\"custom_select\", \"Sum\")\n\n self.invoices = self.get_invoices()\n self.response_data = self.get_response_data_template(chart_type=\"doughnut\", values_appendix=\" zł\")\n self.invoices = self.invoices.values(\"supplier\")\n self.invoices = self._annotate(self.invoices)\n self.invoices = self.invoices.values_list(\"supplier__name\", \"total\").order_by(\"-total\")\n if self.invoices.count() > self.max_positions:\n index = self.max_positions - 1\n else:\n index = self.invoices.count()\n\n labels = list(self.invoices[0:index].values_list(\"supplier__name\", flat=True))\n values = list(self.invoices[0:index].values_list(\"total\", flat=True))\n\n if self.invoices.count() > self.max_positions:\n labels.append(\"Pozostali dostawcy\")\n if self.metric == \"Avg\":\n values.append(\n self.invoices[self.max_positions - 1 :].values(\"total\").aggregate(avg=Round(Avg(\"total\")))[\"avg\"]\n )\n else:\n values.append(\n self.invoices[self.max_positions - 1 :].values(\"total\").aggregate(Sum(\"total\"))[\"total__sum\"]\n )\n\n self.response_data[\"data\"][\"labels\"] = labels\n self.response_data[\"data\"][\"datasets\"].append(self.get_dataset(values, COLORS[: len(values)]))\n\n return JsonResponse(self.response_data)\n\n def get_invoices(self):\n invoices = Invoice.objects.all()\n if self.date_option == \"week\":\n date = datetime.today() - relativedelta(days=6)\n elif self.date_option == \"month\":\n date = datetime.today() - relativedelta(months=1)\n elif self.date_option == \"year\":\n date = (datetime.today() - relativedelta(years=1, months=-1)).replace(day=1)\n else:\n date = None\n if date:\n invoices = invoices.filter(date__gte=date)\n return invoices\n\n def _annotate(self, qs):\n if self.metric == \"Sum\":\n return self.invoices.annotate(total=Sum(F(\"invoiceitem__price\") * F(\"invoiceitem__quantity\")))\n if self.metric == \"Avg\":\n return self.invoices.annotate(total=Round(F(\"invoiceitem__price\") * F(\"invoiceitem__quantity\")))\n elif self.metric == \"Count\":\n self.response_data[\"custom\"][\"values_appendix\"] = \"\"\n return self.invoices.annotate(total=Count(\"id\"))\n\n\nclass WarePurchaseHistory(StaffOnlyMixin, ChartDataMixin, View):\n max_positions = 8\n\n def get(self, *args, **kwargs):\n date_option = self.request.GET.get(\"date_select\", \"week\")\n metric = self.request.GET.get(\"custom_select\", \"Count\")\n now = datetime.today()\n if date_option == \"week\":\n date = now - relativedelta(days=6)\n elif date_option == \"month\":\n date = now - relativedelta(months=1)\n elif date_option == \"year\":\n date = (now - relativedelta(years=1, months=-1)).replace(day=1)\n else:\n date = None\n\n response_data = self.get_response_data_template(chart_type=\"doughnut\", values_appendix=\" zł\")\n wares = Ware.objects.exclude(invoiceitem=None)\n if date:\n wares = wares.filter(invoiceitem__invoice__date__gte=date)\n\n if metric == \"Sum\":\n wares = wares.annotate(\n total=Sum(F(\"invoiceitem__quantity\") * F(\"invoiceitem__price\"), output_field=DecimalField())\n )\n elif metric == \"Count\":\n wares = wares.annotate(total=Sum(\"invoiceitem__quantity\"))\n response_data[\"custom\"][\"values_appendix\"] = \"\"\n wares = wares.values_list(\"index\", \"total\").order_by(\"-total\")\n\n if wares.count() > self.max_positions:\n wares = wares[: self.max_positions]\n\n response_data[\"data\"][\"labels\"] = list(wares.values_list(\"index\", flat=True))\n values = list(wares.values_list(\"total\", flat=True))\n response_data[\"data\"][\"datasets\"].append(self.get_dataset(values, COLORS[: len(values)]))\n\n return JsonResponse(response_data)\n\n\nclass PurchaseInvoicesHistory(StaffOnlyMixin, BigChartHistoryMixin):\n model = Invoice\n date_field = \"date\"\n price_field = \"invoiceitem__price\"\n quantity_field = \"invoiceitem__quantity\"\n\n def _filter_objects(self, **kwargs):\n supplier = kwargs.get(\"supplier\")\n if supplier:\n self.objects = self.objects.filter(supplier__pk=supplier)\n\n def _get_default_date_option(self, **kwargs):\n supplier = kwargs.get(\"supplier\")\n if supplier:\n return \"year\"\n return \"week\"\n\n\nclass SaleInvoicesHistory(StaffOnlyMixin, BigChartHistoryMixin):\n model = SaleInvoice\n date_field = \"issue_date\"\n price_field = \"saleinvoiceitem__price_\"\n quantity_field = \"saleinvoiceitem__quantity\"\n\n def _annotate(self, qs):\n if self.metric == \"SumBrutto\":\n self.metric = \"Sum\"\n self.price_field = \"{}brutto\".format(self.price_field)\n if self.metric == \"SumNetto\":\n self.metric = \"Sum\"\n self.price_field = \"{}netto\".format(self.price_field)\n if self.metric == \"AvgBrutto\":\n self.metric = \"Avg\"\n self.price_field = \"{}brutto\".format(self.price_field)\n if self.metric == \"AvgNetto\":\n self.metric = \"Avg\"\n self.price_field = \"{}netto\".format(self.price_field)\n return super()._annotate(qs)\n\n def _filter_objects(self, **kwargs):\n self.objects = self.objects.exclude(\n invoice_type__in=[SaleInvoice.TYPE_PRO_FORMA, SaleInvoice.TYPE_CORRECTIVE, SaleInvoice.TYPE_WDT_PRO_FORMA]\n )\n\n\nclass CommissionHistory(StaffOnlyMixin, BigChartHistoryMixin):\n model = Commission\n date_field = \"end_date\"\n price_field = \"commissionitem__price\"\n quantity_field = \"commissionitem__quantity\"\n\n def _filter_objects(self, **kwargs):\n self.objects = self.objects.filter(status=Commission.DONE).exclude(end_date=None)\n\n\nclass RefrigerantWeightsHistory(StaffOnlyMixin, BigChartHistoryMixin):\n model = SaleInvoice\n date_field = \"issue_date\"\n values_appendix = \" g\"\n\n def _annotate(self, qs):\n return qs.annotate(total=Sum(\"refrigerantweights__\" + self.metric))\n\n\nclass WarePurchaseCost(StaffOnlyMixin, ChartDataMixin, View):\n min_count = 3\n\n def get(self, *args, **kwargs):\n ware_pk = self.kwargs.get(\"pk\")\n response_data = self.get_response_data_template(values_appendix=\" zł\")\n invoices = Invoice.objects.filter(invoiceitem__ware__pk=ware_pk).order_by(\"date\")\n if invoices.count() < self.min_count:\n return JsonResponse({}, status=404)\n response_data[\"data\"][\"labels\"] = list(invoices.values_list(\"date\", flat=True))\n values = list(invoices.values_list(\"invoiceitem__price\", flat=True))\n response_data[\"data\"][\"datasets\"].append(self.get_dataset(values, COLORS[0]))\n\n response_data[\"options\"][\"legend\"][\"display\"] = False\n return JsonResponse(response_data)\n\n\nclass WarePriceChanges(View):\n def get(self, *args, **kwargs):\n date_from = date_parser.parse(self.request.GET.get(\"date_from\")).date()\n date_to = date_parser.parse(self.request.GET.get(\"date_to\")).date()\n changes = WarePriceChange.objects.filter(\n created_date__date__gte=date_from, created_date__date__lte=date_to\n ).order_by(\"-created_date\")\n response = {\"changes\": []}\n for change in changes:\n response[\"changes\"].append(self.get_change_dict(change))\n return JsonResponse(response)\n\n def get_change_dict(self, change):\n return {\n \"invoice\": {\n \"url\": reverse(\n \"warehouse:invoice_detail\", kwargs={\"pk\": change.invoice.pk, \"slug\": slugify(change.invoice)}\n ),\n \"number\": change.invoice.number,\n },\n \"ware\": {\n \"url\": reverse(\"warehouse:ware_detail\", kwargs={\"pk\": change.ware.pk, \"slug\": slugify(change.ware)}),\n \"index\": change.ware.index,\n },\n \"supplier\": {\n \"url\": reverse(\n \"warehouse:supplier_detail\",\n kwargs={\"pk\": change.invoice.supplier.pk, \"slug\": slugify(change.invoice.supplier)},\n ),\n \"name\": change.invoice.supplier.name,\n },\n \"is_discount\": change.is_discount,\n \"last_price\": \"{0:.2f} zł\".format(change.last_price).replace(\".\", \",\"),\n \"new_price\": \"{0:.2f} zł\".format(change.new_price).replace(\".\", \",\"),\n \"created_date\": _date(change.created_date, \"d E Y\"),\n }\n\n\nclass DuePayments(StaffOnlyMixin, View):\n def get(self, *args, **kwargs):\n invoices = (\n SaleInvoice.objects.exclude(invoice_type__in=[SaleInvoice.TYPE_PRO_FORMA, SaleInvoice.TYPE_WDT_PRO_FORMA])\n .filter(payed=False)\n .order_by(\"payment_date\")\n )\n response = {\"invoices\": []}\n for invoice in invoices:\n if not invoice.payment_date:\n invoice.payed = None\n invoice.save()\n continue\n response[\"invoices\"].append(self.get_invoice_dict(invoice))\n return JsonResponse(response)\n\n def get_invoice_dict(self, invoice):\n return {\n \"url\": reverse(\"invoicing:sale_invoice_detail\", kwargs={\"pk\": invoice.pk, \"slug\": slugify(invoice)}),\n \"number\": invoice.number,\n \"brutto_price\": \"{0:.2f} zł\".format(invoice.total_value_brutto).replace(\".\", \",\"),\n \"payment_date\": _date(invoice.payment_date, \"d E Y\"),\n \"issue_date\": _date(invoice.issue_date, \"d E Y\"),\n \"is_exceeded\": invoice.payment_date < date.today(),\n \"contractor\": {\n \"url\": reverse(\n \"invoicing:contractor_detail\",\n kwargs={\"pk\": invoice.contractor.pk, \"slug\": slugify(invoice.contractor)},\n ),\n \"name\": invoice.contractor.name,\n },\n \"payed_url\": reverse(\"invoicing:sale_invoice_set_payed\", kwargs={\"pk\": invoice.pk}),\n }\n\n\nclass Metrics(StaffOnlyMixin, View):\n wares = None\n suppliers = None\n purchase_invoices = None\n sale_invoices = None\n contractors = None\n commissions = None\n weights = None\n ptus = None\n\n def get(self, *args, **kwargs):\n group = self.request.GET.get(\"group\")\n self.date_from = date_parser.parse(self.request.GET.get(\"date_from\")).date()\n self.date_to = date_parser.parse(self.request.GET.get(\"date_to\")).date()\n\n if group == \"purchase\":\n response = self._get_purchase_metrics()\n elif group == \"sale\":\n response = self._get_sale_metrics()\n else:\n return {}\n return JsonResponse(response)\n\n def _get_purchase_metrics(self):\n response = {\n \"ware_count\": self.get_wares().count(),\n \"supplier_count\": self.get_suppliers().count(),\n \"invoice_count\": self.get_purchase_invoices().count(),\n }\n if self.request.user.is_staff:\n response.update(self._get_purchase_secret_metrics())\n return response\n\n def _get_purchase_secret_metrics(self):\n return {\"invoice_sum\": \"{0:.2f} zł\".format(self.get_purchase_invoices().total()).replace(\".\", \",\")}\n\n def _get_sale_metrics(self):\n response = {\n \"contractor_count\": self.get_contractors().count(),\n \"sale_invoice_count\": self.get_sale_invoices().count(),\n \"commission_count\": self.get_commissions().count(),\n }\n r134a = 0\n r1234yf = 0\n r12 = 0\n r404 = 0\n if self.get_weights():\n r134a = self.get_weights().aggregate(Sum(\"r134a\"))[\"r134a__sum\"]\n r1234yf = self.get_weights().aggregate(Sum(\"r1234yf\"))[\"r1234yf__sum\"]\n r12 = self.get_weights().aggregate(Sum(\"r12\"))[\"r12__sum\"]\n r404 = self.get_weights().aggregate(Sum(\"r404\"))[\"r404__sum\"]\n response[\"r134a_sum\"] = \"{} g\".format(r134a)\n response[\"r1234yf_sum\"] = \"{} g\".format(r1234yf)\n response[\"r12_sum\"] = \"{} g\".format(r12)\n response[\"r404_sum\"] = \"{} g\".format(r404)\n\n if self.request.user.is_staff:\n response.update(self._get_sale_secret_metrics())\n return response\n\n def _get_sale_secret_metrics(self):\n invoices_sum_netto = 0\n invoices_sum_brutto = 0\n tax_sum = 0\n person_tax_sum = 0\n if self.get_sale_invoices():\n invoices_sum_netto = self._get_sale_netto(self.get_sale_invoices())\n invoices_sum_brutto = self._get_sale_brutto(self.get_sale_invoices())\n tax_sum = invoices_sum_brutto - invoices_sum_netto\n person_invoices = self.get_sale_invoices().filter(contractor__nip=None)\n if person_invoices:\n person_netto = self._get_sale_netto(person_invoices)\n person_brutto = self._get_sale_brutto(person_invoices)\n person_tax_sum = person_brutto - person_netto\n response = {}\n response[\"sale_invoice_sum\"] = \"{0:.2f} zł\".format(invoices_sum_netto).replace(\".\", \",\")\n response[\"sale_invoice_sum_brutto\"] = \"{0:.2f} zł\".format(invoices_sum_brutto).replace(\".\", \",\")\n response[\"vat_sum\"] = \"{0:.2f} zł\".format(tax_sum).replace(\".\", \",\")\n response[\"person_vat_sum\"] = \"{0:.2f} zł\".format(person_tax_sum).replace(\".\", \",\")\n response[\"company_vat_sum\"] = \"{0:.2f} zł\".format(tax_sum - person_tax_sum).replace(\".\", \",\")\n\n ptu_sum = 0\n if self.get_ptus():\n ptu_sum = self.get_ptus().aggregate(Sum(\"value\"))[\"value__sum\"]\n response[\"ptu_sum\"] = \"{0:.2f} zł\".format(ptu_sum).replace(\".\", \",\")\n\n response[\"commission_sum\"] = \"{0:.2f} zł\".format(self.get_commissions().total()).replace(\".\", \",\")\n return response\n\n def _get_sale_netto(self, queryset):\n return queryset.total(price_type=\"netto\")\n\n def _get_sale_brutto(self, queryset):\n return queryset.total(price_type=\"brutto\")\n\n def get_wares(self):\n if self.wares is not None:\n return self.wares\n self.wares = Ware.objects.filter(created_date__date__gte=self.date_from, created_date__date__lte=self.date_to)\n return self.wares\n\n def get_suppliers(self):\n if self.suppliers is not None:\n return self.suppliers\n self.suppliers = Supplier.objects.filter(\n created_date__date__gte=self.date_from, created_date__date__lte=self.date_to\n )\n return self.suppliers\n\n def get_purchase_invoices(self):\n if self.purchase_invoices is not None:\n return self.purchase_invoices\n self.purchase_invoices = Invoice.objects.filter(date__gte=self.date_from, date__lte=self.date_to)\n return self.purchase_invoices\n\n def get_contractors(self):\n if self.contractors is not None:\n return self.contractors\n self.contractors = Contractor.objects.filter(\n created_date__date__gte=self.date_from, created_date__date__lte=self.date_to\n )\n return self.contractors\n\n def get_weights(self):\n if self.weights is not None:\n return self.weights\n self.weights = RefrigerantWeights.objects.filter(\n sale_invoice__issue_date__gte=self.date_from, sale_invoice__issue_date__lte=self.date_to\n )\n return self.weights\n\n def get_sale_invoices(self):\n if self.sale_invoices is not None:\n return self.sale_invoices\n self.sale_invoices = SaleInvoice.objects.filter(\n issue_date__gte=self.date_from, issue_date__lte=self.date_to\n ).exclude(\n invoice_type__in=[SaleInvoice.TYPE_PRO_FORMA, SaleInvoice.TYPE_CORRECTIVE, SaleInvoice.TYPE_WDT_PRO_FORMA]\n )\n return self.sale_invoices\n\n def get_commissions(self):\n if self.commissions is not None:\n return self.commissions\n self.commissions = Commission.objects.filter(\n end_date__gte=self.date_from, end_date__lte=self.date_to, status=Commission.DONE\n )\n return self.commissions\n\n def get_ptus(self):\n if self.ptus is not None:\n return self.ptus\n self.ptus = ReceiptPTU.objects.filter(date__gte=self.date_from, date__lte=self.date_to)\n return self.ptus\n\n\nclass PTUList(StaffOnlyMixin, View):\n def get(self, *args, **kwargs):\n try:\n date_from = date_parser.parse(self.request.GET.get(\"date_from\")).date()\n date_to = date_parser.parse(self.request.GET.get(\"date_to\")).date()\n except TypeError:\n return JsonResponse({\"status\": \"error\", \"message\": \"Niepoprawny zakres dat.\"}, status=400)\n delta = date_to - date_from\n response = {\"ptu\": []}\n ptu_sum = 0\n for i in range(delta.days + 1):\n date = date_from + timedelta(days=i)\n try:\n ptu = ReceiptPTU.objects.get(date=date)\n ptu_sum += ptu.value\n response[\"ptu\"].append(\n {\n \"date\": _date(ptu.date, \"d E Y (l)\"),\n \"date_value\": _date(ptu.date, \"d.m.Y\"),\n \"value\": \"{0:.2f} zł\".format(ptu.value).replace(\".\", \",\"),\n \"warning\": False,\n }\n )\n except ReceiptPTU.DoesNotExist:\n response[\"ptu\"].append(\n {\n \"date\": _date(date, \"d E Y (l)\"),\n \"date_value\": _date(date, \"d.m.Y\"),\n \"value\": \"0,00 zł\",\n \"warning\": True,\n }\n )\n response[\"sum\"] = (\"{0:.2f} zł\".format(ptu_sum).replace(\".\", \",\"),)\n return JsonResponse(response)\n\n\nclass GetPTUValue(StaffOnlyMixin, View):\n def get(self, *args, **kwargs):\n try:\n date = date_parser.parse(self.request.GET.get(\"date\")).date()\n except TypeError:\n return JsonResponse({\"status\": \"error\", \"message\": \"Niepoprawna data.\"}, status=400)\n try:\n ptu = ReceiptPTU.objects.get(date=date)\n return JsonResponse({\"value\": ptu.value})\n except ReceiptPTU.DoesNotExist:\n return JsonResponse({\"value\": 0})\n\n\nclass SavePTU(StaffOnlyMixin, View):\n def post(self, *args, **kwargs):\n date = date_parser.parse(self.request.POST.get(\"date\"), dayfirst=True).date()\n value = self.request.POST.get(\"value\")\n if not date or not value:\n return JsonResponse({\"status\": \"error\", \"message\": \"Niepoprawne dane.\"}, status=400)\n try:\n ptu = ReceiptPTU.objects.get(date=date)\n except ReceiptPTU.DoesNotExist:\n ptu = ReceiptPTU(date=date)\n value = value.replace(\",\", \".\")\n ptu.value = value\n ptu.save()\n return JsonResponse({\"status\": \"success\", \"message\": \"Poprawnie zapisano PTU.\"})\n\n\nclass GetSummary(StaffOnlyMixin, View):\n def get(self, *args, **kwargs):\n try:\n date_from = date_parser.parse(self.request.GET.get(\"date_from\")).date()\n date_to = date_parser.parse(self.request.GET.get(\"date_to\")).date()\n except TypeError:\n return JsonResponse({\"status\": \"error\", \"message\": \"Niepoprawny zakres dat.\"}, status=400)\n response = {}\n ptu_sum = self._get_ptu(date_from, date_to)\n response[\"ptu\"] = \"{0:.2f} zł\".format(ptu_sum).replace(\".\", \",\")\n\n commissions_sum = self._get_commissions(date_from, date_to)\n response[\"commissions\"] = \"{0:.2f} zł\".format(commissions_sum).replace(\".\", \",\")\n\n vat_sum = self._get_vat(date_from, date_to)\n response[\"vat\"] = \"{0:.2f} zł\".format(vat_sum).replace(\".\", \",\")\n\n purchase_sum = self._get_purchase(date_from, date_to)\n response[\"purchase\"] = \"{0:.2f} zł\".format(purchase_sum).replace(\".\", \",\")\n\n all_sum = float(commissions_sum) - float(ptu_sum) - float(vat_sum) - float(purchase_sum)\n response[\"sum\"] = \"{0:.2f} zł\".format(all_sum).replace(\".\", \",\")\n date_range = self._get_date_range(date_from, date_to)\n response[\"urls\"] = {\n \"commissions\": \"{}?end_date={}&status=__ALL__\".format(reverse(\"commission:commissions\"), date_range),\n \"invoices\": \"{}?issue_date={}\".format(reverse(\"invoicing:sale_invoices\"), date_range),\n \"purchase\": \"{}?date={}\".format(reverse(\"warehouse:invoices\"), date_range),\n \"wares\": \"{}?purchase_date={}\".format(reverse(\"warehouse:wares\"), date_range),\n }\n response[\"invoices_without_commission\"] = self._get_sale_invoices_wthout_commission(date_from, date_to)\n return JsonResponse(response)\n\n def _get_date_range(self, date_from, date_to):\n return \"{}+-+{}\".format(date_from.strftime(\"%d.%m.%Y\"), date_to.strftime(\"%d.%m.%Y\"))\n\n def _get_ptu(self, date_from, date_to):\n ptu_sum = 0\n ptu_objects = ReceiptPTU.objects.filter(date__gte=date_from, date__lte=date_to)\n if ptu_objects:\n ptu_sum = ptu_objects.aggregate(Sum(\"value\"))[\"value__sum\"]\n return ptu_sum\n\n def _get_commissions(self, date_from, date_to):\n commissions = Commission.objects.filter(end_date__gte=date_from, end_date__lte=date_to, status=Commission.DONE)\n return commissions.total()\n\n def _get_vat(self, date_from, date_to):\n invoices = (\n SaleInvoice.objects.filter(issue_date__gte=date_from, issue_date__lte=date_to)\n .exclude(contractor__nip=None)\n .exclude(\n invoice_type__in=[\n SaleInvoice.TYPE_PRO_FORMA,\n SaleInvoice.TYPE_CORRECTIVE,\n SaleInvoice.TYPE_WDT_PRO_FORMA,\n ]\n )\n )\n return invoices.total(price_type=\"brutto\") - invoices.total(price_type=\"netto\")\n\n def _get_purchase(self, date_from, date_to):\n invoices = Invoice.objects.filter(date__gte=date_from, date__lte=date_to)\n return invoices.total()\n\n def _get_sale_invoices_wthout_commission(self, date_from, date_to):\n invoices = SaleInvoice.objects.filter(issue_date__gte=date_from, issue_date__lte=date_to, commission=None)\n return [\n {\n \"url\": reverse(\"invoicing:sale_invoice_detail\", kwargs={\"pk\": invoice.pk, \"slug\": slugify(invoice)}),\n \"number\": invoice.number,\n \"brutto_price\": \"{0:.2f} zł\".format(invoice.total_value_brutto).replace(\".\", \",\"),\n \"contractor\": {\n \"url\": reverse(\n \"invoicing:contractor_detail\",\n kwargs={\"pk\": invoice.contractor.pk, \"slug\": slugify(invoice.contractor)},\n ),\n \"name\": invoice.contractor.name,\n },\n }\n for invoice in invoices\n ]\n\n\nclass UnpayedDekoInvoicesView(StaffOnlyMixin, View):\n def get(self, *args, **kwargs):\n self.settings = InvoiceDownloadSettings.load()\n with requests.Session() as s:\n url = \"http://sklep.dekoautoparts.pl/pl\"\n headers = {\n \"User-Agent\": (\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)\"\n \" Chrome/75.0.3770.80 Safari/537.36\"\n )\n }\n r = s.get(url, headers=headers)\n if r.status_code != 200:\n return JsonResponse({}, status=500)\n\n soup = BeautifulSoup(r.content, \"html5lib\")\n data = {\n \"__EVENTTARGET\": \"ctl00$ctl00$BodyContentPlaceHolder$LoginForm$LoginButton\",\n \"__EVENTARGUMENT\": \"\",\n \"__VIEWSTATE\": soup.find(\"input\", attrs={\"name\": \"__VIEWSTATE\"})[\"value\"],\n \"__VIEWSTATEGENERATOR\": soup.find(\"input\", attrs={\"name\": \"__VIEWSTATEGENERATOR\"})[\"value\"],\n \"__EVENTVALIDATION\": soup.find(\"input\", attrs={\"name\": \"__EVENTVALIDATION\"})[\"value\"],\n \"ctl00$ctl00$BodyContentPlaceHolder$LoginForm$Username\": self.settings.DEKO_LOGIN,\n \"ctl00$ctl00$BodyContentPlaceHolder$LoginForm$Password\": self.settings.DEKO_PASSWORD,\n }\n r = s.post(url, data=data, headers=headers)\n if r.status_code != 200:\n return JsonResponse({}, status=500)\n\n url = \"http://sklep.dekoautoparts.pl/AjaxServices/Informations.svc/GetFilteredInvoices\"\n data = {\n \"dateFrom\": (date.today() - timedelta(90)).strftime(\"%Y-%m-%d\"),\n \"dateTo\": (date.today() + timedelta(1)).strftime(\"%Y-%m-%d\"),\n \"overdueOnly\": False,\n }\n r = s.post(url, json=data, headers=headers)\n if r.status_code != 200:\n return JsonResponse({}, status=500)\n\n invoices = []\n sum_to_pay = 0\n soup = BeautifulSoup(r.json()[\"d\"], \"html5lib\")\n for row in soup.find(\"table\").find_all(\"tr\")[1:]:\n if row.attrs.get(\"class\") and \"row-separator\" in row.attrs.get(\"class\"):\n continue\n if row.find(\"td\", {\"class\": \"flex-note\"}):\n continue\n if not row.find(\"td\"):\n continue\n to_pay = row.find(\"td\", attrs={\"class\": \"flex-price-to-pay\"}).text.strip()\n if to_pay == \"0 zł\":\n continue\n to_pay = Decimal(remove_suffix(to_pay, \" zł\").replace(\" \", \"\").replace(\",\", \".\"))\n sum_to_pay += to_pay\n number = row.find(\"td\").text.strip()\n number = remove_suffixes(number, [\"Faktura\", \"Nota kredytowa\", \"Korekta\"])\n invoice = {\n \"number\": number,\n \"date\": _date(\n date_parser.parse(\n row.find(\"td\", attrs={\"attr-text\": \"Wydane:\"}).text.strip(), dayfirst=True\n ).date()\n ),\n \"to_pay\": to_pay,\n }\n try:\n obj = Invoice.objects.get(number=number, supplier=self.settings.DEKO_SUPPLIER)\n invoice[\"url\"] = reverse(\"warehouse:invoice_detail\", kwargs={\"slug\": slugify(obj), \"pk\": obj.pk})\n except Invoice.DoesNotExist:\n pass\n invoices.append(invoice)\n return JsonResponse({\"invoices\": invoices, \"to_pay\": sum_to_pay})\n","sub_path":"apps/stats/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":34863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"252587856","text":"#!/usr/bin/env python\n\n__description__ = 'Hex to bin'\n__author__ = 'Didier Stevens'\n__version__ = '0.0.2'\n__date__ = '2019/05/11'\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/12/20: added stdin support\n 2016/01/06: changed name from hex2bin.py to hex-to-bin.py; added man\n 2019/05/07: added option -a\n 2019/05/11: added option -l and -s\n\nTodo:\n\"\"\"\n\nimport optparse\nimport binascii\nimport sys\nimport os\nimport signal\nimport textwrap\n\ndef PrintManual():\n manual = '''\nManual:\n\nThis program reads from the given file or standard input, and converts the hexadecimal data to binary data.\n\nUsing option -a, this tool will look for the first hexadecimal/ASCII dump (see example below) as produced by other tools developed by Didier Stevens, and extract the contained hexadecimal data to convert to binary data.\n\nFile: demo.bin\nMagic header found, dumping data:\n00000000: 4D 5A 90 00 03 00 00 00 04 00 00 00 FF FF 00 00 MZ..............\n00000010: B8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00 ........@.......\n00000020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n\nWith option -a, the tool looks for string 00000000:.\n\nOption -s can be used to select another hexadecimal/ASCII dump than the first one (for example, -s 2 to select the second dump).\n\nOption -l (list) can be used to produce an overview of all hexadecimal/ASCII dumps found in the input, together with an index number to be used with option -s.\n\nThe binary data is written to standard output.\n'''\n for line in manual.split('\\n'):\n print(textwrap.fill(line))\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\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\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 FindBeginHEXASCIIDump(data):\n positions = []\n position = 0\n while position != -1:\n position = data.find('00000000: ', position)\n if position != -1:\n if position == 0 or data[position - 1] == '\\x0A':\n positions.append(position)\n position += 1\n return positions\n\ndef ExtractHEXASCIIDump(data, select):\n positionColon = 8\n lengthHexadecimal = 48\n positions = FindBeginHEXASCIIDump(data)\n if positions == []:\n return ''\n result = ''\n for line in data[positions[select - 1]:].split('\\n'):\n line = line.strip()\n if len(line) <= positionColon:\n break\n if line[positionColon] == ':':\n result += line[positionColon + 2:positionColon + 2 + lengthHexadecimal] + '\\n'\n else:\n break\n return result\n\ndef ListHEXASCIIDumps(data):\n for index, position in enumerate(FindBeginHEXASCIIDump(data)):\n print('%d: %s' % (index + 1, data[position:].split('\\n')[0]))\n\ndef Hex2Bin(filename, options):\n FixPipe()\n if filename == '':\n content = sys.stdin.read()\n else:\n content = File2String(filename)\n if options.asciidump:\n content = ExtractHEXASCIIDump(content, int(options.select))\n elif options.list:\n ListHEXASCIIDumps(content)\n return\n if sys.platform == 'win32':\n import msvcrt\n msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\n StdoutWriteChunked(binascii.unhexlify(content.replace(' ', '').replace('\\t', '').replace('\\r', '').replace('\\n', '')))\n\ndef Main():\n oParser = optparse.OptionParser(usage='usage: %prog [options] [file]\\n' + __description__, version='%prog ' + __version__)\n oParser.add_option('-m', '--man', action='store_true', default=False, help='Print manual')\n oParser.add_option('-a', '--asciidump', action='store_true', default=False, help='Extract Hex/ASCII dump from other tools')\n oParser.add_option('-l', '--list', action='store_true', default=False, help='List all Hex/ASCII dumps')\n oParser.add_option('-s', '--select', default='1', help='select dump nr for extraction (default first dump)')\n (options, args) = oParser.parse_args()\n\n if options.man:\n oParser.print_help()\n PrintManual()\n return\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) == 0:\n Hex2Bin('', options)\n else:\n Hex2Bin(args[0], options)\n\nif __name__ == '__main__':\n Main()\n","sub_path":"hex-to-bin.py","file_name":"hex-to-bin.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"101069346","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-06-09 17:26:21\n# @Author : Your Name (you@example.org)\n# @Link : http://example.org\n# @Version : $Id$\n\n#处理企业微信业务\n\nfrom execsqlscript import *\n\n#将传入的内容通过mdm_erp库以企业微信形式发出\ndef send_ky_qywx_text(receivers,content):\t\n\tcontent = content.replace(\"'\",'\"')\n\tconndict = get_conn_mssql_mdm()\n\tsqlcript = ','.join(receivers)\n\tsqlcript = '''insert into svc.Sms_Queue(ToName,ToMobileNo,Context,CreateOn,SendFlag,Type,Src)\n\t\tselect a.Att,a.Att,\\'''' + content + '''\\',getdate(),'pending','qywx','Check_Data'\n\t\tfrom dbo.FSplitStrToTable(\\'''' + sqlcript + '''\\') a\n\t\t'''\n\n\t# print(\"-------------------------------------------------------------------------------\")\n\t# print(sqlcript)\t\n\t# print(\"-------------------------------------------------------------------------------\")\n\ttry:\n\t\texec_mssql_noreturn(conndict, sqlcript)\t\n\texcept Exception as e:\n\t\t# raise e\n\t\tprint(\"异常Sql语句\\n\" + sqlcript)\n\t\tprint(e)\n\n#send_ky_qywx_text([\"990010331\",\"990100133\"],\"测试而已\")\t","sub_path":"lib/send_my_qywx.py","file_name":"send_my_qywx.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"196333873","text":"import vlc\nimport ctypes\nimport cv2\nimport numpy\nimport os\nfrom PIL import Image\nimport base64\n\t\nos.chdir('/home/ubuntu/stream')\nsdp_path = os.path.abspath(\"bebop.sdp\")\n#sdp_path = 'v4l2:///dev/video1'\n#sdp_path = 'udp://@:55004'\npl = vlc.MediaPlayer(sdp_path, \":network-caching=1000\", \":sout-mux-caching=<>\")\n\n#i = vlc.Instance('--verbose 2'.split())\n#pl = i.media_player_new()\n#pl.set_mrl(sdp_path)\n\nVIDEOWIDTH = 640\nVIDEOHEIGHT = 480\n\nimg = None\nflag = False\n\n# size in bytes when RV32\nsize = VIDEOWIDTH * VIDEOHEIGHT * 4\n# allocate buffer\nbuf = (ctypes.c_ubyte * size)()\n# get pointer to buffer\nbuf_p = ctypes.cast(buf, ctypes.c_void_p)\n\nCorrectVideoLockCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p))\n\n@CorrectVideoLockCb\ndef _lockcb(opaque, planes):\n planes[0] = buf_p\n\n@vlc.CallbackDecorators.VideoDisplayCb\ndef _display(opaque, picture):\n global flag\n flag = True\n pass\n\nvlc.libvlc_video_set_callbacks(pl, _lockcb, None, _display, None)\npl.video_set_format(\"RV32\", VIDEOWIDTH, VIDEOHEIGHT, VIDEOWIDTH * 4)\n\npl.play()\n\ndef start(func):\n global flag\n while True:\n img = Image.frombuffer(\"RGBA\", (VIDEOWIDTH, VIDEOHEIGHT), buf, \"raw\", \"BGRA\", 0, 1)\n if img is not None and flag:\n frame = cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)\n _, encoded = cv2.imencode('.jpg', frame) \n encoded = base64.b64encode(encoded)\n func(encoded.decode('utf8'))\n flag = False\n cv2.waitKey(1)\n","sub_path":"misc_code/stream/stream_client_vlc.py","file_name":"stream_client_vlc.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"497069504","text":"import psycopg2\nfrom flask import current_app, g\nfrom flask.cli import with_appcontext\nimport click\nfrom datetime import datetime\nfrom os import path, environ\nimport json\n\n\ndef get_db():\n db_url = environ.get('DATABASE_URL')\n try:\n if 'db' not in g:\n g.db = psycopg2.connect(db_url)\n return g.db\n except RuntimeError:\n db = psycopg2.connect(db_url)\n return db\n\n\ndef close_db(db_conn=None):\n try:\n db = g.pop('db', None)\n if db is not None:\n db.close()\n except RuntimeError:\n try:\n db_conn.close()\n except:\n print('db close error')\n\n\ndef select_all_data():\n db = get_db()\n cursor = db.cursor()\n all_data = cursor.execute('SELECT id, location, latitude, longitude, created, nickname FROM data;')\n all_data = cursor.fetchall()\n db.commit()\n cursor.close()\n # db.close()\n close_db(db)\n return all_data\n\n\ndef create_table():\n '''\n created new data table in DB\n :return:\n '''\n db = get_db()\n cursor = db.cursor()\n status = cursor.execute('CREATE TABLE data2 (id SERIAL PRIMARY KEY, location TEXT NOT NULL, latitude REAL NOT NULL, longitude REAL NOT NULL, created TIMESTAMP NOT NULL, nickname TEXT);')\n print('status: ', status)\n db.commit()\n cursor.close()\n close_db(db)\n\n\ndef add_column_to_data():\n '''\n adds empty nickname column to data table\n :return:\n '''\n db = get_db()\n cursor = db.cursor()\n status = cursor.execute('ALTER TABLE data ADD COLUMN nickname TEXT;')\n db.commit()\n cursor.close()\n close_db(db)\n\n\ndef insert_into_data(location, latitude, longitude, nickname):\n db = get_db()\n cursor = db.cursor()\n cursor.execute(\"INSERT INTO data (location, latitude, longitude, created, nickname) VALUES (%s, %s, %s, %s, %s)\",\n (location, latitude, longitude, datetime.utcnow(), nickname))\n db.commit()\n cursor.close()\n # db.close()\n close_db(db)\n return True\n\n\ndef select_map_data():\n db = get_db()\n cursor = db.cursor()\n cursor.execute('SELECT latitude, longitude FROM data')\n all_data = cursor.fetchall()\n map_data = []\n for each in all_data:\n # map_data.append([each['latitude'], each['longitude']])\n map_data.append([each[0], each[1]])\n cursor.close()\n # db.close()\n close_db(db)\n return map_data\n\n\ndef select_nicknames():\n db = get_db()\n cursor = db.cursor()\n cursor.execute('SELECT nickname FROM data')\n db_data = cursor.fetchall()\n nicknames = []\n for each in db_data:\n nicknames.append(each[0])\n cursor.close()\n # db.close()\n close_db(db)\n return nicknames\n\n\ndef export_to_json():\n db = get_db()\n cursor = db.cursor()\n cursor.execute('SELECT location, latitude, longitude, nickname FROM data;')\n all_data = cursor.fetchall()\n db.commit()\n cursor.close()\n close_db(db)\n\n headers = ['location', 'latitude', 'longitude', 'nickname']\n json_data = json.dumps([headers, all_data], indent=4, sort_keys=True, separators=(',', ': '), ensure_ascii=True)\n return json_data\n\n\ndef init_app(app):\n app.teardown_appcontext(close_db)\n","sub_path":"db_pg.py","file_name":"db_pg.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"536691171","text":"__author__ = 'Viral_Shah'\n\nfrom b.WordFrequencyCounter import compute_word_frequencies\n\n\ndef compute_palindrome_frequencies(words: list):\n \"\"\"\n :param words: takes in a list of strings\n :return: returns list of frequencies of palindromes in list of strings\n\n SEE ANALYSIS FOR MORE EXPLANATIONS\n\n we create:\n a list of indices of beginnings of words in a joined string of the list of words\n a list of indices of ending of words in a joined string of the list of words\n a joined string of the list of words\n\n we then iterate over the string using range and expand around each character to find palindromes and record them, we then convert to list of frequencies\n \"\"\"\n\n # create an array of palindromes\n palindromes = []\n #check if the words list is empty\n if not words:\n return palindromes\n\n else:\n complete_words, begin_indices, end_indices = setup(words)\n total_length = len(complete_words)\n\n # set the constant of minimum length of palindromes found\n MIN_LEN = 3\n\n for i in range(total_length):\n\n begin = i\n end = i + 1\n # handling odd length strings by setting before pointer to current char\n while (check_indexes(begin, end, total_length) and (check_reverse_match(begin, end, complete_words))):\n # When we encounter a space, we must skip over it, so a palindrome _abba_ is not counted we just move pointer backwards or forwards\n if complete_words[begin] == \" \":\n begin-=1\n continue\n if complete_words[end] == \" \":\n end+=1\n continue\n pal = complete_words[begin : end + 1]\n if (is_valid_palindrome(pal) and (begin in begin_indices) and (end in end_indices)):\n palindromes.append(pal)\n # expand outwards\n begin-=1\n end+=1\n\n # reinitialize begin and end for even length strings by setting pointer before and after current char\n begin = i - 1\n end = i + 1\n\n while (check_indexes(begin, end, total_length) and (check_reverse_match(begin, end, complete_words))):\n # When we encounter a space, we must skip over it, so a palindrome _abba_ is not counted we just move pointer backwards or forwards\n if complete_words[begin] == \" \":\n begin-=1\n continue\n\n if complete_words[end] == \" \":\n end+=1\n continue\n pal = complete_words[begin : end + 1]\n if (is_valid_palindrome(pal) and (begin in begin_indices) and (end in end_indices)):\n palindromes.append(pal)\n # expand outwards\n begin-=1\n end+=1\n\n result = compute_word_frequencies(palindromes)\n return result\n\n\ndef check_indexes(begin, end, total_length):\n \"\"\"\n :param begin: takes in the beginning index of the palindrome string\n :param end: takes in the ending index of palindrome string\n :param total_length: takes in the total length of the string\n :return: returns true if the indexes are valid (between 0 and the total length)\n \"\"\"\n return (begin >= 0) and (end < total_length)\n\ndef check_reverse_match(begin, end, complete_words):\n \"\"\"\n\n :param begin: char index before current char\n :param end: character index after current char\n :param complete_words: string of all the words\n :return: returns true if the characters are equal or either one of them is a space\n \"\"\"\n return complete_words[begin] == complete_words[end] or complete_words[begin] == \" \" or complete_words[end] == \" \"\n\ndef is_valid_palindrome(pal):\n \"\"\"\n :param pal: takes in a string which is a palindrome\n Function checks if the palindrome is longer than 2 letters\n :return: returns boolean value if palindrome is longer than 2 letters\n \"\"\"\n test = len(pal) > 2\n return test\n\ndef setup(words):\n \"\"\"\n :param words: list of strings\n :return: returns list of indices of beginnings and ends and joined string of the words in the list of words\n \"\"\"\n complete_words = \"\"\n begin_indices = []\n end_indices = []\n for word in words:\n b = len(complete_words)\n e = b + (len(word) - 1)\n begin_indices.append(b)\n end_indices.append(e)\n complete_words += word + \" \"\n return (complete_words.strip(), begin_indices, end_indices)","sub_path":"CS-121/Assignment 1/d/PalindromeFrequencyCounter.py","file_name":"PalindromeFrequencyCounter.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"183321165","text":"class fQryRekeningPesertaKUM3:\n def __init__(self,formObj,parentObj):\n self.form = formObj\n self.app = formObj.ClientApplication\n self.FormView = None\n\n def Show(self):\n self.ShowRekening()\n self.FormContainer.Show()\n\n def FilterClick(self,sender):\n self.ShowRekening()\n \n def UnfilterClick(self, sender):\n self.uippeserta.Edit()\n self.uippeserta.tipe = 0\n self.ShowAll()\n\n\n def ShowRekening(self):\n ph = self.app.CreatePacket()\n query1 = self.RekList\n uippeserta = self.uippeserta\n AddParam = ''\n nocol = uippeserta.norek or ''\n nacol = uippeserta.nama or ''\n tipe = uippeserta.tipe or 0\n if nocol != '' :\n AddParam += \" AND %s LIKE '%s'\" % ('AccountNo', nocol)\n if nacol != '' :\n AddParam += \" AND %s LIKE '%s'\" % ('AccountName', nacol)\n #if tipe == 1:\n # AddParam+=\" AND TransactionAccountType = 'F' \"\n #if tipe == 2:\n # AddParam+=\" AND TransactionAccountType = 'L' \"\n query1.OQLText = \"Select from FinancingAccount \\\n [ LMustahiqProduct.LProduct.ProductGroupName='KUM3' %s ] \\\n ( AccountNo, \\\n AccountName, \\\n self); \" % (AddParam)\n #raise 'oql', query1.OQLText\n query1.DisplayData()\n \n def ShowAll(self):\n ph = self.app.CreatePacket()\n #raise 'ids', listid.accno\n query1 = self.RekList\n query1.OQLText = \"Select from FinancingAccount \\\n [ LMustahiqProduct.LProduct.ProductGroupName='KUM3' ] \\\n ( AccountNo, \\\n AccountName, \\\n self); \"\n #raise 'oql', query1.OQLText\n query1.DisplayData()\n \n def ViewData(self):\n key = self.RekList.KeyObjConst\n #raise 'key', key\n ph = self.app.CreateValues(\n ['key', key])\n res = self.FormObject.CallServerMethod('GetMsId', ph)\n mustahiq = res.FirstRecord\n mustahiqkey = \"PObj:MustahiqProduct#PRODUCTID=%s#MUSTAHIQID=%s\" % (mustahiq.pid,mustahiq.msid)\n #raise '', mustahiqkey\n ph = self.app.CreateValues(\n ['key', mustahiqkey])\n dlg = self.app.CreateForm('KUM3/fPesertaKUM3ViewEx','fPesertaKUM3ViewEx',0,ph,None)\n dlg.Show()\n\n\n def ViewPeserta(self, sender):\n self.ViewData()\n\n def ViewHistory(self):\n key = self.RekList.KeyObjConst\n #raise 'key', key\n ph = self.app.CreateValues(\n ['key', key],\n ['tabel', 'fina'])\n dlg = self.app.CreateForm('KUM3/QryHistoryTransaksi','QryHistoryTransaksi',0,ph,None)\n dlg.Show()\n\n def ViewHistoryClick(self, sender):\n self.ViewHistory()\n\n\n \n\n","sub_path":"dialogs/KUM3/fQryRekeningPesertaKUM3_intr.py","file_name":"fQryRekeningPesertaKUM3_intr.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"648166408","text":"import pandas as pd\n#import numpy as np\nimport sys\n\n#############################################################################\n## command to run the code #################################################\n### python script_num1.py FMD-January2020_new.xlsx FMD-January2020_new.csv ##\n##############################################################################\n\ndf = pd.read_excel(sys.argv[1])\n\ndef fix(value):\n #print(value, type(value))\n if type(value) is not str:\n return str(value).zfill(6)\n else:\n return value\ndf['Fabric#'] = df['Fabric#'].map(fix)\n\ntlrd = '''TLRD BRND \nOO at Mill '''\ndef fix2(value):\n return int(value)\ndf[tlrd] = df[tlrd].map(fix2)\ndf.to_csv(sys.argv[2], index=False,header=True )\n\n\n\n","sub_path":"script_num1.py","file_name":"script_num1.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"630199170","text":"import seaborn as sns\nimport pandas as pd\nimport numpy as np\n\n# create freq matrix\ndef cross_freq(arr):\n shape = arr.shape[1]\n f = np.zeros((shape, shape))\n for j in range(0, shape):\n for i in range(j, shape):\n ind = np.where(np.logical_and(~np.isnan(arr[..., j]), ~np.isnan(arr[..., i])))\n f[j, i], f[i, j] = ind[0].shape[0], ind[0].shape[0]\n return f\n\nengines = pd.read_csv('engines.csv', header=0, delimiter=',')\nf = np.array(engines)\nf = cross_freq(f)\ne = pd.DataFrame(f)\n\nnames = {}\nfor i, col in enumerate(engines.columns):\n names[i] = col\n\ne = e.rename(names)\ne = e.rename(columns=names)\nprint(e)\n\nmask = np.zeros_like(e)\nmask[np.triu_indices_from(mask)] = True\n\nsns.set_style(\"white\")\nhmap = sns.heatmap(e, cmap=sns.cubehelix_palette(8, start=1, dark=0.1, light=.85, as_cmap=True),\n linewidths=.3,\n mask = mask,\n vmax = 100,\n vmin = 1)\nsns.plt.yticks(rotation=0)\nsns.plt.xticks(rotation=90)\nsns.plt.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.15)\n# sns.plt.savefig('heatmap.pdf')\nsns.plt.show()\n","sub_path":"z_old/snippets/visualization/seaborn/heatmap.py","file_name":"heatmap.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"36056951","text":"import json\nimport socket\nimport os\nimport _thread\n\n# System parameters\nhost = \"localhost\"\nport = 50001\nsize = 1024\n\n# Create connection to server\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((host,port))\nname = \"\"\n\ndef send_message():\n while True:\n print(\"User name for direct message, b for broadcast or q for quiting\")\n dest = input()\n if dest == \"q\":\n print(\"Bye\")\n data = json.dumps({\"type\": \"quit\", \"payload\": {\"source\": name}})\n s.send(data.encode(\"utf-8\"))\n s.close()\n # Need to use os instead of sys, because sys only stops the thread\n os._exit(0)\n\n print(\"What is the message?\")\n msg = input()\n if dest == \"b\":\n data = json.dumps({\"type\": \"broadcast\", \"payload\": {\"source\": name, \"content\": msg}})\n else:\n data = json.dumps({\"type\": \"message\", \"payload\": {\"source\": name, \"dest\": dest, \"content\": msg}})\n s.send(data.encode(\"utf-8\"))\n\n# Request an user name (must be unique in the system)\nprint(\"What name do you want to use?\")\nwhile True:\n name = input()\n if name == \"b\" or name == \"q\":\n print(\"Reserved name. Try another one\")\n continue\n data = json.dumps({\"type\": \"connection\", \"payload\": {\"name\": name}})\n s.send(data.encode(\"utf-8\"))\n # Waits for server response\n data = s.recv(size)\n if data:\n data = json.loads(data.decode(\"utf-8\"))\n # Ok status means the name has been accepted\n if data[\"payload\"][\"status\"] == \"ok\":\n break\n else:\n print(\"Name already taken. Try another one.\")\n\n_thread.start_new_thread(send_message, ())\n\nwhile True:\n raw_data = s.recv(size)\n if raw_data:\n data = json.loads(raw_data.decode(\"utf-8\"))\n if data[\"type\"] == \"broadcast\":\n print(data[\"payload\"][\"source\"], \"(broadcast) >>\", data[\"payload\"][\"content\"])\n elif data[\"type\"] == \"message\":\n print(data[\"payload\"][\"source\"], \">>\", data[\"payload\"][\"content\"])\n else:\n print(\"Something wrong has happened, tell about this to the system admin!\")\n print(\"And send him this:\", raw_data)\n os._exit(1)\n\n# Close the connection\ns.close()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"444134854","text":"\"\"\" \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nTemplate for implementing StrategyLearner (c) 2016 Tucker Balch \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nCopyright 2018, Georgia Institute of Technology (Georgia Tech) \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nAtlanta, Georgia 30332 \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nAll Rights Reserved \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nTemplate code for CS 4646/7646 \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nGeorgia Tech asserts copyright ownership of this template and all derivative \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nworks, including solutions to the projects assigned in this course. Students \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nand other users of this template code are advised not to share it with others \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nor to make it available on publicly viewable websites including repositories \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nsuch as github and gitlab. This copyright statement should not be removed \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nor edited. \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nWe do grant permission to share solutions privately with non-students such \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nas potential employers. However, sharing with other current or future \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nstudents of CS 7646 is prohibited and subject to being investigated as a \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nGT honor code violation. \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n-----do not edit anything above this line--- \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nStudent Name: Tucker Balch (replace with your name) \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nGT User ID: dmehta32 (replace with your User ID)\nGT ID: 902831571 (replace with your GT ID)\n\"\"\"\n\nimport numpy as np\nimport datetime as dt\nimport pandas as pd\nimport util as ut\nimport random\nimport BagLearner as bl\nimport RTLearner as rt\nimport ManualStrategy as mans\nimport indicators as ind\nimport marketsimcode as ms\n\n\nclass StrategyLearner(object):\n\n # constructor \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n def __init__(self, verbose=False, impact=0.0):\n self.verbose = verbose\n self.impact = impact\n self.learner = bl.BagLearner(learner=rt.RTLearner, kwargs={\"leaf_size\":5}, bags=20)\n\n def addEvidence(self, symbol=\"IBM\", \\\n sd=dt.datetime(2008, 1, 1), \\\n ed=dt.datetime(2009, 1, 1), \\\n sv=10000):\n\n # add your code to do learning here\n # example usage of the old backward compatible util function \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n syms = [symbol]\n dates = pd.date_range(sd, ed)\n prices_all = ut.get_data(syms, dates) # automatically adds SPY \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n prices = prices_all[syms] # only portfolio symbols \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n prices_SPY = prices_all['SPY'] # only SPY, for comparison later\n if self.verbose: print(prices)\n\n # Get Indicators used from Project 6 - Manual Strategy (indicators.py)\n sma = ind.calculate_sma(prices)\n bb_upper, bb_lower, bb_ratio = ind.calculate_bb(prices)\n window = 10\n momentum = ind.calculate_momentum(prices, window)\n indicators = pd.concat((sma, bb_ratio, momentum), axis=1)\n indicators.columns = ['SMA', 'BBR', 'MOM']\n indicators.fillna(0, inplace=True)\n indicators = indicators[:-5]\n trainX = indicators.values\n\n # Create the Training Set for Y Values based on the indicators\n # We use market variance as 2% and use N = 5 days\n N = 5\n YBUY = 0.02 + self.impact\n YSELL = -0.02 - self.impact\n prices = prices / prices.iloc[0]\n trainY = np.zeros(prices.shape[0] - N) # Normalize Prices\n for t in range(prices.shape[0] - N):\n # ret = (price[t+N]/price[t]) - 1.0\n ret = (prices.ix[t + N, symbol] / prices.ix[t, symbol]) - 1.0\n if ret > YBUY:\n trainY[t] = 1 # LONG\n elif ret < YSELL:\n trainY[t] = -1 # SHORT\n else:\n trainY[t] = 0 # CASH\n\n # Feed our bag learner the training data to learn a strategy\n self.learner.addEvidence(trainX, trainY)\n\n # this method should use the existing policy and test it against new data\n def testPolicy(self, symbol=\"IBM\", \\\n sd=dt.datetime(2009, 1, 1), \\\n ed=dt.datetime(2010, 1, 1), \\\n sv=10000):\n\n syms = [symbol]\n dates = pd.date_range(sd, ed)\n prices_all = ut.get_data(syms, dates) # automatically adds SPY\n prices = prices_all[syms] # only portfolio symbols\n # prices_SPY = prices_all['SPY'] # only SPY, for comparison later\n\n # Get Indicators used from Project 6 - Manual Strategy (indicators.py)\n sma = ind.calculate_sma(prices)\n bb_upper, bb_lower, bb_ratio = ind.calculate_bb(prices)\n window = 10\n momentum = ind.calculate_momentum(prices, window)\n indicators = pd.concat((sma, bb_ratio, momentum), axis=1)\n indicators.columns = ['SMA', 'BBR', 'MOM']\n indicators.fillna(0, inplace=True)\n indicators = indicators[:-5]\n testX = indicators.values\n\n # Based on the trained learner, get the predicted Y values\n testY = self.learner.query(testX)\n\n # Make the dataframe for trades\n df_trades = pd.DataFrame(index=prices_all.index, columns=[symbol])\n df_trades.loc[:] = 0\n current_holding = 0\n for i in range(testY.shape[0]):\n # Buy the stock i.e. LONG\n if testY[i] > 0:\n if current_holding == 0:\n df_trades.values[i, :] = 1000\n current_holding += 1000\n elif current_holding == -1000:\n df_trades.values[i, :] = 2000\n current_holding += 2000\n elif current_holding == 1000:\n df_trades.values[i, :] = 0\n\n # Sell the stock i.e. SHORT\n elif testY[i] < 0:\n if current_holding == 0:\n df_trades.values[i, :] = -1000\n current_holding -= 1000\n elif current_holding == 1000:\n df_trades.values[i, :] = -2000\n current_holding -= 2000\n elif current_holding == -1000:\n df_trades.values[i, :] = 0\n\n # HOLD the Stock\n elif testY[i] == 0:\n if current_holding == 1000:\n df_trades.values[i, :] = -1000\n current_holding -= 1000\n elif current_holding == -1000:\n df_trades.values[i, :] = 1000\n current_holding += 1000\n elif current_holding == 0:\n df_trades.values[i, :] = 0\n\n if current_holding == -1000:\n df_trades.values[prices.shape[0] - 1, :] = 1000\n elif current_holding == 1000:\n df_trades.values[prices.shape[0] - 1, :] = -1000\n\n if self.verbose: print(\n type(df_trades)) # it better be a DataFrame!\n if self.verbose: print(df_trades)\n if self.verbose: print(prices_all)\n\n return df_trades\n\n def author(self):\n return 'dmehta32'\n\n\nif __name__ == \"__main__\":\n print(\"One does not simply think up a strategy\")\n","sub_path":"ML4T_2019Fall/strategy_learner/StrategyLearner.py","file_name":"StrategyLearner.py","file_ext":"py","file_size_in_byte":7927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"450896310","text":"import numpy as np\nimport cv2\nimport os\n\n# USER INPUT\nfiledir = \"/homes/mat10/Programming/OpenCV/frames/\"\nsavedir = \"/homes/mat10/Programming/OpenCV/frames/mouths/\"\nfiles = 'all'#'['frame0.jpg'] # put all files in list, if all files are needed write: files = 'all'\n\n\n# PROGRAM\nif not os.path.isdir(savedir):\n print(\"save_directory does not exist\")\n print(\"making save_directory: %s\" % savedir)\n os.mkdir(savedir)\n\nif files == 'all':\n files = [file for file in os.listdir(filedir) if file[-3:] == 'jpg']\n\nface_cascade = cv2.CascadeClassifier(\n '/homes/mat10/Programming/OpenCV/haarcascade_frontalface_default.xml')\nmouth_cascade = cv2.CascadeClassifier(\n '/homes/mat10/Programming/OpenCV/haarcascade_mcs_mouth.xml')\n\n#file = files[0]\nfor i, file in enumerate(files):\n\n img = cv2.imread(filedir + file, 0)\n # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # First detect face - assuming a single face\n faces = face_cascade.detectMultiScale(img, 1.3, 5)\n x, y, w, h = faces[0]\n # cv2.rectangle(gray, (x, y), (x+w, y+h), (0, 255, 0), 3)\n roi_face = img[y:y+h, x:x+w]\n\n # Then detect mouth\n mouth = mouth_cascade.detectMultiScale(roi_face, minNeighbors=100, maxSize=(100, 100))\n ex, ey, ew, eh = mouth[0]\n # cv2.rectangle(roi_face, (ex, ey), (ex+ew, ey+eh) , (0, 255, 0), 1)\n roi_mouth = roi_face[ey:ey+eh, ex:ex+ew]\n\n cv2.imwrite(savedir + \"mouth%d.jpg\" % i, roi_mouth)\n\n # Not fully automated yet!!!\n\n # cv2.imshow('img', roi_mouth)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n","sub_path":"frame2mouth.py","file_name":"frame2mouth.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"559748167","text":"from sqlalchemy import MetaData\n\nimport pytest\n\nfrom acondbs import create_app\nfrom acondbs.db.ops import define_tables\nfrom acondbs.db.sa import sa\n\n##__________________________________________________________________||\n@pytest.fixture\ndef app_with_empty_db():\n database_uri =\"sqlite:///:memory:\"\n app = create_app(SQLALCHEMY_DATABASE_URI=database_uri)\n yield app\n\n##__________________________________________________________________||\ndef test_define_tables_start_with_empty_db(app_with_empty_db):\n \"\"\"test define_tables()\n\n This function tests if tables will be defined starting from new db without\n any tables.\n\n \"\"\"\n\n app = app_with_empty_db\n\n # confirm tables are not defined initially\n with app.app_context():\n metadata = MetaData()\n metadata.reflect(bind=sa.engine)\n assert not metadata.tables\n\n with app.app_context():\n define_tables()\n\n with app.app_context():\n metadata = MetaData()\n metadata.reflect(bind=sa.engine)\n tbl_names = {\n 'simulations', 'simulation_file_paths',\n 'maps', 'map_file_paths',\n 'beams', 'beam_file_paths'\n }\n assert tbl_names == metadata.tables.keys()\n\n##__________________________________________________________________||\ndef test_define_tables_start_with_nonempty_db(app):\n \"\"\"test define_tables()\n\n This function tests if tables will be redefined starting from db\n with tables with entries.\n\n \"\"\"\n\n # confirm tables are defined initially and not empty\n with app.app_context():\n metadata = MetaData()\n metadata.reflect(bind=sa.engine)\n assert metadata.tables\n total_nentries = sum([len([r for r in\n sa.engine.execute(tbl.select())]) for tbl in\n metadata.sorted_tables])\n assert total_nentries > 0\n\n with app.app_context():\n define_tables()\n\n # confirm tables are defined and all empty\n with app.app_context():\n metadata = MetaData()\n metadata.reflect(bind=sa.engine)\n tbl_names = {\n 'simulations', 'simulation_file_paths',\n 'maps', 'map_file_paths',\n 'beams', 'beam_file_paths'\n }\n assert tbl_names == metadata.tables.keys()\n total_nentries = sum([len([r for r in\n sa.engine.execute(tbl.select())]) for tbl in\n metadata.sorted_tables])\n assert total_nentries == 0\n\n##__________________________________________________________________||\n","sub_path":"tests/db/ops/test_define_tables.py","file_name":"test_define_tables.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"208294776","text":"\"\"\"\nDefinition of urls for TheoWebsiteAssignment.\n\"\"\"\n\nfrom datetime import datetime\nfrom django.conf.urls import url\nimport django.contrib.auth.views\n\nimport app.forms\nimport app.views\n\n# Uncomment the next lines to enable the admin:\nfrom django.conf.urls import include\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = [\n # Club url:\n url(r'^clubs$', app.views.clubs, name='clubs'),\n url(r'^clubs/create$', app.views.clubcreate, name='clubcreate'),\n url(r'^clubs/(?P\\d+)$', app.views.clubdetails, name='clubdetails'),\n url(r'^clubs/delete/(?P\\d+)$', app.views.clubdelete, name='clubdelete'),\n\n #Team url:\n url(r'^teams$', app.views.teams, name='teams'),\n url(r'^teams/create$', app.views.teamcreate, name='teamcreate'),\n url(r'^teams/(?P\\d+)$', app.views.teamdetails, name='teamdetails'),\n url(r'^teams/delete/(?P\\d+)$', app.views.teamdelete, name='teamdelete'),\n\n #Player url:\n url(r'^players$', app.views.players, name='players'),\n url(r'^players/create$', app.views.playercreate, name='playercreate'),\n url(r'^players/(?P\\d+)$', app.views.playerdetails, name='playerdetails'),\n url(r'^players/delete/(?P\\d+)$', app.views.playerdelete, name='playerdelete'),\n\n #Generic url\n url(r'^$', app.views.home, name='home'),\n url(r'^login/$',\n django.contrib.auth.views.login,\n {\n 'template_name': 'app/login.html',\n 'authentication_form': app.forms.BootstrapAuthenticationForm,\n 'extra_context':\n {\n 'title': 'Log in',\n 'year': datetime.now().year,\n }\n },\n name='login'),\n url(r'^logout$',\n django.contrib.auth.views.logout,\n {\n 'next_page': '/',\n },\n name='logout'),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n]\n","sub_path":"TheoWebsiteAssignment/TheoWebsiteAssignment/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"644387847","text":"# -*-coding:utf-8-*-\n\nimport datetime\nfrom django.shortcuts import render_to_response\n\nimport models\n\nDEFAULT_COUNT_PER_PAGE = 30\nPAGE_BAD = 0\nPAGE_1ST = 1\nDEFAULT_PAGE = PAGE_1ST\nCATEGORY_ALL = 0\nDEFAULT_CATEGORY = CATEGORY_ALL\nMAX_TITLE_LEN = 75\n\ndef tuan_city_category_page(request, city, category, page):\n \"\"\"\n \"\"\"\n try:\n category = int(category)\n except ValueError:\n category = DEFAULT_CATEGORY\n \n try:\n page = int(page)\n except ValueError:\n page = DEFAULT_CATEGORY\n if page < PAGE_1ST: page = PAGE_1ST\n count = DEFAULT_COUNT_PER_PAGE\n deals = None\n if category == 0:\n deals = models.Deal.objects.filter(city=city)\n else:\n deals = models.Deal.objects.filter(city=city, category=category)\n deals = deals.filter(time_end__gte=datetime.datetime.now()).order_by('-rank')\n total = deals.count()\n if total != 0:\n deals = deals[ (page - 1) * count : (page - 1) * count + count]\n max_page = (total / count) + ( (total % count > 0) and 1 or 0 )\n next_page = (page < max_page) and page + 1 or PAGE_BAD\n prev_page = (page > PAGE_1ST) and (page - 1) or PAGE_BAD\n for deal in deals:\n if len(deal.title) <= MAX_TITLE_LEN:\n deal.title_short = deal.title\n else:\n deal.title_short = deal.title[:MAX_TITLE_LEN] + unicode('…','utf-8') #'...'\n site = models.Site.objects.filter(site=deal.site)\n if site.count() == 1:\n deal.site_name = site[0].name\n site_city = models.SiteCity.objects.filter(site=deal.site,city=deal.city)\n if site_city.count() == 1:\n deal.site_url = site_city[0].url\n else:\n deal.site_url = site[0].url\n else:\n deal.site_name = ''\n # 获取城市名称\n city_name = city\n city_query = models.City.objects.filter(city=city)\n if city_query.count() == 1:\n city_name = city_query[0].name\n # 获取团购网站列表\n site = models.Site.objects.all()\n return render_to_response('tuan.html', locals())\n\ndef tuan_city_category(request, city, category):\n return tuan_city_category_page(request, city, category, DEFAULT_PAGE)\n\ndef tuan_city_page(request, city, page):\n return tuan_city_category_page(request, city, DEFAULT_CATEGORY, page)\n\ndef tuan_city(request, city):\n return tuan_city_page(request, city, DEFAULT_PAGE)\n\ndef tuan_page(request, page):\n return tuan_city_page(request, 'shenzhen', page)\n\ndef tuan(request):\n return tuan_page(request, DEFAULT_PAGE)\n\n\n","sub_path":"ip469/tuan/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"97998020","text":"import time\nimport inspect\nimport random\nfrom math import sqrt, sin, asin\n\nimport cozmo\nfrom cozmo.util import distance_mm, speed_mmps, degrees, Distance, Angle\n\nfrom .base import *\nfrom .events import *\nfrom .cozmo_kin import wheelbase\n\n#________________ Ordinary Nodes ________________\n\nclass ParentCompletes(StateNode):\n def start(self,event=None):\n super().start(event)\n if TRACE.trace_level > TRACE.statenode_startstop:\n print('TRACE%d:' % TRACE.statenode_startstop,\n '%s is causing %s to complete' % (self, self.parent))\n if self.parent:\n self.parent.post_completion()\n\nclass ParentSucceeds(StateNode):\n def start(self,event=None):\n super().start(event)\n if TRACE.trace_level > TRACE.statenode_startstop:\n print('TRACE%d:' % TRACE.statenode_startstop,\n '%s is causing %s to succeed' % (self, self.parent))\n if self.parent:\n self.parent.post_success()\n\nclass ParentFails(StateNode):\n def start(self,event=None):\n super().start(event)\n if TRACE.trace_level > TRACE.statenode_startstop:\n print('TRACE%d:' % TRACE.statenode_startstop,\n '%s is causing %s to fail' % (self, self.parent))\n if self.parent:\n self.parent.post_failure()\n\nclass Iterate(StateNode):\n \"\"\"Iterates over an iterable, posting DataEvents. Completes when done.\"\"\"\n def __init__(self,iterable=None):\n super().__init__()\n self.iterable = iterable\n\n class NextEvent(Event): pass\n\n def start(self,event=None):\n if self.running: return\n super().start(event)\n if isinstance(event, DataEvent):\n self.iterable = event.data\n if isinstance(self.iterable, int):\n self.iterable = range(self.iterable)\n if self.iterable is None:\n raise ValueError('~s has nothing to iterate on.' % repr(self))\n if not isinstance(event, self.NextEvent):\n self.iterator = self.iterable.__iter__()\n try:\n value = next(self.iterator)\n except StopIteration:\n self.post_completion()\n return\n self.post_data(value)\n\nclass MoveLift(StateNode):\n def __init__(self,speed):\n super().__init__()\n self.speed = speed\n\n def start(self,event=None):\n if self.running: return\n super().start(event)\n # Temporary hack supplied by Mark Wesley at Anki\n msg = cozmo._clad._clad_to_engine_iface.EnableLiftPower(True)\n self.robot.conn.send_msg(msg)\n self.robot.move_lift(self.speed)\n\n def stop(self):\n if not self.running: return\n self.robot.move_lift(0)\n super().stop()\n\nclass RelaxLift(StateNode):\n def start(self,event=None):\n if self.running: return\n super().start(event)\n # Temporary hack supplied by Mark Wesley at Anki\n msg = cozmo._clad._clad_to_engine_iface.EnableLiftPower(False)\n self.robot.conn.send_msg(msg)\n\nclass SetLights(StateNode):\n def __init__(self, object, light):\n super().__init__()\n self.object = object\n self.light = light\n\n def start(self,event=None):\n super().start(event)\n if self.object is not self.robot:\n self.object.set_lights(self.light)\n else:\n if self.light.on_color.int_color & 0x00FFFF00 == 0: # no green or blue component\n self.robot.set_all_backpack_lights(self.light)\n else:\n self.robot.set_backpack_lights_off()\n self.robot.set_center_backpack_lights(self.light)\n self.post_completion()\n\n#________________ Coroutine Nodes ________________\n\nclass CoroutineNode(StateNode):\n def __init__(self):\n super().__init__()\n self.handle = None\n\n def start(self,event=None):\n super().start(event)\n cor = self.coroutine_launcher()\n if inspect.iscoroutine(cor):\n self.handle = self.robot.loop.create_task(cor)\n else:\n print('cor=',cor,'type=',type(cor))\n raise ValueError(\"Result of %s launch_couroutine() is %s, not a coroutine.\" %\n (self,cor))\n\n def coroutine_launcher(self):\n raise Exception('%s lacks a coroutine_launcher() method' % self)\n \n def stop(self):\n if not self.running: return\n if self.handle: self.handle.cancel()\n super().stop()\n\n\nclass DriveWheels(CoroutineNode):\n def __init__(self,l_wheel_speed,r_wheel_speed,**kwargs):\n super().__init__()\n self.l_wheel_speed = l_wheel_speed\n self.r_wheel_speed = r_wheel_speed\n self.kwargs = kwargs\n\n def start(self,event=None):\n if (isinstance(event,DataEvent) and isinstance(event.data,(list,tuple)) and\n len(event.data) == 2):\n (lspeed,rspeed) = event.data\n if isinstance(lspeed,(int,float)) and isinstance(rspeed,(int,float)):\n self.l_wheel_speed = lspeed\n self.r_wheel_speed = rspeed\n super().start(event)\n\n def coroutine_launcher(self):\n return self.robot.drive_wheels(self.l_wheel_speed,self.r_wheel_speed,**self.kwargs)\n\n def stop_wheels(self):\n try:\n driver = self.robot.drive_wheels(0,0)\n # driver is either a co-routine or None\n if driver: driver.send(None) # will raise StopIteration\n except StopIteration: pass\n\n def stop(self):\n if not self.running: return\n self.stop_wheels()\n super().stop() \n\n\nclass DriveForward(DriveWheels):\n def __init__(self, distance=50, speed=50, **kwargs):\n if isinstance(distance, cozmo.util.Distance):\n distance = distance.distance_mm\n if isinstance(speed, cozmo.util.Speed):\n speed = speed.speed_mmps\n if distance < 0:\n distance = -distance\n speed = -speed\n self.distance = distance\n self.speed = speed\n self.kwargs = kwargs\n super().__init__(speed,speed,**self.kwargs)\n self.polling_interval = 0.1\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Distance):\n self.distance = event.data.distance_mm\n self.start_position = self.robot.pose.position\n super().start(event)\n\n def poll(self):\n \"\"\"See how far we've traveled\"\"\"\n p0 = self.start_position\n p1 = self.robot.pose.position\n diff = (p1.x - p0.x, p1.y - p0.y)\n dist = sqrt(diff[0]*diff[0] + diff[1]*diff[1])\n if dist >= self.distance:\n self.poll_handle.cancel()\n self.stop_wheels()\n self.post_completion()\n\nclass DriveTurn(DriveWheels):\n def __init__(self, angle=90, speed=50, **kwargs):\n if isinstance(angle, cozmo.util.Angle):\n angle = angle.degrees\n if isinstance(speed, cozmo.util.Speed):\n speed = speed.speed_mmps\n if angle < 0:\n speed = -speed\n self.angle = angle\n self.speed = speed\n self.kwargs = kwargs\n super().__init__(-speed,speed,**self.kwargs)\n # Call parent init before setting polling interval.\n self.polling_interval = 0.05\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Angle):\n self.angle = event.data.degrees\n super().start(event)\n self.last_heading = self.robot.pose.rotation.angle_z.degrees\n self.traveled = 0\n\n def poll(self):\n \"\"\"See how far we've traveled\"\"\"\n p0 = self.last_heading\n p1 = self.robot.pose.rotation.angle_z.degrees\n self.last_heading = p1\n # Assume we're polling quickly enough that diff will be small;\n # typically only about 1 degree. So diff will be large only\n # if the heading has passed through 360 degrees since the last\n # call to poll(). Use 90 degrees as an arbitrary large threshold.\n diff = p1 - p0\n if diff < -90.0:\n diff += 360.0\n elif diff > 90.0:\n diff -= 360.0\n self.traveled += diff\n if abs(self.traveled) > abs(self.angle):\n self.poll_handle.cancel()\n self.stop_wheels()\n self.post_completion()\n\n\nclass DriveArc(DriveWheels):\n \"\"\"Negative radius means right turn; negative angle means drive\n backwards. This node can be passed a DataEvent with a dict\n containing any of the arguments accepted by __init__: radius,\n angle, distance, speed, and angspeed. Values must already be in\n the appropriate units (degrees, mm, deg/sec, or mm/sec).\"\"\"\n def __init__(self, radius=0, angle=0, distance=None,\n speed=None, angspeed=None, **kwargs):\n if isinstance(radius, cozmo.util.Distance):\n radius = radius.distance_mm\n if isinstance(angle, cozmo.util.Angle):\n angle = angle.degrees\n if isinstance(speed, cozmo.util.Speed):\n speed = speed.speed_mmps\n if isinstance(angspeed, cozmo.util.Angle):\n angspeed = angspeed.degrees\n self.calculate_wheel_speeds(radius, angle, distance, speed, angspeed)\n super().__init__(self.l_wheel_speed, self.r_wheel_speed, **kwargs)\n # Call parent init before setting polling interval.\n self.polling_interval = 0.05\n\n def calculate_wheel_speeds(self, radius=0, angle=None, distance=None,\n speed=None, angspeed=None):\n if radius != 0:\n if angle is not None:\n pass\n elif distance is not None:\n angle = self.dist2ang(distance, radius)\n else:\n raise ValueError('DriveArc requires an angle or distance.')\n\n if speed is not None:\n pass\n elif angspeed is not None:\n speed = self.ang2dist(angspeed, radius)\n else:\n speed = 40 # degrees/second\n if angle < 0:\n speed = - speed\n\n self.angle = angle\n self.l_wheel_speed = speed * (1 - wheelbase / radius)\n self.r_wheel_speed = speed * (1 + wheelbase / radius)\n\n else: # radius is 0\n if angspeed is None:\n angspeed = 40 # degrees/second\n s = angspeed\n if angle < 0:\n s = -s\n self.angle = angle\n self.l_wheel_speed = -s\n self.r_wheel_speed = s\n\n def ang2dist(self, angle, radius):\n return (angle / 360) * 2 * pi * abs(radius)\n\n def dist2ang(self, distance, radius):\n return (distance / abs(2 * pi * radius)) * 360\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event,DataEvent) and isinstance(event.data,dict):\n self.calculate_wheel_speeds(**event.data)\n self.last_heading = self.robot.pose.rotation.angle_z.degrees\n self.traveled = 0\n super().start(event)\n\n def poll(self):\n \"\"\"See how far we've traveled\"\"\"\n p0 = self.last_heading\n p1 = self.robot.pose.rotation.angle_z.degrees\n self.last_heading = p1\n # Assume we're polling quickly enough that diff will be small;\n # typically only about 1 degree. So diff will be large only\n # if the heading has passed through 360 degrees since the last\n # call to poll(). Use 90 degrees as an arbitrary large threshold.\n diff = p1 - p0\n if diff < -90.0:\n diff += 360.0\n elif diff > 90.0:\n diff -= 360.0\n self.traveled += diff\n\n if abs(self.traveled) > abs(self.angle):\n self.poll_handle.cancel()\n self.stop_wheels()\n self.post_completion()\n\n\n#________________ Action Nodes ________________\n\nclass ActionNode(StateNode):\n relaunch_delay = 0.050 # 50 milliseconds\n\n def __init__(self, abort_on_stop=True):\n \"\"\"Call this method only after the subclass __init__ has set\n up self.action_kwargs\"\"\"\n self.abort_on_stop = abort_on_stop\n super().__init__()\n if 'in_parallel' not in self.action_kwargs:\n self.action_kwargs['in_parallel'] = True\n if 'num_retries' not in self.action_kwargs:\n self.action_kwargs['num_retries'] = 2\n self.cozmo_action_handle = None\n\n def start(self,event=None):\n super().start(event)\n self.retry_count = 0\n self.launch_or_retry()\n\n def launch_or_retry(self):\n try:\n result = self.action_launcher()\n except cozmo.exceptions.RobotBusy:\n if TRACE.trace_level >= TRACE.statenode_startstop:\n print('TRACE%d:' % TRACE.statenode_startstop, self, 'launch_action raised RobotBusy')\n self.handle = self.robot.loop.call_later(self.relaunch_delay, self.launch_or_retry)\n return\n if isinstance(result, cozmo.action.Action):\n self.cozmo_action_handle = result\n else:\n raise ValueError(\"Result of %s launch_action() is %s, not a cozmo.action.Action.\" %\n (self,result))\n self.post_when_complete()\n\n def action_launcher(self):\n raise Exception('%s lacks an action_launcher() method' % self)\n \n def post_when_complete(self):\n self.robot.loop.create_task(self.wait_for_completion())\n\n async def wait_for_completion(self):\n async_task = self.cozmo_action_handle.wait_for_completed()\n await async_task\n if TRACE.trace_level >= TRACE.await_satisfied:\n print('TRACE%d:' % TRACE.await_satisfied, self,\n 'await satisfied:', self.cozmo_action_handle)\n # check status for 'completed'; if not, schedule relaunch or post failure\n if self.running:\n if self.cozmo_action_handle.state == 'action_succeeded':\n self.post_completion()\n elif self.cozmo_action_handle.failure_reason[0] == 'cancelled':\n print('CANCELLED: ***>',self,self.cozmo_action_handle)\n self.post_completion()\n elif self.cozmo_action_handle.failure_reason[0] == 'retry':\n if self.retry_count < self.action_kwargs['num_retries']:\n print(\"*** ACTION %s FAILED WITH CODE 'retry': TRYING AGAIN\" %\n self.cozmo_action_handle)\n self.retry_count += 1\n self.launch_or_retry()\n else:\n print(\"*** RETRY COUNT EXCEEDED: FAILING\")\n self.post_failure(self.cozmo_action_handle)\n else:\n print(\"*** ACTION %s FAILED AND CAN'T BE RETRIED.\" %\n self.cozmo_action_handle)\n self.post_failure(self.cozmo_action_handle)\n\n def stop(self):\n if not self.running: return\n if self.cozmo_action_handle and self.abort_on_stop and \\\n self.cozmo_action_handle.is_running:\n self.cozmo_action_handle.abort()\n super().stop()\n\n\nclass Say(ActionNode):\n \"\"\"Speaks some text, then posts a completion event.\"\"\"\n\n class SayDataEvent(Event):\n def __init__(self,text=None):\n self.text = text\n \n def __init__(self, text=\"I'm speechless\",\n abort_on_stop=False, **action_kwargs):\n self.text = text\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, self.SayDataEvent):\n utterance = event.text\n else:\n utterance = self.text\n if isinstance(utterance, (list,tuple)):\n utterance = random.choice(utterance)\n if not isinstance(utterance, str):\n utterance = repr(utterance)\n self.utterance = utterance\n super().start(event)\n print(\"Speaking: '\",utterance,\"'\",sep='')\n\n def action_launcher(self):\n return self.robot.say_text(self.utterance, **self.action_kwargs)\n\n\nclass Forward(ActionNode):\n \"\"\" Moves forward a specified distance. Can accept a Distance as a Dataevent.\"\"\"\n def __init__(self, distance=distance_mm(50),\n speed=speed_mmps(50), abort_on_stop=True, **action_kwargs):\n if isinstance(distance, (int,float)):\n distance = distance_mm(distance)\n elif not isinstance(distance, cozmo.util.Distance):\n raise ValueError('%s distance must be a number or a cozmo.util.Distance' % self)\n if isinstance(speed, (int,float)):\n speed = speed_mmps(speed)\n elif not isinstance(speed, cozmo.util.Speed):\n raise ValueError('%s speed must be a number or a cozmo.util.Speed' % self)\n self.distance = distance\n self.speed = speed\n if 'should_play_anim' not in action_kwargs:\n action_kwargs['should_play_anim'] = False\n self.action_kwargs = action_kwargs\n # super's init must come last because it checks self.action_kwargs\n super().__init__(abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Distance):\n self.distance = event.data\n super().start(event)\n\n def action_launcher(self):\n return self.robot.drive_straight(self.distance, self.speed,\n **self.action_kwargs)\n\n\nclass Turn(ActionNode):\n \"\"\"Turns by a specified angle. Can accept an Angle as a DataEvent.\"\"\"\n def __init__(self, angle=degrees(90), abort_on_stop=True, **action_kwargs):\n if isinstance(angle, (int,float)):\n angle = degrees(angle)\n elif not isinstance(angle, cozmo.util.Angle):\n raise ValueError('%s angle must be a number or a cozmo.util.Angle' % self)\n self.angle = angle\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Angle):\n self.angle = event.data\n super().start(event)\n\n def action_launcher(self):\n return self.robot.turn_in_place(self.angle, **self.action_kwargs)\n\nclass GoToPose(ActionNode):\n def __init__(self, pose, abort_on_stop=True, **action_kwargs):\n self.pose = pose\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop)\n\n def action_launcher(self):\n return self.robot.go_to_pose(self.pose, **self.action_kwargs)\n\nclass SetHeadAngle(ActionNode):\n def __init__(self, angle=degrees(0), abort_on_stop=True, **action_kwargs):\n if isinstance(angle, (int,float)):\n angle = degrees(angle)\n elif not isinstance(angle, cozmo.util.Angle):\n raise ValueError('%s angle must be a number or a cozmo.util.Angle' % self)\n self.angle = angle\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop)\n\n def action_launcher(self):\n return self.robot.set_head_angle(self.angle, **self.action_kwargs)\n\nclass SetLiftHeight(ActionNode):\n def __init__(self, height=0, abort_on_stop=True, **action_kwargs):\n self.height = height\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop)\n\n def action_launcher(self):\n # Temporary hack supplied by Mark Wesley at Anki\n msg = cozmo._clad._clad_to_engine_iface.EnableLiftPower(True)\n self.robot.conn.send_msg(msg)\n return self.robot.set_lift_height(self.height, **self.action_kwargs)\n\nclass SetLiftAngle(SetLiftHeight):\n def __init__(self, angle, abort_on_stop=True, **action_kwargs):\n def get_theta(height):\n return asin((height-45)/66)\n if isinstance(angle, cozmo.util.Angle):\n angle = angle.radians\n min_theta = get_theta(cozmo.robot.MIN_LIFT_HEIGHT_MM)\n max_theta = get_theta(cozmo.robot.MAX_LIFT_HEIGHT_MM)\n angle_range = max_theta - min_theta\n height_pct = (angle - min_theta) / angle_range\n super().__init__(height_pct, abort_on_stop=abort_on_stop, **action_kwargs)\n\n\nclass PickUpObject(ActionNode):\n def __init__(self, object=None, abort_on_stop=False, **action_kwargs):\n self.object = object\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop=abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and \\\n isinstance(event.data,cozmo.objects.LightCube):\n self.object = event.data\n super().start(event)\n\n def action_launcher(self):\n if self.object is None:\n raise ValueError('No object to pick up')\n return self.robot.pickup_object(self.object, **self.action_kwargs)\n\nclass PlaceObjectOnGroundHere(ActionNode):\n def __init__(self, object=None, abort_on_stop=False, **action_kwargs):\n self.object = object\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop=abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and \\\n isinstance(event.data,cozmo.objects.LightCube):\n self.object = event.data\n super().start(event)\n\n def action_launcher(self):\n if self.object is None:\n raise ValueError('No object to place')\n return self.robot.place_object_on_ground_here(self.object, **self.action_kwargs)\n\nclass PlaceOnObject(ActionNode):\n def __init__(self, object=None, abort_on_stop=False, **action_kwargs):\n self.object = object\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop=abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and \\\n isinstance(event.data,cozmo.objects.LightCube):\n self.object = event.data\n super().start(event)\n\n def action_launcher(self):\n if self.object is None:\n raise ValueError('No object to place')\n return self.robot.place_on_object(self.object, **self.action_kwargs)\n\n\n\n#________________ Animations ________________\n\nclass AnimationNode(ActionNode):\n def __init__(self, anim_name='anim_bored_01', **kwargs):\n self.anim_name = anim_name\n self.action_kwargs = kwargs\n super().__init__()\n\n def action_launcher(self):\n return self.robot.play_anim(self.anim_name)\n\nclass AnimationTriggerNode(ActionNode):\n def __init__(self, trigger=cozmo.anim.Triggers.CubePouncePounceNormal, **kwargs):\n if not isinstance(trigger, cozmo.anim._AnimTrigger):\n raise TypeError('%s is not an instance of cozmo.anim._AnimTrigger' %\n repr(trigger))\n self.trigger = trigger\n self.action_kwargs = kwargs\n super().__init__()\n\n def action_launcher(self):\n return self.robot.play_anim_trigger(self.trigger)\n\n#________________ Behaviors ________________\n\nclass StartBehavior(StateNode):\n def __init__(self, behavior=None, stop_on_exit=True):\n if not isinstance(behavior, cozmo.behavior._BehaviorType):\n raise ValueError(\"'%s' isn't an instance of cozmo.behavior._BehaviorType\" %\n repr(behavior))\n self.behavior = behavior\n self.behavior_handle = None\n self.stop_on_exit = stop_on_exit\n super().__init__()\n\n def __repr__(self):\n if self.behavior_handle:\n return '<%s %s active=%s>' % \\\n (self.__class__.__name__, self.name, self.behavior_handle.is_active)\n else:\n return super().__repr__() \n\n def start(self,event=None):\n if self.running: return\n super().start(event)\n try:\n if self.robot.behavior_handle:\n self.robot.behavior_handle.stop()\n except: pass\n finally:\n self.robot.behavior_handle = None\n self.behavior_handle = self.robot.start_behavior(self.behavior)\n self.robot.behavior_handle = self.behavior_handle\n self.post_completion()\n\n def stop(self):\n if not self.running: return\n if self.stop_on_exit and self.behavior_handle is self.robot.behavior_handle:\n self.robot.behavior_handle.stop()\n self.robot.behavior_handle = None\n super().stop()\n\nclass StopBehavior(StateNode):\n def start(self,event=None):\n if self. running: return\n super().start(event)\n try:\n if self.robot.behavior_handle:\n self.robot.behavior_handle.stop()\n except: pass\n self.robot.behavior_handle = None\n self.post_completion()\n\nclass FindFaces(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.FindFaces,stop_on_exit)\n\nclass KnockOverCubes(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.KnockOverCubes,stop_on_exit)\n\nclass LookAroundInPlace(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.LookAroundInPlace,stop_on_exit)\n\nclass PounceOnMotion(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.PounceOnMotion,stop_on_exit)\n\nclass RollBlock(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.RollBlock,stop_on_exit)\n\nclass StackBlocks(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.StackBlocks,stop_on_exit)\n","sub_path":"cozmo_fsm/nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":25898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"651197135","text":"from typing import List\n\nfrom asgard.db import AsgardDBSession\nfrom asgard.models.account import Account\nfrom asgard.models.user import User\nfrom asgard.models.user_has_account import UserHasAccount\n\n\nclass UsersBackend:\n async def get_alternate_accounts(\n self, user: User, current_account: Account\n ) -> List[Account]:\n _, UserTable = await user.to_alchemy_obj()\n _, AccountTable = await current_account.to_alchemy_obj()\n\n _join = UserTable.__table__.join(\n UserHasAccount,\n UserTable.id == UserHasAccount.c.user_id,\n isouter=True,\n ).join(\n AccountTable.__table__,\n AccountTable.id == UserHasAccount.c.account_id,\n isouter=True,\n )\n async with AsgardDBSession() as s:\n accounts = (\n await s.query(AccountTable)\n .join(_join)\n .filter(UserTable.tx_email == user.email)\n .filter(AccountTable.id != current_account.id)\n .all()\n )\n all_acc = [await Account.from_alchemy_obj(acc) for acc in accounts]\n return all_acc\n","sub_path":"asgard/backends/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"514987431","text":"import datetime\nimport os\nimport string\n\ndef startDate():\n print('input you wanted start date (YYYY/MM/DD)')\n y = input('Year : ')\n m = input('Month : ')\n d = input('Date : ')\n while(dateCheck(y,m,d)):\n print(\"error. try again.\")\n y = input('Year : ')\n m = input('Month : ')\n d = input('Date : ')\n return (int(y),int(m),int(d))\n\ndef endDate():\n print('input you wanted end date (YYYY/MM/DD)')\n y = input('Year : ')\n m = input('Month : ')\n d = input('Date : ')\n while(dateCheck(y,m,d)):\n print(\"error. try again.\")\n y = input('Year : ')\n m = input('Month : ')\n d = input('Date : ')\n return (int(y),int(m),int(d))\n\ndef dateCheck(year, month, date):\n y = int(year)\n m = int(month)\n d = int(date)\n\n if(not(y>=2017 and y<=2018)):\n return True\n if(not(m>0 and m<=12)):\n return True\n if(not(d>0 and d<=31)):\n return True\n\n if(len(year)!=4):\n return True\n if(len(month)!=2):\n return True\n if(len(date)!=2):\n return True\n return False\ndef replaceDate(y,m,d):\n d+=1\n \n if(d==29 and m == 2):\n m+=1\n d=1\n if(d>30):\n d=1\n m+=1\n if(m==13):\n y+=1\n m=1\n return (y,m,d)\ndef compare3(a,b,c,d,e,f):\n if(a!=b):\n return False\n if(c!=d):\n return False\n if(e!=f):\n return False\n return True\ntoday = datetime.date.today()\nyear = today.year\nmonth = today.month\nday = today.day\n\n(y,m,d) = startDate()\n(ey,em,ed) = endDate()\n\nwhile(not compare3(y,ey,m,em,d,ed)):\n git_add = 'git add daily_commit.md'\n git_commit = '''git commit -m \"Daily commit used Wonho's version\" '''\n file_message = ('''{0}/{1}/{2} : Daily commit sucsessfuly \\r\\n'''.format(y,m,d))\n os.system(\"date {0}/{1}/{2}\".format(y,m,d))\n logFile = open(\"daily_commit.md\",'a')\n logFile.writelines(file_message)\n logFile.close()\n os.system(git_add)\n os.system(git_commit)\n (y,m,d) = replaceDate(y,m,d)\n\nos.system(\"date {0}/{1}/{2}\".format(year,month,day))","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"3423800","text":"# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\nimport pytest\nimport threading\nimport time\nfrom azure.iot.hub.devicesdk.sync_inbox import SyncClientInbox, InboxEmpty\n\n\nclass TestSyncClientInbox(object):\n def test_instantiates_empty(self):\n inbox = SyncClientInbox()\n assert inbox.empty()\n\n def test__put_adds_item_to_inbox(self, mocker):\n inbox = SyncClientInbox()\n assert inbox.empty()\n item = mocker.MagicMock()\n inbox._put(item)\n assert not inbox.empty()\n\n def test_get_removes_item_from_inbox_if_already_there(self, mocker):\n inbox = SyncClientInbox()\n assert inbox.empty()\n item = mocker.MagicMock()\n inbox._put(item)\n assert not inbox.empty()\n retrieved_item = inbox.get()\n assert retrieved_item is item\n assert inbox.empty()\n\n def test_get_waits_for_item_to_be_added_if_inbox_empty_in_blocking_mode(self, mocker):\n inbox = SyncClientInbox()\n assert inbox.empty()\n item = mocker.MagicMock()\n\n def insert_item():\n time.sleep(1) # wait before inserting\n inbox._put(item)\n\n insertion_thread = threading.Thread(target=insert_item)\n insertion_thread.start()\n\n retrieved_item = inbox.get(block=True)\n assert retrieved_item is item\n assert inbox.empty()\n\n def test_get_times_out_while_blocking_if_timeout_specified(self, mocker):\n inbox = SyncClientInbox()\n assert inbox.empty()\n with pytest.raises(InboxEmpty):\n inbox.get(block=True, timeout=1)\n\n def test_get_raises_empty_if_inbox_empty_in_non_blocking_mode(self):\n inbox = SyncClientInbox()\n assert inbox.empty()\n with pytest.raises(InboxEmpty):\n inbox.get(block=False)\n\n def test_operates_according_to_FIFO(self, mocker):\n inbox = SyncClientInbox()\n item1 = mocker.MagicMock()\n item2 = mocker.MagicMock()\n item3 = mocker.MagicMock()\n inbox._put(item1)\n inbox._put(item2)\n inbox._put(item3)\n\n assert inbox.get() is item1\n assert inbox.get() is item2\n assert inbox.get() is item3\n\n def test_can_check_if_empty(self, mocker):\n inbox = SyncClientInbox()\n assert inbox.empty()\n item = mocker.MagicMock()\n inbox._put(item)\n assert not inbox.empty()\n inbox.get()\n assert inbox.empty()\n","sub_path":"azure-iot-hub-devicesdk/tests/test_sync_inbox.py","file_name":"test_sync_inbox.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"508155145","text":"from sympy import Matrix, zeros\n\n\nclass ShortestPathTree(object):\n def __init__(self, length_matrix):\n assert length_matrix.shape[0] == length_matrix.shape[1]\n for i in xrange(length_matrix.shape[0]):\n for j in xrange(length_matrix.shape[1]):\n assert length_matrix[i, j] >= 0\n self.length_matrix = length_matrix\n self.vertex_quantity = length_matrix.shape[0]\n\n def solve(self):\n self.shortest_length = zeros(self.vertex_quantity, 1)\n for i in xrange(1, self.vertex_quantity):\n self.shortest_length[i, 0] = float(\"inf\")\n self.parents = zeros(self.vertex_quantity, 1)\n not_visited = set(range(self.vertex_quantity))\n for i in xrange(self.vertex_quantity):\n min_length = float(\"inf\")\n min_length_ver = -1\n for ver in not_visited:\n if self.shortest_length[ver] < min_length:\n min_length_ver = ver\n min_length = self.shortest_length[ver]\n if min_length_ver == -1:\n break\n not_visited.remove(min_length_ver)\n for j in xrange(self.vertex_quantity):\n if self.length_matrix[min_length_ver, j] != 0:\n if self.shortest_length[min_length_ver, 0] + self.length_matrix[min_length_ver, j] < \\\n self.shortest_length[j, 0]:\n self.shortest_length[j, 0] = self.shortest_length[min_length_ver, 0] + self.length_matrix[\n min_length_ver, j]\n self.parents[j, 0] = min_length_ver\n return self.shortest_length, self.parents\n","sub_path":"8term/OR/lab6/ShortestPathTree.py","file_name":"ShortestPathTree.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"588993443","text":"import re\r\nimport time\r\nfrom utils import *\r\nfrom interface import user_interface\r\n\r\nuse_main_urls = False\r\nvalid_urls_file = \"urls.txt\"\r\nnot_valid_urls_file = \"nv_urls.csv\"\r\ninterface = user_interface(user_interface.ARG_MODE)\r\n\r\ndef get_urls(url):\r\n page = requests.get(url) #getURL\r\n return re.findall(\"]+)\\\">\", page.text) #parseUrl\r\n\r\ndef search_urls(url):\r\n valid_urls = []\r\n nv_urls = []\r\n\r\n urls = get_urls(url)\r\n for i in range(len(urls)): #handleExeptions\r\n try:\r\n if (urls[i][0] == \"/\" and urls[i][1] != \"/\"):\r\n urls[i] = conjugate_urls(url, urls[i])\r\n elif (urls[i][0:2] == '//'):\r\n urls[i] = \"http://\" + urls[i][2:]\r\n except IndexError:\r\n pass #urlTooShort\r\n\r\n urls = check_dup_in_list(urls)\r\n\r\n for i in range(len(urls)): #validadeUrls\r\n if valid_url(urls[i]):\r\n valid_urls.append(urls[i])\r\n else:\r\n nv_urls.append((url, urls[i]))\r\n\r\n a = valid_urls\r\n return [valid_urls, nv_urls]\r\n\r\n\r\ndef save_urls(urls):\r\n global main_urls\r\n with open(valid_urls_file, \"r\", encoding=\"utf-8\") as table_r:\r\n existing_urls = table_r.readlines()\r\n\r\n with open(valid_urls_file, \"a\", encoding=\"utf-8\") as table:\r\n for i in range(len(urls[0])):\r\n for j in range(len(existing_urls)):\r\n existing = existing_urls[j][:-1].split(\"//\")[1]\r\n new = urls[0][i].split(\"//\")[1]\r\n if (existing == new):\r\n unique = False\r\n break\r\n else:\r\n unique = True\r\n\r\n if unique and use_main_urls:\r\n if urls[0][i].split(\"/\")[2] == main_urls[0] or urls[0][i].split(\"/\")[2] == main_urls[1]:\r\n table.write(urls[0][i] + \"\\n\")\r\n elif unique and not use_main_urls:\r\n table.write(urls[0][i] + \"\\n\")\r\n with open(not_valid_urls_file, \"a\", encoding=\"utf-8\") as nv_table:\r\n for i in range(len(urls[1])):\r\n nv_table.write(urls[1][i][0] + \",\" + urls[1][i][1] + \"\\n\")\r\n\r\n\r\ndef main():\r\n global current_line\r\n first_time = time.time()\r\n try:\r\n with open(valid_urls_file, \"r\", encoding=\"utf-8\") as table:\r\n table_content = table.readlines()\r\n current_url = table_content[current_line][:-1]\r\n urls = search_urls(current_url)\r\n if urls[0] != None: #In case there are no new links on site\r\n save_urls(urls)\r\n time_took = round(time.time() - first_time,4)\r\n print(current_line, time_took, current_url, sep=\"\\t\")\r\n current_line += 1\r\n except IndexError:\r\n print(\"END OF FILE REACHED\")\r\n quit(0)\r\n\r\nif __name__ == '__main__':\r\n main_urls = interface.get_values()[\"urls\"]\r\n current_line = interface.get_values()[\"start_line\"]\r\n file_path = interface.get_values()[\"file_path\"]\r\n valid_urls_file = file_path + valid_urls_file\r\n not_valid_urls_file = file_path + not_valid_urls_file\r\n \r\n try:\r\n if (open(valid_urls_file).read() == \"\"):\r\n file_setup(valid_urls_file, list_to_str(main_urls))\r\n except FileNotFoundError:\r\n file_setup(valid_urls_file,list_to_str(main_urls))\r\n\r\n while True:\r\n main()\r\n","sub_path":"WebCrawler.py","file_name":"WebCrawler.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"264149404","text":"from .models import Group, Participate\nimport sys\n\nsys.path.append(\"..\")\nfrom member.models import Member\n\nfrom .serializers import MessageSerializer, GroupSerializer, ParticipateSerializer, Participated_Group_Serializer\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework.viewsets import ModelViewSet\nfrom rest_framework.filters import SearchFilter\n\n\n# 방 검색\nclass GroupViewSet(ModelViewSet):\n queryset = Group.objects.all()\n serializer_class = GroupSerializer\n filter_backends = [SearchFilter]\n search_fields = ['GroupName']\n\n\n# 방 참여\nclass ParticipateViewSet(ModelViewSet):\n queryset = Participate.objects.all()\n serializer_class = ParticipateSerializer\n\n\n# 참여중인 방 목록\nclass ParticipatedGroupViewSet(ModelViewSet):\n queryset = Participate.objects.all()\n serializer_class = Participated_Group_Serializer\n\n def get_queryset(self):\n qs = Participate.objects.all()\n member_id = self.request.query_params.get('member_id', None)\n if member_id is not None:\n member_id_qs = qs.filter(member_id=member_id)\n return member_id_qs\n\n\n# 방 생성\n@api_view(['POST'])\ndef create_group(request):\n if request.method == 'POST':\n try:\n Group.objects.create(GroupName=request.POST['GroupName'], GroupPassword=request.POST['GroupPassword'])\n g_pid = Group.objects.get(GroupName=request.POST['GroupName'])\n m_id = Member.objects.get(member_id=request.POST['member_id'])\n Participate.objects.create(GroupPid=g_pid, member_id=m_id, Nickname=request.POST['Nickname'])\n message = Message(message=\"성공\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n except Exception as ex:\n print(ex)\n message = Message(message=\"실패\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n\n\n# 방 나가기 구현 삭제되면 GroupPid, schedule 같은 데이터 다 삭제\n@api_view(['DELETE'])\ndef del_member(request, GroupPid, member_id):\n if request.method == 'DELETE':\n Participate.objects.filter(GroupPid=GroupPid, member_id=member_id).delete()\n message = Message(message=\"삭제 완료 되었습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n\n\n# 그룹 닉네임 중복확인 함수 && 회원 여부 확인 && 비밀번호 확인\n@api_view(['GET'])\ndef get_check_nick(request, GroupPid, Nickname, member_id, GroupPassword):\n if request.method == 'GET':\n part = Participate.objects.filter(GroupPid=GroupPid)\n part_nick = part.filter(Nickname=Nickname)\n part_member = Participate.objects.filter(GroupPid=GroupPid)\n pass_check = Group.objects.filter(GroupPassword=GroupPassword)\n if pass_check:\n if part_nick and part:\n message = Message(message=\"닉네임을 사용할 수 없습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n else:\n if part_member.filter(member_id=member_id):\n message = Message(message=\"이미 참여하셨습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n else:\n message = Message(message=\"닉네임을 사용할 수 있습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n else:\n message = Message(message=\"비밀번호가 일치하지 않습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n\n\n# 가게이름 중복확인 함수\n@api_view(['GET'])\ndef get_check(request, pk):\n if request.method == 'GET':\n if Group.objects.filter(GroupName=pk):\n message = Message(message=\"가게이름을 사용할 수 없습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n else:\n message = Message(message=\"가게이름으로 사용할 수 있습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n\n\n# 메세지 통일을 위한 클래스.\nclass Message(object):\n def __init__(self, message, created=None):\n self.message = message\n self.created = created","sub_path":"group/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"506098395","text":"\n# coding: utf-8\n\n# In[2]:\n\n\nimport nltk\nimport gensim\nfrom nltk.probability import FreqDist\nimport pickle\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Bidirectional, Dropout,Embedding\nfrom keras.callbacks import Callback\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import OneHotEncoder\nimport tensorflowjs as tfjs\nfrom scipy.sparse import csr_matrix\nimport scipy\n\n\n# In[3]:\n\n\npath_to_save_classifier = '/home/wessam/Desktop/Maher/newClassifier'\npath_to_word2vec = '/home/wessam/Desktop/Maher/GoogleNews-vectors-negative300.bin.gz'\npath_to_datasetWords = '/home/wessam/Desktop/Maher/datasetWordsTokenized.txt'\n#############################################################################\n\n# returns the indices of the words and the strange words will be -1\ndef indexEncoder(strs, bagOfWords):\n out = []\n for word in strs:\n if word in bagOfWords:\n out.append([bagOfWords.index(word)])\n else:\n out.append([-1])\n return out\n \ndef createBagOfWords(words):\n return list(set(words))\n\n#############################################################################\n\nprint('loading the word2vec module ...')\nmodel = gensim.models.KeyedVectors.load_word2vec_format(path_to_word2vec, binary=True )\n\n#############################################################################\n\nprint('loading used words ...')\nf = open(path_to_datasetWords)\nlines = f.readlines()\n\n#############################################################################\n\nstrings = [\"\"] * len(lines)\nY_train = [0] * len(lines)\ntitle = [0] * len(lines) \n\n\nfor i in range(len(lines)) :\n\tl = nltk.word_tokenize(lines[i])\n\tstrings[i] = l[0]\n\ttitle[i] = l[1]\n\tY_train[i] = l[2]\n\n#############################################################################\n\nY_train_main = [int(label) for label in Y_train]\nX_train_main = strings\n\n#############################################################################\n\nprint('analizing words ...')\nfreqd = FreqDist(X_train_main)\ncommon_words = [ w[0] for w in freqd.most_common(100)]\nwith open(\"common_words.txt\", \"wb\") as fp: #Pickling\n pickle.dump(common_words, fp)\n\n#############################################################################\n\nprint('processing the base words ...')\nx_train = X_train_main\ny_train = Y_train_main\n\ny_train = [y_train[i] for i in range(len(y_train)) if x_train[i] in model.vocab]\nx_train = [word for word in x_train if word in model.vocab] # array of words\n# x_train = list(nltk.bigrams(x_train))\ny_train = y_train[:len(x_train)]\n\nprint(len(x_train))\nprint(len(y_train))\n\n# y_test = [ y_test[i] for i in range(len(y_test)) if x_test[i] in model.vocab and x_test[i] in x_train ]\n# x_test = [ word for word in x_test if word in model.vocab and word in x_train] # array of words\n# # x_test = list(nltk.bigrams(x_test))\n# y_test = y_test[:len(x_test)]\n\nbag_of_words = createBagOfWords(x_train);\n\nprint('encoding the words ...')\n# label_encoder = LabelEncoder()\n# integer_encoded = label_encoder.fit_transform(x_train)\ninteger_encoded = indexEncoder(x_train, bag_of_words)\n\nprint(integer_encoded[0:10])\n\n\n# In[4]:\n\n\nonehot_encoder = OneHotEncoder(sparse=True)\n# integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)\n\n\n# In[15]:\n\n\nX_train_sparse = onehot_encoder.fit_transform(integer_encoded)\nY_train_sparse = csr_matrix(np.array(y_train))\n\n\n# In[16]:\n\n\nscipy.sparse.save_npz('/home/wessam/Desktop/Maher/savedSparse/X_train_sparse.npz', X_train_sparse)\nscipy.sparse.save_npz('/home/wessam/Desktop/Maher/savedSparse/Y_train_sparse.npz', Y_train_sparse)\n\n","sub_path":"model_train/batching the training process on 2 steps/step1.py","file_name":"step1.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"485240294","text":"import collections\n\n\n\nYearCount=collections.namedtuple('YearCount','Year Count')\n\n\n\n\n\ndef readWordFile(fileName):\n \"\"\"reads in file and builds dictionary\"\"\"\n table=dict()\n file=open(str(fileName))\n YCLst=[]\n oldLine=[]\n for lines in file:\n lines=lines.strip()\n lines=lines.split(',')\n\n\n if len(lines)==1 and len(oldLine)==2:\n keys=lines[0]\n table[keys] = YCLst\n YCLst = []\n\n if len(lines) == 1:\n keys = lines[0]\n table[keys]=YCLst\n elif len(lines) == 2:\n YCLst.append(YearCount(Year=int(lines[0]),Count=int(lines[1])))\n oldLine=lines\n file.close()\n return table\ndef totalOccurrences(word,table):\n \"\"\"calculates total occurrence user input words\n word=word to calculate occurrence for\n table=dictionary made from readWordFile\n \"\"\"\n if word in table:\n totalOccur=0\n for i in table[word]:\n totalOccur+=i.Count\n return totalOccur\n else:\n return 0\n\n\n\ndef main():\n file=input(\"Enter filename to be checked: \")\n x=(readWordFile(file))\n print(x)\n print(totalOccurrences('airport',x))\n\nmain()","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"643729714","text":"from psychopy.iohub.client import launchHubServer\nfrom psychopy import core, event\nimport numpy as np\nimport pyautogui\n\nio=launchHubServer()\n\nio_keyboard = []\n\n\nprint(\"PRESS KEY NOW.\")\n\nkey_clock = core.Clock()\nkey_clock.reset()\nwhile key_clock.getTime() < 5:\n # pyautogui.down('d')\n keys = io.devices.keyboard.state #check constantly\n io_keyboard.append(keys)\npyautogui.keyUp('d')\n\nio_buttons = []\nbutton_clock = core.Clock()\n\nnp.savetxt(\"key_polling_rate.csv\", io_keyboard, delimiter=',',comments='')\n\nprint(\"PRESS BUTTON NOW.\")\ncore.wait(1)\nbutton_clock.reset()\nwhile button_clock.getTime() < 5:\n buttons = io.devices.keyboard.state #check constantly\n io_buttons.append(buttons)\n print(buttons)\n\nio.quit()\n\nprint('button presses detected ', len(io_buttons))\nprint('key presses detected ', len(io_keyboard))\n\nnp.savetxt(\"button_polling_rate.csv\", str(button_keyboard), delimiter=',',comments='')\n\n\n#so far, there are slightly more key presses detected\n#than button presses...\n\n# print('keys ', io_keyboard)\n# print('buttons ', buttons)\n","sub_path":"simple_rt_experiment_valueC/testing_polling_rate/test_keypress_sensitivity.py","file_name":"test_keypress_sensitivity.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"102297483","text":"from sys import stdin, stdout\n\n#s = str(input())\ns = stdin.readline().strip()\n\nresult = []\nvowels= {'a', 'e', 'i', 'o', 'u'}\ni = 0\nl = len(s)\nwhile i < l:\n if s[i] in vowels and i + 1 < l and s[i + 1] == 'p':\n result.append(s[i])\n i += 3\n else:\n result.append(s[i])\n i += 1\n#print(\"\".join(result))\nresult.append('\\n')\nstdout.write(\"\".join(result)) \n","sub_path":"NYU CS480/Kattis/Kemija.py","file_name":"Kemija.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"333829297","text":"\"\"\"The scheme_tokens module provides functions tokenize_line and tokenize_lines\nfor converting (iterators producing) strings into (iterators producing) lists\nof tokens. A token may be:\n\n * A number (represented as an int or float)\n * A boolean (represented as a bool)\n * A symbol (represented as a string)\n * A delimiter, including parentheses, dots, and single quotes\n\nThis file also includes some features of Scheme that have not been addressed\nin the course, such as Scheme strings.\n\"\"\"\n\nfrom __future__ import print_function # Python 2 compatibility\n\nfrom ucb import main\nimport itertools\nimport string\nimport sys\nimport tokenize\n\n_NUMERAL_STARTS = set(string.digits) | set('+-.')\n_SYMBOL_CHARS = (set('!$%&*/:<=>?@^_~') | set(string.ascii_lowercase) |\n set(string.ascii_uppercase) | _NUMERAL_STARTS)\n_STRING_DELIMS = set('\"')\n_WHITESPACE = set(' \\t\\n\\r')\n_SINGLE_CHAR_TOKENS = set(\"()[]'`\")\n_TOKEN_END = _WHITESPACE | _SINGLE_CHAR_TOKENS | _STRING_DELIMS | {',', ',@'}\nDELIMITERS = _SINGLE_CHAR_TOKENS | {'.', ',', ',@'}\n\ndef valid_symbol(s):\n \"\"\"Returns whether s is a well-formed symbol.\"\"\"\n if len(s) == 0:\n return False\n for c in s:\n if c not in _SYMBOL_CHARS:\n return False\n return True\n\ndef next_candidate_token(line, k):\n \"\"\"A tuple (tok, k'), where tok is the next substring of line at or\n after position k that could be a token (assuming it passes a validity\n check), and k' is the position in line following that token. Returns\n (None, len(line)) when there are no more tokens.\"\"\"\n while k < len(line):\n c = line[k]\n if c == ';':\n return None, len(line)\n elif c in _WHITESPACE:\n k += 1\n elif c in _SINGLE_CHAR_TOKENS:\n if c == ']': c = ')'\n if c == '[': c = '('\n return c, k+1\n elif c == '#': # Boolean values #t and #f\n return line[k:k+2], min(k+2, len(line))\n elif c == ',': # Unquote; check for @\n if k+1 < len(line) and line[k+1] == '@':\n return ',@', k+2\n return c, k+1\n elif c in _STRING_DELIMS:\n if k+1 < len(line) and line[k+1] == c: # No triple quotes in Scheme\n return c+c, k+2\n line_bytes = (bytes(line[k:], encoding='utf-8'),)\n gen = tokenize.tokenize(iter(line_bytes).__next__)\n next(gen) # Throw away encoding token\n token = next(gen)\n if token.type != tokenize.STRING:\n raise ValueError(\"invalid string: {0}\".format(token.string))\n return token.string, token.end[1]+k\n else:\n j = k\n while j < len(line) and line[j] not in _TOKEN_END:\n j += 1\n return line[k:j], min(j, len(line))\n return None, len(line)\n\ndef tokenize_line(line):\n \"\"\"The list of Scheme tokens on line. Excludes comments and whitespace.\"\"\"\n result = []\n text, i = next_candidate_token(line, 0)\n while text is not None:\n if text in DELIMITERS:\n result.append(text)\n elif text == '#t' or text.lower() == 'true':\n result.append(True)\n elif text == '#f' or text.lower() == 'false':\n result.append(False)\n elif text == 'nil':\n result.append(text)\n elif text[0] in _SYMBOL_CHARS:\n number = False\n if text[0] in _NUMERAL_STARTS:\n try:\n result.append(int(text))\n number = True\n except ValueError:\n try:\n result.append(float(text))\n number = True\n except ValueError:\n pass\n if not number:\n if valid_symbol(text):\n result.append(text.lower())\n else:\n raise ValueError(\"invalid numeral or symbol: {0}\".format(text))\n elif text[0] in _STRING_DELIMS:\n result.append(text)\n else:\n print(\"warning: invalid token: {0}\".format(text), file=sys.stderr)\n print(\" \", line, file=sys.stderr)\n print(\" \" * (i+3), \"^\", file=sys.stderr)\n text, i = next_candidate_token(line, i)\n return result\n\ndef tokenize_lines(input):\n \"\"\"An iterator over lists of tokens, one for each line of the iterable\n input sequence.\"\"\"\n return (tokenize_line(line) for line in input)\n\ndef count_tokens(input):\n \"\"\"Count the number of non-delimiter tokens in input.\"\"\"\n return len(list(itertools.chain(*tokenize_lines(input))))\n\n@main\ndef run(*args):\n import argparse\n parser = argparse.ArgumentParser(description='Count Scheme tokens.')\n parser.add_argument('file', nargs='?',\n type=argparse.FileType('r'), default=sys.stdin,\n help='input file to be counted')\n args = parser.parse_args()\n print('counted', count_tokens(args.file), 'tokens')","sub_path":"project/pro4-scheme/scheme_tokens.py","file_name":"scheme_tokens.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"237356914","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 28 15:15:49 2019\n\n\nGiven the head of a singly linked list, swap every two nodes and return its head.\n\nFor example, given 1 -> 2 -> 3 -> 4, return 2 -> 1 -> 4 -> 3.\n\n@author: carlgval\n\"\"\"\n\n\nclass Single_Linked_List(object):\n def __init__(self, value=None):\n self.head = Node(value)\n self.tail = self.head\n\n def _append(self, node):\n self.tail.next_node = node\n self.tail = node\n\n def append(self, value):\n node = Node(value)\n self._append(node)\n\n\nclass Node(object):\n def __repr__(self, i=0):\n if self.next_node is not None:\n return '' * i + 'Node %i: %s \\n' % (i, str(self.value)) \\\n + self.next_node.__repr__(i+1)\n else:\n return ' ' * i + 'Node %i: %s \\n' % (i, str(self.value))\n\n def __init__(self, value):\n self.next_node = None\n self.value = value\n\n def _disconect(self):\n self.next_node = None\n\n def swap(self):\n if self is not None and self.next_node is not None:\n temp = self.next_node\n self.next_node = self.next_node.next_node\n temp.next_node = self\n\n self.next_node = self.next_node.swap()\n\n return temp\n else:\n return self\n\n\nif __name__ == '__main__':\n sll = Single_Linked_List()\n\n for i in range(100):\n sll.append(i)\n s = sll.head.swap()\n print(s)\n","sub_path":"swap_2_nodes_singly_linked_list.py","file_name":"swap_2_nodes_singly_linked_list.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"593853233","text":"import signal\nimport sys\n\nfrom celery import states\nfrom celery.exceptions import Ignore\n\nfrom proj.celery import app\nfrom proj.utils import chaturbate\nfrom proj.utils import database\nfrom proj.utils import logging\n\nlogger = logging.get_logger(__name__, False)\n\n\n@app.task(bind=True)\ndef record_model(self, model, save_to):\n logger.info(\"Recording model: %r\", model)\n register_exit_signals()\n\n try:\n database.connect()\n database.add_recording(model)\n result = chaturbate.record_model(model, save_to)\n except:\n logger.exception(\"Exception occured in record_model task: \")\n result = 'FATAL_RECORD_MODEL_ERROR'\n finally:\n database.remove_recording(model)\n database.remove_queued(model)\n database.close()\n\n logger.info(\"Finished recording model: %r, result: %r\", model, result)\n if 'saved' not in result:\n self.update_state(\n state=states.FAILURE,\n meta=result\n )\n raise Ignore()\n return result\n\n\ndef exit_gracefully():\n sys.exit(0)\n\n\ndef register_exit_signals():\n signal.signal(signal.SIGTERM, exit_gracefully)\n","sub_path":"proj/tasks/chaturbate.py","file_name":"chaturbate.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"12204912","text":"import json\nimport copy\nimport argparse\nimport os\nimport collections\nimport numpy as np\n\narg = argparse.ArgumentParser(\"mylabel2KITTIlabel\")\n\ntarget_label = collections.OrderedDict()\ntarget_label['type'] = 'Dontcare'\ntarget_label['truncated'] = 0.0\ntarget_label['occluded'] = 0 # used in image\ntarget_label['alpha'] = 0\ntarget_label['bbox'] = [0, 0, 50, 50] # used in image\ntarget_label['dimensions'] = []\ntarget_label['location'] = []\ntarget_label['rotation_y'] = 0\n# target_label['score'] = 'Dontcare'\n\n# the height of velodyne camera\ncamera_height = -1.73\n\ntransform_location = np.mat([\n [0, -1, 0],\n [0, 0, -1],\n [1, 0, 0],\n])\n\n\ndef get_transformed_values(_list, m):\n r = m * np.mat(_list).T\n r = r.T\n return r.tolist()[0]\n\n\ndef get_dimensions(_list):\n x = _list[0]\n y = _list[1]\n z = _list[2]\n return list([z, x, y])\n\n\nstart_number = 0\n\nif __name__ == '__main__':\n arg.add_argument(\"--input\", \"-i\", default=\"\", type=str,\n help=\"input file obtained from https://3d.supervise.ly/projects\", required=True)\n arg.add_argument(\"--output_folder\", \"-o\", default=\"\", type=str, help=\"output folder\", required=True)\n args = arg.parse_args()\n\n input_filename = args.input\n output_folder = args.output_folder\n print('input filename:\\t', input_filename)\n print('output folder:\\t', output_folder)\n\n with open(input_filename) as f:\n data = json.load(f)\n\n if not os.path.exists(output_folder):\n os.mkdir(output_folder)\n\n for idx, annotations in enumerate(data):\n KITTI_annotations = []\n my_annotations = annotations['annotations']\n data_name = annotations['name']\n print('reading {} with {} label(s)'.format(data_name, len(my_annotations)))\n\n if len(my_annotations) == 0:\n print('warning {} is empty'.format(data_name))\n continue\n\n # produce new annotations\n for annotation in my_annotations:\n tmp_target_label = copy.deepcopy(target_label)\n tmp_target_label['type'] = annotation['className']\n # print(list(annotation['geometry']['dimensions'].values()))\n tmp_target_label['dimensions'] = get_dimensions(\n list(annotation['geometry']['dimensions'].values()))\n # print('dimensions', tmp_target_label['dimensions'])\n position = list(annotation['geometry']['position'].values())\n position[2] = camera_height # z\n position[0] = position[0] - 0.27 # x\n tmp_target_label['location'] = get_transformed_values(position, transform_location)\n # print('location', tmp_target_label['location'])\n tmp_target_label['rotation_y'] = -float(annotation['geometry']['rotation'][\"z\"])\n KITTI_annotations.append(tmp_target_label)\n # exit()\n # save current annotation into\n save_filename = \"{:06n}.txt\".format(idx + start_number)\n save_path = output_folder + '/' + save_filename\n print('saving {}'.format(save_path))\n\n with open(save_path, 'w') as f:\n for item in KITTI_annotations:\n value_list = list(item.values())\n for value in value_list:\n if isinstance(value, list):\n for v in value:\n f.write(str(round(v, 2)) + ' ')\n else:\n if isinstance(value, str):\n f.write(value + ' ')\n else:\n f.write(str(round(value, 2)) + ' ')\n f.write('\\n')\n","sub_path":"tools/converter_label/rough_detection/older_version/converter_mylabel2KITTIlabel.py","file_name":"converter_mylabel2KITTIlabel.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"286593630","text":"from numpy import *\nfrom matplotlib.pyplot import *\nfrom scipy.stats import*\nfrom matplotlib.mlab import griddata\nfrom module2 import*\nfrom plottingTools import *\n\nNarr = array([1000, 1500, 2000, 2500, 3000])\nn = Narr.shape[0]\n\nNmean = empty(n)\nNvar = empty(n)\nNskew = empty(n)\nNkur = empty(n)\nNmin = empty(n)\n\nerrMean = empty(n)\nerrVar = empty(n)\nerrSkew = empty(n)\nerrKur = empty(n)\nerrMin = empty(n)\n\n\n\nmatplotlib.rcParams.update({'font.size': 15})\n\nfor l,N in enumerate(Narr):\n\n M = load('./Matrices_N/matrix_'+str(N)+'.npy')\n v = load('./Matrices_N/v_'+str(N)+'.npy')\n d = load('./Matrices_N/d_'+str(N)+'.npy')\n\n PosL1 = getPE(M,d)\n\n me = empty(N-1)\n variance = empty(N-1)\n kur = empty(N-1)\n sk = empty(N-1)\n minimum = empty(N-1)\n\n i = 0\n j = 0\n\n while j NEWLINE* statement ( NEWLINE+ statement )*\n\t\t# almost identical to Parser.block, but without '}' tokens\n\t\tstmts = []\n\t\twhile self.match(TokenType.NEWLINE):\n\t\t\tself.next()\n\t\tstmts.append(self._statement())\n\t\twhile self.token and not self.match(TokenType.EOF):\n\t\t\tif not self.accept(TokenType.NEWLINE):\n\t\t\t\tself.syntax_error(\"unexpected symbol\", self.token)\n\t\t\twhile self.match(TokenType.NEWLINE):\n\t\t\t\tself.next()\n\t\t\tstmt = self._statement()\n\t\t\tif stmt is None:\n\t\t\t\tbreak\n\t\t\tstmts.append(stmt)\n\t\treturn stmts\n\n\tdef _statement(self):\n\n\t\topening = self.token\n\n\t\t# statement -> NETWORK IDENTIFIER\n\t\tif self.accept(TokenType.NETWORK):\n\t\t\ttoken = self.accept(TokenType.IDENTIFIER)\n\t\t\tif token:\n\t\t\t\treturn ParseTreeNode(NodeType.NETWORK, token.value, start=opening)\n\t\t\telse:\n\t\t\t\tself.syntax_error(\"expected network name\", self.token)\n\n\t\t# statement -> VIEWPORT NUMBER NUMBER NUMBER NUMBER\n\t\telif self.accept(TokenType.VIEWPORT):\n\t\t\tx1 = self.accept(TokenType.NUMBER)\n\t\t\tif not x1:\n\t\t\t\tself.error(\"expected number\", x1)\n\t\t\ty1 = self.accept(TokenType.NUMBER)\n\t\t\tif not y1:\n\t\t\t\tself.error(\"expected number\", y1)\n\t\t\tx2 = self.accept(TokenType.NUMBER)\n\t\t\tif not x2:\n\t\t\t\tself.error(\"expected number\", x2)\n\t\t\ty2 = self.accept(TokenType.NUMBER)\n\t\t\tif not y2:\n\t\t\t\tself.error(\"expected number\", y2)\n\t\t\tpoint1 = (float(x1.value), float(y1.value))\n\t\t\tpoint2 = (float(x2.value), float(y2.value))\n\t\t\treturn ParseTreeNode(NodeType.VIEWPORT, point1, point2, start=opening)\n\n\t\t# statement -> IDENTIFIER AT NUMBER token+\n\t\t# statement -> IDENTIFIER SLASH ( NUMBER | LEVER_NUMBER ) ( LEFT | RIGHT ) NUMBER\n\t\t# statement -> IDENTIFIER NUMBER NUMBER NUMBER NUMBER\n\t\telif self.match(TokenType.IDENTIFIER):\n\t\t\tid = self.accept(TokenType.IDENTIFIER)\n\n\t\t\tif self.accept(TokenType.AT):\n\t\t\t\toffset = self.accept(TokenType.NUMBER)\n\t\t\t\tif not offset:\n\t\t\t\t\tself.error(\"expected number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\tpath = []\n\t\t\t\twhile self.token and not self.match(TokenType.NEWLINE, TokenType.EOF):\n\t\t\t\t\tif self.token.value is not None:\n\t\t\t\t\t\tpath.append(self.token.value)\n\t\t\t\t\ttoken = self.next()\n\t\t\t\treturn ParseTreeNode(NodeType.TRACK, id.value,\n\t\t\t\t\tfloat(offset.value), \" \".join(path), start=opening)\n\n\t\t\telif self.accept(TokenType.SLASH):\n\t\t\t\tlever = self.accept(TokenType.NUMBER, TokenType.LEVER_NUMBER)\n\t\t\t\tif not lever:\n\t\t\t\t\tself.error(\"expected lever number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\tside = self.accept(TokenType.LEFT, TokenType.RIGHT)\n\t\t\t\tif not side:\n\t\t\t\t\tself.error(\"expected 'left' or 'right'\", self.token)\n\t\t\t\t\treturn\n\t\t\t\toffset = self.accept(TokenType.NUMBER)\n\t\t\t\tif not offset:\n\t\t\t\t\tself.error(\"expected number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\toffsetval = float(offset.value)\n\t\t\t\tif not 0 <= offsetval <= 1:\n\t\t\t\t\tself.error(\"expected number between 0 and 1\", offset)\n\t\t\t\t\treturn\n\t\t\t\treturn ParseTreeNode(NodeType.SWITCH, id.value, lever.value,\n\t\t\t\t\t\"L\" if side.type == TokenType.LEFT else \"R\", offsetval, start=opening)\n\n\t\t\telif self.match(TokenType.NUMBER):\n\t\t\t\tx1 = self.accept(TokenType.NUMBER)\n\t\t\t\ty1 = self.accept(TokenType.NUMBER)\n\t\t\t\tif not y1:\n\t\t\t\t\tself.error(\"expected number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\tx2 = self.accept(TokenType.NUMBER)\n\t\t\t\tif not x2:\n\t\t\t\t\tself.error(\"expected number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\ty2 = self.accept(TokenType.NUMBER)\n\t\t\t\tif not y2:\n\t\t\t\t\tself.error(\"expected number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\tpoint1 = (float(x1.value), float(y1.value))\n\t\t\t\tpoint2 = (float(x2.value), float(y2.value))\n\t\t\t\treturn ParseTreeNode(NodeType.INTERLOCKING, id.value, point1, point2, start=opening)\n\n\t\t\telse:\n\t\t\t\tself.error(\"unexpected symbol\", self.token)\n\n\t\telif self.match(TokenType.EOF):\n\t\t\treturn\n\n\t\telse:\n\t\t\tself.error(\"unexpected symbol\", self.token)\n\n\nclass LayoutReader(Logger):\n\n\tdef __init__(self, network, data, filename, warn=False):\n\t\tLogger.__init__(self, filename, warn)\n\n\t\tself.network = network\n\t\tself.parser = LayoutParser(data, filename, warn=warn)\n\t\tself.lines = self.parser.lines\n\t\tself.tree = self.parser.parse()\n\n\tdef create_layouts(self):\n\t\tlayouts = {}\n\t\t_layout_locations = {}\n\n\t\tfor stmt in self.tree:\n\t\t\tif stmt.type == NodeType.NETWORK:\n\t\t\t\tself._match_network(stmt)\n\t\t\telif stmt.type == NodeType.VIEWPORT:\n\t\t\t\tlayouts[\"_viewport\"] = list(stmt.items)\n\t\t\telse:\n\t\t\t\tlayout = self._create(stmt)\n\t\t\t\tif layout is None:\n\t\t\t\t\tcontinue\n\n\t\t\t\tkey, val = layout\n\t\t\t\tif key in layouts:\n\t\t\t\t\tself.error(\"object already defined\", stmt)\n\t\t\t\t\tself.note(\"object first defined here\", _layout_locations[key])\n\t\t\t\t\treturn\n\t\t\t\tlayouts[key] = val\n\t\t\t\t_layout_locations[key] = stmt\n\n\t\tif self.errors != 0:\n\t\t\treturn None\n\t\treturn layouts\n\n\tdef _match_network(self, stmt):\n\t\tname = stmt.items[0]\n\t\tif name != self.network.id:\n\t\t\tself.error(\"network name does not match\", stmt)\n\n\tdef _create(self, stmt):\n\t\tif stmt.type == NodeType.INTERLOCKING:\n\t\t\tname = stmt.items[0]\n\t\t\tintg = self.network.interlocking(name)\n\t\t\tif intg is None:\n\t\t\t\tself.error(\"no such interlocking\", stmt)\n\t\t\t\treturn None\n\n\t\t\treturn intg, list(stmt.items[1:])\n\n\t\telif stmt.type == NodeType.TRACK:\n\t\t\ttrack, offset, path = stmt.items\n\t\t\tsec = self.network.track_section(\"{0}@{1}\".format(track, offset))\n\t\t\tif sec is None:\n\t\t\t\tself.error(\"no such track section\", stmt)\n\t\t\t\treturn None\n\n\t\t\treturn sec, path\n\n\t\telif stmt.type == NodeType.SWITCH:\n\t\t\tintg, lever, side, offset = stmt.items\n\t\t\tswitch = self.network.lever_object(\"{0}/{1}\".format(intg, lever))\n\t\t\tif switch is None or not isinstance(switch, Switch):\n\t\t\t\tself.error(\"no such switch\", stmt)\n\t\t\t\treturn None\n\n\t\t\treturn switch, (side, offset)\n","sub_path":"s3/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":5800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"578520718","text":"# Copyright (c) 2019. Partners HealthCare and other members of\n# Forome Association\n#\n# Developed by Sergey Trifonov based on contributions by Joel Krier,\n# Michael Bouzinier, Shamil Sunyaev and other members of Division of\n# Genetics, Brigham and Women's Hospital\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, logging\nfrom app.config.a_config import AnfisaConfig\nfrom app.eval.condition import ConditionMaker\nfrom app.model.sol_pack import SolutionPack\nfrom app.model.tab_report import ReportTabSchema\nfrom .favor import FavorSchema\n#===============================================\nsCfgFilePath = os.path.dirname(os.path.abspath(__file__)) + \"/files/\"\n\ndef cfgPath(fname):\n global sCfgFilePath\n return sCfgFilePath + fname\n\ndef cfgPathSeq(fnames):\n return [cfgPath(fname) for fname in fnames]\n\n\n#===============================================\nsStdFMark = AnfisaConfig.configOption(\"filter.std.mark\")\ndef stdNm(name):\n global sStdFMark\n return sStdFMark + name\n\n\n#===============================================\nsSolutionsAreSet = False\n\nLoF_CSQ = [\n \"CNV: deletion\",\n \"transcript_ablation\",\n \"splice_acceptor_variant\",\n \"splice_donor_variant\",\n \"stop_gained\",\n \"frameshift_variant\"\n]\n\nNON_SYNONYMOUS_CSQ = LoF_CSQ + [\n \"inframe_insertion\",\n \"inframe_deletion\",\n \"missense_variant\",\n \"protein_altering_variant\",\n \"incomplete_terminal_codon_variant\"\n]\n\nMODERATE_IMPACT_CSQ = NON_SYNONYMOUS_CSQ + [\n \"synonymous_variant\",\n \"splice_region_variant\",\n \"coding_sequence_variant\"\n]\n\nLOW_IMPACT_CSQ = [\n \"intron_variant\",\n \"intergenic_variant\",\n \"non_coding_transcript_exon_variant\",\n \"upstream_gene_variant\",\n \"downstream_gene_variant\",\n \"TF_binding_site_variant\",\n \"regulatory_region_variant\"\n]\n\ndef condition_consequence_xBrowse():\n return ConditionMaker.condEnum(\"Transcript_consequence\",\n MODERATE_IMPACT_CSQ)\n\ndef condition_high_quality():\n return (condition_high_confidence()\n + condition_high_quality_all_samples())\n\ndef condition_high_confidence_QD():\n return condition_good_confidence() + [\n ConditionMaker.condNum(\"QD\", min_val = 4)]\n\ndef condition_high_confidence():\n return condition_good_confidence() + [\n ConditionMaker.condNum(\"QUAL\", min_val = 40)]\n\ndef condition_good_confidence():\n return [\n ConditionMaker.condEnum(\"FT\", [\"PASS\"]),\n ConditionMaker.condNum(\"Max_GQ\", min_val = 50),\n ConditionMaker.condNum(\"FS\", max_val = 30)]\n\ndef condition_high_quality_all_samples():\n return [ConditionMaker.condNum(\"Min_GQ\", min_val = 40)]\n\ndef condition_all_genotypes_called():\n return [ConditionMaker.condNum(\"Num_NO_CALL\", max_val = 0)]\n\ndef impacting_splicing():\n return [ConditionMaker.condNum(\"splice_ai_dsmax\", min_val = 0.2)]\n\ndef clinVar_not_benign():\n return [ConditionMaker.condEnum(\"Clinvar_Trusted_Simplified\",\n [\"benign\"], \"NOT\")]\n\n#===============================================\ndef checkSolutionUnits(sol_kind, sol_name, unit_names, requires):\n if \"Rules\" in unit_names:\n if not requires or \"WS\" not in requires:\n logging.error(\n 'Solution %s/%s: \"WS\" must be set as requirement (uses Rules)'\n % (sol_kind, sol_name))\n return False\n if \"Compound_Het\" in unit_names:\n if (not requires\n or len({\"trio\", \"trio_base\", \"trio_pure\"} & requires) == 0):\n logging.error(\n ('Solution %s/%s: \"trio\"/\"trio_base\"/\"trio_pure\" must be set'\n ' as requirement (uses Compound_Het)')\n % (sol_kind, sol_name))\n return False\n return True\n\n#===============================================\ndef readySolutions():\n global sSolutionsAreSet\n if sSolutionsAreSet:\n return\n sSolutionsAreSet = True\n favor_pack = SolutionPack(\"FAVOR\", checkSolutionUnits)\n setupGenericPack(favor_pack)\n FavorSchema.readySolutions(favor_pack)\n\n base_pack = SolutionPack(\"CASE\", checkSolutionUnits)\n setupGenericPack(base_pack)\n readySolutions_Case(base_pack)\n\n#===============================================\ndef readySolutions_Case(base_pack):\n # BGM Filters, should belong to \"Undiagnosed Patients Solution Pack\"\n base_pack.regFilter(\"BGM_De_Novo\", [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Callers\", [\"BGM_BAYES_DE_NOVO\", \"RUFUS\"])],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"BGM_Homozygous_Rec\", [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Callers\", [\"BGM_HOM_REC\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Inheritance_Mode\", dict(),\n [\"Homozygous Recessive\"])],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"BGM_Compound_Het\", [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Callers\", [\"BGM_CMPD_HET\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Compound_Het\",\n {\"approx\": \"transcript\"}, [\"Proband\"])],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"BGM_Autosomal_Dominant\", [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Callers\", [\"BGM_DE_NOVO\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"])],\n requires = {\"trio_base\", \"WS\"})\n\n # Standard mendelian Filters, should belong to\n # \"Undiagnosed Patients Solution Pack\"\n base_pack.regFilter(\"X_Linked\", condition_high_quality() + [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Inheritance_Mode\", dict(), [\"X-linked\"])],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"Mendelian_Homozygous_Rec\",\n condition_high_quality() + condition_all_genotypes_called()\n + clinVar_not_benign() + [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Inheritance_Mode\", dict(),\n [\"Homozygous Recessive\"]),\n ConditionMaker.condEnum(\"Proband_Zygosity\", [\"Homozygous\"])\n ],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"Mendelian_Compound_Het\",\n condition_high_quality() + clinVar_not_benign() + [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Compound_Het\",\n {\"approx\": \"transcript\"}, [\"Proband\"])],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"Mendelian_Auto_Dom\",\n condition_high_quality() + clinVar_not_benign() + [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Inheritance_Mode\", dict(),\n [\"Autosomal Dominant\"]),\n ConditionMaker.condEnum(\"Proband_Zygosity\", [\"Heterozygous\"])\n ],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"InSilico_Possibly_Damaging\",\n condition_high_confidence() + [ConditionMaker.condEnum(\n \"Rules\", [stdNm(\"Possibly_Damaging_Predictions\")])],\n requires = {\"WS\"})\n\n base_pack.regFilter(\"InSilico_Damaging\", condition_high_confidence()\n + [ConditionMaker.condEnum(\"Rules\",\n [stdNm(\"Damaging_Predictions\")])],\n requires = {\"WS\"})\n\n # SEQaBOO Filters, should belong to \"Hearing Loss Solution Pack\"\n # base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_01\", [\n # ConditionMaker.condEnum(\"Rules\",\n # [stdNm(\"SEQaBOO_Hearing_Loss_v_01\")]),\n # ConditionMaker.condEnum(\"Rules\", [stdNm(\"ACMG59\")], \"NOT\")],\n # requires = {\"WS\"})\n # base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_02\", [\n # ConditionMaker.condEnum(\"Rules\",\n # [stdNm(\"SEQaBOO_Hearing_Loss_v_02\")]),\n # ConditionMaker.condEnum(\"Rules\", [stdNm(\"ACMG59\")], \"NOT\")],\n # requires = {\"WS\"})\n # base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_03\", [\n # ConditionMaker.condEnum(\"Rules\",\n # [stdNm(\"SEQaBOO_Hearing_Loss_v_03\")]),\n # ConditionMaker.condEnum(\"Rules\", [stdNm(\"ACMG59\")], \"NOT\")],\n # requires = {\"WS\"})\n # base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_03_5\", [\n # ConditionMaker.condEnum(\"Rules\",\n # [stdNm(\"SEQaBOO_Hearing_Loss_v_03\")]),\n # ConditionMaker.condEnum(\"Panels\", [\"All_Hearing_Loss\"])],\n # requires = {\"WS\"})\n base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_4\", [\n ConditionMaker.condEnum(\"Rules\", [stdNm(\"Hearing Loss, v.4\")])],\n requires = {\"WS\"})\n base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_5\", [\n ConditionMaker.condEnum(\"Rules\", [stdNm(\"Hearing Loss, v.5\")])],\n requires = {\"WS\"})\n base_pack.regFilter(\"SEQaBOO_Hearing_Quick\", [\n ConditionMaker.condEnum(\"Rules\", [stdNm(\"Hearing Loss Quick\")])],\n requires = {\"WS\"})\n\n # SEQaBOO Filters, should belong to \"Base Solution Pack\"\n base_pack.regFilter(\"SEQaBOO_ACMG59\", [\n ConditionMaker.condEnum(\"Rules\", [stdNm(\"ACMG59\")])],\n requires = {\"WS\"})\n # base_pack.regFilter(\"SEQaBOO_ACMG59\", [\n # ConditionMaker.condEnum(\"Rules\", [stdNm(\"SEQaBOO_ACMG59\")]),\n # ConditionMaker.condEnum(\"Rules\", [stdNm(\"ACMG59\")], \"AND\")],\n # requires = {\"WS\"})\n\n base_pack.regFilter(\"Loss_Of_Function\", condition_high_quality() + [\n ConditionMaker.condEnum(\"Most_Severe_Consequence\", LoF_CSQ)])\n\n base_pack.regFilter(\"Non_Synonymous\", condition_high_quality() + [\n ConditionMaker.condEnum(\"Most_Severe_Consequence\",\n NON_SYNONYMOUS_CSQ)])\n\n base_pack.regFilter(\"UTR_and_Worse\", condition_high_quality() + [\n ConditionMaker.condEnum(\"Most_Severe_Consequence\",\n LOW_IMPACT_CSQ, join_mode = \"NOT\")])\n\n base_pack.regFilter(\"Impact_Splicing\",\n condition_high_confidence() + impacting_splicing())\n\n base_pack.regFilter(\"ClinVar_VUS_or_Worse\",\n condition_high_confidence() + [\n ConditionMaker.condEnum(\"Clinvar_stars\", [\"1\", \"2\", \"3\", \"4\"]),\n ConditionMaker.condEnum(\"Clinvar_conflicts\", [\"True\"],\n join_mode = \"NOT\"),\n ConditionMaker.condEnum(\"Clinvar_Benign\", [\"VUS or Pathogenic\"])\n ], requires={\"XL\"})\n\n base_pack.regFilter(\"In_Silico_Damaging\",\n condition_high_confidence() + [\n ConditionMaker.condEnum(\"Polyphen_2_HVAR\", [\"D\"]),\n ConditionMaker.condEnum(\"SIFT\", [\"deleterious\"])\n ], requires={\"XL\"})\n\n # base_pack.regFilter(\"Impact_Splicing\",\n # condition_high_quality() + impacting_splicing())\n\n # Production Decision Trees\n base_pack.regDTree(\"BGM Research\",\n cfgPathSeq([\"bgm_xbrowse.pyt\"]),\n requires = {\"trio_base\"})\n base_pack.regDTree(\"BGM Red Button\",\n cfgPathSeq([\"bgm_strict.pyt\"]),\n requires = {\"trio_base\"})\n base_pack.regDTree(\"Trio Candidates\",\n cfgPathSeq([\"quality.pyt\", \"rare.pyt\", \"trio.pyt\"]),\n requires = {\"trio_base\"})\n base_pack.regDTree(\"All Rare Variants\",\n cfgPathSeq([\"quality.pyt\", \"rare.pyt\", \"return_true.pyt\"]))\n base_pack.regDTree(\"Hearing Loss, v.4\",\n cfgPathSeq([\"quality.pyt\", \"hearing_loss.pyt\"]))\n base_pack.regDTree(\"Hearing Loss, v.5\",\n cfgPathSeq([\"quality.pyt\", \"hearing_loss_v5.pyt\"]))\n base_pack.regDTree(\"Hearing Loss Quick\",\n cfgPathSeq([\"quality.pyt\", \"hearing_loss_ws.pyt\"]), requires={\"WS\"})\n base_pack.regDTree(\"ACMG59 Variants\",\n cfgPathSeq([\"quality.pyt\", \"acmg59.pyt\"]))\n base_pack.regDTree(\"Damaging_Predictions\",\n cfgPathSeq([\"damaging.pyt\"]))\n base_pack.regDTree(\"Possibly_Damaging_Predictions\",\n cfgPathSeq([\"possibly_damaging.pyt\"]))\n\n # Test trees\n # base_pack.regDTree(\"Q Test\",\n # cfgPathSeq([\"quality.pyt\", \"return_true.pyt\"]))\n # base_pack.regDTree(\"R Test\",\n # cfgPathSeq([\"rare.pyt\", \"return_true.pyt\"]))\n # base_pack.regDTree(\"T Test\",\n # [cfgPath(\"trio.pyt\")],\n # requires = {\"trio_base\"})\n # base_pack.regDTree(\"H Test\",\n # [cfgPath(\"hearing_loss.pyt\")])\n\n base_pack.regZone(\"Gene\", \"Symbol\")\n base_pack.regZone(\"Gene List\", \"Panels\")\n base_pack.regZone(\"Sample\", \"Has_Variant\")\n base_pack.regZone(\"Cohort\", \"Variant_in\", requires = {\"cohorts\"})\n base_pack.regZone(\"Tag\", \"_tags\")\n\n demo_tab_schema = ReportTabSchema(\"demo\", use_tags = True)\n demo_tab_schema.addField(\"gene(s)\", \"/_view/general/genes[]\")\n demo_tab_schema.addField(\"variant\", \"/__data/label\")\n demo_tab_schema.addField(\"gnomAD_AF\", \"/_filters/gnomad_af_fam\")\n base_pack.regTabSchema(demo_tab_schema)\n\n#===============================================\ndef setupGenericPack(base_pack):\n base_pack.regItemDict(\"Clinvar_Trusted_Submitters\", {\n \"Laboratory for Molecular Medicine, \"\n + \"Partners HealthCare Personalized Medicine\": \"LMM\",\n \"GeneDx\": \"GeneDx\",\n \"Invitae\": \"Invitae\"})\n\n base_pack.regPanel(\"ACMG59\", \"Symbol\",\n cfgPath(\"acmg59.lst\"))\n base_pack.regPanel(\"All_Hearing_Loss\", \"Symbol\",\n cfgPath(\"all_hearing_loss.lst\"))\n base_pack.regPanel(\"Reportable_Hearing_Loss\", \"Symbol\",\n cfgPath(\"rep_hearing_loss.lst\"))\n base_pack.regPanel(\"Complement_System\", \"Symbol\",\n cfgPath(\"complement_system.lst\"))\n base_pack.regPanel(\"PharmGKB_VIP\", \"Symbol\",\n cfgPath(\"pharmgkb_vip.lst\"))\n base_pack.regPanel(\"Coagulation_System\", \"Symbol\",\n cfgPath(\"coagulation_system.lst\"))\n base_pack.regPanel(\"Thrombotic_Thrombocytopenic_Purpura\", \"Symbol\",\n cfgPath(\"ttp.lst\"))\n base_pack.regPanel(\"Immune_Dysregulation\", \"Symbol\",\n cfgPath(\"immune_dysregulation.lst\"))\n base_pack.regPanel(\"Autism_Spectrum\", \"Symbol\",\n cfgPath(\"autism.lst\"))\n base_pack.regPanel(\"Holoprosencephaly\", \"Symbol\",\n cfgPath(\"hpe.lst\"))\n base_pack.regPanel(\"Tubulinopathies\", \"Symbol\",\n cfgPath(\"tubulinopathies.lst\"))\n base_pack.regPanel(\"Notch_Signaling_Pathway\", \"Symbol\",\n cfgPath(\"notch.lst\"))\n base_pack.regPanel(\"SSH1_Interactors\", \"Symbol\",\n cfgPath(\"ssh.lst\"))\n base_pack.regPanel(\"Wnt1_Interactors\", \"Symbol\",\n cfgPath(\"wnt.lst\"))\n # base_pack.regPanel(\"TTP1\", \"Symbol\",\n # cfgPath(\"ttp1.lst\"))\n # base_pack.regPanel(\"TTP2\", \"Symbol\",\n # cfgPath(\"ttp2.lst\"))\n # base_pack.regPanel(\"TTP3\", \"Symbol\",\n # cfgPath(\"ttp3.lst\"))\n # base_pack.regPanel(\"TTP4\", \"Symbol\",\n # cfgPath(\"ttp4.lst\"))\n\n base_pack.regPanel(\"Check-Tags\", \"_tags\", items = [\n \"Previously categorized\",\n \"Previously Triaged\",\n \"Not categorized\",\n \"Benign/Likely benign\",\n \"False positives\"]\n )\n\n csv_tab_schema = ReportTabSchema(\"csv\", use_tags = False)\n csv_tab_schema.addField(\"chromosome\", \"/_filters/chromosome\")\n csv_tab_schema.addMustiStrField(\"variant\", \"|\", [\n \"/_filters/chromosome\",\n \"/_filters/start\",\n \"/_filters/ref\",\n \"/_filters/alt\"])\n base_pack.regTabSchema(csv_tab_schema)\n\ndef completeDsModes(ds_h):\n if ds_h.getDataSchema() == \"CASE\":\n family_info = ds_h.getFamilyInfo()\n trio_seq = family_info.getTrioSeq()\n if trio_seq:\n ds_h.addModes({\"trio\"})\n if trio_seq[0][0] == \"Proband\":\n ds_h.addModes({\"trio_base\"})\n if len(family_info) == 3:\n ds_h.addModes({\"trio_pure\"})\n if ds_h.getDataInfo()[\"meta\"].get(\"cohorts\"):\n ds_h.addModes({\"cohorts\"})\n elif ds_h.getDataSchema() == \"FAVOR\":\n FavorSchema.completeDsModes(ds_h)\n","sub_path":"app/config/solutions.py","file_name":"solutions.py","file_ext":"py","file_size_in_byte":16908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"272614319","text":"class Solution:\n def lengthOfLastWord1(self, s):\n if not s.split():\n return 0\n return len(s.split()[-1])\n \n def lengthOfLastWord2(self, s):\n r = -1\n # r指標用以避免右側空格\n while r >= -len(s) and s[r] == \" \":\n r-=1\n # 跳過右側空格後 l 從 r 的位置再開始計算\n l = r\n while l >= -len(s) and s[l] != \" \":\n l-=1\n return r - l\n \nif __name__ == \"__main__\":\n s = Solution()\n print(s.lengthOfLastWord1(s = \"Hello World\"))\n print(s.lengthOfLastWord2(s = \"a \"))\n ","sub_path":"058-Length-of-Last-Word/Length-of-Last-Word.py","file_name":"Length-of-Last-Word.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"317201072","text":"#! /usr/bin/python\nimport asyncio\nimport os\nimport argparse\nimport time\n\n\n# Definicion de los argumentos\nparser = argparse.ArgumentParser(description='Tp4 - servidor web asincrono')\nparser.add_argument('-d', '--documentroot', default='/home/valenscalco/comp2/lab/alumnos/58103-Scalco-Valentina/TP4/', type=str,\n help='Directorio donde están los documentos web')\nparser.add_argument('-p', '--port', default=5000, help='Puertoen donde espera conexiones')\nparser.add_argument('-s', '--size', default=1024, help='Bloque de lectura máximo para los documentos')\nparser.add_argument('-b', '--debug', default=False, help='Debug')\n\nargs = parser.parse_args()\n\n\nasync def handle(reader, writer):\n data = await reader.read(1024)\n ip, port = writer.get_extra_info('peername')\n encabezado = \"\"\n\n try:\n encabezado = data.decode().splitlines()[0]\n archivo = \".\" + encabezado.split()[1]\n if args.debug:\n asyncio.create_task(debug('handle', archivo))\n if archivo == './':\n archivo = './index.html'\n except:\n archivo = './index.html'\n\n code = '200 OK'\n task = asyncio.create_task(open_file(archivo, writer, code))\n task1 = asyncio.create_task(logs(ip, port))\n\n await task\n await task1\n\n\nasync def open_file(archivo, writer, code):\n if args.debug:\n asyncio.create_task(debug('open_file', archivo))\n archivo = args.documentroot + archivo\n size = args.size\n try:\n fd = open(archivo, \"rb\")\n await escritura(archivo, fd, writer, code, size)\n except FileNotFoundError:\n archivo = args.documentroot + \"404Error.html\"\n code = \"404 Not Found\"\n fd = open(archivo, \"rb\")\n await escritura(archivo, fd, writer, code, size)\n except:\n archivo = args.documentroot + '500error.html'\n code = \"500 Internal server error\"\n fd = open(archivo, \"rb\")\n await escritura(archivo, fd, writer, code, size)\n\n\nasync def escritura(archivo, fd, writer, code, size):\n if args.debug:\n req = archivo.lstrip(args.documentroot)\n asyncio.create_task(debug('escritura', req))\n dic = {\".txt\": \" text/plain\", \".jpg\": \" image/jpeg\", \".ppm\": \" image/x-portable-pixmap\", \".html\": \" text/html\", \".pdf\": \" application/pdf\"}\n\n extension = os.path.splitext(archivo)[1]\n header = bytearray(\"HTTP/1.1 \" + code + \"\\r\\nContent-type:\" + dic[extension] + \"\\r\\nContent-length:\" + str(os.path.getsize(archivo)) + \"\\r\\n\\r\\n\" , \"utf8\")\n\n writer.write(header)\n await writer.drain()\n\n while True:\n data = fd.read(size)\n writer.write(data)\n if len(data) != size:\n break\n\n await writer.drain()\n writer.close()\n await writer.wait_closed()\n\n\nasync def logs(ip, port):\n now = time.ctime()\n log = f'> client: {ip}:{port}; date:{now}\\n'\n with open('logs.txt', 'a') as logs:\n logs.write(log)\n\n\nasync def debug(furName, req):\n now = time.ctime()\n mjs = f'> funtion: {furName}; date:{now}; file:{req}\\n'\n with open('debug.txt', 'a') as f:\n f.write(mjs)\n\n\nasync def main():\n port = args.port\n server = await asyncio.start_server(handle, '172.17.0.1', port)\n async with server:\n await server.serve_forever()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","sub_path":"alumnos/58103-Scalco-Valentina/TP4/try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"32610304","text":"import os\nimport re\nimport error # type: ignore\nimport webbrowser\nimport requests\n\nisUrl = re.compile(r'((\\S*)?:\\/\\/(.)?)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.?[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)')\nisLocal = re.compile(r'^(.*/)([^/]*)$')\n\nclass Path:\n def __init__(self, path: str):\n self.path = path\n \n if isUrl.match(self.path):\n self.type = 'web'\n elif isLocal.match(self.path):\n self.type = 'local'\n else:\n raise error.UnknownPathTypeError()\n \n def getType(self):\n return self.type\n \n def getRawPath(self):\n return self.path\n \n def getRealPath(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.realpath(self.path)\n \n def isFile(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.isfile(self.path)\n \n def isDir(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.isdir(self.path)\n \n def getRelativePath(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.relpath(self.path)\n \n def getLastAccessTime(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.getatime(self.path)\n \n def getLastModifiedTime(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.getmtime(self.path)\n\n def openInBrowser(self):\n if self.type == 'local':\n raise error.InvalidOperationPerformedError()\n else:\n webbrowser.open(self.path)\n \n def getRequest(self):\n if self.type == 'local':\n raise error.InvalidOperationPerformedError()\n else:\n res = requests.get(self.path)\n \n return res\n \n def getRequestStatusCode(self):\n if self.type == 'local':\n raise error.InvalidOperationPerformedError()\n else:\n res = requests.get(self.path)\n \n return res.status_code\n","sub_path":"py_everything/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"499878984","text":"import numpy as np\nfrom PIL import Image\nimport os\n\nimg_size = 128\nn_v = img_size * img_size \nbatch_size = 1\n\nones_vec = np.ones((batch_size, 1))\n\ndef load_input_data():\n input_data_array = [] \n files = os.listdir(\"./\")\n for fname in files:\n _, ext = os.path.splitext(fname)\n if ext == '.jpg' or ext == '.png':\n print(fname)\n img = Image.open(fname).convert('L')\n imgArray = np.reshape(np.asarray(img), (1, n_v))\n input_data_array.append(imgArray)\n\n batch_size = len(input_data_array)\n input_data = np.zeros((batch_size, n_v))\n\n for i in range(batch_size):\n input_data[i, :] = input_data_array[i]\n\n return (input_data, batch_size)\n\n\n\ndef regularize_img(img_batch):\n img_batch = img_batch \\\n - ones_vec * img_batch.mean(axis=0).reshape((1, n_v))\n sigma = ones_vec * np.sqrt( np.square(img_batch).mean(axis=0) / batch_size).reshape((1, n_v))\n img_batch = np.divide(img_batch, sigma)\n return img_batch\n\ndef array_to_grayimg(v):\n #v: (batch_size, n_v)\n #return: transformed v of which each pixels have 0~1 value.\n mins = ones_vec * v.min(axis=0).reshape((1, n_v))\n maxs = ones_vec * v.max(axis=0).reshape((1, n_v))\n return (v - mins).astype(float) / (maxs - mins).astype(float)\n\ndef save_modified_imgbatch(img_batch, fname_suffix):\n for i in range(batch_size):\n tmp_img = np.reshape(np.uint8(255*img_batch[i]), (img_size, img_size))\n img = Image.fromarray(tmp_img).convert('L')\n img.show()\n img.save('%s_%d.jpg' % (fname_suffix, i), 'jpeg')\n\n\n\n\n#main loop\ninput_data, batch_size = load_input_data()\nprint('input_data')\nprint(input_data)\n\nregularized_input_data = regularize_img(input_data)\nprint('regularized_input_data')\nprint(regularized_input_data)\nsave_modified_imgbatch(input_data, 'regularized')\n\ndecoded_input_data = array_to_grayimg(regularized_input_data)\nprint('decoded_input_data')\nprint(decoded_input_data)\nsave_modified_imgbatch(decoded_input_data, 'decoded')\n","sub_path":"miku_img/img_regularize_cnvter.py","file_name":"img_regularize_cnvter.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"101971466","text":"#@author: hant 27-02-2013\n\n\"\"\"\n Device_self (the name shelf was an error here) is a self to display products on devices.\n This service get the list of all device_self.\n\"\"\"\ndef get():# software\n# software = request.args(0)\n \n try:\n rows = db().select(db.clsb_device_shelf.ALL, orderby=db.clsb_device_shelf.shelf_order).as_list()\n d = list()\n for row in rows:\n temp = dict()\n temp['device_self_name'] = row['device_shelf_name']\n temp['device_self_code'] = row['device_shelf_code']\n temp['device_self_type'] = row['device_shelf_type']\n temp['shelf_order'] = row['shelf_order']\n temp['description'] = row['description']\n\n d.append(temp)\n return dict(items=d)\n except Exception as e:\n return dict(error = CB_0003 + str(e)) #DB_RQ_FAILD","sub_path":"cbs20/controllers/device_shelf.py","file_name":"device_shelf.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"153286239","text":"# height = float(input('Please enter your height input meters(decimals): '))\n# weight = int(input('Please enter your weight input kg: '))se\ndef bmi_calc(weight, height):\n if(height>0 and weight>0):\n bmi = int(weight / (height * height))\n elif height==0:\n return \"Divide by zero\"\n elif height<0 or weight<=0:\n return \"Ivalid value\"\n return bmi\n\n\ndef bmi_toweight(bmi):\n if bmi <= 18.5:\n print('Your BMI is', bmi, 'which means you are underweight.')\n return \"underweight\"\n\n elif bmi > 18.5 and bmi < 25:\n print('Your BMI is', bmi, 'which means you are normal.')\n return \"nnormal\"\n\n elif bmi > 25 and bmi < 50:\n print('your BMI is', bmi, 'overweight.')\n return \"ooverweight\"\n elif bmi > 50:\n print('Your BMI is', bmi, 'which means you are obese.')\n return \"oobese\"\n else:\n print('There is an error with your input')\n print('Please check you have entered whole numbers\\n'\n 'and decimals were asked.')\n return None","sub_path":"bmi.py","file_name":"bmi.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"152531730","text":"from sklearn.model_selection import train_test_split\nfrom sklearn import datasets\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.svm import SVR\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import RandomForestRegressor\n\niris = datasets.load_iris()\nX = iris.data[:, [2, 3]]\ny = iris.target\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\n\nprint(X_train.shape, y_train.shape, X_test.shape, y_test)\n\nlogreg = LogisticRegression()\nlogreg.fit(X_train, y_train)\nprint('LogisticRegression:', logreg.score(X_test, y_test))\n\nlinear = LinearRegression()\nlinear.fit(X_train, y_train)\nprint('LinearRegression:', linear.score(X_test, y_test))\n\ndecisiont = DecisionTreeRegressor()\ndecisiont.fit(X_train, y_train)\nprint('DecisionTreeRegressor:', decisiont.score(X_test, y_test))\nres = decisiont.predict([[3.2, 1]])\nprint('prediction:', res)\n\nnb = GaussianNB()\nnb.fit(X_train, y_train)\nprint('GaussianNB:', nb.score(X_test, y_test))\nprint('prediction:', nb.predict([[3.2, 1]]))\n\nrd = RandomForestClassifier()\nrd.fit(X_train, y_train)\nprint('RandomForestClassifier:', rd.score(X_test, y_test))\n\nrr = RandomForestRegressor()\nrr.fit(X_train, y_train)\nprint('RandomForestRegressor:', rr.score(X_test, y_test))\n\nsvm = SVC()\nsvm.fit(X_train, y_train)\nprint('SVC:', svm.score(X_test, y_test))\n\nsvr = SVR()\nsvr.fit(X_train, y_train)\nprint('SVR:', svr.score(X_test, y_test))\n","sub_path":"iris_database/compare_models2.py","file_name":"compare_models2.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"384272115","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'ipetrash'\n\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import Qt\n\n\nclass Widget(QWidget):\n def __init__(self):\n super().__init__()\n\n self.old_pos = None\n\n def mousePressEvent(self, event):\n if event.button() == Qt.LeftButton:\n self.old_pos = event.pos()\n\n def mouseMoveEvent(self, event):\n delta = event.pos() - self.old_pos\n self.move(self.pos() + delta)\n\n\nif __name__ == '__main__':\n app = QApplication([])\n\n w = Widget()\n w.show()\n\n app.exec()\n","sub_path":"pyqt__mouse_manual_move.py","file_name":"pyqt__mouse_manual_move.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"183207965","text":"import http.server\r\nimport socketserver\r\nimport json\r\nfrom io import BytesIO\r\n\r\nPORT = 8080\r\n# Handler = http.server.SimpleHTTPRequestHandler\r\nSTATUS = b'1'\r\n\r\nclass myHHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):\r\n def __init__(self, *args, directory=None, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n \r\n def do_GET(self):\r\n \"\"\"Serve a GET request.\"\"\"\r\n if self.path == \"/\" or self.path == \"/index.html\":\r\n f = self.send_head()\r\n if f:\r\n try:\r\n self.copyfile(f, self.wfile)\r\n finally:\r\n f.close()\r\n elif(self.path == \"/api/status\"):\r\n self.send_response(200)\r\n self.end_headers()\r\n self.wfile.write(STATUS)\r\n \r\n def do_POST(self):\r\n global STATUS # note: must be global here\r\n\r\n content_length = int(self.headers['Content-Length'])\r\n body = self.rfile.read(content_length)\r\n self.send_response(200)\r\n self.end_headers()\r\n response = BytesIO()\r\n STATUS = body\r\n print('status is {0}'.format(STATUS))\r\n response.write(body)\r\n # self.wfile.write(b'whatever')\r\n\r\nif __name__ == \"__main__\":\r\n\r\n Handler = myHHTTPRequestHandler\r\n with socketserver.TCPServer((\"\", PORT), Handler) as httpd:\r\n print(\"serving at port\", PORT)\r\n httpd.serve_forever() # it will call construtor of the Handler each time\r\n\r\n\r\n","sub_path":"WebApp/server-demo/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"472272442","text":"\r\n# this one was fun\r\n\r\nn = int(input())\r\n\r\nfractions = []\r\n\r\nimport re\r\n\r\nfor i in range (0, n):\r\n\tfraction = input()\r\n\r\n\tm = re.match(r\"(\\d*)/(\\d*)\", fraction)\r\n\tfractions.append( (int(m.group(1)), int(m.group(2))))\r\n\r\n\r\ncommonFractions = []\r\n\r\n\r\nfor i in range(0, len(fractions)):\r\n\tcommonFractions.append(fractions[i])\r\n\tfor k in range(0, len(fractions)):\r\n\t\tif(i != k):\r\n\t\t\tcommonFractions[i] = (commonFractions[i][0] * fractions[k][1], commonFractions[i][1] * fractions[k][1])\r\n\r\nnumSum = 0\r\ndenom = commonFractions[0][1]\r\nfor element in commonFractions:\r\n\tnumSum += element[0]\r\n\r\nfor i in range(denom + 1, 1, -1):\r\n\tif(numSum % i == 0 and denom % i == 0):\r\n\t\tnumSum = numSum // i\r\n\t\tdenom = denom // i\r\n\r\nprint(str(numSum) + \"/\" + str(denom))","sub_path":"Easy/226.py","file_name":"226.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"271669907","text":"\"\"\" Utility functions and classes for SRP\n\nContext : SRP\nModule : SRPELT\nVersion : 1.0.0\nAuthor : Stefano Covino\nDate : 29/03/2017\nE-mail : stefano.covino@brera.inaf.it\nURL: : http://www.merate.mi.astro.it/utenti/covino\n\nUsage : \n\nRemarks :\n\nHistory : (29/03/2017) First version.\n\"\"\"\n\nimport numpy as np\nimport scipy.integrate as integrate\nfrom pynverse import inversefunc\nfrom SRPELT.aspheric_polar_der import aspheric_polar_der\nfrom SRPELT.aspheric_polar import aspheric_polar\n\n\n\ndef mpdf(r,area):\n return fpdf(r)/area\n\ndef mycdf(r,r_min,area):\n return integrate.quad(mpdf,r_min,r,args=(area,))[0]\n\n\ndef uni_aspher (nlat,nlon,r_min,r_max,CR,k,r2=0.,r4=0.):\n \"\"\"Generate an uniform distribution of points on an aspheric surface\"\"\"\n # azimuth\n stph = 360./nlon\n ph = np.arange(0.,360.,stph)\n # CDF\n samplecdf = np.arange(0,1,1./nlat)\n fpdf = lambda r: (1. + aspheric_polar_der(r,CR,k,0.,r4)**2)\n Area = integrate.quad(fpdf,r_min,r_max)[0]\n mpdf = lambda r: (fpdf(r)/Area)\n myint = lambda r: integrate.quad(mpdf,r_min,r)[0]\n invas = inversefunc(myint)\n rcds = []\n for i in samplecdf:\n rcds.append(invas(i))\n #\n rr,pp = np.meshgrid(np.array(rcds),ph)\n #\n x = rr*np.cos(np.radians(pp))\n y = rr*np.sin(np.radians(pp))\n z = aspheric_polar(rr,CR,k,r2,r4)\n return np.ravel(x),np.ravel(y),np.ravel(z)\n","sub_path":"python3/SRPAstro/SRP.ELT/SRPELT/uni_aspher.py","file_name":"uni_aspher.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"331928396","text":"import json\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404\nfrom django.template import RequestContext\nfrom django.template.loader import render_to_string\nfrom django.views.decorators.http import require_POST\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.decorators import permission_required\n\nfrom kaleo.compat import get_user_model\nfrom kaleo.forms import InviteForm\nfrom kaleo.models import JoinInvitation, InvitationStat\n\n\n@login_required\n@require_POST\ndef invite(request):\n form = InviteForm(request.POST, user=request.user)\n if form.is_valid():\n email = form.cleaned_data[\"email_address\"]\n JoinInvitation.invite(request.user, email)\n form = InviteForm(user=request.user)\n data = {\n \"html\": render_to_string(\n \"kaleo/_invite_form.html\", {\n \"form\": form,\n \"user\": request.user\n }, context_instance=RequestContext(request)\n ),\n \"fragments\": {\n \".kaleo-invites-remaining\": render_to_string(\n \"kaleo/_invites_remaining.html\", {\n \"invites_remaining\": request.user.invitationstat.invites_remaining()\n }, context_instance=RequestContext(request)\n ),\n \".kaleo-invites-sent\": render_to_string(\n \"kaleo/_invited.html\", {\n \"invited_list\": request.user.invites_sent.all()\n }, context_instance=RequestContext(request)\n )\n }\n }\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\n\n\n@login_required\n@permission_required(\"kaleo.manage_invites\", raise_exception=True)\ndef invite_stat(request, pk):\n user = get_object_or_404(get_user_model(), pk=pk)\n return HttpResponse(json.dumps({\n \"html\": render_to_string(\n \"kaleo/_invite_stat.html\", {\n \"stat\": user.invitationstat\n }, context_instance=RequestContext(request)\n )\n }), content_type=\"application/json\")\n\n\n@login_required\n@permission_required(\"kaleo.manage_invites\", raise_exception=True)\n@require_POST\ndef topoff_all(request):\n amount = int(request.POST.get(\"amount\"))\n InvitationStat.topoff(amount)\n return HttpResponse(json.dumps({\n \"inner-fragments\": {\".invite-total\": amount}\n }), content_type=\"application/json\")\n\n\n@login_required\n@permission_required(\"kaleo.manage_invites\", raise_exception=True)\n@require_POST\ndef topoff_user(request, pk):\n user = get_object_or_404(get_user_model(), pk=pk)\n amount = int(request.POST.get(\"amount\"))\n InvitationStat.topoff_user(user=user, amount=amount)\n return HttpResponse(json.dumps({\n \"html\": amount\n }), content_type=\"application/json\")\n\n\n@login_required\n@permission_required(\"kaleo.manage_invites\", raise_exception=True)\n@require_POST\ndef addto_all(request):\n amount = int(request.POST.get(\"amount\"))\n InvitationStat.add_invites(amount)\n return HttpResponse(json.dumps({\n \"inner-fragments\": {\".amount-added\": amount}\n }), content_type=\"application/json\")\n\n\n@login_required\n@permission_required(\"kaleo.manage_invites\", raise_exception=True)\n@require_POST\ndef addto_user(request, pk):\n user = get_object_or_404(get_user_model(), pk=pk)\n amount = int(request.POST.get(\"amount\"))\n InvitationStat.add_invites_to_user(user=user, amount=amount)\n return HttpResponse(json.dumps({\n \"html\": amount\n }), content_type=\"application/json\")\n","sub_path":"wsgi/mysite/mysiteenv/lib/python2.7/site-packages/kaleo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"176636367","text":"#!/usr/bin/env python3\n\nimport rospy\nfrom q_learning_project.msg import QMatrix, QMatrixRow, QLearningReward, RobotMoveDBToBlock\nimport numpy as np\n\nclass QLearning(object):\n def __init__(self):\n # set alpha/gamma/epsilon for easy access when optimizing algorithm during testing\n self.alpha = 1\n self.gamma = 0.5\n self.epsilon = 1\n \n # Initialize q_learning node\n rospy.init_node('q_learning')\n\n # Set publishers\n self.q_matrix_pub = rospy.Publisher(\"/q_learning/q_matrix\", QMatrix, queue_size=10)\n self.robot_action_pub = rospy.Publisher(\"/q_learning/robot_action\", RobotMoveDBToBlock, queue_size=10)\n \n # ROS Subscribe to rewards\n rospy.Subscriber(\"q_learning/reward\", QLearningReward, self.q_algo)\n\n # Waits for publisher to be attached\n rospy.sleep(3)\n\n # create a reference for dumbell colors\n self.dumbells = [\"red\", \"green\", \"blue\"]\n \n # create a table that stores the different actions (as a tuple: (db_moved, block_moved_to)) the robot can take\n self.action_table = []\n for db in range(3):\n for block in range(1,4):\n self.action_table.append((self.dumbells[db], block))\n \n # create an array that represents every possible state\n self.state_matrix = []\n for b in range(4):\n for g in range(4):\n for r in range(4):\n self.state_matrix.append((r, g, b))\n \n # Initialize and publish Q Matrix\n self.q_matrix = QMatrix()\n self.q_matrix.q_matrix = np.full((64, 9), 0)\n self.q_matrix_pub.publish(self.q_matrix)\n \n # intialize iterations\n self.iterations = 0\n self.iterations_converging = 0\n\n # Initialize action Matrix\n self.init_action_matrix()\n\n # Start state as 0, next state hasn't been determined yet\n self.curr_state = 0\n self.next_state = -1\n \n # initialialize action chosen (-1 before any have been chosen)\n self.action_choice = -1\n \n # keeps track of whether the q_matrix has converged\n self.converged = False\n \n self.final_action_seq = []\n\n # initialize action matrix\n def init_action_matrix(self):\n \n # creating the action matrix\n self.action_matrix = []\n self.action_matrix = np.full((64, 64), -1)\n \n for start, col in enumerate(self.action_matrix):\n for next in range(len(col)):\n start_state = self.state_matrix[start]\n next_state = self.state_matrix[next]\n \n # check that transition to next state is valid:\n is_valid_action = True\n # 1) need to check (at least) 1 and only 1 move has been made and that no dumbell has been moved back to origin/between blocks\n # an array of moves in the format (db_color_moved, block_number)\n moves = []\n for i in range(3):\n if start_state[i] != next_state[i]:\n if start_state[i] == 0:\n moves.append((self.dumbells[i], next_state[i]))\n else:\n is_valid_action = False\n break\n\n if len(moves) != 1:\n is_valid_action = False\n break \n # 2) check no more than one dumbell at each block\n for db in range(1, 4):\n num = 0\n for block in range(0, 3):\n if next_state[block] == db:\n num = num + 1\n if num > 1:\n is_valid_action = False\n break\n \n if is_valid_action:\n # get the action number that matches the move\n action = 0\n for i, a in enumerate(self.action_table):\n if a == moves[0]:\n action = i\n # add the action that changes the state from the start_state to next_state\n self.action_matrix[start][next] = action\n\n def random_action(self):\n # choose a random action given the robot's current state \n possible_actions = np.array(self.action_matrix[self.curr_state]) \n self.action_choice = np.random.choice(possible_actions)\n while self.action_choice == -1:\n self.action_choice = np.random.choice(possible_actions)\n action = self.action_table[self.action_choice]\n\n # publish chosen action\n robot_action = RobotMoveDBToBlock(robot_db = self.dumbells[action[0]], block_id = action[1])\n self.robot_action_pub.publish(robot_action)\n\n\n # updates q_matrix based on rewards\n def q_algo(self, data):\n \n # get current and new values of the row\n curr_value = self.q_matrix.q_matrix[self.curr_state].q_matrix_row[self.action_choice]\n self.q_matrix.q_matrix[self.curr_state].q_matrix_row[self.action_choice] = curr_value + (self.alpha * (data.reward + self.gamma * max(self.q_matrix.q_matrix[self.next_state].q_matrix_row) - curr_value))\n new_value = self.q_matrix.q_matrix[self.curr_state].q_matrix_row[self.action_choice]\n\n # if q_matrix vals don't change, increase converging count\n if abs(new_value - curr_value) < self.epsilon:\n self.iterations_converging += 1\n # if vals do change, reset convergence count\n else: \n self.iterations_converging = 0\n\n # publish q_matrix and update state\n self.q_matrix_pub.publish(self.q_matrix)\n self.curr_state = self.next_state\n\n # resets state when all 3 dumbells have been moved\n if self.iterations % 3 == 0:\n self.current_state = 0\n rospy.sleep(1)\n\n # checks if matrix converged\n if self.converged is False:\n # choose next action\n self.random_action()\n self.iterations += 1\n self.check_convergence()\n \n def check_convergence(self):\n # check if iterated minmum amount of times\n if self.iterations > 200:\n if self.iterations_converging >= 300:\n self.converged = True\n self.state = 0\n self.change_subscriptions()\n # find best sequential actions for robot at each stage\n for a in range(1,3):\n row = self.q_matrix.q_matrix[self.state].q_matrix_row\n best_action = row.index(max(row))\n print(a, \" best action: \", best_action)\n\n # add action to final list of actions\n self.final_action_seq.append(self.action_table[best_action])\n \n # publish chosen action\n robot_action = RobotMoveDBToBlock(robot_db = self.dumbells[best_action[0]], block_id = best_action[1])\n self.robot_move_pub.publish(robot_action)\n\n # get next state\n self.state = self.action_matrix[self.state].index(best_action)\n \n print(\"matrix converged\")\n \n def change_subscriptions(self):\n self.robot_action_pub.unregister()\n self.robot_move_pub = rospy.Publisher(\"/q_learning/robot_move\", RobotMoveDBToBlock, queue_size=10)\n\n def run(self):\n rospy.spin()\n\n\nif __name__ == \"__main__\":\n node = QLearning()\n node.run()","sub_path":"scripts/q_learning.py","file_name":"q_learning.py","file_ext":"py","file_size_in_byte":7726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"483581653","text":"import sys\nfrom . import player\nfrom . import schedule\nfrom . import auction_draft\nfrom .parsers import personal_notes\nfrom .parsers import numberfire_projections\nfrom .parsers import espn_rankings\nfrom .parsers import auction_history\nfrom .parsers import points_against\nfrom .parsers import espn_teams\n\n_RAW_DATA_DIR = './data-raw/'\n_PROCESSED_DIR = './data-processed/'\n\n\ndef initData():\n print('Initializing data')\n\n # print 'process league notes - who owns each player?'\n players = personal_notes.parse(_RAW_DATA_DIR + 'notes.csv')\n\n # print 'processing projections - how much is everyone worth?'\n numberfire_projections.parse(\n players,\n _RAW_DATA_DIR + 'numberfire.projections.2017.aug.01.md',\n _PROCESSED_DIR + 'numbefire.projections.csv')\n with open(_PROCESSED_DIR + 'numbefire.projections.csv', 'r') as input:\n for line in input:\n items = line[:-1].split(';')\n players[items[0]].projection = float(items[1])\n player.setProjectionBasedRankings(players)\n\n # print 'processing espn rankings'\n espn_rankings.parse(\n players,\n _RAW_DATA_DIR + 'espn.rankings.2017.aug.01.md',\n _PROCESSED_DIR + 'espn.rankings.csv')\n with open(_PROCESSED_DIR + 'espn.rankings.csv', 'r') as input:\n posRanks = {'QB': 1, 'RB': 1, 'WR': 1, 'TE': 1, 'D/ST': 1, 'K': 1}\n for line in input:\n items = line[:-1].split(';')\n rank = int(items[0]) + 1\n name = items[1]\n\n players[name].overallRank = rank\n players[name].posRank = posRanks[players[name].pos]\n posRanks[players[name].pos] += 1\n\n # print 'processing historical auction prices'\n auctionFiles = [_RAW_DATA_DIR + x for x in [\n 'draft.2013.raw.txt',\n 'draft.2014.raw.txt',\n 'draft.2015.raw.txt',\n 'draft.2016.raw.txt',\n 'draft.2017.raw.txt']]\n prices = auction_history.parse(auctionFiles)\n\n for _, p in players.items():\n pos = p.pos\n if p.posRank < len(prices[pos]):\n p.cost = prices[pos][p.posRank - 1]\n\n # If we didn't give a projected value in the notes,\n # use the projection to estimate a value\n if p.value == -1:\n p.value = max(1, prices[pos][p.posRankByProj - 1])\n\n return players\n\n\ndef main():\n if len(sys.argv) < 2:\n print('Not enough args. Valid options:')\n print(' python process.py draft')\n sys.exit(2)\n\n players = initData()\n\n if sys.argv[1] == 'draft':\n auction_draft.run(players)\n\n elif sys.argv[1] == 'schedule':\n points_against.parse(2017, _PROCESSED_DIR)\n schedule.run(sys.argv[2:])\n\n elif sys.argv[1] == 'trade':\n espn_teams.parse(_PROCESSED_DIR)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"FantasyFootball/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"355781350","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 17 11:28:08 2022\r\n\r\n@author: Marc\r\n\"\"\"\r\n\r\n\r\ndef function_features_extration(sac_conc): \r\n sac_k = sac_conc.copy()\r\n import numpy.matlib\r\n import os\r\n import numpy as np\r\n from obspy import read, read_inventory\r\n import math\r\n import time\r\n import matplotlib.pyplot as plt\r\n import scipy as sp\r\n import pandas as pd\r\n from obspy.signal.trigger import classic_sta_lta,trigger_onset\r\n import sys\r\n from Funciones import utils_magnitude\r\n \r\n ##Los siguientes parametros no deberian modificarse, ya que fueron los con que se entreno la red\r\n \r\n nro_canales = 3 #Number of channel to use, 1 or 3, if is set to 1, it will take the Z channel.\r\n umbral_corte = 0.03 # Threshold, based on the decay of the signal #0.1 is 10% # if is setted in 1 preserves the entire trace\r\n frame_length = 4 #size in seconds of the frame length\r\n frame_shift = 2 #frame shift\r\n Energy = 'E3' # There are different types of energy used \r\n Vel = True #True: the traces are converted to velocity, False the traces are kept in count\r\n escala_features_fft = 'logaritmica' # 'lineal' o 'logaritmica' \r\n escala_features_energia = 'logaritmica'\r\n escala_signal = 1e+10 #Scale to amplify the signal, especially useful when the signal is in velocity\r\n version = 'original' #'original', 'fourier_completa' o 'raw'\r\n\r\n id_estacion = {'PB09':1,'PB06':2,'AC02':3,'CO02':4,'PB14':5,'CO01':6,'GO01':7,'GO03':8, 'MT16':9, 'PB18':10,\r\n 'CO10':11}\r\n features_canales_temporal,features_canales_global = [], [] \r\n feat_por_evento_temporal, feat_por_evento_global = [], []\r\n for ch in range(len(sac_k)):\r\n sac_k[ch].data = sac_k[ch].data*escala_signal\r\n estoy_en_Z = 0\r\n \r\n sta = sac_k[ch].stats.channel\r\n \r\n \r\n fs = int(sac_k[ch].stats.sampling_rate)\r\n fs_real = int(sac_k[ch].stats.sampling_rate)\r\n if fs ==100:\r\n sac_k[ch].data = sp.signal.resample(sac_k[ch].data,int(len(sac_k[ch].data)*40/100))\r\n sac_k[ch].stats.sampling_rate = 40\r\n sac_k[ch] = sac_k[ch].slice(sac_k[ch].stats.starttime+1, sac_k[ch].stats.endtime-1)\r\n fs = 40\r\n elif fs==40:\r\n sac_k[ch] = sac_k[ch].slice(sac_k[ch].stats.starttime+1, sac_k[ch].stats.endtime-1)\r\n elif fs!=40:\r\n print('Hay sampling rate distinto a 40, revisar!!')\r\n \r\n frame_len = frame_length*fs\r\n frame_shi = frame_shift*fs \r\n nfft = pow(2,math.ceil(np.log2(frame_len)))\r\n \r\n if Vel == True: # Signal are converted to velocity\r\n \r\n sta = sac_k[ch].stats.station\r\n cha = sac_k[ch].stats.channel\r\n\r\n inv = read_inventory('nuevos_xml/'+sta+'.xml')\r\n sac_k[ch].remove_response(inventory=inv, output=\"VEL\")\r\n \r\n data_k = utils_magnitude.butter_highpass_lfilter(sac_k[ch].data, cutoff=1, fs=fs, order=3) \r\n \r\n \r\n if sac_k[ch].stats.channel[-1]=='Z':\r\n \r\n \r\n \r\n if Energy == 'E1':\r\n Energia_Z_ref = utils_magnitude.E1(data_k, frame_len, frame_shi, nfft,escala = 'lineal')\r\n elif Energy == 'E2':\r\n Energia_Z_ref = utils_magnitude.E2(data_k, frame_len, frame_shi,escala = 'lineal')\r\n elif Energy == 'E3':\r\n Energia_Z_ref = utils_magnitude.E3(data_k, frame_len,frame_shi,escala = 'lineal')\r\n \r\n \r\n arg_amp_maxima = np.argmax(Energia_Z_ref) #Assumption: The maximun energy is in S-wave\r\n arg_amp_minima = np.argmin(Energia_Z_ref[:arg_amp_maxima]) # take the minimum energy between the start of the signal and the S-wave\r\n delta_energia = Energia_Z_ref[arg_amp_maxima]-Energia_Z_ref[arg_amp_minima] \r\n energia_umbral_corte = delta_energia*umbral_corte+Energia_Z_ref[arg_amp_minima] #energy threshold\r\n \r\n arg_fin_nueva_coda = arg_amp_maxima + np.argmin(np.abs(Energia_Z_ref[arg_amp_maxima:]-energia_umbral_corte)) \r\n muestra_corte_coda = int(fs*frame_len*arg_fin_nueva_coda/frame_shi) \r\n data_k_or = data_k\r\n \r\n data_k = data_k[:muestra_corte_coda] #The signal is cut \r\n \r\n feat_k = utils_magnitude.parametrizador(data_k, frame_len, frame_shi,nfft, escala = escala_features_fft)\r\n \r\n #The signal is windowed\r\n feat_t = utils_magnitude.get_frames(data_k,frame_len, frame_shi) \r\n #FFT\r\n feat_fourier_completa = np.fft.fft(feat_t, nfft, axis=1) \r\n #Real and imaginary part are concatenated\r\n feat_fourier_completa = np.hstack((feat_fourier_completa.real[:,:feat_fourier_completa.shape[1]//2 +1],\r\n feat_fourier_completa.imag[:,:feat_fourier_completa.shape[1]//2 +1])) \r\n feat_fourier_completa = np.delete(feat_fourier_completa,[129,257],1)\r\n #Energy\r\n if Energy == 'E1':\r\n feat_Energy = utils_magnitude.E1(data_k, frame_len, frame_shi, nfft,escala = escala_features_energia)\r\n feat_k = np.hstack((feat_k, np.array([feat_Energy]).T ))\r\n elif Energy == 'E2':\r\n feat_Energy = utils_magnitude.E2(data_k, frame_len, frame_shi,escala = escala_features_energia)\r\n feat_k = np.hstack((feat_k, np.array([feat_Energy]).T ))\r\n elif Energy == 'E3':\r\n feat_Energy = utils_magnitude.E3(data_k, frame_len,frame_shi,escala = escala_features_energia)\r\n feat_k = np.hstack((feat_k, np.array([feat_Energy]).T)) \r\n \r\n \r\n if version == 'original':\r\n features_canales_temporal.append(feat_k)\r\n elif version == 'fourier_completa':\r\n features_canales_temporal.append(feat_fourier_completa)\r\n elif version == 'raw':\r\n features_canales_temporal.append(feat_t)\r\n \r\n feat_canales_temporal = np.hstack(features_canales_temporal) \r\n \r\n if sac_k[ch].stats.channel[-1]=='Z':\r\n ##Global features selection\r\n #feat_distancia_evento = [lat,lon,depth,dist]\r\n #features_canales_global.append(np.hstack(([Coordenadas_estaciones[estaciones[i]], id_estacion[estaciones[i]],time_sp, features_distancia_evento])))\r\n features_canales_global.append(np.hstack(([id_estacion[sta]])))\r\n \r\n feat_canales_global = np.hstack(features_canales_global)\r\n\r\n\r\n\r\n feat_por_evento_temporal.append(feat_canales_temporal)\r\n \r\n #print('Shape temporal features: {:d}x{:d}'.format(feat_canales_temporal.shape[0],feat_canales_temporal.shape[1])) \r\n #print('Shape global features: {:d}'.format(feat_canales_global.shape[0])) \r\n\r\n if True:\r\n feat_out = os.path.join('Features/').replace('\\\\', '/')\r\n #print('The features were saved')\r\n np.save(feat_out+'feat_temporal_test_integracion_magnitude.npy', np.array( feat_canales_temporal))\r\n np.save(feat_out+'feat_global_test_integracion_magnitude.npy', feat_canales_global) \r\n \r\n \r\ndef DNN_magnitude():\r\n import matplotlib.pyplot as plt\r\n from keras.models import Model, load_model\r\n from keras.layers import Dense, LSTM, Bidirectional,Concatenate,Input,concatenate\r\n import numpy as np\r\n from keras.utils import Sequence\r\n import time\r\n from tensorflow.python.keras import backend as K\r\n import tensorflow as tf\r\n from keras.callbacks import EarlyStopping\r\n import os\r\n from keras.optimizers import Adam\r\n import json\r\n from Funciones import utils_magnitude \r\n \r\n tipo_de_escalamiento = 'MinMax' #'Standard', 'MinMax', 'MVN', 'None' #Normalization, must be the same than in training\r\n #Path to features and labels\r\n path_root = os.getcwd()\r\n path_feat = \"Features/\"\r\n path_feat_in_test_temporal = path_feat + 'feat_temporal_test_integracion_magnitude.npy'\r\n path_feat_in_test_global = path_feat + 'feat_global_test_integracion_magnitude.npy'\r\n \r\n #Path where the model was saved\r\n path_model = 'DNN_magnitude.h5'\r\n path_normalization = 'normalization_parameters_magnitude.json'\r\n class MyBatchGenerator(Sequence):\r\n 'Generates data for Keras'\r\n def __init__(self, X, x, y, batch_size=1, shuffle=False):\r\n 'Initialization'\r\n self.X = X\r\n self.x = x\r\n self.y = y\r\n self.batch_size = batch_size\r\n self.shuffle = shuffle\r\n self.on_epoch_end()\r\n \r\n def __len__(self):\r\n 'Denotes the number of batches per epoch'\r\n return int(np.floor(len(self.y)/self.batch_size))\r\n \r\n def __getitem__(self, index):\r\n return self.__data_generation(index)\r\n \r\n def on_epoch_end(self):\r\n 'Shuffles indexes after each epoch'\r\n self.indexes = np.arange(len(self.y))\r\n if self.shuffle == True:\r\n np.random.shuffle(self.indexes)\r\n \r\n def __data_generation(self, index):\r\n Xb = np.empty((self.batch_size, *self.X[index].shape))\r\n xb = np.empty((self.batch_size, *self.x[index].shape))\r\n yb = np.empty((self.batch_size, *self.y[index].shape))\r\n # naively use the same sample over and over again\r\n for s in range(0, self.batch_size):\r\n Xb[s] = self.X[index]\r\n xb[s] = self.x[index]\r\n yb[s] = self.y[index]\r\n \r\n return [Xb, xb], yb\r\n \r\n \r\n \r\n \r\n \r\n feat_in_test_temporal = np.load(path_feat_in_test_temporal, allow_pickle=True)\r\n feat_in_test_global = np.load(path_feat_in_test_global, allow_pickle=True)\r\n \r\n #mag_real_test = np.load(path_mag_real_test)\r\n #id_test = mag_real_test[:,0]\r\n #mag_real_test = np.array([mag_real_test[i,1] for i in range(len(mag_real_test))],dtype=float)\r\n \r\n \r\n dictParameters = open(path_normalization, \"r\", encoding='utf-8')\r\n dictParameters = json.load(dictParameters)\r\n \r\n \r\n # =============================================================================\r\n # Se Normaliza los features: 'MVN' normaliza los features de acuerdo a los features del evento en cuestion\r\n #'Standard' y 'MinMax' normaliza los features de acuerdo a promedios y desv estandar de features de acuerdo a la base de entrenamiento\r\n # =============================================================================\r\n if tipo_de_escalamiento == 'Standard': #The features are normalized using Z-Score over all the data base\r\n print('Se normalizan los features utilizando', tipo_de_escalamiento)\r\n mean_over_feat_train_temporal = np.array(dictParameters['mean_temporal'])\r\n std_over_feat_train_temporal = np.array(dictParameters['std_temporal'])\r\n mean_over_feat_train_global = np.array(dictParameters['mean_global'])\r\n std_over_feat_train_global = np.array(dictParameters['std_global'])\r\n \r\n feat_norm_test_temporal = np.array([ (feat_in_test_temporal[i]-mean_over_feat_train_temporal)/std_over_feat_train_temporal \r\n for i in range(len(feat_in_test_temporal))],dtype=object)\r\n \r\n feat_norm_test_global = np.array([ (feat_in_test_global[i]-mean_over_feat_train_global)/std_over_feat_train_global \r\n for i in range(len(feat_in_test_global))],dtype=object)\r\n \r\n \r\n \r\n elif tipo_de_escalamiento == 'MinMax': #Features are translated into a range between 0 and 1\r\n #print('Se normalizan los features utilizando', tipo_de_escalamiento)\r\n \r\n min_f_train_temporal = np.array(dictParameters['min_temporal'])\r\n max_f_train_temporal = np.array(dictParameters['max_temporal'])\r\n min_f_train_global = np.array(dictParameters['min_global'])\r\n max_f_train_global = np.array(dictParameters['max_global'])\r\n \r\n \r\n feat_norm_test_temporal = np.array([(feat_in_test_temporal[i]-min_f_train_temporal)/(max_f_train_temporal-min_f_train_temporal)\r\n for i in range(len(feat_in_test_temporal))],dtype=object)\r\n \r\n feat_norm_test_global = np.array([(feat_in_test_global[i]-min_f_train_global)/(max_f_train_global-min_f_train_global)\r\n for i in range(len(feat_in_test_global))],dtype=object)\r\n \r\n elif tipo_de_escalamiento == 'MVN':\r\n print('Se normalizan los features utilizando', tipo_de_escalamiento)\r\n feat_norm_test_temporal = np.array([utils_magnitude.cmvn(feat_in_test_temporal[i]) for i in range(len(feat_in_test_temporal))],dtype=object)\r\n \r\n feat_norm_test_global = feat_in_test_global\r\n \r\n \r\n elif tipo_de_escalamiento == 'None':\r\n print('No se normalizan los features')\r\n feat_norm_test_temporal = np.array([feat_in_test_temporal[i] for i in range(len(feat_in_test_temporal))],dtype=object)\r\n feat_norm_test_global = np.array([feat_in_test_global[i] for i in range(len(feat_in_test_global))],dtype=object)\r\n \r\n \r\n\r\n X_test_temporal, y_test = feat_norm_test_temporal, np.zeros(len(feat_norm_test_temporal))\r\n X_test_global = feat_norm_test_global\r\n x_test = MyBatchGenerator( [X_test_temporal],X_test_global, np.zeros(1), batch_size=1, shuffle=False)\r\n model = load_model(path_model)\r\n y_estimada_test = np.hstack(model.predict(x_test,verbose=0))\r\n \r\n \r\n \r\n return np.round(y_estimada_test[0],2) \r\n \r\ndef magnitude_estimation(sac_conc):\r\n \r\n function_features_extration(sac_conc)\r\n \r\n magnitude = DNN_magnitude()\r\n #print('Magnitud estimada de: ', magnitude)\r\n \r\n return magnitude","sub_path":"test_magnitude_estimation.py","file_name":"test_magnitude_estimation.py","file_ext":"py","file_size_in_byte":13790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"114166108","text":"# 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。\n#\n# 示例:\n#\n# 输入: n = 4, k = 2\n# 输出:\n# [\n# [2,4],\n# [3,4],\n# [2,3],\n# [1,2],\n# [1,3],\n# [1,4],\n# ]\nclass Solution:\n\tdef combine(self, n, k):\n\t\t\"\"\"\n\t\t:type n: int\n\t\t:type k: int\n\t\t:rtype: List[List[int]]\n\t\t\"\"\"\n\t\tself.res = []\n\t\tself.n = n\n\t\tself.k = k\n\t\t#第一阶段的所有决策, 参数:组合,当前列,上一个列的选择\n\t\tself.recurs([],1,0)\n\t\treturn self.res\n\tdef recurs(self,nums,cur,pre):\n\t\tif cur == self.k+1:\n\t\t\tself.res.append(nums.copy())\n\t\t\treturn\n\n\t\t#决策: 比如上一列的选择是1那么这个列的选择就是2,3,4..., 如果上一列的选择是2那么这列就是3,4,5...\n\t\tfor i in range(pre+1,self.n+1):\n\t\t\tnums.append(i)\n\t\t\tself.recurs(nums,cur+1,i)\n\t\t\tnums.pop()\n\t\treturn self.res","sub_path":"递归/回溯/combinations.py","file_name":"combinations.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"434679395","text":"\"\"\"\r\n\n\nCreate a function that subtracts one positive integer from another, without\nusing any arithmetic operators such as `-`, `%`, `/`, `+`, etc.\n\n### Examples\n\n my_sub(5, 9) ➞ 4\n \n my_sub(10, 30) ➞ 20\n \n my_sub(0, 0) ➞ 0\n\n### Notes\n\n * Do not multiply by `-1`.\n * Use bitwise operations only: `<<`, `|`, `~`, `&`, etc.\n\n\"\"\"\r\n\ndef my_sub(y, x):\n while y != 0:\n borrow = (~x) & y \n x = x ^ y \n y = borrow << 1\n return x\n\n","sub_path":"7eQNpraoWR3JxZMKB_24.py","file_name":"7eQNpraoWR3JxZMKB_24.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"139157183","text":"\ndef get_key(my_dict,val):\n for key, value in my_dict.items(): \n if val == value: \n return key \n \n return None\n\n\nfile = open(\"alice29.txt\",\"r\")\ncontent = file.readlines()\nprint(content)\nd = {}\nmask = 1\nresult = []\nbro = []\nfor line in content:\n\tbro = []\n\tl_cont = line.split()\n\tfor word in l_cont:\n\t\tif d.get(word):\n\t\t\tbro.append(str(d.get(word)))\n\t\telse:\n\t\t\td[word] = str(mask)\n\t\t\tbro.append(str(mask))\n\t\t\tmask+=1\n\tresult.append(bro)\nprint(result)\ndecomp = []\nres2=[]\nfor x in result:\n\tdecomp = []\n\tfor y in x:\n\t\tactual = get_key(d,y)\n\t\tdecomp.append(actual)\n\tres2.append(decomp)\nout = open(\"compressed.txt\",\"w+\")\ndic = open(\"dict.txt\",\"w+\")\ndic_line = []\nfor i,j in d.items():\n\tdic_line.append(str(i)+\":\"+j)\ndic.write(\" \".join(dic_line))\ndic.write(\"\\n\")\nfor line in result:\n\tl = \" \".join(line)\n\tout.write(l)\n\tout.write(\"\\n\")\nout.close()\nfile.close()\n\n\n\n","sub_path":"comp.py","file_name":"comp.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"110480827","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\ndf = pd.read_excel('雷达图.xlsx') \ndf = df.set_index('性能评价指标') \ndf = df.T \ndf.index.name = '品牌' \ndef plot_radar(data, feature): \n plt.rcParams['font.sans-serif'] = ['SimHei'] \n plt.rcParams['axes.unicode_minus'] = False \n cols = ['动力性', '燃油经济性', '制动性', '操控稳定性', '行驶平顺性', '通过性', '安全性', '环保性'] \n colors = ['green', 'blue', 'red', 'yellow'] \n angles = np.linspace(0.1 * np.pi, 2.1 * np.pi, len(cols), endpoint = False) \n angles = np.concatenate((angles, [angles[0]])) \n fig = plt.figure(figsize = (8, 8)) \n ax = fig.add_subplot(111, polar = True)\n for i, c in enumerate(feature): \n stats = data.loc[c] \n stats = np.concatenate((stats, [stats[0]])) \n ax.plot(angles, stats, '-', linewidth = 6, c = colors[i], label = '%s'%(c)) \n ax.fill(angles, stats, color = colors[i], alpha = 0.25) \n ax.legend() \n ax.set_yticklabels([]) \n ax.set_thetagrids(angles * 180 / np.pi, cols, fontsize = 16)\n plt.show()\n return fig\nfig = plot_radar(df, ['A品牌'])\n","sub_path":"ch2-办公-表格Excel/python-let-excel-fly-202007/08/案例05 制作雷达图对比多项指标/制作某一品牌性能评价指标雷达图.py","file_name":"制作某一品牌性能评价指标雷达图.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"561050109","text":"#!/usr/bin/env python3\n\nimport glob\nimport argparse\nimport gzip\nimport json\nimport lzma\nimport os\nimport random\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport traceback\nimport urllib.parse\nfrom collections import defaultdict\nfrom multiprocessing import Pool\nfrom pathlib import Path\n\nimport requests\nfrom tqdm import tqdm\n\nimport tldextract\n\nsys.path.append(\"{0}/..\".format(os.path.dirname(os.path.realpath(__file__))))\nscriptDir = os.path.dirname(os.path.realpath(sys.argv[0]))\n\nfrom utils.common import open_gzip_or_plain\n\nrandom.seed(31415926535)\n\nstep_descr = {1: [\"Prepare the working directory\", 'working_dir'],\n 2: [\"Produce a list of domains from a langstat file\", 'lang1', 'lang2', 'langstat_path', 'langstat_threshold'],\n 3: [\"Split domains for N machines\", 'domain_splits'],\n 4: [\"Crawl domains using HTTrack\", 'split_process', 'httrack_dir', 'crawl_time', 'threads'],\n 5: [\"Produce LETT files from the downloaded data\", 'split_process', 'lang1', 'lang2', 'threads'],\n 6: [\"Merge LETT files with the same domain\", 'split_process'],\n 7: [\"**DELETED** Upload lett files to Azure blob storage\"],\n 8: [\"**DELETED** Download lett files from Azure blob storage\"],\n 9: [\"Extract LETT files\", 'sentence_splitter', 'lang1', 'lang2', 'threads'],\n 10: [\"Deduplicate foreign text\", 'lang2', 'threads'],\n 11: [\"Bulk translate foreign text to English\", 'translation_script_path', 'lang2'],\n 12: [\"Apply translations to foreign text\", 'lang2'],\n 13: [\"Document alignment\", 'lang1', 'lang2', 'document_threshold', 'moses_dir'],\n 14: [\"Sentence alignment\", 'lang1', 'lang2', 'document_threshold', 'bleu_threshold']\n }\n\n\ndef output_step_descr():\n ret = \"Steps: \"\n\n for key, value in step_descr.items():\n ret += \"(\" + str(key) + \") \" + value[0] + \" \"\n\n return ret\n\ndef print_step(num):\n print(\">>> Step\", num, step_descr[num][0], \"<<<\")\n\n\ndef check_required_variables(args, steps):\n\n def check_arg_vars(vs):\n for v in vs:\n assert(vars(args)[v])\n\n progress = 0\n\n try:\n for s in steps:\n progress = s\n check_arg_vars(step_descr[s][1:])\n\n except AssertionError:\n expected_vars_with_dashes = [\n \"--\" + n.replace('_', '-') for n in sorted(step_descr[progress][1:])]\n sys.stderr.write(\"Some arguments for step {0} are missing!\\nExpected arguments: {1}\\n\".format(\n progress, str(expected_vars_with_dashes)))\n sys.exit(1)\n\ndef systemCheck(cmd):\n sys.stderr.write(\"Executing:\" + cmd + \"\\n\")\n sys.stderr.flush()\n\n subprocess.check_call(cmd, shell=True)\n\n\ndef prepare(dirpath):\n #p = Path(dirpath)\n #if not p.exists():\n # p.mkdir()\n #elif len(list(p.glob('./*'))) > 0:\n # raise Exception(\"The working directory is not empty!\")\n systemCheck(\"mkdir -p \" + dirpath)\n\n\ndef load_domains(file_path):\n domains = set()\n with file_path.open(\"r\") as f:\n for line in f:\n line = line.strip()\n if len(line):\n domains.add(line)\n\n return domains\n\n\ndef find_domains_in_langstat(lang1, lang2, langstat_path, threshold, exclude_path):\n l12 = [lang1.lower(), lang2.lower()]\n domains = defaultdict(dict)\n\n excluded_set = set()\n if exclude_path:\n excluded_set = load_domains(Path(exclude_path))\n\n sys.stderr.write(\n \"Gathering domain information for {0} and {1}...\\n\".format(*l12))\n with tqdm(total=None) as pbar:\n with open_gzip_or_plain(langstat_path) as f:\n for line in f:\n split_line = line.strip().split()\n if len(split_line) != 3:\n continue\n\n domain, lang, byte_len = split_line\n if lang.lower() in l12:\n domains[domain][lang.lower()] = byte_len\n\n pbar.update(1)\n\n domains_to_crawl = set()\n for k, v in domains.items():\n if tldextract.extract(k).domain in excluded_set:\n continue\n\n if len(v) == 2:\n lang1_bytes = int(v[l12[0]])\n lang2_bytes = int(v[l12[1]])\n if lang1_bytes >= int(threshold) and lang2_bytes >= int(threshold):\n domains_to_crawl.add(k)\n\n sys.stderr.write(\n \"{0} domains found.\\nDone.\\n\".format(len(domains_to_crawl)))\n return domains_to_crawl\n\n\ndef output_domains(domain_path, domains):\n with domain_path.open(\"w\") as f:\n for d in domains:\n f.write(\"{0}\\n\".format(d))\n\n\ndef output_binned_domains(binned_domains_dir, binned_domains):\n for idx, domains in enumerate(binned_domains):\n with binned_domains_dir.joinpath(\"domains.{0}\".format(idx)).open(\"w\") as f:\n for d in domains:\n f.write(\"{0}\\n\".format(d))\n\n\ndef bin_domains(domains_path, n_splits):\n # load domains\n domain_map = defaultdict(list)\n with domains_path.open(\"r\") as f:\n for line in f:\n full_domain = line.strip()\n domain = tldextract.extract(full_domain).domain\n domain_map[domain].append(full_domain)\n\n # create bins\n bins = [[] for n in range(n_splits)]\n\n # sort domains in a stable way\n sorted_domains = sorted([(len(x), x)\n for x in domain_map.values()], reverse=True)\n\n # fill the bins\n for domain in sorted_domains:\n # find the smallest bin\n smallest_bin = min([(len(bins[n]), n) for n in range(len(bins))])\n\n # add to the smallest bin\n bins[smallest_bin[1]].extend(domain[1])\n\n # shuffle bins so that we distribute crawling better\n for idx in range(len(bins)):\n random.shuffle(bins[idx])\n\n return bins\n\n\ndef crawl_process(args):\n httrack_dir, url, crawl_time, webdir = args\n cmd = [\n \"{0}/bin/httrack\".format(httrack_dir), \"--skeleton\",\n \"-C0\", \"-Q\", \"-q\", \"-%i0\", \"-I0\", \"-u2\",\n \"-E{0}\".format(crawl_time), \"-O\", webdir, url\n ]\n systemCheck(\" \".join(cmd))\n\n\ndef download_webdomains(httrack_dir, webdir_path, domains, threads, crawl_time):\n webdir_path.parent.mkdir(parents=True, exist_ok=True)\n webdir_path.mkdir(parents=True, exist_ok=True)\n\n domains = list(domains)\n args = [(httrack_dir, d, crawl_time, webdir_path._str) for d in domains]\n\n p = Pool(threads)\n p.map(crawl_process, args)\n\n if webdir_path.joinpath('cookies.txt').exists():\n webdir_path.joinpath('cookies.txt').unlink()\n\n\ndef convert_webdir_to_lett_process(args):\n domain_name, paths, langs = args\n paths['lettdir'].joinpath(domain_name).mkdir(parents=True, exist_ok=True)\n\n cmd_webdir2ett = \"{0} -l {1},{2}\".format(\n str(paths['script_ett2lett']), langs[0], langs[1])\n cmd_ett2lett = \"{0} {1}\".format(str(paths['script_webdir2ett']), str(\n paths['webdir'].joinpath(domain_name)))\n lett_path = paths['lettdir'].joinpath(domain_name).joinpath(\"v2.lett.gz\")\n cmd = \"{0} | {1} | gzip -c > {2}\".format(\n cmd_webdir2ett, cmd_ett2lett, str(lett_path))\n p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)\n p.communicate()\n\n\ndef convert_webdir_to_lett(bitextor_dir, webdir_path, lettdir_path, lang1, lang2, threads, keepBoilerplate):\n lettdir_path.parent.mkdir(parents=True, exist_ok=True)\n lettdir_path.mkdir(parents=True, exist_ok=True)\n\n #print(\"webdir_path\", webdir_path)\n #print(\"lettdir_path\", lettdir_path)\n #print(\"keepBoilerplate\", keepBoilerplate)\n\n cmd = \"ls \" + str(webdir_path) + \" | parallel -v --no-notice -j \" + str(threads)\n\n if keepBoilerplate:\n keepBoilerplateStr = \" -b \"\n else:\n keepBoilerplateStr = \" \"\n\n cmd += \" '\" \\\n + \"mkdir -p \" + str(lettdir_path) + \"/{} && \" \\\n + bitextor_dir + \"/bin/bitextor-webdir2ett \" + keepBoilerplateStr + str(webdir_path) + \"/{} | \" \\\n + bitextor_dir + \"/bin/bitextor-ett2lett -l \" + lang1 + \",\" + lang2 + \" | \" \\\n + \" xz -c > \" + str(lettdir_path) + \"/{}/v2.lett.xz\" \\\n + \"'\"\n\n systemCheck(cmd)\n\n\ndef merge_lett(lettdir_path, lettdirmerged_path):\n lettdirmerged_path.parent.mkdir(parents=True, exist_ok=True)\n lettdirmerged_path.mkdir(parents=True, exist_ok=True)\n\n domain_map = defaultdict(list)\n for f in lettdir_path.glob(\"./*\"):\n domain = tldextract.extract(f.name).domain\n domain_map[domain].append(f.name)\n\n for domain_extract, domains_full in domain_map.items():\n lettdirmerged_domain_path = lettdirmerged_path.joinpath(domain_extract)\n lettdirmerged_domain_path.mkdir(parents=True, exist_ok=True)\n\n with lzma.open(str(lettdirmerged_domain_path.joinpath('v2.lett.xz')), \"wb\") as fw:\n for d in domains_full:\n lett_path = lettdir_path.joinpath(d).joinpath('v2.lett.xz')\n if lett_path.exists():\n with lzma.open(str(lett_path), \"rb\") as fr:\n shutil.copyfileobj(fr, fw)\n\n\ndef extract_lett_process(args):\n lett_dir_path, sentence_splitter, langs = args\n\n extracted_lett_path = Path(os.path.dirname(\n os.path.realpath(__file__))).joinpath(\"../utils/extract_lett.py\")\n\n lett_path = Path(lett_dir_path).joinpath(\"v2.lett.xz\")\n if not lett_path.exists():\n return\n\n cmd = [\n \"python3\", str(extracted_lett_path),\n \"--langs\", langs,\n \"--splitter\", sentence_splitter,\n \"--prune_type\", \"words\",\n \"--prune\", \"80\",\n \"--output_dir\", str(lett_dir_path)\n ]\n\n with lzma.open(str(lett_path), \"rb\") as gf:\n p = subprocess.Popen(cmd, stdin=subprocess.PIPE)\n out, err = p.communicate(gf.read())\n\n\ndef extract_lett(domains_dir_path, sentence_splitter, lang1, lang2, threads):\n\n args = [(d, sentence_splitter, \"{0},{1}\".format(\n lang1, lang2)) for d in domains_dir_path.iterdir()]\n\n p = Pool(threads)\n p.map(extract_lett_process, args)\n\n\ndef dedupe_extracted(working_dir, lett_dir_path, shards, lang2, threads):\n print(\"lett_dir_path\", lett_dir_path)\n print(\"shards\", shards)\n\n deduped_path = working_dir + \"/deduped\"\n p = Path(deduped_path)\n p.mkdir(parents=True, exist_ok=True)\n\n\n # read and deduplicate\n for shard in shards:\n unique_lines = set()\n\n for domain in lett_dir_path.joinpath(shard).iterdir():\n extracted_path = domain.joinpath(\"{0}.extracted.xz\".format(lang2))\n if not extracted_path.exists():\n continue\n\n with lzma.open(str(extracted_path), \"rb\") as rf:\n for line in rf:\n line_split = line.decode(\"utf-8\").strip().split(\"\\t\", 1)\n if len(line_split) != 2:\n continue\n\n unique_lines.add(line_split[1])\n\n # write to dedbuped file\n with lzma.open(deduped_path + \"/extracted.{0}.dedup.{1}.xz\".format(lang2, shard), \"wb\") as wf:\n for line in unique_lines:\n wf.write(\"{0}\\n\".format(line).encode(\"utf-8\"))\n\n\ndef bulkTranslate(working_dir, translation_script, lang2, shard):\n\n deduped_path = working_dir + \"/deduped\"\n\n extracted_dedup_path = deduped_path + \"/extracted.{0}.dedup.{1}.xz\".format(lang2, shard)\n\n with lzma.open(str(extracted_dedup_path), \"rb\") as rf:\n output_path = deduped_path + \"/extracted.{0}.dedup.translated.{1}.xz\".format(lang2, shard)\n cmd = \"{0} | xz -c > {1}\".format(translation_script, output_path)\n p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)\n p.communicate(rf.read())\n\ndef translateExtracts(working_dir, lang2, shard):\n lettDir = working_dir + \"/lettdir_merged/\" + shard\n\n exFile = working_dir + \"/deduped/extracted.\" + lang2 + \".dedup.\" + shard\n transFile = working_dir + \"/deduped/extracted.\" + lang2 + \".dedup.translated.\" + shard\n\n cmd = \"xz -d \" + exFile + \".xz \" + transFile + \".xz\"\n systemCheck(cmd)\n\n cmd = \"paste \" + exFile + \" \" + transFile \\\n + \" | xz -c > \" \\\n + working_dir + \"/deduped/\" + shard + \".\" + lang2 + \".all.dedup.bitext.xz\"\n systemCheck(cmd)\n\n cmd = scriptDir + \"/../utils/translate_table_batch.py --dir \" + lettDir \\\n + \" --lang \" + lang2 \\\n + \" --translations \" + working_dir + \"/deduped/\" + shard + \".\" + lang2 + \".all.dedup.bitext.xz\"\n systemCheck(cmd)\n\n cmd = \"xz \" + exFile + \" \" + transFile\n systemCheck(cmd)\n\n\ndef docAlign(threads, lettDir, lang1, lang2, docThreshold, mosesDir, shard):\n cmd = scriptDir + \"/../parallel/doc_align_parallel.sh \" + str(threads) + \" \" + lettDir + \"/lettdir_merged/\" + shard + \" \" + lang2 \\\n + \" \" + docThreshold + \" 0 translate-script-here-again \" + mosesDir\n systemCheck(cmd)\n\ndef bleuAlign(threads, working_dir, lang1, lang2, docThreshold, bleuThreshold, shard):\n lettDir = working_dir + \"/lettdir_merged/\" + shard\n cmd = scriptDir + \"/../parallel/bleualign-parallel.py --root-path \" + lettDir \\\n + \" --lang1 \" + lang1 + \" --lang2 \" + lang2 \\\n + \" --doc-threshold \" + docThreshold \\\n + \" --bleu-threshold \" + bleuThreshold\n systemCheck(cmd)\n\n bitextPath = Path(working_dir + \"/bitext\")\n bitextPath.mkdir(parents=True, exist_ok=True)\n\n destPath = str(bitextPath) + \"/\" + shard + \".bitext.xz\"\n with lzma.open(destPath, \"wb\") as fw:\n sourcePaths = glob.glob(lettDir + \"/*/aligned.*.xz\")\n for sourcePath in sourcePaths:\n with lzma.open(sourcePath, \"rb\") as fr:\n shutil.copyfileobj(fr, fw)\n\n\n###########################################################################################################################\n\ndef run_steps(args, steps):\n progress = -1\n try:\n # Prepare the working directory\n if 1 in steps:\n progress = 1\n print_step(1)\n prepare(args.working_dir)\n\n # Produce a list of domains from a langstat file\n if 2 in steps:\n progress = 2\n print_step(2)\n\n wd_path = Path(args.working_dir)\n if not wd_path.exists():\n raise Exception(\"The working folder does not exist!\")\n domain_path = wd_path.joinpath(\"domains_to_crawl\")\n\n domains = find_domains_in_langstat(\n args.lang1.lower(),\n args.lang2.lower(),\n args.langstat_path,\n args.langstat_threshold,\n args.excluded_domains)\n\n # output domains to be crawled\n output_domains(domain_path, domains)\n\n # Split domains for N machines\n if 3 in steps:\n progress = 3\n print_step(3)\n\n wd_path = Path(args.working_dir)\n if not wd_path.exists():\n raise Exception(\"The working folder does not exist!\")\n domain_path = wd_path.joinpath(\"domains_to_crawl\")\n\n # get bins\n binned_domains = bin_domains(domain_path, int(args.domain_splits))\n\n # create the bins directory\n binned_domains_dir = wd_path.joinpath(\"domain_bins\")\n if not binned_domains_dir.exists():\n binned_domains_dir.mkdir()\n\n # output to the bins directory\n output_binned_domains(binned_domains_dir, binned_domains)\n\n # Crawl domains using HTTrack\n if 4 in steps:\n progress = 4\n print_step(4)\n\n wd_path = Path(args.working_dir)\n for p in args.split_process.split(\",\"):\n binned_domain_path = wd_path.joinpath(\n \"domain_bins\").joinpath(\"domains.{0}\".format(p))\n domains = load_domains(binned_domain_path)\n download_webdomains(args.httrack_dir, wd_path.joinpath(\"webdir\").joinpath(\n p), domains, int(args.threads), args.crawl_time)\n\n # Produce LETT files from the downloaded data\n if 5 in steps:\n progress = 5\n print_step(5)\n\n wd_path = Path(args.working_dir)\n for p in args.split_process.split(\",\"):\n convert_webdir_to_lett(\n args.bitextor_dir,\n wd_path.joinpath(\"webdir\").joinpath(p),\n wd_path.joinpath(\"lettdir\").joinpath(p),\n args.lang1,\n args.lang2,\n int(args.threads),\n args.keep_boilerplate\n )\n\n # Merge LETT files with the same domain\n # This needs to be optimised! Currently wastes a lot of space\n # by essentially making a copy of all LETT files.\n if 6 in steps:\n progress = 6\n print_step(6)\n\n wd_path = Path(args.working_dir)\n for p in args.split_process.split(\",\"):\n merge_lett(\n wd_path.joinpath(\"lettdir\").joinpath(p),\n wd_path.joinpath(\"lettdir_merged\").joinpath(p)\n )\n\n # Upload lett files to Azure blob storage\n if 7 in steps:\n progress = 7\n print_step(7)\n\n #lettmerged_dir_path = Path(\n # args.working_dir).joinpath(\"lettdir_merged\")\n #run_cmd([\n # \"az\", \"storage\", \"blob\", \"upload-batch\",\n # \"--account-key\", args.az_account_key,\n # \"--account-name\", args.az_account_name,\n # \"-s\", str(lettmerged_dir_path),\n # \"-d\", args.blob_container\n #])\n\n # Download lett files from Azure blob storage\n if 8 in steps:\n progress = 8\n print_step(8)\n\n #lett_dir_path = Path(args.working_dir).joinpath(\"lettdir_blob\")\n #lett_dir_path.mkdir(parents=True, exist_ok=True)\n\n #for p in args.split_process.split(\",\"):\n # run_cmd([\n # \"az\", \"storage\", \"blob\", \"download-batch\",\n # \"--account-key\", args.az_account_key,\n # \"--account-name\", args.az_account_name,\n # \"--source\", args.blob_container,\n # \"--destination\", str(lett_dir_path),\n # \"--pattern {0}/*\".format(p)\n # ])\n\n # Extract LETT files\n if 9 in steps:\n progress = 9\n print_step(9)\n\n lett_dir_path = Path(args.working_dir).joinpath(\"lettdir_merged\")\n\n for p in args.split_process.split(\",\"):\n extract_lett(\n lett_dir_path.joinpath(p),\n args.sentence_splitter,\n args.lang1,\n args.lang2,\n int(args.threads)\n )\n\n # Deduplicate foreign language\n if 10 in steps:\n progress = 10\n print_step(10)\n\n lett_dir_path = Path(args.working_dir).joinpath(\"lettdir_merged\")\n\n dedupe_extracted(\n args.working_dir,\n lett_dir_path,\n args.split_process.split(\",\"),\n args.lang2,\n int(args.threads)\n )\n\n # Send to another server to translate everything\n if 11 in steps:\n progress = 11\n print_step(11)\n\n for p in args.split_process.split(\",\"):\n bulkTranslate(args.working_dir, args.translation_script_path, args.lang2, p)\n\n # match translations to extracted sentences\n if 12 in steps:\n progress = 12\n print_step(12)\n \n for p in args.split_process.split(\",\"):\n translateExtracts(args.working_dir,\n args.lang2.lower(),\n p)\n\n # match translations to extracted sentences\n if 13 in steps:\n progress = 13\n print_step(13)\n \n for p in args.split_process.split(\",\"):\n docAlign(args.threads,\n args.working_dir,\n args.lang1.lower(),\n args.lang2.lower(),\n args.document_threshold,\n args.moses_dir,\n p)\n\n if 14 in steps:\n progress = 14\n print_step(14)\n \n for p in args.split_process.split(\",\"):\n bleuAlign(args.threads,\n args.working_dir,\n args.lang1.lower(),\n args.lang2.lower(),\n args.document_threshold,\n args.bleu_threshold,\n p)\n\n progress = 0\n\n except Exception as err:\n traceback.print_exc(file=sys.stderr)\n print(\"ERROR: {0}\".format(err))\n\n finally:\n return progress\n\n###########################################################################################################################\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description='Parse web domains containing specific languages and locate sources of frequent domains.'\n + output_step_descr())\n parser.add_argument('--threads', dest='threads', default=12,\n help='number of concurrent threads')\n\n parser.add_argument('--langstat-path', dest='langstat_path',\n help='Path to a file containing statistics on language distribution per domain', required=False)\n parser.add_argument('--langstat-threshold', dest='langstat_threshold',\n help='Minimum byte length required to accept a domain', required=False)\n parser.add_argument('--domain-splits', dest='domain_splits', type=int, default=1,\n help='Splits domains into N files. The files are split so that subdomains are in the same file as their domain.', required=False)\n parser.add_argument('--split-process', dest='split_process', default=\"0\",\n help='Choose a comma-separated list of split IDs to process', required=False)\n parser.add_argument('--excluded-domains', dest='excluded_domains', default=None,\n help='List of domains to exclude')\n parser.add_argument('--az-account-key', dest='az_account_key', default=None,\n help='Azure storage account key.')\n parser.add_argument('--az-account-name', dest='az_account_name', default=None,\n help='Azure storage account name.')\n parser.add_argument('--blob-container', dest='blob_container',\n help='Azure BLOB clontainer\\'s name', required=False)\n\n parser.add_argument('--working-dir', dest='working_dir',\n help='Where to store everything', required=True)\n parser.add_argument('--httrack-dir', dest='httrack_dir',\n help='Root path of httrack', required=False)\n parser.add_argument('--moses-dir', dest='moses_dir',\n help='Root directory of Moses code', required=False)\n parser.add_argument('--bitextor-dir', dest='bitextor_dir',\n help='Bitextor installation directory', required=False)\n\n parser.add_argument('--translation-script-path', dest='translation_script_path',\n help=\"Script that takes stdin in lang1 and output to stdout in lang2. Pre- and post-processing to be done by script\")\n parser.add_argument('--sentence-splitter', dest='sentence_splitter',\n help=\"Script that splits text into sentences.\")\n\n parser.add_argument('--lang1', dest='lang1',\n help='First language to parse')\n parser.add_argument('--lang2', dest='lang2',\n help='Second language to parse')\n\n parser.add_argument('--crawl-time', dest='crawl_time',\n help='Maximum time to download each domain (sec)', required=False)\n parser.add_argument('--keep-boilerplate', dest='keep_boilerplate', action='store_true',\n help=\"Don't discard boiler plate data\")\n parser.add_argument('--first-step', dest='first_step', type=int,\n help='', required=True)\n parser.add_argument('--last-step', dest='last_step', type=int,\n help='', required=True)\n parser.add_argument('--document-threshold', dest='document_threshold',\n help='Document threshold')\n parser.add_argument('--bleu-threshold', dest='bleu_threshold',\n help='Sentence-level BLEU threshold')\n\n args = parser.parse_args()\n\n print(\"Starting...\")\n steps = list(range(args.first_step, args.last_step + 1))\n check_required_variables(args, steps)\n ret_code = run_steps(args, steps)\n print(\"\")\n if ret_code == 0:\n print(\"Successfully Finished!\")\n else:\n print(\"Error occured! Interrupted during step: {0}\".format(ret_code))\n","sub_path":"crawl/langstat-2-aligned-corpora.py","file_name":"langstat-2-aligned-corpora.py","file_ext":"py","file_size_in_byte":25006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"384625172","text":"# Copyright 2018 Alex Seymour\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.\nimport datetime\nimport pytz\nfrom tornado.testing import AsyncHTTPTestCase\nfrom bson.objectid import ObjectId\nfrom crontab import CronTab\n\nimport server\nfrom utilities import socket_utils\nfrom utilities import db_utils\nfrom . import common_setup\n\nclass TestCron(AsyncHTTPTestCase):\n def setUp(self):\n super().setUp()\n test_setup = common_setup.SetupTests()\n self.db = test_setup.setup_database()\n self.default_leaderboard_id = test_setup.setup_leaderboard()\n self.default_event_id = test_setup.setup_event(self.default_leaderboard_id)\n self.default_admin_id = test_setup.setup_admin()\n self.admin_cookie = test_setup.login_admin(self)\n timezone = pytz.timezone('Europe/London')\n time_now = timezone.localize(datetime.datetime.now())\n tomorrow = timezone.localize(datetime.datetime.now() + datetime.timedelta(days=1))\n self.now_formatted = datetime.datetime.strftime(time_now, '%Y-%m-%d %H:%M')\n self.tomorrow_formatted = datetime.datetime.strftime(tomorrow, '%Y-%m-%d %H:%M')\n\n def get_app(self):\n socket_manager = socket_utils.SocketManager()\n return server.Application(socket_manager, xsrf_cookies=False)\n\n def test_http_fetch_remote_cron(self):\n \"\"\" Tests that a 403 error is returned if attempting a GET to /remote/cron. \"\"\"\n response = self.fetch(\n '/remote/schedule/update/event/{}/action/start/auth/secret'.format(\n self.default_event_id)\n )\n self.assertEqual(response.code, 403)\n\n def test_http_post_remote_cron_invalid_secret(self):\n \"\"\" Tests that a 403 error is returned if the secret is invalid. \"\"\"\n response = self.fetch(\n '/remote/schedule/update/event/{}/action/start/auth/invalid'.format(\n self.default_event_id),\n method='POST',\n body=''\n )\n self.assertEqual(response.code, 403)\n\n def test_http_post_remote_cron_valid_secret_start(self):\n \"\"\" Tests that an event is started correctly with a valid call to the remote endpoint. \"\"\"\n response = self.fetch(\n '/remote/schedule/update/event/{}/action/start/auth/secret'.format(\n self.default_event_id),\n method='POST',\n body=''\n )\n event = self.db.events.find_one({'_id': ObjectId(self.default_event_id)})\n self.assertEqual(response.code, 200)\n self.assertTrue(event['active'])\n self.assertFalse(event['locked'])\n\n def test_http_post_remote_cron_valid_secret_stop(self):\n \"\"\" Tests that an event is stopped correctly with a valid call to the remote endpoint. \"\"\"\n self.db.events.update_one({\n '_id': ObjectId(self.default_event_id)\n }, {\n '$set': {\n 'active': True,\n 'locked': False\n }\n })\n response = self.fetch(\n '/remote/schedule/update/event/{}/action/stop/auth/secret'.format(\n self.default_event_id),\n method='POST',\n body=''\n )\n event = self.db.events.find_one({'_id': ObjectId(self.default_event_id)})\n self.assertEqual(response.code, 200)\n self.assertFalse(event['active'])\n self.assertFalse(event['locked'])\n\n def test_http_post_remote_cron_valid_secret_error(self):\n \"\"\" Tests that a 500 eror code is returned upon database error. \"\"\"\n self.db.events.delete_one({'_id': ObjectId(self.default_event_id)})\n response = self.fetch(\n '/remote/schedule/update/event/{}/action/start/auth/secret'.format(\n self.default_event_id),\n method='POST',\n body=''\n )\n self.assertEqual(response.code, 500)\n\n def test_http_post_cron_create(self):\n \"\"\" Tests that a CRON entry is created correctly. \"\"\"\n self.fetch(\n '/admin/events',\n method='POST',\n body='event_name=New+Event&event_description=description&event_start={}&event_end={}'\n .format(self.now_formatted, self.tomorrow_formatted),\n headers={\n 'Cookie': 'user={}'.format(self.admin_cookie)\n }\n )\n db_manager = db_utils.DatabaseManager({\n 'database_addr': 'localhost',\n 'database_port': '27017',\n 'database_name': 'BUCSS-CTF-TESTS',\n 'database_user': '',\n 'database_pass': ''\n })\n event_id = self.db.events.find_one({'name': 'New Event'})['_id']\n event = db_manager.retrieve_event(event_id)\n timezone = pytz.timezone('Europe/London')\n cron = CronTab(user=True)\n start_job = list(cron.find_comment('{}_start'.format(str(event['_id']))))[0]\n stop_job = list(cron.find_comment('{}_end'.format(str(event['_id']))))[0]\n start_time = timezone.localize(datetime.datetime(\n datetime.datetime.now().year,\n int(start_job.month.render()),\n int(start_job.day.render()),\n hour=int(start_job.hour.render()),\n minute=int(start_job.minute.render())\n ))\n end_time = timezone.localize(datetime.datetime(\n datetime.datetime.now().year,\n int(stop_job.month.render()),\n int(stop_job.day.render()),\n int(stop_job.hour.render()),\n int(stop_job.minute.render())\n ))\n self.assertEqual(start_time, event['start_time'])\n self.assertEqual(end_time, event['end_time'])\n cron.remove_all(comment='{}_start'.format(str(event['_id'])))\n cron.remove_all(comment='{}_end'.format(str(event['_id'])))\n cron.write()\n\n def test_http_post_cron_create_empty_date(self):\n \"\"\" Tests that a CRON entry is not created for empty dates. \"\"\"\n self.fetch(\n '/admin/events',\n method='POST',\n body='event_name=New+Event&event_description=description&event_start=&event_end=',\n headers={\n 'Cookie': 'user={}'.format(self.admin_cookie)\n }\n )\n event = self.db.events.find_one({'name': 'New Event'})\n cron = CronTab(user=True)\n start_job = list(cron.find_comment('{}_start'.format(str(event['_id']))))\n end_job = list(cron.find_comment('{}_end'.format(str(event['_id']))))\n self.assertEqual(len(start_job), 0)\n self.assertEqual(len(end_job), 0)\n\n def tearDown(self):\n super().tearDown()\n common_setup.SetupTests().cleanup(self)\n","sub_path":"test/cron_tests.py","file_name":"cron_tests.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"546348144","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#---------------------------------\nfrom config import *\nfrom main import *\nfrom flask import Flask, render_template, request, redirect, url_for, g, send_from_directory\nfrom flask.ext.babel import gettext\nfrom config import DEFAULT_TITLE_FILTER\n#---------------------------------\n# 上传文件\nimport os\nfrom flask_wtf import FlaskForm\nfrom flask_wtf.file import FileField, FileRequired\nfrom wtforms import SubmitField, FieldList, IntegerField, StringField , validators\nfrom werkzeug.utils import secure_filename\n\nfrom wtforms.validators import ValidationError \n\nimport time; # 引入time模块\n\nfrom utilities import init_project \nfrom scaffold import genTOC, gen_project\nfrom txt2html import Book, Chapter\n\n#--------------------------------\n# 引入session\nfrom Script_UserSession import sessionQueryFileUpload, sessionSaveFileUpload, sessionDelFileUpload, sessionSaveTOC, sessionQueryTitleFilter, sessionSaveTitleFilter, sessionSaveChapterMaxLength, sessionQueryChapterMaxLength\n#--------------------------------\n# 运行shell\n# import commands\n#--------------------------------\nfrom flask_socketio import SocketIO, emit\nfrom Script_socketio import *\n\nimport shutil\n\nimport re\n\nimport random\n\nimport subprocess\n#=================================\n\ndef readSlogan():\n \n if(not os.path.exists(os.path.join(Txt2mobiPath,'resources','slogan.dat'))):\n return ''\n\n lines = []\n with open(os.path.join(Txt2mobiPath,'resources','slogan.dat')) as f:\n for line in f:\n li=line.strip()\n if (not li.startswith(\"#\")) and len(li) > 0:\n lines.append(li)\n \n if(len(lines) == 0):\n return ''\n else:\n r_l = random.randint(0,len(lines)-1)\n # print('debug : rand ', r_l,len(lines), file=sys.stderr)\n return lines[r_l]\n\n\nclass TransformForm(FlaskForm):\n\n TOClistindex = FieldList( IntegerField())\n confirmTOC = SubmitField('确认目录')\n\n titleFilter = StringField('过滤规则')\n ChapterMaxLength = IntegerField()\n confirmtitleFilter = SubmitField('重新生成目录')\n\n\n def validate_confirmTOC(self, field):\n if(sessionQueryFileUpload() == None):\n raise ValidationError(gettext('错误 : 没有检测到上传文件'))\n\n def validate_titleFilter(self, field):\n if(self.confirmtitleFilter.data):\n if(field.data == None or len(field.data) == 0):\n raise ValidationError(gettext('需要目录过滤规则'))\n \n titleFilter = field.data \n else:\n titleFilter = sessionQueryTitleFilter()\n\n try:\n re.compile(titleFilter)\n except:\n # sessionSaveTitleFilter(titleFilter)\n raise ValidationError(gettext('目录过滤规则有误.'))\n\n\n\n\n@app.route('/ConfirmTransformEbook' , methods = ['GET', 'POST'] )\ndef ConfirmTransformEbook():\n #....\n\n fileDict = sessionQueryFileUpload()\n # print('fileDict:', fileDict)\n\n if (fileDict == None):\n return redirect(\"/TransformEbook\")\n\n\n # 确认转换\n formTran = TransformForm()\n\n try:\n book , TOC = genTOC(sessionQueryTitleFilter(), fileDict['filePath'], fileDict['saveFileName'], sessionQueryChapterMaxLength())\n except:\n return redirect(\"/404/转换失败,请联系网站管理员.\")\n if(book is None):\n return redirect(\"/404/没有检测到上传的书.\")\n\n\n print(\"|----formTran----\", file=sys.stderr)\n if formTran.validate_on_submit():\n\n if(formTran.confirmtitleFilter.data):\n\n titleFilter = formTran.titleFilter.data\n ChapterMaxLength = formTran.ChapterMaxLength.data\n if(ChapterMaxLength == None or ChapterMaxLength <0):\n ChapterMaxLength = 25\n\n # book , TOC = genTOC(titleFilter, fileDict['filePath'], fileDict['saveFileName'])\n sessionSaveTitleFilter(titleFilter)\n sessionSaveChapterMaxLength(ChapterMaxLength)\n\n # book , TOC = genTOC(None, filePath, saveFileName)\n \n if(book is None):\n return redirect(\"/404/没有检测到上传的书.\")\n # 链接目录\n # 创建目录\n # if (not os.path.exists(os.path.join(app.config['UPLOAD_FOLDERTOC'],fileDict['saveFileName']) )):\n # os.makedirs(os.path.join(app.config['UPLOAD_FOLDERTOC'],fileDict['saveFileName'])) \n # 连接\n # 删除之前的链接\n # os.remove(os.path.join(os.path.join(app.config['UPLOAD_FOLDERTOC'],fileDict['saveFileName']),'project-TOC.html'))\n # # os.link(os.path.join(fileDict['filePath'],'project-TOC.html'), \\\n # # os.path.join(os.path.join(app.config['UPLOAD_FOLDERTOC'],fileDict['saveFileName']),'project-TOC.html'))\n # shutil.copy2(os.path.join(fileDict['filePath'],'project-TOC.html'), \\\n # os.path.join(os.path.join(app.config['UPLOAD_FOLDERTOC'],fileDict['saveFileName']),'project-TOC.html'))\n\n return redirect(\"/ConfirmTransformEbook\")\n\n else:\n\n print(\"|----submit----\", file=sys.stderr)\n # print(formTran.confirmTOC.data)\n # if(formTran.confirmTOC.data):\n print(\"|-确认目录\", file=sys.stderr)\n fileDict = sessionQueryFileUpload()\n print('|---------index----------', file=sys.stderr)\n print(formTran.TOClistindex.data, file=sys.stderr)\n\n titleFilter = sessionQueryTitleFilter()\n if(titleFilter == None):\n titleFilter = DEFAULT_TITLE_FILTER\n\n try:\n book , TOC = genTOC(titleFilter, fileDict['filePath'], fileDict['saveFileName'], sessionQueryChapterMaxLength())\n except:\n return redirect(\"/404/转换失败,请联系网站管理员.\")\n if(book == None):\n print(\"没有检测到上传的书\", file=sys.stderr)\n sessionDelFileUpload()\n return redirect(\"/404/没有检测到上传的书.\")\n \n #-----------------\n # 删除目录\n if(len(formTran.TOClistindex.data) >0 ):\n book.combineChapter(formTran.TOClistindex.data)\n #-----------------\n\n # 用bookCount代表已经转化完book\n fileDict['bookCount'] = book.book_count()\n\n # 转化封面\n if(not fileDict['isCoverUpload']):\n coverFontFlag = ' -font \\'' + os.path.join(Txt2mobiPath,'resources','STHeiti.ttf') + '\\''\n # 添加乞讨语\n coverFlag = coverFontFlag + ' -gravity South -pointsize 30 -annotate +0+100 '\n coverName = readSlogan()\n info_o = os.system(\"convert \" + os.path.join(fileDict['filePath'] , \"cover.png\") + coverFlag + '\\'' + coverName + '\\' ' +os.path.join(fileDict['filePath'] , \"cover.png\"))\n # 书名\n coverFlag = coverFontFlag + ' -gravity North -pointsize 50 -annotate +0+100 '\n coverName = (fileDict['filename'].rsplit('.',1)[0]).replace('\\'','').replace('\\\\','').replace('\\\"','')\n \n if(fileDict['bookCount'] == 1):\n info_o = os.system(\"convert \" + os.path.join(fileDict['filePath'] , \"cover.png\") + coverFlag + '\\'' + coverName + '\\' ' +os.path.join(fileDict['filePath'] , \"cover-1.png\"))\n # print(\"convert \" + os.path.join(filePath , \"cover.png\") + coverFlag + '\\'' + coverName + '\\' ' +os.path.join(filePath , \"cover.png\"))\n print(\"|-转化封面 : \", info_o, file=sys.stderr) \n else:\n for idx in range(1, fileDict['bookCount']+1):\n info_o = os.system(\"convert \" + os.path.join(fileDict['filePath'] , \"cover.png\") + coverFlag + '\\'' + coverName + '\\n P-%s\\' ' % idx +os.path.join(fileDict['filePath'] , \"cover-%s.png\" % idx))\n print(\"|-转化封面 : \", info_o, file=sys.stderr) \n else:\n\n coverFlag = ' -resize 960x640 '\n if(fileDict['bookCount'] == 1):\n info_o = os.system(\"convert \" + os.path.join(fileDict['filePath'] , \"cover.png\") + coverFlag +os.path.join(fileDict['filePath'] , \"cover-1.png\"))\n\n print(\"|-转化封面 : \", info_o, file=sys.stderr) \n else:\n coverFontFlag = ' -font \\'' + os.path.join(Txt2mobiPath,'resources','STHeiti.ttf') + '\\''\n # 上传书籍仅需要添加 'Part-xx'\n coverFlag = coverFontFlag + ' -resize 960x640 -gravity North -pointsize 50 -annotate +0+0 '\n\n for idx in range(1, fileDict['bookCount']+1):\n info_o = os.system(\"convert \" + os.path.join(fileDict['filePath'] , \"cover.png\") + coverFlag + '\\'P-%s\\' ' % idx +os.path.join(fileDict['filePath'] , \"cover-%s.png\" % idx))\n print(\"|-转化封面 : \", info_o, file=sys.stderr) \n\n\n\n # 生成项目文件 \n try:\n gen_project(book, titleFilter, fileDict['filePath'], fileDict['saveFileName'])\n except subprocess.TimeoutExpired:\n return redirect(\"/404/转化超时,请减小电子书大小\")\n \n\n sessionDelFileUpload()\n info = sessionSaveFileUpload(fileDict)\n if info != 0:\n print(\"储存文件错误 : \", info, file=sys.stderr)\n return redirect(\"/404/转存错误\")\n \n return redirect(\"/ConfirmTransformEbook\")\n\n\n return render_template('ConfirmTransformEbook.html.j2', app = app, formTran=formTran, os=os, TOC=TOC, jsV=jsV)\n\n\n@app.route('/TransformDownloads//')\ndef downloads(saveFileName,filename):\n fileDict = sessionQueryFileUpload()\n if(fileDict == None):\n return redirect('/404')\n elif(not ('bookCount' in fileDict.keys())):\n return redirect('/TransformEbook')\n elif(saveFileName != fileDict['saveFileName']):\n return redirect('/404/没有找到文件')\n elif(not re.match('project-[0-9]{1,2}\\.mobi', filename)):\n return redirect('/404/没有找到文件')\n\n print(\"download page : \" + fileDict['filePath'], file=sys.stderr)\n\n return send_from_directory(fileDict['filePath'],\n filename)\n","sub_path":"code/Pages/ConfirmTransformEbook.py","file_name":"ConfirmTransformEbook.py","file_ext":"py","file_size_in_byte":10421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"294675417","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 17-7-5 下午1:10\n# @Author : Tom.Lee\n# @Description : \n# @File : study_logging.py\n# @Product : PyCharm\n# @Docs : http://blog.csdn.net/hallo_ween/article/details/64906838\n\n\"\"\"\n注意:basicConfig有一个 很大的缺点。\n调用basicConfig其实是给root logger添加了一个handler,\n这样当你的程序和别的使用了 logging的第三方模块一起工作时,\n会影响第三方模块的logger行为。这是由logger的继承特性决定的。\n\"\"\"\n\nimport logging\nimport sys\n\nFORMAT_STR = '[%(asctime)s] %(levelname)s :: %(module)s :: %(filename)s-L%(lineno)d: %(message)s'\n\n\n# logger = logging.getLogger(\"django\")\n# logger.debug(logging.DEBUG) # 使用django热加载\n\n\ndef config1():\n \"\"\"\n **********************Config 1**********************\n \"\"\"\n # config 1.\n # 设置默认的level为DEBUG\n # 设置log的格式\n # 注意:basicConfig有一个 很大的缺点。\n # 调用basicConfig其实是给root logger添加了一个handler,\n # 这样当你的程序和别的使用了 logging的第三方模块一起工作时,\n # 会影响第三方模块的logger行为。这是由logger的继承特性决定的。\n logging.basicConfig(\n level=logging.DEBUG,\n format=\"[%(asctime)s] %(name)s:%(levelname)s: %(message)s\"\n )\n\n # 记录log\n logging.debug('debug')\n logging.info('info')\n logging.warn('warn')\n logging.error('error')\n logging.critical('critical')\n\n\ndef config2():\n \"\"\"\n ********************Config 2************************\n \"\"\"\n # # config 2\n # 使用一个名字为fib的logger\n logger = logging.getLogger('app_name')\n # 设置logger的level为DEBUG\n logger.setLevel(logging.DEBUG)\n # 创建一个输出日志到控制台的StreamHandler\n handler = logging.StreamHandler()\n formatter = logging.Formatter('[%(asctime)s] %(name)s:%(levelname)s: %(message)s')\n handler.setFormatter(formatter)\n # 给logger添加上handler\n logger.addHandler(handler)\n\n logger.debug('debug message')\n logger.info('hello world')\n\n\ndef config3():\n \"\"\"\n config3 输出到文件\n \"\"\"\n # 获取logger实例,如果参数为空则返回root logger\n logger = logging.getLogger(\"AppName\")\n # 指定logger输出格式\n formatter = logging.Formatter(FORMAT_STR)\n # 文件日志\n file_handler = logging.FileHandler(\"/tmp/config3.log\")\n file_handler.setFormatter(formatter) # 可以通过setFormatter指定输出格式\n # 控制台日志\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.formatter = formatter # 也可以直接给formatter赋值\n # 为logger添加的日志处理器,可以自定义日志处理器让其输出到其他地方\n logger.addHandler(file_handler)\n logger.addHandler(console_handler)\n # 指定日志的最低输出级别,默认为WARN级别\n logger.setLevel(logging.INFO)\n\n # 输出不同级别的log\n logger.debug('this is debug info')\n logger.info('this is information')\n logger.warn('this is warning message')\n logger.error('this is error message')\n logger.fatal('this is fatal message, it is same as logger.critical')\n logger.critical('this is critical message')\n\n\ndef config4():\n import glob\n import logging.handlers\n\n log_filename = '/tmp/logging_rotating_file_example.out'\n\n # Set up a specific logger with our desired output level\n my_logger = logging.getLogger('MyLogger')\n my_logger.setLevel(logging.DEBUG)\n\n # Add the log message handler to the logger\n # filename 日志名称\n # maxBytes 最大字节\n # backupCount 备份数量\n handler = logging.handlers.RotatingFileHandler(\n filename=log_filename,\n maxBytes=10,\n backupCount=2)\n\n my_logger.addHandler(handler)\n\n # Log some messages\n for i in range(20):\n my_logger.debug('i = %d' % i)\n\n # See what files are created\n log_files = glob.glob('%s*' % log_filename)\n\n for filename in log_files:\n print(filename)\n\n\ndef config5():\n import glob\n import re\n import logging.handlers\n from time import sleep\n log_filename = '/tmp/logging_time_rotating_file_example.log'\n\n # Set up a specific logger with our desired output level\n my_logger = logging.getLogger('MyLogger')\n my_logger.setLevel(logging.DEBUG)\n\n # Add the log message handler to the logger\n # filename 日志名称\n # when 周期时间\n # backupCount 备份数量\n handler = logging.handlers.TimedRotatingFileHandler(\n filename=log_filename,\n when='S',\n backupCount=2)\n # 修改默认值,必须同时修改该俩个属性\n # handler.suffix = '{}.bak'.format(handler.suffix)\n # handler.extMatch = re.compile(r\"^\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}.bak$\")\n\n my_logger.addHandler(handler)\n\n # Log some messages\n for i in range(20):\n sleep(1)\n my_logger.debug('i = %d' % i)\n\n # See what files are created\n log_files = glob.glob('%s*' % log_filename)\n\n for filename in log_files:\n print(filename)\n\n\nclass ConsoleLoggerHaveBug(object):\n \"\"\"\n BUG\n BUG\n\n 使用new方法,错误的方式,同名的name会打印重复\n \"\"\"\n\n def __new__(cls, name='%(module)s'):\n __format = '%(asctime)s %(levelname)s {model} :: %(message)s'.format(model=name)\n __logger = logging.getLogger(name)\n __logger.setLevel(logging.DEBUG)\n handler = logging.StreamHandler()\n formatter = logging.Formatter(__format)\n handler.setFormatter(formatter)\n __logger.addHandler(handler)\n return __logger\n\n\nclass ConsoleLogger(logging.Logger):\n \"\"\"\n 自定义logger\n examples:\n logger = ConsoleLogger('mode_name')\n logger.info(\"ok!\")\n \"\"\"\n\n def __init__(self, name, level=logging.DEBUG):\n super(ConsoleLogger, self).__init__(name, level)\n self.formatter = logging.Formatter('[%(asctime)s] %(name)s: %(levelname)s: %(message)s')\n self.handler = logging.StreamHandler()\n self.handler.setFormatter(self.formatter)\n # 给logger添加上handler\n self.addHandler(self.handler)\n\n\nclass FileLogger(logging.Logger):\n \"\"\"\n 自定义logger\n examples:\n logger = FileLogger('file_path','mode_name')\n logger.info(\"ok!\")\n \"\"\"\n\n # def __new__(cls, file_path, name='sys'):\n # __logger = logging.getLogger(name)\n # formatter = logging.Formatter(FORMAT_STR)\n # file_handler = logging.FileHandler(file_path)\n # file_handler.setFormatter(formatter)\n # console_handler = logging.StreamHandler()\n # console_handler.formatter = formatter\n # __logger.setLevel(logging.DEBUG)\n # __logger.addHandler(file_handler)\n # __logger.addHandler(console_handler)\n #\n # return __logger\n def __init__(self, name, level=logging.DEBUG):\n super(FileLogger, self).__init__(name, level)\n self.log_file_path = '/tmp/logger.log'\n self.formatter = logging.Formatter('[%(asctime)s] %(name)s: %(levelname)s: %(message)s')\n self.file_handler = logging.FileHandler(self.log_file_path)\n self.file_handler.setFormatter(self.formatter)\n self.console_handler = logging.StreamHandler()\n self.console_handler.setFormatter(self.formatter)\n self.addHandler(self.file_handler)\n self.addHandler(self.console_handler)\n\n\nif __name__ == '__main__':\n # logger = FileLogger('fileTest')\n # logger.info(\"FileLogger ok!\")\n #\n # logger2 = ConsoleLogger('app')\n # logger2.info(\"logger2 ConsoleLogger ok!\")\n # logger3 = ConsoleLogger('app')\n # logger3.info(\"logger3 ConsoleLogger ok!\")\n #\n # # 这种方式存在bug, 同名的name会打印重复\n # l = ConsoleLoggerHaveBug('test')\n # l.debug('l: 123')\n # l2 = ConsoleLoggerHaveBug('test')\n # l2.debug('l2: 456')\n # config3()\n\n # config4()\n config5()\n","sub_path":"2.7/standard_library/study_logging.py","file_name":"study_logging.py","file_ext":"py","file_size_in_byte":8016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"613526061","text":"# COMPARE STRINGS WHICH MIGHT CONTAIN UNICODES\n############################################################################\ndef insensitive(string):\n \"\"\"Given a string, returns its lower/upper case insensitive string\"\"\"\n if getattr(str,'casefold',None) is not None:\n insen = lambda str_name: str_name.casefold()\n else:\n insen = lambda str_name: str_name.upper().lower()\n\n return insen(string)\n\n","sub_path":"Kuru/Utils/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"303784940","text":"import glob\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nimport os\nos.chdir('/Users/evanbiederstedt/Downloads/RRBS_data_files')\n\n\n\nnormal_B = glob.glob(\"stacked_RRBS_normal_B*\")\n\nnewdf1 = pd.DataFrame()\nfor filename in normal_B[:2]:\n df = pd.read_csv(filename)\n df['filename'] = str(filename)\n df = df.sum()\n df[\"total_cpg_no_filter\"] = df[\"avgReadCpGs\"]\n df[\"filename\"] = str(filename)\n df[\"filename\"] = df[\"filename\"][8:48]\n \n newdf1 = newdf1.append(df, ignore_index=True)\n\nnewdf1.to_csv(\"cpg_normalB1.csv\")\n\nnormal_B = glob.glob(\"stacked_RRBS_normal_B*\")\n\nnewdf2 = pd.DataFrame()\nfor filename in normal_B:\n df = pd.read_csv(filename)\n df['filename'] = str(filename)\n df = df[df['avgReadCpGs'] > 1]\n df = df.sum()\n df[\"total_cpg_gtrthan1\"] = df[\"avgReadCpGs\"]\n df[\"filename\"] = str(filename)\n df[\"filename\"] = df[\"filename\"][8:48]\n newdf2 = newdf2.append(df, ignore_index=True)\n\nnewdf2.to_csv(\"cpg_normalB2.csv\")\n\n\n\nnormal_B = glob.glob(\"stacked_RRBS_normal_B*\")\n\n\nnewdf3 = pd.DataFrame()\nfor filename in normal_B:\n df = pd.read_csv(filename)\n df['filename'] = str(filename)\n df = df[df['avgReadCpGs'] >= 3.8]\n df = df.sum()\n df[\"total_cpg_gtrthan38\"] = df[\"avgReadCpGs\"]\n df[\"filename\"] = str(filename)\n df[\"filename\"] = df[\"filename\"][8:48]\n newdf3 = newdf3.append(df, ignore_index=True)\n\nnewdf3.to_csv(\"cpg_normalB3.csv\")\n\n\n\n","sub_path":"scripts/normalB_cpg.py","file_name":"normalB_cpg.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"446194575","text":"def print_formatted(number):\n n = len(format(number, 'b'))\n for i in range(1, number + 1): \n s = str(i)\n sx = format(i, 'x').upper()\n so = format(i, 'o').upper()\n sb = format(i, 'b')\n print(s.rjust(n, ' '), sx.rjust(n, ' '), so.rjust(n, ' '), sb.rjust(n, ' '))\n\nif __name__ == '__main__':\n n = int(input())\n print_formatted(n)","sub_path":"stringformatting.py","file_name":"stringformatting.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"551615456","text":"from rest_framework import serializers\n\nfrom .models import Question, Answer\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.auth import get_user_model\n\n\n###################### User ########################\nUser = get_user_model()\n\n\nclass UserDetailSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = [\n 'username',\n 'email',\n 'first_name',\n 'last_name',\n ]\n\n\nclass UserCreateSerializer(serializers.ModelSerializer):\n email = serializers.EmailField(label='Email Address')\n email2 = serializers.EmailField(label='Confirm Email')\n\n class Meta:\n model = User\n fields = [\n 'username',\n 'email',\n 'email2',\n 'password',\n \n ]\n extra_kwargs = {\n \"password\":{\"write_only\": True}\n }\n\n def validate(self, data):\n return data\n\n def validate_email(self, value):\n data = self.get_initial()\n email1 = data.get(\"email2\")\n email2 = value\n if email1 != email2:\n raise serializers.ValidationError(\"Emails must match.\")\n \n user_qs = User.objects.filter(email=email2)\n if user_qs.exists():\n raise serializers.ValidationError(\"This user has already registered.\")\n\n return value\n\n def validate_email2(self, value):\n data = self.get_initial()\n email1 = data.get(\"email\")\n email2 = value\n if email1 != email2:\n raise serializers.ValidationError(\"Emails must match.\")\n return value\n\n def create(self, validated_data):\n username = validated_data['username']\n email = validated_data['email']\n password = validated_data['password']\n user_obj = User(\n username = username,\n email = email\n )\n user_obj.set_password(password)\n user_obj.save()\n return validated_data\n\n\nclass UserLoginSerializer(serializers.ModelSerializer):\n token = serializers.CharField(allow_blank=True, read_only=True)\n username = serializers.CharField()\n email = serializers.EmailField(label='Email Address')\n\n class Meta:\n model = User\n fields = [\n 'username',\n 'email',\n 'password',\n 'token',\n ]\n extra_kwargs = {\n \"password\": {\"write_only\": True}\n }\n\n def validate(self, data):\n return data\n\n\n###################### Question ###########################\nclass QuestionCreateUpdateSerializer(serializers.ModelSerializer):\n class Meta:\n model = Question\n fields = (\n 'id',\n 'title',\n 'content'\n )\n\n\nquestion_detail_url = serializers.HyperlinkedIdentityField(\n view_name='question_detail',\n lookup_field='pk'\n)\n\n\nclass QuestionDetailSerializer(serializers.ModelSerializer):\n url = question_detail_url\n user = UserDetailSerializer(read_only=True)\n image = serializers.SerializerMethodField()\n answers = serializers.SerializerMethodField()\n\n class Meta:\n model = Question\n fields = (\n 'id',\n 'user',\n 'image',\n 'url',\n 'title',\n 'slug',\n 'content',\n 'answers'\n )\n\n def get_image(self, obj):\n try:\n image = obj.image.path\n except:\n image = None\n return image\n\n def get_answers(self, obj):\n a_qs = Answer.objects.filter_by_instance(obj)\n answers = AnswerSerializer(a_qs, many=True).data\n return answers\n\n\nclass QuestionListSerializer(serializers.ModelSerializer):\n url = question_detail_url\n user = UserDetailSerializer(read_only=True)\n class Meta:\n model = Question\n fields = [\n 'id',\n 'url',\n 'user',\n 'title',\n 'content',\n ]\n\n\n####################### Answer Serializers ###############################\ndef create_answer_serializer(model_type='post', pk=None, parent_id=None, user=None):\n class AnswerCreateSerializer(serializers.ModelSerializer):\n class Meta:\n model = Answer\n fields = [\n 'id',\n 'parent',\n 'content',\n 'timestamp'\n ]\n\n def __init__(self, *args, **kwargs):\n self.model_type = model_type\n self.pk = pk\n self.parent_obj = None\n if parent_id:\n parent_qs = Answer.objects.filter(id=parent_id)\n if parent_qs.exists() and parent_qs.count() == 1:\n self.parent_obj = parent_qs.first()\n return super(AnswerCreateSerializer, self).__init__(*args, **kwargs)\n\n def validate(self, data):\n model_type = self.model_type\n model_qs = ContentType.objects.filter(model=model_type)\n if not model_qs.exists() or model_qs.count() != 1:\n raise serializers.ValidationError(\"This is not a valid content type.\")\n SomeModel = model_qs.first().model_class()\n obj_qs = SomeModel.objects.filter(pk=self.pk)\n if not obj_qs.exists() or obj_qs.count() != 1:\n raise serializers.ValidationError(\"This is not a pk for this content type.\")\n return data\n\n def create(self, validated_data):\n content = validated_data.get(\"content\")\n if user:\n main_user = user\n else:\n main_user = User.objects.all().first()\n model_type = self.model_type\n pk = self.pk\n parent_obj = self.parent_obj\n answer = Answer.objects.create_by_model_type(\n model_type=model_type,\n pk=pk,\n content=content,\n user=main_user,\n parent_obj=parent_obj\n )\n return answer\n\n return AnswerCreateSerializer\n\n\nclass AnswerSerializer(serializers.ModelSerializer):\n reply_count = serializers.SerializerMethodField()\n class Meta:\n model = Answer\n fields = (\n 'id',\n 'content_type',\n 'object_id',\n 'parent',\n 'content',\n 'reply_count',\n 'timestamp'\n )\n\n def get_reply_count(self, obj):\n if obj.is_parent:\n return obj.children().count()\n return 0\n\n\nclass AnswerListSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='answer_detail')\n reply_count = serializers.SerializerMethodField()\n class Meta:\n model = Answer\n fields = [\n 'url',\n 'id',\n 'content',\n 'reply_count',\n 'timestamp',\n ]\n \n def get_reply_count(self, obj):\n if obj.is_parent:\n return obj.children().count()\n return 0\n\n\nclass AnswerChildSerializer(serializers.ModelSerializer):\n user = UserDetailSerializer(read_only=True)\n class Meta:\n model = Answer\n fields = (\n 'id',\n 'user',\n 'content',\n 'timestamp'\n )\n\n\nclass AnswerDetailSerializer(serializers.ModelSerializer):\n user = UserDetailSerializer(read_only=True)\n url = serializers.HyperlinkedIdentityField(\n view_name='answer_detail')\n reply_count = serializers.SerializerMethodField()\n content_object_url = serializers.SerializerMethodField()\n replies = serializers.SerializerMethodField()\n class Meta:\n model = Answer\n fields = [\n 'id',\n 'user',\n 'url',\n 'content',\n 'reply_count',\n 'replies',\n 'timestamp',\n 'content_object_url',\n ]\n read_only_fields = [\n 'reply_count',\n 'replies',\n ]\n\n def get_content_object_url(self, obj):\n try:\n return obj.content_object.get_api_url()\n except:\n return None\n\n def get_replies(self, obj):\n if obj.is_parent:\n return AnswerChildSerializer(obj.children(), many=True).data\n return None\n\n def get_reply_count(self, obj):\n if obj.is_parent:\n return obj.children().count()\n return 0\n","sub_path":"blog/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":8391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"446983097","text":"import os\nimport signal\nimport sys\nimport time\nimport math\nfrom threading import Thread, Lock, RLock\nimport threading\nimport numpy as np\nfrom kinematicController import KinematicController\nimport TRINAConfig #network configs and other configs\nfrom motionStates import * #state structures\nfrom copy import deepcopy,copy\nfrom klampt.math import vectorops,so3\n# from klampt import vis\nfrom klampt.model import ik, collide\nimport numpy as np\nfrom klampt import WorldModel\nimport os\n\nimport logging\nfrom datetime import datetime\n\nif not os.path.exists('errorLogs'):\n os.makedirs('errorLogs')\nlogger = logging.getLogger(__name__)\n# Create handlers\nc_handler = logging.StreamHandler()\nfilename = \"errorLogs/logFile_\" + datetime.now().strftime('%d%m%Y') + \".log\"\nf_handler = logging.FileHandler(filename)\nc_handler.setLevel(logging.WARNING)\nf_handler.setLevel(logging.NOTSET)\n# Create formatters and add it to handlers\nc_format = logging.Formatter('%(asctime)s %(levelname)s-%(message)s',datefmt='%H:%M:%S')\nf_format = logging.Formatter('%(asctime)s %(funcName)s :%(levelname)s- %(message)s',datefmt='%H:%M:%S')\nc_handler.setFormatter(c_format)\nf_handler.setFormatter(f_format)\n# Add handlers to the logger\nlogger.addHandler(c_handler)\nlogger.addHandler(f_handler)\n\nclass Motion:\n\n def __init__(self,mode = 'Kinematic', components = ['left_limb','right_limb'], debug_logging = False, codename = 'seed'):\n \"\"\"\n This class provides a low-level controller to the TRINA robot.\n\n Parameters\n ------------\n mode: The 'Kinematic' mode starts a kinematic simlation of the robot. The 'Physical' mode interfaces with\n the robotic hardware directly.\n model_path: The TRINA robot model path.\n components: In the physical mode, we would like to have the option of starting only a subset of the components.\n It is a list of component names, including: left_limb, right_limb, base, torso (including the support legs.),\n left_gripper, right_gripper.\n \"\"\"\n self.codename = codename\n self.mode = mode\n self.model_path = \"data/TRINA_world_\" + self.codename + \".xml\"\n self.computation_model_path = \"data/TRINA_world_\" + self.codename + \".xml\"\n self.debug_logging = debug_logging\n if(self.debug_logging):\n self.logging_filename = time.time()\n self.logging_file = 'teleoperation_log/log_file_' + time.strftime('%Y')+'_'+time.strftime('%m')+'_'+time.strftime('%d')+'_'+time.strftime('%H')+'_'+time.strftime('%M')+'_'+time.strftime('%S')+'.csv'\n\n if(os.path.exists(self.logging_file)):\n pass\n else:\n with open(self.logging_file,'w') as f:\n f.write('arm|ik_time|collision_check_time|current_position|target_position|iterations|condition_number\\r\\n')\n f.close()\n\n self.log_file = open(self.logging_file,'a')\n #Klampt world and robot and used for computation\n self.world = WorldModel()\n res = self.world.readFile(self.computation_model_path)\n if not res:\n logger.error('unable to load model')\n raise RuntimeError(\"unable to load model\")\n #Initialize collision detection\n self.collider = collide.WorldCollider(self.world)\n self.robot_model = self.world.robot(0)\n #End-effector links and active dofs used for arm cartesian control and IK\n self.left_EE_link = self.robot_model.link(TRINAConfig.get_left_tool_link_N(self.codename))\n self.left_active_Dofs = TRINAConfig.get_left_active_Dofs(self.codename)\n self.right_EE_link = self.robot_model.link(TRINAConfig.get_right_tool_link_N(self.codename))\n self.right_active_Dofs = TRINAConfig.get_right_active_Dofs(self.codename)\n #UR5 arms need correct gravity vector\n self.currentGravityVector = [0,0,-9.81]\n\n #Enable some components of the robot\n self.left_limb_enabled = False\n self.right_limb_enabled = False\n self.base_enabled = False\n self.torso_enabled = False\n self.left_gripper_enabled = False\n self.right_gripper_enabled = False\n #Initialize components\n if self.mode == \"Kinematic\":\n self.left_limb_enabled = True\n self.right_limb_enabled = True\n self.base_enabled = True\n print(\"initiating Kinematic controller\")\n self.simulated_robot = KinematicController(self.model_path,codename = self.codename)\n print(\"initiated Kinematic controller\")\n\n elif self.mode == \"Physical\":\n from limbController import LimbController\n from baseController import BaseController\n from torsoController import TorsoController\n from gripperController import GripperController\n for component in components:\n if component == 'left_limb':\n self.left_limb = LimbController(TRINAConfig.left_limb_address,gripper=False,gravity = TRINAConfig.left_limb_gravity_upright,\\\n payload = TRINAConfig.left_limb_payload,tcp = TRINAConfig.left_limb_TCP)\n self.left_limb_enabled = True\n logger.debug('left limb enabled')\n elif component == 'right_limb':\n self.right_limb = LimbController(TRINAConfig.right_limb_address,gripper=False,gravity = TRINAConfig.right_limb_gravity_upright)\n self.right_limb_enabled = True\n logger.debug('right limb enabled')\n elif component == 'base':\n self.base = BaseController()\n self.base_enabled = True\n logger.debug('base enabled')\n elif component == 'torso':\n self.torso = TorsoController()\n self.torso_enabled = True\n logger.debug('torso enabled')\n elif component == 'left_gripper':\n self.left_gripper = GripperController()\n self.left_gripper_enabled = True\n logger.debug('left gripper enabled')\n elif component == 'right_gripper':\n self.right_gripper = GripperController()\n self.right_gripper_enabled = True\n logger.debug('right gripper enabled')\n else:\n logger.error('Motion: wrong component name specified')\n raise RuntimeError('Motion: wrong component name specified')\n else:\n logger.error('Wrong Mode specified')\n raise RuntimeError('Wrong Mode specified')\n\n self.left_limb_state = LimbState()\n self.right_limb_state = LimbState()\n\n self.base_state = BaseState()\n self.left_limb_state = LimbState()\n self.right_limb_state = LimbState()\n self.base_state = BaseState()\n self.torso_state = TorsoState()\n self.left_gripper_state = GripperState()\n\n self.startTime = time.time()\n #time since startup\n self.t = 0\n self.startUp = False\n #Control loop rate\n self.dt = 0.002\n #automatic mode for future\n self.automatic_mode = False\n self.stop_motion_flag = False\n self.stop_motion_sent = False\n self.shut_down_flag = False\n self.cartedian_drive_failure = False\n self._controlLoopLock = RLock()\n #signal.signal(signal.SIGINT, self.sigint_handler) # catch SIGINT (ctrl-c)\n\n def sigint_handler(self, signum, frame):\n \"\"\" Catch Ctrl+C tp shutdown the robot\n\n \"\"\"\n assert(signum == signal.SIGINT)\n logger.warning('SIGINT caught...shutting down the api!')\n print(\"SIGINT caught...shutting down the api!\")\n self.shutdown()\n\n def time(self):\n \"\"\"Time since the controller has started\n\n return:\n ---------------\n float: time since the controller has started in secs\n\n \"\"\"\n return self.t\n\n def startup(self):\n \"\"\" Starts up all the individual components and the main control thread.\n\n Each component is started sequentially. After starting, all components stay where they are and\n start updating their states immediately.\n \"\"\"\n\n if not self.startUp:\n if self.mode == \"Kinematic\":\n self.simulated_robot.start()\n elif self.mode == \"Physical\":\n if self.torso_enabled:\n self.torso.start()\n logger.info('Motion: torso started')\n print(\"Motoin: torso started\")\n if self.base_enabled:\n self.base.start()\n logger.info('Motion: base started')\n print(\"Motion: base started\")\n if self.left_limb_enabled or self.right_limb_enabled:\n if self.torso_enabled:\n #TODO read torso position\n #tilt_angle =\n pass\n else:\n tilt_angle = 0.0\n R_tilt = so3.from_axis_angle(([0,1,0],tilt_angle))\n R_local_global_left = so3.mul(R_tilt,TRINAConfig.R_local_global_upright_left)\n R_local_global_right = so3.mul(R_tilt,TRINAConfig.R_local_global_upright_right)\n #gravity_left = so3.apply(so3.inv(R_local_global_left),[0,0,-9.81])\n #gravity_right = so3.apply(so3.inv(R_local_global_right),[0,0,-9.81])\n #self.left_limb.setGravity(gravity_left)\n #self.right_limb.setGravity(gravity_right)\n if self.left_limb_enabled:\n res = self.left_limb.start()\n time.sleep(1)\n if res == False:\n #better to replace this with logger\n logger.error('left limb start failure.')\n print(\"motion.startup(): ERROR, left limb start failure.\")\n return False\n else:\n logger.info('left limb started.')\n print(\"motion.startup(): left limb started.\")\n self.left_limb_state.sensedq = self.left_limb.getConfig()[0:6]\n self.left_limb_state.senseddq = self.left_limb.getVelocity()[0:6]\n self.left_limb_state.sensedWrench =self.left_limb.getWrench()\n if self.right_limb_enabled:\n res = self.right_limb.start()\n time.sleep(1)\n if res == False:\n #better to replace this with logger\n logger.error('right limb start failure.')\n print(\"motion.startup(): ERROR, right limb start failure.\")\n return False\n else:\n logger.info('right limb started.')\n print(\"motion.startup(): right limb started.\")\n self.right_limb_state.sensedq = self.right_limb.getConfig()[0:6]\n self.right_limb_state.senseddq = self.right_limb.getVelocity()[0:6]\n self.right_limb_state.sensedWrench = self.right_limb.getWrench()\n if self.left_gripper_enabled:\n self.left_gripper.start()\n print('left gripper started')\n logger.info('left gripper started')\n if self.right_gripper_enabled:\n self.right_gripper.start()\n logger.info('right gripper started')\n\n\n controlThread = threading.Thread(target = self._controlLoop)\n controlThread.start()\n logger.info('robot started.')\n print(\"motion.startup():robot started\")\n self.startUp = True\n else:\n ##warning\n logger.warning('Already started.')\n print(\"motion.startup():Already started\")\n return self.startUp\n\n def _controlLoop(self):\n \"\"\"main control thread, synchronizing all components\n in each loop,states are updated and new commands are issued\n \"\"\"\n\n counter = 0\n self.robot_start_time = time.time()\n logger.info('controlLoop started.')\n print(\"motion.controlLoop(): controlLoop started.\")\n while not self.shut_down_flag:\n loopStartTime = time.time()\n self.t = time.time() - self.startTime\n ###lock the thread\n self._controlLoopLock.acquire()\n if self.mode == \"Physical\":\n if self.stop_motion_flag:\n if not self.stop_motion_sent: #send only once to avoid drifting...\n if self.torso_enabled:\n self.torso.stopMotion()\n if self.base_enabled:\n self.base.stopMotion()\n if self.left_limb_enabled:\n self.left_limb.stopMotion()\n if self.right_limb_enabled:\n self.right_limb.stopMotion()\n if self.left_gripper_enabled:\n self.left_gripper.stopMotion()\n if self.right_gripper_enabled:\n self.right_gripper.stopMotion()\n self.stop_motion_sent = True #unused\n else:\n #Update current state. Only read state if a new one has been posted\n if self.base_enabled and self.base.newState():\n self.base_state.measuredVel = self.base.getMeasuredVelocity()\n self.base_state.measuredPos = self.base.getPosition()\n self.base.markRead()\n\n if self.torso_enabled and self.torso.newState():\n tilt, height, _, _ = self.torso.getStates()\n self.torso_state.measuredTilt = tilt\n self.torso_state.measuredHeight = height\n self.torso.markRead()\n\n if self.left_limb_enabled and self.left_limb.newState():\n self.left_limb_state.sensedq = self.left_limb.getConfig()[0:6]\n self.left_limb_state.senseddq = self.left_limb.getVelocity()[0:6]\n self.left_limb_state.sensedWrench =self.left_limb.getWrench()\n self.left_limb.markRead()\n if self.right_limb_enabled and self.right_limb.newState():\n self.right_limb_state.sensedq = self.right_limb.getConfig()[0:6]\n self.right_limb_state.senseddq = self.right_limb.getVelocity()[0:6]\n self.right_limb_state.sensedWrench = self.right_limb.getWrench()\n self.right_limb.markRead()\n\n if self.left_gripper_enabled and self.left_gripper.newState():\n self.left_gripper_state.sense_finger_set = self.left_gripper.sense_finger_set\n self.left_gripper.mark_read()\n #Send Commands\n if self.left_limb_enabled:\n if self.left_limb_state.commandQueue:\n if self.left_limb_state.commandType == 0:\n tmp = time.time() - self.left_limb_state.commandQueueTime\n if tmp <= self.left_limb_state.commandedQueueDuration:\n self.simulated_robot.setLeftLimbConfig(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,tmp/self.left_limb_state.commandedQueueDuration)))\n else:\n self.simulated_robot.setLeftLimbConfig(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,1.0)))\n self.setLeftLimbPosition(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,1.0)))\n #### cartesian drive mode\n elif self.left_limb_state.cartesianDrive:\n flag = 1\n while flag:\n res, target_config = self._left_limb_cartesian_drive(self.left_limb_state.driveTransform)\n if res == 0:\n #res = 0 means IK has failed completely, 1 means keep trying smaller steps, 2 means success\n #set to position mode...\n self.cartesian_drive_failure = True\n self.left_limb_state.commandSent = False\n self.left_limb_state.commandedq = deepcopy(self.sensedLeftLimbPosition())\n self.left_limb_state.commandeddq = []\n self.left_limb_state.commandType = 0\n self.left_limb_state.commandQueue = False\n self.left_limb_state.commandedqQueue = []\n self.left_limb_state.cartesianDrive = False\n break\n elif res == 1:\n flag = 1\n elif res == 2:\n flag = 0\n self.left_limb.setConfig(target_config)\n\n else:\n if not self.left_limb_state.commandSent:\n ###setting position will clear velocity commands\n if self.left_limb_state.commandType == 0:\n self.left_limb.setConfig(self.left_limb_state.commandedq+[0.0])\n elif self.left_limb_state.commandType == 1:\n self.left_limb.setVelocity(self.left_limb_state.commandeddq + [0.0])\n self.left_limb_state.commandSent = True\n if self.right_limb_enabled:\n if self.right_limb_state.commandQueue:\n if self.right_limb_state.commandType == 0:\n tmp = time.time() - self.right_limb_state.commandQueueTime\n if tmp <= self.right_limb_state.commandedQueueDuration:\n self.simulated_robot.setRightLimbConfig(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,tmp/self.right_limb_state.commandedQueueDuration)))\n else:\n self.simulated_robot.setRightLimbConfig(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,1.0)))\n self.setRightLimbPosition(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,1.0)))\n elif self.right_limb_state.cartesianDrive:\n flag = 1\n while flag:\n #res = 0 means IK has failed completely, 1 means keep trying smaller steps, 2 means success\n res, target_config = self._right_limb_cartesian_drive(self.right_limb_state.driveTransform)\n if res == 0:\n #set to position mode...\n self.cartesian_drive_failure = True\n self.right_limb_state.commandSent = False\n self.right_limb_state.commandedq = deepcopy(self.sensedRightLimbPosition())\n self.right_limb_state.commandeddq = []\n self.right_limb_state.commandType = 0\n self.right_limb_state.commandQueue = False\n self.right_limb_state.commandedqQueue = []\n self.right_limb_state.cartesianDrive = False\n break\n elif res == 1:\n flag = 1\n elif res == 2:\n flag = 0\n self.simulated_robot.setRightLimbConfig(target_config)\n else:\n if not self.right_limb_state.commandSent:\n ###setting position will clear velocity commands\n if self.right_limb_state.commandType == 0:\n self.right_limb.setConfig(self.right_limb_state.commandedq+[0.0])\n elif self.right_limb_state.commandType == 1:\n self.right_limb.setVelocity(self.right_limb_state.commandeddq + [0.0])\n self.right_limb_state.commandSent = True\n\n #TODO:Base add set path later\n if self.base_enabled:\n if self.base_state.commandType == 1:\n self.base.setCommandedVelocity(self.base_state.commandedVel)\n elif self.base_state.commandType == 0 and not base_state.commandSent:\n self.base_state.commandSent = True\n self.base.setTargetPosition(self.base_state.commandedVel)\n if self.torso_enabled:\n if not self.torso_state.commandSent:\n self.torso_state.commandSent = True\n self.torso.setTargetPositions(self.torso_state.commandedHeight, self.torso_state.commandedTilt)\n\n if self.left_gripper_enabled:\n if self.left_gripper_state.commandType == 0:\n self.left_gripper.setPose(self.left_gripper_state.command_finger_set)\n elif self.left_gripper_state.commandType == 1:\n self.left_gripper.setVelocity(self.left_gripper_state.command_finger_set)\n\n if self.right_gripper_enabled:\n if self.right_gripper_state.commandType == 0:\n self.right_gripper.setPose(self.right_gripper_state.command_finger_set)\n elif self.right_gripper_state.commandType == 1:\n self.right_gripper.setVelocity(self.right_gripper_state.command_finger_set)\n #update internal robot model, does not use the base's position and orientation\n #basically assumes that the world frame is the frame centered at the base local frame, on the floor.\n robot_model_Q = TRINAConfig.get_klampt_model_q(self.codename,left_limb = self.left_limb_state.sensedq, right_limb = self.right_limb_state.sensedq)\n #robot_model_Q = [0]*3 + [0]*7 +self.left_limb_state.sensedq+[0]*4+self.right_limb_state.sensedq+[0]*2\n self.robot_model.setConfig(robot_model_Q)\n\n elif self.mode == \"Kinematic\":\n if self.stop_motion_flag:\n self.simulated_robot.stopMotion()\n else:\n if self.simulated_robot.newState():\n self.left_limb_state.sensedq = self.simulated_robot.getLeftLimbConfig()[0:6]\n self.left_limb_state.senseddq = self.simulated_robot.getLeftLimbVelocity()[0:6]\n self.left_limb_state.sensedWrench = []\n self.right_limb_state.sensedq = self.simulated_robot.getRightLimbConfig()[0:6]\n self.right_limb_state.senseddq = self.simulated_robot.getRightLimbVelocity()[0:6]\n self.right_limb_state.sensedWrench = []\n self.base_state.measuredVel = self.simulated_robot.getBaseVelocity()\n self.base_state.measuredPos = self.simulated_robot.getBaseConfig()\n #self.left_gripper_state.sense_finger_set = selfprint(\"motion.controlLoop(): controlLoop started.\")\n\n ###left limb\n if self.left_limb_state.commandQueue:\n if self.left_limb_state.commandType == 0:\n tmp = time.time() - self.left_limb_state.commandQueueTime\n if tmp <= self.left_limb_state.commandedQueueDuration:\n self.simulated_robot.setLeftLimbConfig(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,tmp/self.left_limb_state.commandedQueueDuration)))\n else:\n self.simulated_robot.setLeftLimbConfig(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,1.0)))\n self.setLeftLimbPosition(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,1.0)))\n\n #elif self.left_limb_state.commandType == 1:\n # if len(self.left_limb_state.commandeddqQueue) > 0:\n # #if ((time.time() - self.left_limb_state.lastCommandQueueTime) > TRINAConfig.simulated_robot_control_rate):\n # self.simulated_robot.setLeftLimbVelocity(self.left_limb_state.commandeddqQueue.pop(0))\n # #self.left_limb_state.lastCommandQueueTime = time.time()\n\n\n #### cartesian drive mode\n elif self.left_limb_state.cartesianDrive:\n #clock1 = time.time()\n flag = 1\n while flag:\n res, target_config = self._left_limb_cartesian_drive(self.left_limb_state.driveTransform)\n if res == 0:\n #set to position mode...\n self.cartesian_drive_failure = True\n self.left_limb_state.commandSent = False\n self.left_limb_state.commandedq = deepcopy(self.sensedLeftLimbPosition())\n self.left_limb_state.commandeddq = []\n self.left_limb_state.commandType = 0\n self.left_limb_state.commandQueue = False\n self.left_limb_state.difference = []\n self.left_limb_state.commandedqQueueStart = []\n self.left_limb_state.commandQueueTime = 0.0\n self.left_limb_state.commandedQueueDuration = 0.0\n self.left_limb_state.cartesianDrive = False\n break\n elif res == 1:\n flag = 1\n elif res == 2:\n flag = 0\n self.simulated_robot.setLeftLimbConfig(target_config)\n\n\n else:\n if not self.left_limb_state.commandSent:\n ###setting position will clear velocity commands\n if self.left_limb_state.commandType == 0:\n self.simulated_robot.setLeftLimbConfig(self.left_limb_state.commandedq)\n elif self.left_limb_state.commandType == 1:\n self.simulated_robot.setLeftLimbVelocity(self.left_limb_state.commandeddq)\n self.left_limb_state.commandSent = True\n\n ##right limb\n if self.right_limb_state.commandQueue:\n if self.right_limb_state.commandType == 0:\n tmp = time.time() - self.right_limb_state.commandQueueTime\n if tmp <= self.right_limb_state.commandedQueueDuration:\n self.simulated_robot.setRightLimbConfig(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,tmp/self.right_limb_state.commandedQueueDuration)))\n else:\n self.simulated_robot.setRightLimbConfig(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,1.0)))\n self.setRightLimbPosition(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,1.0)))\n\n elif self.right_limb_state.cartesianDrive:\n flag = 1\n while flag:\n #res = 0 means IK has failed completely, 1 means keep trying smaller steps, 2 means success\n res, target_config = self._right_limb_cartesian_drive(self.right_limb_state.driveTransform)\n if res == 0:\n #set to position mode...\n self.cartesian_drive_failure = True\n self.right_limb_state.commandSent = False\n self.right_limb_state.commandedq = deepcopy(self.sensedRightLimbPosition())\n self.right_limb_state.commandeddq = []\n self.right_limb_state.commandType = 0\n self.right_limb_state.commandQueue = False\n self.right_limb_state.difference = []\n self.right_limb_state.commandedqQueueStart = []\n self.right_limb_state.commandQueueTime = 0.0\n self.right_limb_state.commandedQueueDuration = 0.0\n self.right_limb_state.cartesianDrive = False\n break\n elif res == 1:\n flag = 1\n elif res == 2:\n flag = 0\n self.simulated_robot.setRightLimbConfig(target_config)\n else:\n if not self.right_limb_state.commandSent:\n ###setting position will clear velocity commands\n if self.right_limb_state.commandType == 0:\n self.simulated_robot.setRightLimbConfig(self.right_limb_state.commandedq)\n elif self.right_limb_state.commandType == 1:\n self.simulated_robot.setRightLimbVelocity(self.right_limb_state.commandeddq)\n self.right_limb_state.commandSent = True\n\n if self.base_state.commandType == 1:\n self.simulated_robot.setBaseVelocity(self.base_state.commandedVel)\n elif self.base_state.commandType == 0 and not base_state.commandSent:\n base_state.commandSent = True\n self.base.setTargetPosition(self.base_state.commandedVel)\n\n ##gripper\n self.simulated_robot.setLeftGripperPosition(self.left_gripper_state.command_finger_set)\n robot_model_Q = TRINAConfig.get_klampt_model_q(self.codename,left_limb = self.left_limb_state.sensedq, right_limb = self.right_limb_state.sensedq)\n self.robot_model.setConfig(robot_model_Q)\n self._controlLoopLock.release()\n elapsedTime = time.time() - loopStartTime\n self.t = time.time() - self.startTime\n if elapsedTime < self.dt:\n time.sleep(self.dt-elapsedTime)\n else:\n pass\n #print(\"Elapsed Time:\", time.time() - loopStartTime)\n logger.info('controlThread exited.')\n print(\"motion.controlThread: exited\")\n\n #TODO: finish setting the entire robot\n def setPosition(self,q):\n \"\"\"set the position of the entire robot\n\n Parameter:\n ---------------\n q: a merged list of joint positions, in the order of torso,base,left limb, right limb, left gripper...\n \"\"\"\n #assert len(q) == 12, \"motion.setPosition(): Wrong number of dimensions of config sent\"\n #self.setLeftLimbPosition(q[0:6])\n #self.setRightLimbPosition(q[6:12])\n pass\n return\n def setLeftLimbPosition(self,q):\n \"\"\"Set the left limb joint positions, and the limb moves as fast as possible\n\n This will clear the motion queue.\n\n Parameter:\n --------------\n q: a list of 6 doubles. The desired joint positions.\n \"\"\"\n logger.debug('number of joint positions sent : %d', len(q))\n assert len(q) == 6, \"motion.setLeftLimbPosition(): Wrong number of joint positions sent\"('controlThread exited.')\n if self.left_limb_enabled:\n self._controlLoopLock.acquire()\n self._check_collision_linear_adaptive(self.robot_model,self._get_klampt_q(left_limb = self.left_limb_state.sensedq),self._get_klampt_q(left_limb = q))\n self.left_limb_state.commandSent = False\n self.left_limb_state.commandedq = deepcopy(q)\n self.left_limb_state.commandeddq = []\n self.left_limb_state.commandType = 0\n self.left_limb_state.commandQueue = False\n self.left_limb_state.difference = []\n self.left_limb_state.commandedqQueueStart = []\n self.left_limb_state.commandQueueTime = 0.0\n self.left_limb_state.commandedQueueDuration = 0.0\n self.left_limb_state.cartesianDrive = False\n self._controlLoopLock.release()\n else:\n logger.warning('Left limb not enabled')\n print(\"motion.setLeftLimbPosition():Left limb not enabled\")\n return\n\n def setRightLimbPosition(self,q):\n \"\"\"Set the right limb joint positions, and the limb moves as fast as possible\n\n This will clear the motion queue.\n\n Parameter:\n --------------\n q: a list of 6 doubles. The desired joint positions.\n \"\"\"\n logger.debug('number of joint positions sent : %d', len(q))\n assert len(q) == 6, \"motion.setLeftLimbPosition(): Wrong number of joint positions sent\"\n if self.right_limb_enabled:\n self._controlLoopLock.acquire()\n self._check_collision_linear_adaptive(self.robot_model,self._get_klampt_q(right_limb = self.right_limb_state.sensedq),self._get_klampt_q(right_limb = q))\n self.right_limb_state.commandSent = False\n self.right_limb_state.commandedq = deepcopy(q)\n self.right_limb_state.commandeddq = []\n self.right_limb_state.commandType = 0\n self.right_limb_state.commandQueue = False\n self.right_limb_state.difference = []\n self.right_limb_state.commandedqQueueStart = []\n self.right_limb_state.commandQueueTime = 0.0\n self.right_limb_state.commandedQueueDuration = 0.0\n self.right_limb_state.cartesianDrive = False\n self._controlLoopLock.release()\n else:\n logger.warning('Right limb not enabled')\n print(\"motion.setRightLimbPosition():Right limb not enabled\")\n return\n\n def setLeftLimbPositionLinear(self,q,duration):\n \"\"\"Set Left limb to moves to a configuration in a certain amount of time at constant speed\n\n Set a motion queue, this will clear the setPosition() commands\n\n Parameters:\n ----------------\n q: a list of 6 doubles. The desired joint positions.\n duration: double. The desired duration.\n \"\"\"\n logger.debug('number of joint positions sent : %d and duration is %d', len(q), duration)\n assert len(q) == 6, \"motion.setLeftLimbPositionLinear(): Wrong number of joint positions sent\"\n assert duration > 0, \"motion.setLeftLimbPositionLinear(): Duration needs to be a positive number\"\n print(q)\n #TODO:add velocity check. Maybe not be able to complete the motion within the duration\"\n #TODO:Also collision checks\n if self.left_limb_enabled:\n self._controlLoopLock.acquire()\n self._check_collision_linear_adaptive(self.robot_model,self._get_klampt_q(left_limb = self.left_limb_state.sensedq),self._get_klampt_q(left_limb = q))\n #planningTime = 0.0 + TRINAConfig.ur5e_control_rate\n #positionQueue = []\n #currentq = self.left_limb_state.sensedq\n #difference = vectorops.sub(q,currentq)\n #while planningTime < duration:\n # positionQueue.append(vectorops.add(currentq,vectorops.mul(difference,planningTime/duration)))\n # planningTime = planningTime + self.dt #TRINAConfig.ur5e_control_rate\n #positionQueue.append(q)\n self.left_limb_state.commandSent = False\n self.left_limb_state.commandType = 0\n self.left_limb_state.difference = vectorops.sub(q,self.left_limb_state.sensedq)\n self.left_limb_state.commandedqQueueStart = deepcopy(self.left_limb_state.sensedq)\n self.left_limb_state.commandQueue = True\n self.left_limb_state.commandedq = []\n self.left_limb_state.commandeddq = []\n self.left_limb_state.cartesianDrive = False\n self.left_limb_state.commandedQueueDuration = duration\n self.left_limb_state.commandQueueTime = time.time()\n self._controlLoopLock.release()\n else:\n logger.warning('Left limb not enabled')\n print(\"motion.setLeftLimbPosition():Left limb not enabled\")\n print \n\n def setRightLimbPositionLinear(self,q,duration):\n \"\"\"Set right limb to moves to a configuration in a certain amount of time at constant speed\n\n Set a motion queue, this will clear the setPosition() commands\n\n Parameters:\n ----------------\n q: a list of 6 doubles. The desired joint positions.\n duration: double. The desired duration.\n \"\"\"\n logger.debug('number of joint positions sent : %d and duration is %d', len(q), duration)\n assert len(q) == 6, \"motion.setRightLimbPositionLinear(): Wrong number of joint positions sent\"\n assert duration > 0, \"motion.setRightLimbPositionLinear(): Duration needs to be a positive number\"\n #TODO:add velocity check. Maybe not be able to complete the motion within the duration\"\n #Also collision checks\n if self.right_limb_enabled:\n self._controlLoopLock.acquire()\n self._check_collision_linear_adaptive(self.robot_model,self._get_klampt_q(right_limb = self.right_limb_state.sensedq),self._get_klampt_q(right_limb = q))\n self.right_limb_state.commandSent = False\n self.right_limb_state.commandType = 0\n self.right_limb_state.difference = vectorops.sub(q,self.right_limb_state.sensedq)\n self.right_limb_state.commandedqQueueStart = deepcopy(self.right_limb_state.sensedq)\n self.right_limb_state.commandQueue = True\n self.right_limb_state.commandedq = []\n self.right_limb_state.commandeddq = []\n self.right_limb_state.cartesianDrive = False\n self.right_limb_state.commandedQueueDuration = duration\n self.right_limb_state.commandQueueTime = time.time()\n self._controlLoopLock.release()\n else:\n logger.warning('Right limb not enabled')\n print(\"motion.setRightLimbPosition():Right limb not enabled\")\n return\n\n def sensedLeftLimbPosition(self):\n \"\"\"The current joint positions of the left limb\n\n Return:\n --------------\n A list of 6 doubles. The limb configuration.\n \"\"\"\n if self.left_limb_enabled:\n return copy(self.left_limb_state.sensedq)\n else:\n logger.warning('left limb not enabled')\n print(\"motion().sensedLeftLimbPosition: left limb not enabled\")\n return [0]*6\n\n def sensedRightLimbPosition(self):\n \"\"\"The current joint positions of the right limb\n\n Return:\n --------------\n A list of 6 doubles. The limb configuration.\n \"\"\"\n if self.right_limb_enabled:\n return copy(self.right_limb_state.sensedq)\n else:\n logger.warning('Right limb not enabled')\n print(\"motion().sensedRightLimbPosition: right limb not enabled\")\n return [0]*6\n def setVelocity(self,qdot):\n \"\"\"set the velocity of the entire robot, under development rn\n\n \"\"\"\n #assert len(qdot) == 12, \"motion.setPosition(): Wrong number of dimensions of config sent\"\n #self.setLeftLimbVelocity(qdot[0:6])\n #self.setRightLimbVelcity(qdot[6:12])\n pass\n return\n\n def setLeftLimbVelocity(self,qdot):\n \"\"\"Set the left limb joint velocities\n\n Parameter:\n ----------------\n qdot: a list of 6 doubles. Joint velocities\n \"\"\"\n if self.left_limb_enabled:\n logger.debug('number of joint velocities sent : %d', len(qdot))\n assert len(qdot) == 6, \"motion.setLeftLimbVelocity()): Wrong number of joint velocities sent\"\n self._controlLoopLock.acquire()\n self.left_limb_state.commandSent = False\n self.left_limb_state.commandeddq = deepcopy(qdot)\n self.left_limb_state.commandedq = []\n self.left_limb_state.commandType = 1\n self.left_limb_state.commandQueue = False\n self.left_limb_state.difference = []\n self.left_limb_state.commandedqQueueStart = []\n self.left_limb_state.commandQueueTime = 0.0\n self.left_limb_state.commandedQueueDuration = 0.0\n self.left_limb_state.cartesianDrive = False\n self._controlLoopLock.release()\n else:\n logger.warning('Left limb not enabled')\n print(\"Left limb not enabled\")\n\n return\n\n def setRightLimbVelocity(self,qdot):\n \"\"\"Set the right limb joint velocities\n\n Parameter:\n ----------------\n qdot: a list of 6 doubles. Joint velocities\n \"\"\"\n if self.right_limb_enabled:\n logger.debug('number of joint velocities sent : %d', len(qdot))\n assert len(qdot) == 6, \"motion.setRightLimbVelocity()): Wrong number of joint velocities sent\"\n self._controlLoopLock.acquire()\n self.right_limb_state.commandSent = False\n self.right_limb_state.commandeddq = deepcopy(qdot)\n self.right_limb_state.commandedq = []\n self.right_limb_state.commandType = 1\n self.right_limb_state.commandQueue = False\n self.right_limb_state.difference = []\n self.right_limb_state.commandedqQueueStart = []\n self.right_limb_state.commandQueueTime = 0.0\n self.right_limb_state.commandedQueueDuration = 0.0\n self.right_limb_state.cartesianDrive = False\n self._controlLoopLock.release()\n else:\n logger.warning('Right limb not enabled')\n print(\"Right limb not enabled.\")\n return\n\n def setLeftEEInertialTransform(self,Ttarget,duration):\n \"\"\"Set the trasform of the arm w.r.t. the base frame, movement complsetLeftLimbCo\n \"\"\"\n start_time = time.time()\n if self.left_limb_enabled:\n self._controlLoopLock.acquire()\n\n initial = self.robot_model.getConfig()\n #initial = [0]*3 + [0]*7 +self.left_limb_state.sensedq+[0]*11+self.right_limb_state.sensedq+[0]*10\n #self.robot_model.setConfig(initial)\n\n goal = ik.objective(self.left_EE_link,R=Ttarget[0],t = Ttarget[1])\n # solver = ik.solver(objectives = goal)\n # solver.setActiveDofs(self.left_active_Dofs)\n # result = solver.solve()\n # iterations = solver.lastSolveIters()\n if ik.solve(goal,activeDofs = self.left_active_Dofs):\n # if ik.solve_nearby(goal,maxDeviation=3,activeDofs = self.left_active_Dofs):\n #if result:\n target_config = self.robot_model.getConfig()\n logger.info('IK solve successful')\n print(\"motion.setLeftEEInertialTransform():IK solve successful\")\n else:\n self._controlLoopLock.release()\n #\"warning\"\n logger.warning('IK solve failure: no IK solution found')\n print('motion.setLeftEEInertialtransform():IK solve failure: no IK solution found')\n return 'motion.setLeftEEInertialtransform():IK solve failure: no IK solution found'\n ik_solve_time = time.time() -start_time\n # print(\"Solving IK takes\", time.time() -start_time,' and {} iterations'.format(iterations))\n start_time_2 = time.time()\n res = self._check_collision_linear_adaptive(self.robot_model,initial,target_config)\n col_check_time = time.time()-start_time_2\n # print(\"collision checking takes\", time.time() - start_time_2)\n #print(res)\n if res:\n self._controlLoopLock.release()\n logger.warning('Self-collision midway')\n print('motion.setLeftEEInertialtransform():Self-collision midway')\n return 'motion.setLeftEEInertialtransform():Self-collision midway'\n else:\n logger.info('No collision')\n print(\"motion.setLeftEEInertialTransform():No collision\")\n\n self.robot_model.setConfig(initial)\n self._controlLoopLock.release()\n start_time = time.time()\n self.setLeftLimbPositionLinear(target_config[self.left_active_Dofs[0]:self.left_active_Dofs[5]+1],duration)\n # print(\"setting linear position takes\", time.time() - start_time)\n else:\n logger.warning('Left limb not enabled')\n print(\"Left limb not enabled.\")\n return ''\n\n def setLeftEEVelocity(self,v, tool = [0,0,0]):\n \"\"\"Set the end-effect cartesian velocity, in the base frame.\n\n Implemented using position control and IK. Will keep moving until infeasible.\n TODO: implement collision detection\n\n Parameter:\n --------------\n v: A list of 6 doubled. v[0:3] is the desired cartesian position velocities and v[3:6] is the desired rotational velocity\n\n \"\"\"\n if self.left_limb_enabled:\n self._controlLoopLock.acquire()\n self.left_limb_state.commandedq = []\n self.left_limb_state.commandeddq = []\n self.left_limb_state.commandQueue = False\n self.left_limb_state.difference = []\n self.left_limb_state.commandedqQueueStart = []\n self.left_limb_state.commandQueueTime = 0.0\n self.left_limb_state.commandedQueueDuration = 0.0\n self.cartesian_drive_failure = False\n ##cartesian velocity drive\n if len(v) == 3:\n self.left_limb_state.cartesianDriveV = deepcopy(v)\n self.left_limb_state.cartesianMode = 1\n\n elif len(v) == 6:\n self.left_limb_state.cartesianDriveV = deepcopy(v[0:3])\n self.left_limb_state.cartesianDriveW = deepcopy(v[3:6])\n self.left_limb_state.cartesianMode = 0\n else:\n #error\n logger.error('wrong input')\n print(\"motion.setLeftEEVelocity(): wrong input\")\n return\n\n self.left_limb_state.cartesianDrive = True\n (R,t) = self.left_EE_link.getTransform()\n self.left_limb_state.startTransform = (R,vectorops.add(so3.apply(R,tool),t))\n self.left_limb_state.driveTransform = (R,vectorops.add(so3.apply(R,tool),t))\n self.left_limb_state.driveSpeedAdjustment = 1.0\n self.left_limb_state.toolCenter = deepcopy(tool)\n self._controlLoopLock.release()\n else:\n logger.warning('Left limb not enabled')\n print(\"Left limb not enabled.\")\n\n return ''\n\n def setRightEEInertialTransform(self,Ttarget,duration):\n \"\"\"Set the trasform of the arm w.r.t. the base frame, movement complete in a certain amount of time\n\n This current version assmumes that the torso is at zero position.\n #TODO: implement version with torso not at zero.\n\n Parameter:\n ---------------\n Ttarget: A klampt rigid transform (R,t). R is a column major form of a rotation matrix. t is a 3-element list\n duration: double. The duration of the movement\n \"\"\"\n start_time = time.time()\n\n if self.right_limb_enabled:\n self._controlLoopLock.acquire()\n initial = self.robot_model.getConfig()\n\n #initial = [0]*3 + [0]*7 +self.left_limb_state.sensedq+[0]*11+self.right_limb_state.sensedq+[0]*10\n #self.robot_model.setConfig(initial)\n\n goal = ik.objective(self.right_EE_link,R=Ttarget[0],t = Ttarget[1])\n ## this is for debugging purposes only\n # solver = ik.solver(objectives = goal)\n # solver.setActiveDofs(self.right_active_Dofs)\n # result = solver.solve()\n # ik_solve_time = time.time() -start_time\n\n # iterations = solver.lastSolveIters()\n # this is for debugging purposes only\n if ik.solve(goal,activeDofs = self.right_active_Dofs):\n #if result:\n #if ik.solve_nearby(goal,maxDeviation=3,activeDofs = self.right_active_Dofs):\n target_config = self.robot_model.getConfig()\n logger.info('IK solve successful')\n print(\"motion.setRightEEInertialTransform():IK solve successful\")\n else:\n self._controlLoopLock.release()\n logger.warning('IK solve failure: no IK solution found')\n print('motion.setRightEEInertialtransform():IK solve failure: no IK solution found')\n return 'motion.setRightEEInertialtransform():IK solve failure: no IK solution found'\n start_time_2 = time.time()\n res = self._check_collision_linear_adaptive(self.robot_model,initial,target_config)\n col_check_time = time.time()-start_time_2\n\n #print(res)\n if res:\n self._controlLoopLock.release()\n logger.warning('Self-collision midway')\n print('motion.setRighttEEInertialtransform():Self-collision midway')\n return 'motion.setRighttEEInertialtransform():Self-collision midway'\n else:\n logger.info('No collision')\n print(\"motion.setRightEEInertialTransform():No collision\")\n\n self.robot_model.setConfig(initial)\n self._controlLoopLock.release()\n self.setRightLimbPositionLinear(target_config[self.right_active_Dofs[0]:self.right_active_Dofs[5]+1],duration)\n else:\n logger.warning('Right limb not enabled')\n print(\"Right limb not enabled. \")\n return ''\n\n def setRightEEVelocity(self,v, tool = [0,0,0]):\n \"\"\"Set the end-effect cartesian velocity, in the base frame.\n\n Implemented using position control and IK. Will keep moving until infeasible.\n TODO: implement collision detection\n\n Parameter:\n --------------\n v: A list of 6 doubled. v[0:3] is the desired cartesian position velocities and v[3:6] is the desired rotational velocity\n\n \"\"\"\n if self.right_limb_enabled:\n self._controlLoopLock.acquire()\n self.right_limb_state.commandedq = []\n self.right_limb_state.commandeddq = []\n self.right_limb_state.commandQueue = False\n self.right_limb_state.difference = []\n self.right_limb_state.commandedqQueueStart = []\n self.right_limb_state.commandQueueTime = 0.0\n self.right_limb_state.commandedQueueDuration = 0.0\n self.cartesian_drive_failure = False\n ##cartesian velocity drive\n if len(v) == 3:\n self.right_limb_state.cartesianDriveV = deepcopy(v)\n self.right_limb_state.cartesianMode = 1\n\n elif len(v) == 6:\n self.right_limb_state.cartesianDriveV = deepcopy(v[0:3])\n self.right_limb_state.cartesianDriveW = deepcopy(v[3:6])\n self.right_limb_state.cartesianMode = 0\n else:\n logger.error('wrong input')\n print(\"motion.setRightEEVelocity(): wrong input\")\n return\n\n self.right_limb_state.cartesianDrive = True\n (R,t) = self.right_EE_link.getTransform()\n self.right_limb_state.startTransform = (R,vectorops.add(so3.apply(R,tool),t))\n self.right_limb_state.driveTransform = (R,vectorops.add(so3.apply(R,tool),t))\n self.right_limb_state.driveSpeedAdjustment = 1.0\n self.right_limb_state.toolCenter = deepcopy(tool)\n self._controlLoopLock.release()\n else:\n logger.warning('Right limb not enabled.')\n print(\"Right limb not enabled.\")\n return ''\n\n def sensedLeftEETransform(self):\n \"\"\"Return the transform w.r.t. the base frame\n\n Return:\n -------------\n (R,t)\n \"\"\"\n if self.left_limb_enabled:\n return self.left_EE_link.getTransform()\n else:\n logger.warning('Left limb not enabled.')\n print(\"Left limb not enabled.\")\n return\n\n def sensedLeftEEVelcocity(self,local_pt = [0,0,0]):\n \"\"\"Return the EE translational and rotational velocity w.r.t. the base DataFrame\n\n Parameter:\n ----------------\n local_pt: the local point in the EE local frame.\n\n Return:\n ----------------\n (v,w), a tuple of 2 velocity vectors\n\n \"\"\"\n if self.left_limb_enabled:\n position_J = np.array(self.left_EE_link.getJacobian(local_pt))\n q_dot = TRINAConfig.get_klampt_model_q(left_limb = self.left_limb_state.senseddq)\n EE_vel = np.dot(position_J,q_dot)\n return ([EE_vel[3],EE_vel[4],EE_vel[5]],[EE_vel[0],EE_vel[1],EE_vel[2]])\n else:\n return \"NA\"\n\n def sensedRightEETransform(self):\n \"\"\"Return the transform w.r.t. the base frame\n\n Return:\n -------------\n (R,t)\n \"\"\"\n if self.right_limb_enabled:\n return self.right_EE_link.getTransform()\n else:\n logger.warning('Right limb not enabled.')\n print(\"Right limb not enabled.\")\n return\n\n def sensedRightEEVelcocity(self,local_pt = [0,0,0]):\n \"\"\"Return the EE translational and rotational velocity w.r.t. the base DataFrame\n\n Parameter:\n ----------------\n local_pt: the local point in the EE local frame.\n\n Return:\n ----------------\n (v,w), a tuple of 2 velocity vectors\n\n \"\"\"\n if self.right_limb_enabled:\n position_J = np.array(self.right_EE_link.getJacobian(local_pt))\n q_dot = TRINAConfig.get_klampt_model_q(right_limb = self.right_limb_state.senseddq)\n EE_vel = np.dot(position_J,q_dot)\n return ([EE_vel[3],EE_vel[4],EE_vel[5]],[EE_vel[0],EE_vel[1],EE_vel[2]])\n else:\n return \"NA\"\n\n def sensedLeftLimbVelocity(self):\n \"\"\" Return the current limb joint velocities\n\n Return:\n ---------------\n A list of 6 doubles. The joint velocities.\n \"\"\"\n if self.left_limb_enabled:\n return copy(self.left_limb_state.senseddq)\n else:\n logger.warning('Left limb not enabled.')\n print(\"Left limb not enabled.\")\n return\n\n def sensedRightLimbVelocity(self):\n \"\"\" Return the current limb joint velocities\n\n Return:\n ---------------\n A list of 6 doubles. The joint velocities.\n \"\"\"\n if self.right_limb_enabled:\n return copy(self.right_limb_state.senseddq)\n else:\n logger.warning('Right limb not enabled.')\n print('Right limb not enabled.')\n return\n\n def setBaseTargetPosition(self, q, vel):\n \"\"\"Set the local target position of the base.\n\n The base constructs a path to go to the desired position, following the desired speed along the path\n Parameter:\n ---------------\n q: a list of 3 doubles. The desired x,y position and rotation.\n Vel: double. Desired speed along the path.\n \"\"\"\n if self.base_enabled:\n logger.debug('dimensions : %d', len(q))\n assert len(q) == 3, \"motion.setBaseTargetPosition(): wrong dimensions\"\n self._controlLoopLock.acquire()\n self.base_state.commandType = 0\n self.base_state.commandedTargetPosition = deepcopy(q)\n self.base_state.pathFollowingVel = vel\n self.base_state.commandSent = False\n self._controlLoopLock.release()\n else:\n logger.warning('Base not enabled.')\n print('Base not enabled.')\n\n def setBaseVelocity(self, q):\n \"\"\"Set the velocity of the base relative to the local base frame\n\n Parameter:\n ---------------\n q: a list of 2 doubles. The linear and rotational velocites.\n \"\"\"\n if self.base_enabled:\n logger.debug('dimensions : %d', len(q))\n assert len(q) == 2 ,\"motion.setBaseVelocity(): wrong dimensions\"\n self._controlLoopLock.acquire()\n self.base_state.commandType = 1\n self.base_state.commandedVel = deepcopy(q)\n self.base_state.commandSent = False\n self._controlLoopLock.release()\n else:\n logger.warning('Base not enabled.')\n print('Base not enabled.')\n\n def setTorsoTargetPosition(self, q):\n \"\"\"Set the torso target position.\n\n Moves to the target as fast as possible.\n\n Parameter:\n --------------\n q: a list of 2 doubles. The lift and tilt positions.\n \"\"\"\n if self.torso_enabled:\n logger.debug('dimensions : %d', len(q))\n assert len(q) == 2, \"motion.SetTorsoTargetPosition(): wrong dimensions\"\n height, tilt = q\n self._controlLoopLock.acquire()\n self.torso_state.commandedHeight = height\n self.torso_state.commandedTilt = tilt\n self.torso_state.commandSent = False\n self._controlLoopLock.release()\n else:\n logger.warning('Torso not enabled.')\n print('Torso not enabled.')\n\n def sensedBaseVelocity(self):\n \"\"\"Returns the current base velocity\n\n Return:\n -----------\n A list of 2 doubles. Linear and Rotational velocities.\n \"\"\"\n if self.base_enabled:\n return copy(self.base_state.measuredVel)\n else:\n logger.warning('Base not enabled.')\n print('Base not enabled')\n\n def sensedBasePosition(self):\n \"\"\"Returns the current base position. Zero position is the position when the base is started.\n\n Return:\n -------------\n A list of 3 doubles. Position and rotation.\n\n \"\"\"\n if self.base_enabled:\n return copy(self.base_state.measuredPos)\n else:\n logger.warning('Base not enabled.')\n print('Base not enabled')\n\n def sensedTorsoPosition(self):\n \"\"\"Returns the current torso position\n\n Return:\n -------------\n A list of 2 doubles. The positions.\n \"\"\"\n if self.torso_enabled:\n return copy([self.torso_state.measuredHeight, self.torso_state.measuredTilt])\n else:\n logger.warning('Torso not enabled.')\n print('Torso not enabled.')\n\n def setLeftGripperPosition(self, position):\n \"\"\"Set the position of the gripper. Moves as fast as possible.\n\n Parameters:\n -----------------\n position: a list of 4 doubles, the angles of finger 1,2 , the angle of the thumb,\n the rotation of finger 1&2 (they rotate together)\n \"\"\"\n self._controlLoopLock.acquire()\n self.left_gripper_state.commandType = 0\n self.left_gripper_state.command_finger_set = deepcopy(position)\n self._controlLoopLock.release()\n\n def setLeftGripperVelocity(self,velocity):\n \"\"\"Set the velocity of the gripper. Moves as fast as possible.\n #TODO\n ###Under development\n \"\"\"\n self.left_gripper_state.commandType = 1\n self.left_gripper_state.command_finger_set = deepcopy(velocity)\n\n def sensedLeftGripperPosition(self):\n \"\"\"Return the current positions of the fingers.\n #TODO\n ###Under development\n \"\"\"\n return copy(self.left_gripper_state.sense_finger_set)\n\n def getKlamptCommandedPosition(self):\n \"\"\"Return the entire commanded position, in Klampt format. The base returns velocity instead\n \"\"\"\n if self.left_limb_state.commandedq and self.right_limb_state.commandedq:\n return TRINAConfig.get_klampt_model_q(self.codename,left_limb = self.left_limb_state.commandedq, right_limb = self.right_limb_state.commandedq,base = self.base_state.commandedVel + [0])\n else:\n return self.getKlamptSensedPosition()\n\n def getKlamptSensedPosition(self):\n \"\"\"Return the entire sensed Klampt position, in Klampt format.\n \"\"\"\n #return TRINAConfig.get_klampt_model_q(self.codename,left_limb = self.left_limb_state.sensedq, right_limb = self.right_limb_state.sensedq,base = self.base_state.measuredPos)\n return self.robot_model.getConfig()\n def shutdown(self):\n \"\"\"Shutdown the componets.\n\n \"\"\"\n self.shut_down_flag = True\n if self.mode == \"Physical\":\n if self.base_enabled:\n self.base.shutdown()\n if self.torso_enabled:\n self.torso.shutdown()\n if self.left_limb_enabled:\n self.left_limb.stop()\n if self.right_limb_enabled:\n self.right_limb.stop()\n #TODO: integrate gripper code\n if self.left_gripper_enabled:\n self.left_gripper.shutDown()\n\n elif self.mode == \"Kinematic\":\n self.simulated_robot.shutdown()\n return 0\n\n def isStarted(self):\n \"\"\"Return whether the robot has started\n\n Return:\n ------------\n bool\n \"\"\"\n return self.startUp\n\n def isShutDown(self):\n \"\"\"Return whether the robot is shutdown\n\n Return:\n ------------\n bool\n \"\"\"\n return self.shut_down_flag\n\n def moving(self):\n \"\"\"Returns true if the robot is currently moving.\n\n Return:\n ------------\n bool\n \"\"\"\n return self.left_limb.moving() or self.right_limb.moving() or self.base.moving() or self.left_gripper.moving() or self.torso.moving()\n\n def mode(self):\n \"\"\"Returns the current mode. \"Kinematic\" or \"Physical\"\n\n Return:\n ------------\n string\n \"\"\"\n return self.mode\n\n def stopMotion(self):\n \"\"\"Pause the motion of the robot, starting from the next control loop.\n\n This is not shutdown. Just a pause.\n \"\"\"\n self.stop_motion_flag = True\n self.stop_motion_sent = False\n self._purge_commands()\n return\n\n\n\n ### ------------------------- ###\n ###current change up to here#######\n def resumeMotion(self):\n \"\"\"Unpause the robot.\n\n After unpausing, the robot is still stationery until some new commands is added\n \"\"\"\n self.base.startMotion()\n self.startMotionFlag = False\n self.left_gripper.resume()\n return\n\n def mirror_arm_config(self,config):\n \"\"\"given the Klampt config of the left or right arm, return the other\n\n Paremeters:\n ---------------\n A list of 6 doubles. Limb configuration.\n\n Return:\n ---------------\n A list of 6 doubles. Limb configuration.\n \"\"\"\n RConfig = []\n RConfig.append(-config[0])\n RConfig.append(-config[1]-math.pi)\n RConfig.append(-config[2])\n RConfig.append(-config[3]+math.pi)\n RConfig.append(-config[4])\n RConfig.append(-config[5])\n\n for ele in RConfig:\n if ele >= 2*math.pi or ele <= -2*math.pi:\n print('out of range..')\n return []\n return RConfig\n\n def getWorld(self):\n \"\"\" Return the simulated robot\n\n Return:\n -------------\n The Klampt world of the simulated robot.\n \"\"\"\n if self.mode == \"Kinematic\":\n return self.simulated_robot.getWorld()\n else:\n print(\"wrong robot mode.\")\n\n def cartesianDriveFail(self):\n \"\"\" Return if cartedian drive has failed or not\n\n Return:\n ----------------\n bool\n \"\"\"\n return self.cartesian_drive_failure\n\n\n def setRobotToDefualt(self):\n \"\"\" Some helper function when debugging\"\"\"\n leftUntuckedConfig = [-0.2028,-2.1063,-1.610,3.7165,-0.9622,0.0974]\n rightUntuckedConfig = self.mirror_arm_config(leftUntuckedConfig)\n self.setLeftLimbPositionLinear(leftUntuckedConfig,1)\n self.setRightLimbPositionLinear(rightUntuckedConfig,1)\n\n ###Below are internal helper functions\n def _purge_commands(self):\n \"\"\"Clear all the motion commands\n \"\"\"\n self._controlLoopLock.acquire()\n if self.left_limb_enabled:\n self.left_limb_state.commandedq = []\n self.left_limb_state.difference = []\n self.left_limb_state.commandedqQueueStart = []\n self.left_limb_state.commandQueueTime = 0.0\n self.left_limb_state.commandedQueueDuration = 0.0\n self.left_limb_state.commandSent = True\n self.left_limb_state.commandQueue = False\n self.left_limb_state.commandeddq = []\n self.left_limb_state.cartesianDrive = False\n if self.right_limb_enabled:\n self.right_limb_state.commandedq = []\n self.right_limb_state.difference = []\n self.right_limb_state.commandedqQueueStart = []\n self.right_limb_state.commandQueueTime = 0.0\n self.right_limb_state.commandedQueueDuration = 0.0\n self.right_limb_state.commandSent = True\n self.right_limb_state.commandQueue = False\n self.right_limb_state.commandeddq = []\n self.right_limb_state.cartesianDrive = False\n if self.base_enabled:\n self.base_state.commandedVel = [0.0, 0.0]\n self.base_state.commandedTargetPosition = [] #[x, y, theta]\n self.base_state.commandSent = True\n if self.left_gripper_enabled:\n self.left_gripper_state.command_finger_set = [0.0, 0.0, 0.0, 0.0]\n if self.torso_enabled:\n self.torso_state.commandedHeight = 0.0\n self.torso_state.commandedTilt = 0.0\n self.torso_state.commandSent = True\n self.torso_state.leftLeg = 0\n self.torso_state.rightLeg = 0\n\n self._controlLoopLock.release()\n\n def _check_collision_linear(self,robot,q1,q2,discretization):\n \"\"\" Check collision between 2 robot configurations\n\n Parameters:\n -----------------\n robot: klampt robot model\n q1: a list of 6 doubles\n q2: a list of 6 doubles\n discretization: integers, the number of collision checks\n\n Return:\n -----------------\n bool\n \"\"\"\n\n lin = np.linspace(0,1,discretization)\n initialConfig = robot.getConfig()\n diff = vectorops.sub(q2,q1)\n counter = 0\n for c in lin:\n Q=vectorops.madd(q1,diff,c)\n robot.setConfig(Q)\n collisions = self.collider.robotSelfCollisions(robot)\n colCounter = 0\n for col in collisions:\n colCounter = colCounter + 1\n if colCounter > 0:\n return True\n #add_ghosts(robot,vis,[robot.getConfig()],counter)\n counter = counter + 1\n robot.setConfig(initialConfig)\n return False\n\n def _check_collision_linear_adaptive(self,robot,q1,q2):\n \"\"\" Check collision between 2 robot configurations, but with adaptive number of collision checks\n\n Parameters:\n -----------------\n robot: klampt robot model\n q1: a list of 6 doubles\n q2: a list of 6 doubles\n\n Return:\n -----------------\n bool\n \"\"\"\n discretization = math.ceil(vectorops.distance(q1,q2)/TRINAConfig.collision_check_interval)\n #print(\"N of discretization\",discretization)\n lin = np.linspace(0,1,discretization + 1)\n initialConfig = robot.getConfig()\n diff = vectorops.sub(q2,q1)\n counter = 0\n iteration_counter = 0\n for c in lin:\n if iteration_counter > 0:\n #print('_check_collision_linear():started',c)\n Q=vectorops.madd(q1,diff,c)\n robot.setConfig(Q)\n collisions = self.collider.robotSelfCollisions(robot)\n colCounter = 0\n for col in collisions:\n colCounter = colCounter + 1\n if colCounter > 0:\n return True\n #add_ghosts(robot,vis,[robot.getConfig()],counter)\n counter = counter + 1\n else:\n iteration_counter = iteration_counter + 1\n robot.setConfig(initialConfig)\n return False\n\n def _limit_arm_position(self,config):\n \"\"\"Modify the arm configuration to be within joint position limits\n\n Parameters:\n ---------------\n config: a list of 6 doubles\n\n Return:\n ---------------\n a list of 6 doubles\n \"\"\"\n modified = []\n for i in range(6):\n if config[i] > TRINAConfig.limb_position_upper_limits[i]:\n modified.append(TRINAConfig.limb_position_upper_limits[i])\n elif config[i] < TRINAConfig.limb_position_lower_limits[i]:\n modified.append(TRINAConfig.limb_position_lower_limits[i])\n else:\n modified.append(config[i])\n return modified\n\n def _arm_is_in_limit(self,config,upper,lower):\n \"\"\"Check if the config is within the limits\n\n Parameters:\n ---------------\n Lists of same length\n\n Return:\n ---------------\n bool\n \"\"\"\n for [q,qu,ql] in zip(config,upper,lower):\n if q > qu or q < ql:\n return False\n\n return True\n\n def _left_limb_cartesian_drive(self,current_transform):\n ###TODO: robot_model config is no longer updated in the main loop ....\n\n \"\"\" Calculate the next position command for cartedian velocity drive\n\n Parameters:\n -------------\n current_transform: klampt rigid transform.\n\n Return:\n -------------\n result flag\n target_configuration, a list of 6 doubles\n\n \"\"\"\n v = self.left_limb_state.cartesianDriveV\n w = self.left_limb_state.cartesianDriveW\n amount = self.dt * self.left_limb_state.driveSpeedAdjustment\n #print(\"Before:\",self.left_limb_state.driveTransform)\n #print(v,amount,vectorops.mul(v,amount))\n target_transform = (so3.mul(so3.from_moment(vectorops.mul(w,amount)),\\\n self.left_limb_state.driveTransform[0]),vectorops.add(\\\n self.left_limb_state.driveTransform[1],vectorops.mul(v,amount)))\n\n ###debugging\n\n #print(\"After:\",self.left_limb_state.driveTransform)\n #joint position limits from the joint speed limit\n joint_upper_limits = vectorops.add(self.left_limb_state.sensedq,vectorops.mul(\\\n TRINAConfig.limb_velocity_limits,self.dt))\n joint_lower_limits = vectorops.add(self.left_limb_state.sensedq,vectorops.mul(\\\n TRINAConfig.limb_velocity_limits,-self.dt))\n if self.left_limb_state.cartesianMode == 0:\n goal = ik.objective(self.left_EE_link,R=target_transform[0],\\\n t = vectorops.sub(target_transform[1],so3.apply(target_transform[0],self.left_limb_state.toolCenter)))\n elif self.left_limb_state.cartesianMode == 1:\n goal = ik.objective(self.left_EE_link,local = [0,0,0], \\\n world = vectorops.sub(target_transform[1],so3.apply(target_transform[0],self.left_limb_state.toolCenter)))\n #elif self.left_limb_state.cartesianMode == 2:\n # goal = ik.objective(self.left_EE_link,R=target_transform[0])\n initialConfig = self.robot_model.getConfig()\n res = ik.solve_nearby(goal,maxDeviation=0.5,activeDofs = self.left_active_Dofs,tol=0.000001)\n\n # print(\"\\n\\n\\n number of iterations: \",ik.)\n failFlag = False\n if res:\n if self._arm_is_in_limit(self.robot_model.getConfig()[self.left_active_Dofs[0]:self.left_active_Dofs[5]+1],joint_upper_limits,joint_lower_limits):\n pass\n else:\n failFlag = True\n else:\n failFlag = True\n #print(\"motion.controlLoop():IK solution not found\")\n if failFlag:\n self.left_limb_state.driveSpeedAdjustment = self.left_limb_state.driveSpeedAdjustment - 0.1\n if self.left_limb_state.driveSpeedAdjustment < 0.001:\n self.left_limb_state.cartesianDrive = False\n logger.error('CartesianDrive IK has failed completely,exited..')\n print(\"motion.controlLoop():CartesianDrive IK has failed completely,exited..\")\n return 0,0 # 0 means the IK has failed completely\n else:\n #print(\"motion.controlLoop():CartesianDrive IK has failed, next trying: \",\\\n # self.left_limb_state.driveSpeedAdjustment)\n return 1,0 # 1 means the IK has failed partially and we should do this again\n else:\n target_config = self.robot_model.getConfig()[self.left_active_Dofs[0]:self.left_active_Dofs[5]+1]\n self.left_limb_state.driveTransform = target_transform\n if self.left_limb_state.driveSpeedAdjustment < 1:\n self.left_limb_state.driveSpeedAdjustment = self.left_limb_state.driveSpeedAdjustment + 0.1\n\n self.robot_model.setConfig(initialConfig)\n\n return 2,target_config #2 means success..\n\n def _right_limb_cartesian_drive(self,current_transform):\n \"\"\" Calculate the next position command for cartedian velocity drive\n\n Parameters:\n -------------\n current_transform: klampt rigid transform.\n\n Return:\n -------------\n result flag\n target_configuration, a list of 6 doubles\n\n \"\"\"\n v = self.right_limb_state.cartesianDriveV\n w = self.right_limb_state.cartesianDriveW\n amount = self.dt * self.right_limb_state.driveSpeedAdjustment\n #print(\"Before:\",self.right_limb_state.driveTransform)\n #print(v,amount,vectorops.mul(v,amount))\n target_transform = (so3.mul(so3.from_moment(vectorops.mul(w,amount)),\\\n self.right_limb_state.driveTransform[0]),vectorops.add(\\\n self.right_limb_state.driveTransform[1],vectorops.mul(v,amount)))\n #print(\"After:\",self.right_limb_state.driveTransform)\n #joint position limits from the joint speed limit\n joint_upper_limits = vectorops.add(self.right_limb_state.sensedq,vectorops.mul(\\\n TRINAConfig.limb_velocity_limits,self.dt))\n joint_lower_limits = vectorops.add(self.right_limb_state.sensedq,vectorops.mul(\\\n TRINAConfig.limb_velocity_limits,-self.dt))\n if self.right_limb_state.cartesianMode == 0:\n goal = ik.objective(self.right_EE_link,R=target_transform[0],\\\n t = vectorops.sub(target_transform[1],so3.apply(target_transform[0],self.right_limb_state.toolCenter)))\n elif self.right_limb_state.cartesianMode == 1:\n goal = ik.objective(self.right_EE_link,local = [0,0,0], \\\n world = vectorops.sub(target_transform[1],so3.apply(target_transform[0],self.right_limb_state.toolCenter)))\n\n initialConfig = self.robot_model.getConfig()\n res = ik.solve_nearby(goal,maxDeviation=0.5,activeDofs = self.right_active_Dofs,tol=0.000001)\n failFlag = False\n if res:\n if self._arm_is_in_limit(self.robot_model.getConfig()[self.right_active_Dofs[0]:self.right_active_Dofs[5]+1],joint_upper_limits,joint_lower_limits):\n pass\n else:\n failFlag = True\n else:\n failFlag = True\n #print(\"motion.controlLoop():IK solution not found\")\n if failFlag:\n self.right_limb_state.driveSpeedAdjustment = self.right_limb_state.driveSpeedAdjustment - 0.1\n if self.right_limb_state.driveSpeedAdjustment < 0.001:\n self.right_limb_state.cartesianDrive = False\n logger.error('CartesianDrive IK has failed completely,exited..')\n print(\"motion.controlLoop():CartesianDrive IK has failed completely,exited..\")\n return 0,0 # 0 means the IK has failed completely\n else:\n #print(\"motion.controlLoop():CartesianDrive IK has failed, next trying: \",\\\n # self.right_limb_state.driveSpeedAdjustment)\n return 1,0 # 1 means the IK has failed partially and we should do this again\n else:\n target_config = self.robot_model.getConfig()[self.right_active_Dofs[0]:self.right_active_Dofs[5]+1]\n self.right_limb_state.driveTransform = target_transform\n if self.right_limb_state.driveSpeedAdjustment < 1:\n self.right_limb_state.driveSpeedAdjustment = self.right_limb_state.driveSpeedAdjustment + 0.1\n\n self.robot_model.setConfig(initialConfig)\n\n return 2,target_config #2 means success..\n\n def _get_klampt_q(self,left_limb = [],right_limb = []):\n if left_limb:\n return TRINAConfig.get_klampt_model_q(self.codename,left_limb = left_limb, right_limb = self.right_limb_state.sensedq)\n elif right_limb:\n return TRINAConfig.get_klampt_model_q(self.codename,left_limb = self.left_limb_state.sensedq, right_limb = right_limb)\nif __name__==\"__main__\":\n #########Check Collision Detection Speed ###############\n #robot = Motion(mode = 'Kinematic',components = ['left_limb'],codename = \"anthrax\")\n # computation_model_path = \"data/TRINA_world_anthrax.xml\"\n # world = WorldModel()\n # res = world.readFile(computation_model_path)\n # if not res:\n # logger.error('unable to load model')\n # raise RuntimeError(\"unable to load model\")\n # #Initialize collision detection\n # collider = collide.WorldCollider(world)\n # robot_model = world.robot(0)\n\n # startTime = time.time()\n # totalN = 100\n # for i in range(totalN):\n # robot_model.randomizeConfig()\n # collisions = collider.robotSelfCollisions(robot_model)\n # colCounter = 0\n # for col in collisions:\n # colCounter = colCounter + 1\n # #if colCounter > 0:\n # #print(i,\"collision\")\n # #else:\n # #print(i)\n # print(\"average time:\", (time.time() - startTime)/float(totalN))\n ##################################\n # robot = Motion(mode = 'Kinematic',components = ['left_limb'],codename = \"anthrax\")\n # robot.startup()\n # time.sleep(0.2)\n # left_limb_q = robot.sensedLeftLimbPosition()\n # left_limb_q[2] =left_limb_q[2] + 0.01\n # robot.setLeftLimbPosition(left_limb_q)\n # time.sleep(1.2)\n # robot.shutdown()\n\n\n #################################\n robot = Motion(mode = 'Kinematic',components = ['left_limb'],codename = \"anthrax\")\n robot.startup()\n # logger.info('Robot start() called')\n # print('Robot start() called')\n time.sleep(0.2)\n leftTuckedConfig = [0.7934980392456055, -2.541288038293356, -2.7833543555, 4.664876623744629, -0.049166981373, 0.09736919403076172]\n leftUntuckedConfig = [-0.2028,-2.1063,-1.610,3.7165,-0.9622,0.0974] #motionAPI format\n rightTuckedConfig = robot.mirror_arm_config(leftTuckedConfig)\n rightUntuckedConfig = robot.mirror_arm_config(leftUntuckedConfig)\n world = robot.getWorld()\n vis.add(\"world\",world)\n vis.show()\n #move to untucked position\n robot.setLeftLimbPositionLinear(leftUntuckedConfig,5)\n robot.setRightLimbPositionLinear(rightUntuckedConfig,5)\n #robot.setLeftLimbPosition(leftUntuckedConfig)\n #robot.setRightLimbPosition(rightUntuckedConfig)\n startTime = time.time()\n \n while (time.time()-startTime < 5):\n vis.lock()\n #robot.setBaseVelocity([0.5,0.1])\n vis.unlock()\n time.sleep(0.02)\n\n robot.setRightEEVelocity([0.05,0,0,0,0.1,0])\n robot.setLeftEEVelocity([0.05,0,0,0,0.1,0])\n startTime = time.time()\n while (time.time()-startTime < 10):\n vis.lock()\n #robot.setBaseVelocity([0.5,0.1])\n vis.unlock()\n time.sleep(0.02)\n robot.shutdown()\n # print(time.time()-startTime)\n # robot.setBaseVelocity([0,0])\n # robot.setGripperPosition([1,1,1,0])\n # startTime = time.time()\n # world = robot.getWorld()\n # vis.add(\"world\",world)\n # vis.show()\n # while (time.time()-startTime < 5):\n # vis.lock()\n # #robot.setBaseVelocity([0.5,0.1])\n # vis.unlock()\n # time.sleep(0.02)\n #\n # # print(time.time()-startTime)\n # # robot.setBaseVelocity([0,0])\n # # robot.setGripperPosition([1,1,1,0])\n # # startTime = time.time()\n # # while (time.time()-startTime < 5):\n # # vis.lock()\n # # #robot.setBaseVelocity([0.5,0.1])\n # # vis.unlock()\n # # time.sleep(0.02)\n # ##cartesian drive...\n # startTime = time.time()\n # # [0.0,-0.05,0],[0,0,0]\n # robot.setLeftEEInertialTransform([[-0.06720643425243836, -0.7527169832325281, -0.6549047716766548, 0.9749095012575034, -0.18912346734793367, 0.11732283620745665, -0.2121687525365566, -0.6305869228358743, 0.7465423645978749],[0.5536765011424929, 0.10578081079393827, 0.5977151817981915]],3)\n # while (time.time()-startTime < 5):\n # vis.lock()\n # #robot.setBaseVelocity([0.5,0.1])\n # vis.unlock()\n # time.sleep(0.02)\n # try:\n # robot.getKlamptSensedPosition()\n # except:\n # print(\"except\")\n # if robot.cartesianDriveFail():\n # break\n # print(time.time()-startTime)\n #\n # vis.kill()\n\n # robot.shutdown()\n","sub_path":"Motion/motion.py","file_name":"motion.py","file_ext":"py","file_size_in_byte":83621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"613748097","text":"#!/usr/bin/env python3\nimport os\nimport sys\nfrom fenics import *\nfrom dolfin import *\nimport numpy as np\n\nsampleBeta = {}\nsampleSigma = {}\nInfectedDays = {}\nInfectedDetailed = {}\n\n\ndef model(s):\n beta_param = s[\"Parameters\"][0]\n sig = s[\"Parameters\"][1]\n sampleId = s[\"Sample Id\"]\n dev = []\n result = []\n result_detailed = []\n\n # define all needed parameters\n T = 9.0 # final time in days\n deltat = 1.0 / 10.0\n dt = Constant(deltat) # time step size at beginning\n theta_factor = Constant(1.1) # factor to represent the underreporting of movement\n beta_factor = Constant(beta_param) # infection rate\n oneoverd = Constant(1.0 / 5.0) # one over average duration of infection\n oneoverz = Constant(1.0 / 5.0) # one over average latency period\n\n theta = Constant(0.5) # theta = 0.5 means Crank-Nicolson\n t = 0.0 # global time\n area_switzerland = 41285000000.0 # area of Switzerland in square meter\n bev = 8570000.0\n\n\n # get mesh from file in folder mesh\n mesh = Mesh('mesh/mesh2d.xml.gz')\n\n # get data on commuters between cantons and write to array\n array_alpha = np.genfromtxt('shapefiles/alpha.txt')\n array_beta = np.genfromtxt('shapefiles/beta.txt')\n\n # define function space for system\n P1 = FiniteElement('P', triangle, 1)\n element = MixedElement([P1, P1, P1])\n V = FunctionSpace(mesh, element)\n W = FunctionSpace(mesh, P1)\n\n # define test functions\n v_1, v_2, v_3 = TestFunctions(V)\n\n # define used functions\n SEI_low = Function(V)\n SEI_n = Function(V)\n d = Function(V)\n source_s_n = Function(W)\n source_e_n = Function(W)\n source_i_n = Function(W)\n\n # setting Initial Conditions\n SEI_0 = Expression(('1.0',\n '0.0',\n '0.0084856 * exp(-0.00000039*(pow(x[0]-720000.0,2)+pow(x[1]-130000.0,2)))'),\n degree=2)\n SEI_n = project(SEI_0, V)\n\n # Diffusion, inverse population density and beta from files\n f1 = Function(W)\n f_in = XDMFFile(\"difffun/diff.xdmf\")\n f_in.read_checkpoint(f1, \"g\", 0)\n f1.set_allow_extrapolation(True)\n d_0 = Expression(('function',\n 'function',\n 'function'),\n function=f1, degree=2)\n d = project(d_0, V)\n\n f2 = Function(W)\n f_in = XDMFFile(\"difffun/rhoinv.xdmf\")\n f_in.read_checkpoint(f2, \"g\", 0)\n f2.set_allow_extrapolation(True)\n rhoinv_0 = Expression(('function',\n 'function',\n 'function'),\n function=f2, degree=2)\n rhoinv = project(rhoinv_0, V)\n\n f3 = Function(W)\n f_in = XDMFFile(\"difffun/beta.xdmf\")\n f_in.read_checkpoint(f3, \"g\", 0)\n f3.set_allow_extrapolation(True)\n beta = project(beta_factor * f3, W)\n\n # check diffusion, 1/rho and beta and plot S, E, I for t=0 and safe as images\n _S_0, _E_0, _I_0 = SEI_n.split()\n\n result.append(assemble(_I_0 * dx) * bev/ area_switzerland)\n result_detailed.append(assemble(_I_0 * dx) * bev/ area_switzerland)\n\n # split system functions to access components\n S_low, E_low, I_low = split(SEI_low)\n S_n, E_n, I_n = split(SEI_n)\n d_s, d_e, d_i = split(d)\n rhoinv_s, rhoinv_e, rhoinv_i = split(rhoinv)\n\n # get functions and areas to represent cantons\n cantonfun = [0.0]\n if 1 == 1:\n c1 = Function(W)\n f_in = XDMFFile(\"cantfun/01.xdmf\")\n f_in.read_checkpoint(c1, \"g\", 0)\n c1.set_allow_extrapolation(True)\n\n c2 = Function(W)\n f_in = XDMFFile(\"cantfun/02.xdmf\")\n f_in.read_checkpoint(c2, \"g\", 0)\n c2.set_allow_extrapolation(True)\n\n c3 = Function(W)\n f_in = XDMFFile(\"cantfun/03.xdmf\")\n f_in.read_checkpoint(c3, \"g\", 0)\n c3.set_allow_extrapolation(True)\n\n c4 = Function(W)\n f_in = XDMFFile(\"cantfun/04.xdmf\")\n f_in.read_checkpoint(c4, \"g\", 0)\n c4.set_allow_extrapolation(True)\n\n c5 = Function(W)\n f_in = XDMFFile(\"cantfun/05.xdmf\")\n f_in.read_checkpoint(c5, \"g\", 0)\n c5.set_allow_extrapolation(True)\n\n c6 = Function(W)\n f_in = XDMFFile(\"cantfun/06.xdmf\")\n f_in.read_checkpoint(c6, \"g\", 0)\n c6.set_allow_extrapolation(True)\n\n c7 = Function(W)\n f_in = XDMFFile(\"cantfun/07.xdmf\")\n f_in.read_checkpoint(c7, \"g\", 0)\n c7.set_allow_extrapolation(True)\n\n c8 = Function(W)\n f_in = XDMFFile(\"cantfun/08.xdmf\")\n f_in.read_checkpoint(c8, \"g\", 0)\n c8.set_allow_extrapolation(True)\n\n c9 = Function(W)\n f_in = XDMFFile(\"cantfun/09.xdmf\")\n f_in.read_checkpoint(c9, \"g\", 0)\n c9.set_allow_extrapolation(True)\n\n c10 = Function(W)\n f_in = XDMFFile(\"cantfun/10.xdmf\")\n f_in.read_checkpoint(c10, \"g\", 0)\n c10.set_allow_extrapolation(True)\n\n c11 = Function(W)\n f_in = XDMFFile(\"cantfun/11.xdmf\")\n f_in.read_checkpoint(c11, \"g\", 0)\n c11.set_allow_extrapolation(True)\n\n c12 = Function(W)\n f_in = XDMFFile(\"cantfun/12.xdmf\")\n f_in.read_checkpoint(c12, \"g\", 0)\n c12.set_allow_extrapolation(True)\n\n c13 = Function(W)\n f_in = XDMFFile(\"cantfun/13.xdmf\")\n f_in.read_checkpoint(c13, \"g\", 0)\n c13.set_allow_extrapolation(True)\n\n c14 = Function(W)\n f_in = XDMFFile(\"cantfun/14.xdmf\")\n f_in.read_checkpoint(c14, \"g\", 0)\n c14.set_allow_extrapolation(True)\n\n c15 = Function(W)\n f_in = XDMFFile(\"cantfun/15.xdmf\")\n f_in.read_checkpoint(c15, \"g\", 0)\n c15.set_allow_extrapolation(True)\n\n c16 = Function(W)\n f_in = XDMFFile(\"cantfun/16.xdmf\")\n f_in.read_checkpoint(c16, \"g\", 0)\n c16.set_allow_extrapolation(True)\n\n c17 = Function(W)\n f_in = XDMFFile(\"cantfun/17.xdmf\")\n f_in.read_checkpoint(c17, \"g\", 0)\n c17.set_allow_extrapolation(True)\n\n c18 = Function(W)\n f_in = XDMFFile(\"cantfun/18.xdmf\")\n f_in.read_checkpoint(c18, \"g\", 0)\n c18.set_allow_extrapolation(True)\n\n c19 = Function(W)\n f_in = XDMFFile(\"cantfun/19.xdmf\")\n f_in.read_checkpoint(c19, \"g\", 0)\n c19.set_allow_extrapolation(True)\n\n c20 = Function(W)\n f_in = XDMFFile(\"cantfun/20.xdmf\")\n f_in.read_checkpoint(c20, \"g\", 0)\n c20.set_allow_extrapolation(True)\n\n c21 = Function(W)\n f_in = XDMFFile(\"cantfun/21.xdmf\")\n f_in.read_checkpoint(c21, \"g\", 0)\n c21.set_allow_extrapolation(True)\n\n c22 = Function(W)\n f_in = XDMFFile(\"cantfun/22.xdmf\")\n f_in.read_checkpoint(c22, \"g\", 0)\n c22.set_allow_extrapolation(True)\n\n c23 = Function(W)\n f_in = XDMFFile(\"cantfun/23.xdmf\")\n f_in.read_checkpoint(c23, \"g\", 0)\n c23.set_allow_extrapolation(True)\n\n c24 = Function(W)\n f_in = XDMFFile(\"cantfun/24.xdmf\")\n f_in.read_checkpoint(c24, \"g\", 0)\n c24.set_allow_extrapolation(True)\n\n c25 = Function(W)\n f_in = XDMFFile(\"cantfun/25.xdmf\")\n f_in.read_checkpoint(c25, \"g\", 0)\n c25.set_allow_extrapolation(True)\n\n c26 = Function(W)\n f_in = XDMFFile(\"cantfun/26.xdmf\")\n f_in.read_checkpoint(c26, \"g\", 0)\n c26.set_allow_extrapolation(True)\n\n cantonfun.append(c1)\n cantonfun.append(c2)\n cantonfun.append(c3)\n cantonfun.append(c4)\n cantonfun.append(c5)\n cantonfun.append(c6)\n cantonfun.append(c7)\n cantonfun.append(c8)\n cantonfun.append(c9)\n cantonfun.append(c10)\n cantonfun.append(c11)\n cantonfun.append(c12)\n cantonfun.append(c13)\n cantonfun.append(c14)\n cantonfun.append(c15)\n cantonfun.append(c16)\n cantonfun.append(c17)\n cantonfun.append(c18)\n cantonfun.append(c19)\n cantonfun.append(c20)\n cantonfun.append(c21)\n cantonfun.append(c22)\n cantonfun.append(c23)\n cantonfun.append(c24)\n cantonfun.append(c25)\n cantonfun.append(c26)\n\n # Define source term for long connections\n source_s_0 = Expression('0.0', degree=2)\n source_e_0 = Expression('0.0', degree=2)\n source_i_0 = Expression('0.0', degree=2)\n\n # time stepping\n n = 0\n while t < T:\n # compute number of susceptible, exposed and infected in every canton in advance and save as array\n array_S_n = [0.0]\n array_E_n = [0.0]\n array_I_n = [0.0]\n\n array_factor_S_n = [0.0]\n array_factor_E_n = [0.0]\n array_factor_I_n = [0.0]\n\n k = 1\n while k < 27:\n array_S_n.append(Constant(assemble(S_n * cantonfun[k] * dx)))\n array_E_n.append(Constant(assemble(E_n * cantonfun[k] * dx)))\n array_I_n.append(Constant(assemble(I_n * cantonfun[k] * dx)))\n k += 1\n\n # calculate source terms for current time\n print(\"initializing sources now ...\")\n ID_KT_i = 1\n while ID_KT_i < 27:\n ID_KT_j = 1\n factor_s_n = 0.0\n factor_e_n = 0.0\n factor_i_n = 0.0\n while ID_KT_j < 27:\n index = (ID_KT_i - 1) * 26 + ID_KT_j - 1\n factor_s_n += array_alpha[index] * array_S_n[ID_KT_j] - array_beta[index] * array_S_n[ID_KT_i]\n factor_e_n += array_alpha[index] * array_E_n[ID_KT_j] - array_beta[index] * array_E_n[ID_KT_i]\n factor_i_n += array_alpha[index] * array_I_n[ID_KT_j] - array_beta[index] * array_I_n[ID_KT_i]\n\n ID_KT_j += 1\n array_factor_S_n.append(factor_s_n)\n array_factor_E_n.append(factor_e_n)\n array_factor_I_n.append(factor_i_n)\n\n ID_KT_i += 1\n\n coeff_s = array_factor_S_n\n coeff_e = array_factor_E_n\n coeff_i = array_factor_I_n\n source_s_n = project(source_s_0 + coeff_s[1] * c1 + coeff_s[2] * c2 + \\\n coeff_s[3] * c3 + coeff_s[4] * c4 + coeff_s[5] * c5 + \\\n coeff_s[6] * c6 + coeff_s[7] * c7 + coeff_s[8] * c8 + \\\n coeff_s[9] * c9 + coeff_s[10] * c10 + coeff_s[11] * c11 + \\\n coeff_s[12] * c12 + coeff_s[13] * c13 + coeff_s[14] * c14 + \\\n coeff_s[15] * c15 + coeff_s[16] * c16 + coeff_s[17] * c17 + \\\n coeff_s[18] * c18 + coeff_s[19] * c19 + coeff_s[20] * c20 + \\\n coeff_s[21] * c21 + coeff_s[22] * c22 + coeff_s[23] * c23 + \\\n coeff_s[24] * c24 + coeff_s[25] * c25 + coeff_s[26] * c26)\n\n source_e_n = project(source_e_0 + coeff_e[1] * c1 + coeff_e[2] * c2 + \\\n coeff_e[3] * c3 + coeff_e[4] * c4 + coeff_e[5] * c5 + \\\n coeff_e[6] * c6 + coeff_e[7] * c7 + coeff_e[8] * c8 + \\\n coeff_e[9] * c9 + coeff_e[10] * c10 + coeff_e[11] * c11 + \\\n coeff_e[12] * c12 + coeff_e[13] * c13 + coeff_e[14] * c14 + \\\n coeff_e[15] * c15 + coeff_e[16] * c16 + coeff_e[17] * c17 + \\\n coeff_e[18] * c18 + coeff_e[19] * c19 + coeff_e[20] * c20 + \\\n coeff_e[21] * c21 + coeff_e[22] * c22 + coeff_e[23] * c23 + \\\n coeff_e[24] * c24 + coeff_e[25] * c25 + coeff_e[26] * c26)\n\n source_i_n = project(source_i_0 + coeff_i[1] * c1 + coeff_i[2] * c2 + \\\n coeff_i[3] * c3 + coeff_i[4] * c4 + coeff_i[5] * c5 + \\\n coeff_i[6] * c6 + coeff_i[7] * c7 + coeff_i[8] * c8 + \\\n coeff_i[9] * c9 + coeff_i[10] * c10 + coeff_i[11] * c11 + \\\n coeff_i[12] * c12 + coeff_i[13] * c13 + coeff_i[14] * c14 + \\\n coeff_i[15] * c15 + coeff_i[16] * c16 + coeff_i[17] * c17 + \\\n coeff_i[18] * c18 + coeff_i[19] * c19 + coeff_i[20] * c20 + \\\n coeff_i[21] * c21 + coeff_i[22] * c22 + coeff_i[23] * c23 + \\\n coeff_i[24] * c24 + coeff_i[25] * c25 + coeff_i[26] * c26)\n\n print(\"source_n done ...\")\n\n # Define variational problem for SEI_low\n F = S_low * v_1 * dx - S_n * v_1 * dx - theta * dt * (-beta * S_low * I_low * v_1 * dx + \\\n theta_factor * (- rhoinv_s * d_s * dot(grad(S_low), grad(v_1)) * dx + rhoinv_s * source_s_n * v_1 * dx)) - \\\n (1.0 - theta) * dt * (-beta * S_n * I_n * v_1 * dx + theta_factor * (- rhoinv_s * d_s * dot(grad(S_n), grad(v_1)) * dx + rhoinv_s * source_s_n * v_1 * dx)) + \\\n E_low * v_2 * dx - E_n * v_2 * dx - theta * dt * (beta * S_low * I_low * v_2 * dx - oneoverz * E_low * v_2 * dx + \\\n theta_factor * (- rhoinv_e * d_e * dot(grad(E_low), grad(v_2)) * dx + rhoinv_e * source_e_n * v_2 * dx)) - \\\n (1.0 - theta) * dt * (beta * S_n * I_n * v_2 * dx - oneoverz * E_n * v_2 * dx + \\\n theta_factor * (- rhoinv_e * d_e * dot(grad(E_n), grad(v_2)) * dx + rhoinv_e * source_e_n * v_2 * dx)) + \\\n I_low * v_3 * dx - I_n * v_3 * dx - theta * dt * (oneoverz * E_low * v_3 * dx - oneoverd * I_low * v_3 * dx + \\\n theta_factor * (- rhoinv_i * d_i * dot(grad(I_low), grad(v_3)) * dx + rhoinv_i * source_i_n * v_3 * dx)) - \\\n (1.0 - theta) * dt * (oneoverz * E_n * v_3 * dx - oneoverd * I_n * v_3 * dx + \\\n theta_factor * (- rhoinv_i * d_i * dot(grad(I_n), grad(v_3)) * dx + rhoinv_i * source_i_n * v_3 * dx))\n\n Jac = derivative(F, SEI_low, TrialFunction(V))\n\n # solve variational problem for SEI_low\n solve(F == 0, SEI_low, J=Jac)\n\n n += 1\n t += deltat\n print(\"This is iteration number: \", n)\n print(\"And the time is: \", t)\n\n # if error small enough or minimum timestep reached, update and go to the next timestep\n _S, _E, _I = SEI_low.split()\n if n % 10 == 0:\n result.append(assemble(_I * dx) * bev / area_switzerland)\n result_detailed.append(assemble(_I * dx) * bev / area_switzerland)\n\n\n SEI_n.assign(SEI_low)\n\n for x in result:\n dev.append(sig)\n\n sampleBeta[sampleId] = beta_param\n sampleSigma[sampleId] = sig\n InfectedDays[sampleId] = result\n InfectedDetailed[sampleId] = result_detailed\n\n s[\"Beta\"] = beta_param\n s[\"Sigma\"] = sig\n s[\"InfectedPerDay\"] = result\n s[\"InfectedDetailed\"] = result_detailed\n","sub_path":"propagation/_model/work.py","file_name":"work.py","file_ext":"py","file_size_in_byte":14825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"462458041","text":"\"\"\"\r\nSchematics are simplified representations of networks, intended to explain their structure and make the way they operate\r\nunderstandable. The arcgis.schematics module contains the types and functions for working with schematic layers and\r\ndatasets.\r\n\r\n\"\"\"\r\n\r\nfrom arcgis.gis import Layer\r\n\r\n\"\"\"This class provides access to diagrams and schematic layers, as well as diagram templates.\"\"\"\r\nclass SchematicLayers(Layer):\r\n def __init__(self, url, gis=None):\r\n super(SchematicLayers, self).__init__(url, gis)\r\n try:\r\n from arcgis.gis.server._service._adminfactory import AdminServiceGen\r\n self.service = AdminServiceGen(service=self, gis=gis)\r\n except: pass\r\n\r\n @property\r\n def diagrams(self):\r\n \"\"\"\r\n The Schematic Diagrams resource represents all the schematic diagrams\r\n under a schematic service. It is returned as an array of Schematic\r\n Diagram resource by the REST API.\r\n \"\"\"\r\n params = {\"f\" : \"json\"}\r\n exportURL = self._url + \"/diagrams\"\r\n return self._con.get(path=exportURL,\r\n params=params, token=self._token)\r\n #----------------------------------------------------------------------\r\n @property\r\n def folders(self):\r\n \"\"\"\r\n The Schematic Folders resource represents the set of schematic folders\r\n in the schematic dataset(s) related to the schematic layers under a\r\n schematic service. It is returned as an array of \r\n by the REST API.\r\n \"\"\"\r\n params = {\"f\" : \"json\"}\r\n exportURL = self._url + \"/folders\"\r\n return self._con.get(path=exportURL,\r\n params=params, token=self._token)\r\n #----------------------------------------------------------------------\r\n @property\r\n def layers(self):\r\n \"\"\"\r\n The Schematic Layers resource represents all the schematic layers\r\n under a schematic service published by ArcGIS Server. It is returned\r\n as an array of Schematic Layer resources by the REST API.\r\n \"\"\"\r\n params = {\"f\" : \"json\"}\r\n exportURL = self._url + \"/schematicLayers\"\r\n return self._con.get(path=exportURL,\r\n params=params, token=self._token)\r\n #----------------------------------------------------------------------\r\n @property\r\n def templates(self):\r\n \"\"\"\r\n The Schematic Diagram Templates represents all the schematic diagram\r\n templates related to the published schematic layers under a schematic\r\n service. It is returned as an array of Schematic Diagram Template\r\n resources by the REST API.\r\n \"\"\"\r\n params = {\"f\" : \"json\"}\r\n exportURL = self._url + \"/templates\"\r\n return self._con.get(path=exportURL,\r\n params=params, token=self._token)\r\n #----------------------------------------------------------------------\r\n def search_diagrams(self,whereClause=None,relatedObjects=None,\r\n relatedSchematicObjects=None):\r\n \"\"\"\r\n The Schematic Search Diagrams operation is performed on the schematic\r\n service resource. The result of this operation is an array of Schematic\r\n Diagram Information Object.\r\n\r\n It is used to search diagrams in the schematic service by criteria;\r\n that is, diagrams filtered out via a where clause on any schematic\r\n diagram class table field, diagrams that contain schematic features\r\n associated with a specific set of GIS features/objects, or diagrams\r\n that contain schematic features associated with the same GIS features/\r\n objects related to another set of schematic features.\r\n\r\n Inputs:\r\n whereClause - A where clause for the query filter. Any legal SQL\r\n where clause operating on the fields in the schematic\r\n diagram class table is allowed. See the Schematic\r\n diagram class table fields section below to know the\r\n exact list of field names that can be used in this\r\n where clause.\r\n relatedObjects - An array containing the list of the GIS features/\r\n objects IDs per feature class/table name that are in\r\n relation with schematic features in the resulting\r\n queried diagrams. Each GIS feature/object ID\r\n corresponds to a value of the OBJECTID field in the\r\n GIS feature class/table.\r\n relatedSchematicObjects - An array containing the list of the\r\n schematic feature names per schematic\r\n feature class ID that have the same\r\n associated GIS features/objects with\r\n schematic features in the resulting\r\n queried diagrams. Each schematic feature\r\n name corresponds to a value of the\r\n SCHEMATICTID field in the schematic\r\n feature class.\r\n \"\"\"\r\n params = {\"f\" : \"json\"}\r\n if whereClause:\r\n params[\"where\"] = whereClause\r\n if relatedObjects:\r\n params[\"relatedObjects\"] = relatedObjects\r\n if relatedSchematicObjects:\r\n params[\"relatedSchematicObjects\"] = relatedSchematicObjects\r\n\r\n exportURL = self._url + \"/searchDiagrams\"\r\n return self._con.get(path=exportURL,\r\n params=params, token=self._token)","sub_path":"arcpyenv/arcgispro-py3-clone/Lib/site-packages/arcgis/schematics/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"442775961","text":"#!/usr/bin/python\n#\n# Licensed to the Software Freedom Conservancy (SFC) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The SFC licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport calendar\nimport time\nimport unittest\nimport random\nimport pytest\nfrom selenium.test.selenium.webdriver.common import utils\n\n\nclass CookieTest(unittest.TestCase):\n\n def setUp(self):\n self._loadPage(\"simpleTest\")\n # Set the cookie to expire in 30 minutes\n timestamp = calendar.timegm(time.gmtime()) + (30 * 60)\n self.COOKIE_A = {\"name\": \"foo\",\n \"value\": \"bar\",\n \"path\": \"/\",\n \"secure\": False}\n\n def tearDown(self):\n self.driver.delete_all_cookies()\n\n def testAddCookie(self):\n self.driver.execute_script(\"return document.cookie\")\n self.driver.add_cookie(self.COOKIE_A)\n cookie_returned = str(self.driver.execute_script(\"return document.cookie\"))\n self.assertTrue(self.COOKIE_A[\"name\"] in cookie_returned)\n\n def testAddingACookieThatExpiredInThePast(self):\n if self.driver.name == 'internet explorer':\n pytest.skip(\"Issue needs investigating\")\n cookie = self.COOKIE_A.copy()\n cookie[\"expiry\"] = calendar.timegm(time.gmtime()) - 1\n self.driver.add_cookie(cookie)\n cookies = self.driver.get_cookies()\n self.assertEquals(0, len(cookies))\n \n\n def testDeleteAllCookie(self):\n self.driver.add_cookie(utils.convert_cookie_to_json(self.COOKIE_A))\n self.driver.delete_all_cookies()\n self.assertFalse(self.driver.get_cookies())\n\n def testDeleteCookie(self):\n self.driver.add_cookie(utils.convert_cookie_to_json(self.COOKIE_A))\n self.driver.delete_cookie(\"foo\")\n self.assertFalse(self.driver.get_cookies())\n\n def testShouldGetCookieByName(self): \n key = \"key_%d\" % int(random.random()*10000000)\n self.driver.execute_script(\"document.cookie = arguments[0] + '=set';\", key)\n\n cookie = self.driver.get_cookie(key)\n self.assertEquals(\"set\", cookie[\"value\"])\n\n def testGetAllCookies(self):\n key1 = \"key_%d\" % int(random.random()*10000000)\n key2 = \"key_%d\" % int(random.random()*10000000)\n \n cookies = self.driver.get_cookies()\n count = len(cookies)\n \n one = {\"name\" :key1,\n \"value\": \"value\"}\n two = {\"name\":key2,\n \"value\": \"value\"}\n \n self.driver.add_cookie(one)\n self.driver.add_cookie(two)\n \n self._loadPage(\"simpleTest\")\n cookies = self.driver.get_cookies()\n self.assertEquals(count + 2, len(cookies))\n \n def testShouldNotDeleteCookiesWithASimilarName(self):\n cookieOneName = \"fish\"\n cookie1 = {\"name\" :cookieOneName,\n \"value\":\"cod\"}\n cookie2 = {\"name\" :cookieOneName + \"x\",\n \"value\": \"earth\"}\n self.driver.add_cookie(cookie1)\n self.driver.add_cookie(cookie2)\n\n self.driver.delete_cookie(cookieOneName)\n cookies = self.driver.get_cookies()\n\n self.assertFalse(cookie1[\"name\"] == cookies[0][\"name\"], msg=str(cookies))\n self.assertEquals(cookie2[\"name\"] , cookies[0][\"name\"], msg=str(cookies))\n \n\n def _loadPage(self, name):\n self.driver.get(self._pageURL(name))\n\n def _pageURL(self, name):\n return self.webserver.where_is(name + '.html')\n","sub_path":"py/test/selenium/webdriver/common/cookie_tests.py","file_name":"cookie_tests.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"634787460","text":"import math\nfrom functools import partial\n\nfrom dpipe.dl.model_controller import ModelController\nfrom dpipe.utils.batch_iter_factory import BatchIterFactory\nfrom .utils import make_find_next_lr, make_check_loss_decrease\n\n\ndef train_with_lr_decrease(\n model_controller: ModelController,\n train_batch_iter_factory: BatchIterFactory,\n val_ids, load_x, load_y, *, n_epochs, lr_init, lr_dec_mul=0.5,\n patience: int, rtol=0, atol=0):\n x_val = [load_x(p) for p in val_ids]\n y_val = [load_y(p) for p in val_ids]\n\n find_next_lr = make_find_next_lr(\n lr_init, lambda lr: lr * lr_dec_mul,\n partial(make_check_loss_decrease, patience=patience,\n rtol=rtol, atol=atol))\n\n lr = find_next_lr(math.inf)\n with train_batch_iter_factory:\n for _ in range(n_epochs):\n with next(train_batch_iter_factory) as train_batch_iter:\n train_loss = model_controller.train(train_batch_iter, lr=lr)\n y_pred, val_loss = model_controller.validate(x_val, y_val)\n lr = find_next_lr(train_loss)\n","sub_path":"dpipe/train/train_with_lr_decrease.py","file_name":"train_with_lr_decrease.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"440948488","text":"from ctypes import *\nfrom hkws.model.model import *\nimport cv2\nimport ffmpy3\nfilePath = 'D:/project/bblock/db/'\nimport numpy as np\nimport io\n\nl_lst = [1]\nhikFunc = CFUNCTYPE(\n None,\n c_long, # lRealHandle 当前的预览句柄,NET_DVR_RealPlay_V40的返回值\n c_ulong, # dwDataType 数据类型 1-系统头数据, 2-流数据(包括符合流或者音视频分开的流数据),3-音频数据,112-私有数据,包括智能信息\n POINTER(c_byte), # *pBuffer 存放数据的缓冲区指针\n c_ulong, # dwBufSize 缓冲区大小\n c_ulong, # *pUser 用户数据\n)\n\n\n@CFUNCTYPE(None, c_long, c_ulong, POINTER(c_byte), c_ulong, c_ulong)\ndef g_real_data_call_back(lRealPlayHandle: c_long,\n dwDataType: c_ulong,\n pBuffer: POINTER(c_byte),\n dwBufSize: c_ulong,\n dwUser: c_ulong):\n print(' aaaaaaaaaaa callback pBufSize is ', lRealPlayHandle, pBuffer, dwBufSize)\n print(dwDataType)\n\n\n@CFUNCTYPE(None, c_long, c_ulong, POINTER(c_byte), c_ulong, c_ulong)\ndef g_standard_data_call_back(lRealPlayHandle: c_long,\n dwDataType: c_ulong,\n pBuffer: POINTER(c_ubyte),\n dwBufSize: c_ulong,\n dwUser: c_ulong):\n print(' bbbbbbbbbbb callback pBufSize is ', lRealPlayHandle, pBuffer, dwBufSize)\n if dwDataType == 2:\n a = string_at(pBuffer, dwBufSize)\n print(a.decode())\n print(dwDataType)\n l_lst[0] = pBuffer\n\n\n\n\nalarm_stracture = CFUNCTYPE(\n c_bool,\n c_long,\n NET_DVR_ALARMER,\n NET_VCA_FACESNAP_RESULT,\n c_ulong,\n c_void_p,\n)\n\n\n@CFUNCTYPE(c_bool, c_long, POINTER(NET_DVR_ALARMER), POINTER(NET_VCA_FACESNAP_RESULT), c_ulong, c_void_p)\ndef face_alarm_call_back(lCommand: c_long,\n pAlarmer: POINTER(NET_DVR_ALARMER),\n pAlarmInfo: POINTER(NET_VCA_FACESNAP_RESULT),\n dwBufLen: c_ulong,\n pUser: c_void_p):\n print(\"lCommand \", lCommand)\n alarm_info = NET_VCA_FACESNAP_RESULT()\n memmove(pointer(alarm_info), pAlarmInfo, dwBufLen)\n print(\"是否有体温数据\", alarm_info.byAddInfo)\n if alarm_info.byAddInfo:\n face_addinfo_buff = NET_VCA_FACESNAP_ADDINFO()\n print(sizeof(NET_VCA_FACESNAP_ADDINFO))\n memmove(pointer(face_addinfo_buff), alarm_info.pAddInfoBuffer, sizeof(NET_VCA_FACESNAP_ADDINFO))\n print(\"体温为\", face_addinfo_buff.fFaceTemperature)\n len_pic = alarm_info.dwFacePicLen + 1\n print(\"人脸截图长度\", len_pic)\n print(\"图片指针为:\", alarm_info.pBuffer1)\n a = string_at(alarm_info.pBuffer1, alarm_info.dwFacePicLen)\n with open(\"test.jpg\", \"wb\") as p_file:\n p_file.write(a)\n p_file.close()\n print(type(a))\n print(\"检测到人脸\")\n return True\n","sub_path":"hkws/callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"104067111","text":"# -*- coding: utf-8 -*-\nfrom openerp.report import report_sxw\nfrom dateutil.tz import tzlocal,tzutc\nfrom datetime import datetime\n\nclass picking_slip_ext(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context):\n super(picking_slip_ext, self).__init__(cr, uid, name, context=context)\n self.localcontext.update({\n 'get_formatted_date':self.get_formatted_date,\n 'get_product_desc': self.get_product_desc,\n })\n\n def get_formatted_date(self, date):\n utcdate = datetime.strptime(date, '%Y-%m-%d %H:%M:%S').replace(tzinfo=tzutc())\n localdate = utcdate.astimezone(tzlocal()).strftime('%m/%d/%Y %H:%M:%S')\n return localdate\n\n def get_product_desc(self, move_line):\n desc = move_line.product_id.name\n if move_line.product_id.default_code:\n desc = '[' + move_line.product_id.default_code + ']' + ' ' + desc\n return desc\n\n\nreport_sxw.report_sxw('report.stock.picking.picking_slip1','stock.picking',\n 'stock_report_custom/report/report_picking_slip.rml',parser=picking_slip_ext)\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:","sub_path":"stock_report_custom/report/report_picking_slip.py","file_name":"report_picking_slip.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"330203880","text":"import asyncio\nimport aiohttp\nimport logging\n\nfrom modules import (\n websocket_echo_handler,\n notification_echo_handler\n)\nfrom modules.wss import WSSession\n\n\nasync def notification_ws_get(request):\n app = request.app\n store = request.app.notification_store\n topic = request.match_info.get('code', None)\n\n ws = aiohttp.web.WebSocketResponse()\n await ws.prepare(request)\n\n\n session = WSSession(store=store, key=topic)\n if not await session.is_exists():\n raise aiohttp.web.HTTPUnauthorized()\n\n data = await session.get_data()\n topic = data['user_id']\n await session.destroy()\n\n logging.debug('New websocket connection')\n\n if topic not in app['sockets']:\n app['sockets'][topic] = []\n task = asyncio.create_task(notification_echo_handler(store, app['sockets'][topic], topic))\n app['tasks'][topic] = task\n app['sockets'][topic].append(ws)\n\n try:\n await asyncio.gather(websocket_echo_handler(ws))\n finally:\n logging.debug('Connection closed')\n app['sockets'][topic].remove(ws)\n if len(app['sockets'][topic]) == 0:\n app['sockets'].pop(topic)\n task = app['tasks'].pop(topic)\n task.cancel()\n\n return ws\n\n\n","sub_path":"src/web_sockets/resources/notification_ws.py","file_name":"notification_ws.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"415418987","text":"import pyodbc\nimport pandas as pd\nimport re\nimport os\nfrom openpyxl import load_workbook\n\noutdir = os.path.dirname(os.path.realpath(__file__))\nissql = re.compile('.*\\.sql$') #Matches ending in .sql\n\ncnxn = pyodbc.connect('Driver={SQL Server};' # server type driver \n 'Server=;' #server \n 'DATABASE=;' #database\n 'Trusted_Connection=yes;'\n 'UID=;' #user id\n 'PWD=') #password\n\n\nwith pd.ExcelWriter(str(outdir)+'\\export.xlsx', engine='openpyxl', mode= 'a') as writer:\n writer.book = load_workbook('export.xlsx') ## this will error if does not exist need error handling for this\n for subdir, dir, files in os.walk(outdir): # search dirctory for sql scripts\n for file in files:\n if issql.match(file):\n readfile = open(file, 'r')\n df = pd.read_sql_query(readfile.read(), cnxn) ## get results\n sheet_name = str(file).replace('.sql','') ## parse the .sql for tab name\n if sheet_name in writer.book.sheetnames: ## remove if exist otherwise just write \n idx = writer.book.sheetnames.index(sheet_name)\n writer.book.remove(writer.book.worksheets[idx])\n df.to_excel(writer, sheet_name=sheet_name, index=None, header=True, startrow=3)","sub_path":"Python_Scripts/RunReportfromSQL.py","file_name":"RunReportfromSQL.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"287909577","text":"#!/usr/bin/env python\nfrom argparse import ArgumentParser\nimport subprocess\nimport os\nimport django\nos.environ['DJANGO_SETTINGS_MODULE'] = 'csa.settings'\ndjango.setup()\nfrom csa.models.user import User, UserProfile\nfrom csa.models.core import ProductCategory, ProductMeasureUnit, Product, ProductStock\n\n\ndef test_data():\n unit_kilo = ProductMeasureUnit.objects.create(name='κιλό')\n unit_matso = ProductMeasureUnit.objects.create(name='μάτσο')\n category_laxanika = ProductCategory.objects.create(name='Λαχανικά')\n ProductCategory.objects.bulk_create([\n ProductCategory(name='Φρούτα'),\n ProductCategory(name='Μεταποιημένα')\n ])\n\n ProductCategory.objects.create(\n name='Ντομάτες',\n parent=ProductCategory.objects.get(name='Λαχανικά'))\n\n password = 'p4ssw0rd'\n admin = User.objects.create_superuser(\n username='admin',\n email='csa@example.com',\n password=password,\n first_name='CSA',\n last_name='Διαχειρηστής')\n\n consumer = User.objects.create_user(\n username='consumer',\n email='consumer@example.com',\n password=password,\n first_name='Τάκης',\n last_name='Σουπερμαρκετάκης')\n UserProfile.objects.create(\n user=consumer,\n phone_number='+306976823542')\n\n producer = User.objects.create_user(\n username='producer',\n email='producer@example.com',\n password=password,\n first_name='Βάσω',\n last_name='Παρασύρη')\n UserProfile.objects.create(\n user=producer,\n phone_number='+306976823542')\n\n aggouri = Product.objects.create(\n name='Αγγούρι',\n description='Το αγγούρι είναι καρπός που προέρχεται από το έρπον και '\n 'αναρριχώμενο ετήσιο φυτό της αγγουριάς Cucumis sativus-Σικυός ο '\n 'ήμερος. Ανήκει στην οικογένεια (βιολογία) κολοκυνθοειδών όπως το πεπόνι, '\n 'το καρπούζι, το κολοκύθι. Η αγγουριά καλλιεργείται στην ύπαιθρο τους '\n 'καλοκαιρινούς μήνες και σε θερμοκήπιο τον υπόλοιπο χρόνο, λόγω της '\n 'ευαισθησίας στις χαμηλές θερμοκρασίες. Η υψηλή θερμοκρασία και υγρασία '\n 'ευνοούν την ανάπτυξή της.',\n unit=unit_kilo)\n aggouri.categories.add(category_laxanika)\n\n ProductStock.objects.create(\n product=aggouri,\n producer=producer,\n variety='Κλωσσούδι',\n description='Τα λεγόμενα αγγουράκια της Βάσως',\n quantity=10,\n price=150)\n\n\n\nparser = ArgumentParser(description='CSA database setup tool')\nparser.add_argument('--drop', action='store_true', help='drop tables')\nparser.add_argument('--init', action='store_true', help='creates tables and initialize')\nparser.add_argument('--test-data', action='store_true', help='add test data')\n\nargs = parser.parse_args()\n\nif args.drop:\n subprocess.check_call(\n './manage.py sqlflush | ./manage.py dbshell',\n shell=True)\n\nif args.init:\n for cmd in [\n './manage.py makemigrations --no-input',\n './manage.py makemigrations csa --no-input',\n './manage.py migrate --no-input'\n ]:\n subprocess.check_call(cmd, shell=True)\n\nif args.test_data:\n test_data()\n","sub_path":"bin/db-setup.py","file_name":"db-setup.py","file_ext":"py","file_size_in_byte":3641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"322944837","text":"from application import db\nfrom application.models import Movies\n\ndb.drop_all()\ndb.create_all()\n\nnew_movie = Movies(movie = \"Citizen Kane, Thriller, Orson Welles: \")\ndb.session.add(new_movie)\n\ndb.session.commit()\n","sub_path":"create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"599007499","text":"import numpy as np\nfrom pymanopt.core.problem import Problem\n\nclass SolverRBFGS:\n MaxIterations = 150\n ArmijoPromisedDecreaseScaling = 1e-4\n ArmijoStepSizeContraction = 0.7\n ArmijoInitialStepSize = 1\n ObjectiveFunctionTolerance = 1e-12\n GradientNormTolerance = 1e-8\n SE3Dimension = 6\n\n def __init__(self, problem, normalized = False):\n if not isinstance(problem, Problem):\n raise ValueError('The problem must be an instance of pymanopt.core.problem.TestCases')\n\n self._solutionSpace = problem.manifold\n self._objectiveFunction = problem.cost\n self._gradient = problem.grad\n\n self.normalized = normalized\n\n def ContinueOptimization(self, currentPoint, currentGradient, iterations):\n return (self._solutionSpace.norm(currentPoint, currentGradient) > self.GradientNormTolerance\n and self._objectiveFunction(currentPoint) > self.ObjectiveFunctionTolerance) \\\n and iterations < self.MaxIterations #before was or then and\n\n def ArmijoLineSearch(self, currentPoint, currentGradient, searchDirection):\n fCurrentPoint = self._objectiveFunction(currentPoint)\n promisedDecrease = self._solutionSpace.inner(currentPoint, currentGradient, searchDirection)\n currentStepSize = self.ArmijoInitialStepSize\n\n def armijoCondition(stepSize):\n return self._objectiveFunction(self._solutionSpace.exp(currentPoint, [stepSize * SearchDirection for SearchDirection in searchDirection])) > fCurrentPoint \\\n + stepSize * self.ArmijoPromisedDecreaseScaling * promisedDecrease\n\n while armijoCondition(currentStepSize) and currentStepSize > 1e-10:\n currentStepSize = self.ArmijoStepSizeContraction * currentStepSize\n\n return currentStepSize\n\n def SearchSolution(self, initialGuess, initialApproximateInverseHessian):\n iterations = 0\n\n currentPoint = initialGuess\n currentGradient = self._gradient(currentPoint)\n\n updateDirection = - currentGradient\n\n approximateInverseHessian = initialApproximateInverseHessian\n\n print(\"f_\" + str(iterations) + \" = \" + str(self._objectiveFunction(currentPoint)))\n print(\"|gradf_\" + str(iterations) + \"| = \" + str(self._solutionSpace.norm(currentPoint, currentGradient)))\n\n while self.ContinueOptimization(currentPoint, currentGradient, iterations):\n iterations = iterations + 1\n\n stepSize = self.ArmijoLineSearch(currentPoint, currentGradient, updateDirection)\n newPoint = self._solutionSpace.exp(currentPoint,\n [stepSize * UpdateDirection for UpdateDirection in updateDirection])\n\n previousGradient = currentGradient\n newGradient = self._gradient(newPoint)\n\n approximateInverseHessian = self.UpdateApproximateInverseHessian(\n approximateInverseHessian,\n newGradient,\n previousGradient,\n [stepSize * UpdateDirection for UpdateDirection in updateDirection])\n\n updateDirection = self.ConvertToTangentVector(\n currentPoint,\n -approximateInverseHessian @ self.ConvertToVectorInRn(newGradient))\n\n currentPoint = newPoint\n\n currentGradient = newGradient\n\n # print(\"f_\" + str(iterations) + \" = \" + str(self._objectiveFunction(currentPoint)))\n # print(\"|gradf_\" + str(iterations) + \"| = \" + str(self._solutionSpace.norm(currentPoint, currentGradient)))\n\n print(\"f_\" + str(iterations) + \" = \" + str(self._objectiveFunction(currentPoint)))\n print(\"|gradf_\" + str(iterations) + \"| = \" + str(self._solutionSpace.norm(currentPoint, currentGradient)))\n\n return tuple(currentPoint), approximateInverseHessian, iterations\n\n def UpdateApproximateInverseHessian(self,\n oldInverseHessian,\n currentGradient,\n previousGradient,\n previousSearchDirection):\n\n yk = self.ConvertToVectorInRn(currentGradient) - self.ConvertToVectorInRn(previousGradient)\n sk = self.ConvertToVectorInRn(previousSearchDirection)\n\n if self.normalized:\n metricMatrix = np.eye(int(self._solutionSpace.dim))\n else:\n metricMatrix = np.diag(np.concatenate((np.array([2., 2., 2., 1., 1., 1.]),\n np.ones(int(self._solutionSpace.dim) - self.SE3Dimension))))\n\n def inner(u, v):\n return np.inner(u, metricMatrix @ v)\n\n skTGyk = inner(sk, yk)\n\n if not skTGyk > 0:\n return oldInverseHessian\n\n intermediateScalar = inner(sk, yk) + inner(yk , oldInverseHessian @ yk)\n\n if skTGyk < 1e-11:# and np.linalg.norm(oldInverseHessian - np.eye(int(self._solutionSpace.dim))) >= 1e-14 :\n return np.eye(int(self._solutionSpace.dim))\n skTG = sk.T @ metricMatrix\n\n return oldInverseHessian \\\n + np.outer(sk, skTG) * intermediateScalar / (skTGyk * skTGyk)\\\n - (np.outer(oldInverseHessian @ yk, skTG)\n + np.outer(sk, yk.T @ metricMatrix) @ oldInverseHessian) / skTGyk\n\n def ConvertToVectorInRn(self, tangentVector):\n if self.normalized:\n return np.concatenate((self.InvSkew(tangentVector[0]) * np.sqrt(2.) , tangentVector[1], tangentVector[2]))\n else:\n return np.concatenate((self.InvSkew(tangentVector[0]), tangentVector[1], tangentVector[2]))\n\n\n def ConvertToTangentVector(self, currentPoint, vector):\n if self.normalized:\n return self._solutionSpace.proj(currentPoint, (self.Skew(vector[:3]) / np.sqrt(2.), vector[3:6], vector[6:]))\n else:\n return [self.Skew(vector[:3]), vector[3:6], vector[6:]]\n\n def Skew(self, w):\n return np.array([[0., -w[2], w[1]], [w[2], 0., -w[0]], [-w[1], w[0], 0.]])\n\n def InvSkew(self, S):\n return np.array([S[2, 1], S[0, 2], S[1, 0]])\n","sub_path":"src/Solver/SolverRBFGSPositioning.py","file_name":"SolverRBFGSPositioning.py","file_ext":"py","file_size_in_byte":6111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"293176345","text":"class match:\n def __init__(self, s_ip, d_ip):\n self.s_ip = s_ip\n self.d_ip = d_ip\n\nclass flow:\n def __init__(self, match, primary = [], secondary = [], path = [], start = None, stop = None, active = True):\n self.flow_match = match\n self.primary_path = primary\n self.secondary_path = secondary\n self.used_path = path\n self.start = start\n self.active = active\n\nclass switch:\n def __init__(self, dpid, ports = []):\n if not dpid:\n raise AssertionError(\"OpenFlowSwitch should have dpid\")\n self.dpid = dpid\n self.ports = ports # list of active ports (that have connected links)\n\nclass port:\n def __init__(self, number, n_dpid, n_port_no):\n self.number = number\n self.neighbour_dpid = n_dpid\n self.neighbour_port_no = n_port_no\n\nclass link:\n def __init__(self, sw1, port1, sw2, port2, capacity = 10485760, link_cost = 0, cur_counter = 0, prev_counter = 0, last_load = 0, first_poll = True):\n self.sw1 = sw1\n self.port1 = port1\n self.sw2 = sw2\n self.port2 = port2\n self.capacity = capacity # in Bytes, default is 10MByte per sec or 10.485.760 bytes 1Byte=8bits\n self.link_cost = link_cost # not currently used -> maybe set to ((load/10)/capacity)*100)\n self.cur_counter = cur_counter # byte counter for the current polling instance\n self.prev_counter = prev_counter # byte counter for the previous polling instance\n self.last_load=last_load # byte count measured during the last polling period\n self.first_poll = first_poll # has this link been polled before\n # self.cashed_flrmv_count=\n\ndef toSubnet(ip):\n # only for /24 subnet. Transform an IP address to its /24 subnet.\n l = ip.split('.')\n l = \".\".join(l[0:3])+'.0'\n return l\n","sub_path":"Port_FlowRemoved/MyTopoClasses.py","file_name":"MyTopoClasses.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"361486898","text":"#!/usr/bin/env python3 -B\nimport unittest\n\nfrom tests import TestKnoedlerPipelineOutput, classification_sets, classification_tree, classified_identifier_sets\nfrom cromulent import vocab\n\nvocab.add_attribute_assignment_check()\n\nclass PIRModelingTest_AR91(TestKnoedlerPipelineOutput):\n def test_modeling_ar91(self):\n '''\n AR-91: Model buyer/seller agents\n '''\n output = self.run_pipeline('ar91')\n activities = output['model-activity']\n# import json\n# print(json.dumps(activities, indent=4))\n \n # seller 'for': Clark, Jonas G.\n # selelr 'through': Goupil et Cie.\n # buyer: M. Knoedler & Co.\n tx1 = activities['tag:getty.edu,2019:digital:pipeline:REPLACE-WITH-UUID:knoedler#TX,In,1,192,6']\n self.verifyTransaction(tx1, sellers={'Clark, Jonas G.'}, seller_agents={'Goupil et Cie.'}, buyer_agents=set(), buyers={'M. Knoedler & Co.'})\n \n tx2 = activities['tag:getty.edu,2019:digital:pipeline:REPLACE-WITH-UUID:knoedler#TX,In,6,223,30']\n self.verifyTransaction(tx2, sellers={'Gill, James Dwyer'}, seller_agents={'KILTON, W.S.'}, buyer_agents=set(), buyers={'M. Knoedler & Co.'})\n \n tx3 = activities['tag:getty.edu,2019:digital:pipeline:REPLACE-WITH-UUID:knoedler#TX,In,11,195,3']\n self.verifyTransaction(tx3, sellers={'HOWARD, JEAN'}, seller_agents={'DABISH, GRACE'}, buyer_agents=set(), buyers={'M. Knoedler & Co.'})\n\n tx4 = activities['tag:getty.edu,2019:digital:pipeline:REPLACE-WITH-UUID:knoedler#TX,In,3,203,11']\n self.verifyTransaction(tx4, sellers={'Tufts, Edwin'}, seller_agents={'MATTHEWS, N.'}, buyer_agents=set(), buyers={'M. Knoedler & Co.'})\n\n tx5 = activities['tag:getty.edu,2019:digital:pipeline:REPLACE-WITH-UUID:knoedler#TX,Out,11,195,3']\n self.verifyTransaction(tx5, sellers={'M. Knoedler & Co.'}, seller_agents=set(), buyer_agents={'DABISH, GRACE'}, buyers={'HOWARD, JEAN'})\n self.verifyReturnAcquisition(tx5)\n\n def verifyReturnAcquisition(self, tx):\n # There was a bug that was causing \"Returned\" transactions to go through the ETL modeling process twice, resulting in multiple Acquisition identifiers\n # This sanity-checks that the return transaction looks right.\n acqs = [p for p in tx['part'] if p.get('type') == 'Acquisition']\n self.assertEqual(len(acqs), 1)\n acq = acqs[0]\n self.assertEqual(\n \tclassified_identifier_sets(acq),\n \t{\n \t\tNone: {'Knoedler return of Stock Number A8960 (1966-02-01)'}\n \t}\n )\n pass\n\n def verifyTransaction(self, tx, sellers, seller_agents, buyer_agents, buyers):\n payments = [p for p in tx['part'] if p.get('type') == 'Payment']\n if payments:\n payment = payments[0]\n payee = {p.get('_label') for p in payment['paid_to']}\n payer = {p.get('_label') for p in payment['paid_from']}\n self.assertEqual(payee, sellers)\n self.assertEqual(payer, buyers)\n\n acqs = [p for p in tx['part'] if p.get('type') == 'Acquisition']\n self.assertEqual(len(acqs), 1)\n acq = acqs[0]\n reciever = {p.get('_label') for p in acq['transferred_title_from']}\n sender = {p.get('_label') for p in acq['transferred_title_to']}\n self.assertEqual(sender, buyers)\n self.assertEqual(reciever, sellers)\n\n agent_parts = [p for p in acq.get('part', [])]\n agents = {p.get('_label') for part in agent_parts for p in part['carried_out_by']}\n self.assertEqual(agents, seller_agents|buyer_agents)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_knoedler_issue_ar91.py","file_name":"test_knoedler_issue_ar91.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"47163471","text":"# python 3\nimport os\nimport csv\n\n\ndef stripStr(fieldContent):\n \"\"\" remove blank spaces (right and left) \"\"\"\n return fieldContent.strip()\n\n\ndef rmComma(fieldContent):\n \"\"\" replace . by , \"\"\"\n return fieldContent.replace(\".\", \",\")\n\n\ndef rmPoint(fieldContent):\n \"\"\" replace . by - \"\"\"\n return fieldContent.replace(\".\", \"-\")\n\n\ndef numAsStr(fieldContent):\n \"\"\" to maintain the number when opening on a spreadsheet \"\"\"\n if len(fieldContent) > 0:\n return \"_\" + fieldContent\n \n return fieldContent\n\n\ndef fieldSet(fieldContent):\n \"\"\" clean numbers; ex: 1,223.3- to -1223,3 \"\"\"\n theResult = fieldContent.find(\"-\")\n fieldContent = stripStr(fieldContent)\n \n if theResult >= 0:\n fieldContent = fieldContent.replace(\"-\", \"\")\n fieldContent = \"-\" + fieldContent\n\n fieldContent = fieldContent.replace(\",\", \"\")\n return fieldContent\n\n\ndef cleanContent(outputFile, spamReader):\n \"\"\" clean and output rows \"\"\"\n try:\n for row in spamReader:\n if (len(row) > 20): # 10+ column\n theYearMonth = stripStr(row[1]) # ano/mes\n theTI = stripStr(row[3]) # ti\n\n if (theTI != \"Ti\" and theYearMonth != \"*\" and theYearMonth != \"**\"):\n theRef = stripStr(row[2]) # referencia\n theDocNum = stripStr(row[4]) # n doc\n theCI = stripStr(row[5]) # ci\n theCompany = stripStr(row[6]) # empr\n theAccount = stripStr(row[7]) # conta\n theDiv = stripStr(row[8]) # div\n theDocDate = stripStr(row[9]) # data doc\n theLauDate = stripStr(row[10]) # data lan\n theAmount = stripStr(row[11]) # montante em mi\n theCL = stripStr(row[12]) # cl\n theCC = stripStr(row[13]) # cc\n theCoin = stripStr(row[14]) # moeda\n theAtrib = stripStr(row[15]) # atribuicao\n theDoc = stripStr(row[16]) # doc compra\n theUser = stripStr(row[17]) # usuario\n theSocPar = stripStr(row[18]) # soc par\n theText = stripStr(row[19]) # texto\n theDocComp = stripStr(row[20]) # doc comp\n theComp = stripStr(row[21]) # comp\n\n theAmount = fieldSet(theAmount)\n \n theOutRow = \"\"\"\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\"\\n\"\"\".format(theYearMonth,\n theRef, theTI, theDocNum, theCI, theCompany, theAccount, theDiv, rmPoint(theDocDate), rmPoint(theLauDate),\n rmComma(theAmount), theCL, numAsStr(theCC), theCoin, theAtrib, theDoc, theUser, theSocPar, theText, theDocComp, theComp)\n\n outputFile.write(theOutRow)\n except:\n print(\"max lim\")\n\n\ndef readFile(outputFileName, inputFileName):\n outputFile = open(outputFileName, \"w\")\n outputFile.write(\"\\\"Ano/Mes\\\";\\\"Referencia\\\";\\\"Ti\\\";\\\"N doc\\\";\\\"CI\\\";\\\"Empr\\\";\\\"Conta\\\";\\\"Div\\\";\\\"Data doc\\\";\\\"Data lanc\\\";\\\"Montante\\\";\\\"CL\\\";\\\"CC\\\";\\\"Moeda\\\";\\\"Atribuicao\\\";\\\"Doc compra\\\";\\\"Usuario\\\";\\\"SocPar\\\";\\\"Texto\\\";\\\"Doc comp\\\";\\\"Comp\\\"\\n\")\n\n print(\"open: \" + inputFileName)\n inputFile = open(inputFileName)\n spamReader = csv.reader(inputFile, delimiter = \"|\", quoting = csv.QUOTE_NONE)\n cleanContent(outputFile, spamReader)\n inputFile.close()\n\n outputFile.close()\n\n\n# SAP FBL3N - not converted file\ninputFileName = \"sap.txt\"\noutputFileName = \"fbl3n_conv.csv\"\nreadFile(outputFileName, inputFileName)\n","sub_path":"Other/sap_fbl3n_drica.py","file_name":"sap_fbl3n_drica.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"326341143","text":"\"\"\"\nAuthor: Bruno Luca\nDate: 11-09-2020\nTitle: dictionary\n\"\"\"\n\ndef load_dictionary(file_name):\n d = dict()\n fin = open(file_name)\n for i,line in enumerate(fin):\n d[line.strip()] = i\n\n fin.close()\n\n return d\n\ndef main():\n words = load_dictionary(\"words.txt\")\n\n if \"dog\" in words:\n print(f\"[dog]\\t->\\t{words['dog']}\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"tpsit_IV/summer_works/es11_1.py","file_name":"es11_1.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"364244016","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport scipy.stats\nimport csv\n\nname_string = '6_010_35-65_65-85_late'\nc1 = '_40'\nc2 = '_60'\n\nres = int(name_string[2:5])\nres = float(res/1000)\n\nprint(res)\n\nx_low = int(name_string[6:8])\nif(name_string[10] == '*'):\n x_high = 100\nelse:\n x_high = int(name_string[9:11])\ny_low = int(name_string[12:14])\nif(name_string[16] == '*'):\n y_high = 100\nelse:\n y_high = int(name_string[15:17])\n\nx_low = float(x_low/100)\nx_high = float(x_high/100)\nx_high += res\ny_low = float(y_low/100)\ny_high = float(y_high/100)\ny_high += res\n\nprint(x_low)\nprint(x_high)\nprint(y_low)\nprint(y_high)\n\nx_size = round((x_high - x_low)/res)\ny_size = round((y_high - y_low)/res)\n\nprint(x_size)\nprint(y_size)\n\n\n\nwith open('avg/' + name_string + c1 + '.csv', newline='') as myFile:\n reader = csv.reader(myFile)\n reader = list(reader)\n for i in range(y_size):\n for j in range(x_size):\n reader[i][j] = float(reader[i][j])\n\nwith open('avg/' + name_string + c2 + '.csv', newline='') as myFile:\n readeric = csv.reader(myFile)\n readeric = list(readeric)\n for i in range(y_size):\n for j in range(x_size):\n readeric[i][j] = abs(float(readeric[i][j]) - reader[i][j])\n\nx = np.arange(x_low, x_high, res)\ny = np.arange(y_low, y_high, res)\nx, y = np.meshgrid(x, y)\n\n\nplt.pcolormesh(x, y, readeric)\nplt.xlabel(\"Bias\")\nplt.ylabel(\"Homophily\")\nplt.ylim([y_low,y_high-res])\nplt.colorbar() #need a colorbar to show the intensity scale\nplt.show() #boom\n","sub_path":"Oscillation_Classifier/ic_comp.py","file_name":"ic_comp.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"543680582","text":"\"\"\"six\n\nRevision ID: c01d8c37e1be\nRevises: 3024925381ed\nCreate Date: 2019-07-10 11:30:06.630940\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c01d8c37e1be'\ndown_revision = '3024925381ed'\nbranch_labels = None\ndepends_on = None\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint('fk_temp_products_id_product_products', 'temp_products', type_='foreignkey')\n op.create_foreign_key(op.f('fk_temp_products_id_products'), 'temp_products', 'products', ['id'], ['id'])\n op.drop_column('temp_products', 'id_product')\n # ### end Alembic commands ###\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('temp_products', sa.Column('id_product', sa.INTEGER(), autoincrement=False, nullable=True))\n op.drop_constraint(op.f('fk_temp_products_id_products'), 'temp_products', type_='foreignkey')\n op.create_foreign_key('fk_temp_products_id_product_products', 'temp_products', 'products', ['id_product'], ['id'])\n # ### end Alembic commands ###\n","sub_path":"pyramid_cafe/alembic/versions/20190710_c01d8c37e1be.py","file_name":"20190710_c01d8c37e1be.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"443806387","text":"# Test cases for Prospectors mapping functions in August 2020\n# created by Daan Hommersom and Antonino Sabetta at SAP\n#\n# For every function in prospector/map.py two test cases are created:\n# - The first one tests cases that should succeed\n# - The second one tests the cases for which an exception should be raised\n\nimport pytest\nimport os \nimport sys\nimport json\nimport random\nimport spacy\nnlp = spacy.load('en_core_web_sm')\n\ncurrent_working_directory = os.getcwd()\n\nos.chdir('../../prospector')\nsys.path.insert(1, '../prospector')\n\nimport rank\n\nos.chdir(current_working_directory)\n\n##################################\n###\n### FIXTURES\n###\n##################################\n\n@pytest.fixture()\ndef example_commit_content():\n example_commit_content = {\n 'message': [\"Add #795 to changelog as it's now merged\"],\n 'diff': ['diff --git a/CHANGELOG.md b/CHANGELOG.md', 'index 507498f..66834c6 100644', '--- a/CHANGELOG.md', '+++ b/CHANGELOG.md', '@@ -11,2 +11,3 @@ A pre-release can be downloaded from https://ci.jenkins.io/job/Plugins/job/docke', ' * Update terminology and reference non-deprecated image names [#802](https://github.com/jenkinsci/docker-plugin/issues/802), [#811](https://github.com/jenkinsci/docker-plugin/issues/811)', '+* Enhancement: templates can now specify cpu period and cpu quota [#795](https://github.com/jenkinsci/docker-plugin/issues/795)']\n }\n return example_commit_content\n\n##################################\n###\n### FILTERING TEXT\n###\n##################################\n\n#\n# CamelCase split \n#\n\n\n@pytest.mark.text_preprocessing\n@pytest.mark.parametrize('token, result', [\n ('ExampleCamelCase', ['ExampleCamelCase', 'example', 'camel', 'case']),\n ('exampleCamelcase', ['exampleCamelcase', 'example', 'camelcase']),\n ('shouldreturnnone', None) \n])\ndef test_camel_case_split(token, result):\n assert result == rank.camel_case_split(token)\n\n@pytest.mark.exception_handling\n@pytest.mark.parametrize('token, error', [\n (['CamelCaseToken.'], TypeError)\n])\ndef test_camel_case_split_errors(token, error):\n with pytest.raises(error):\n rank.camel_case_split(token)\n\n\n#\n# snake_case split \n#\n@pytest.mark.text_preprocessing\n@pytest.mark.parametrize('token, result', [\n ('example_snake_case', ['example_snake_case', 'example', 'snake', 'case']),\n ('shouldreturnnone', None) \n])\ndef test_snake_case_split(token, result):\n assert result == rank.snake_case_split(token)\n\n@pytest.mark.exception_handling\n@pytest.mark.parametrize('token, error', [\n (['snake_case_token'], TypeError)\n])\ndef test_snake_case_split_errors(token, error):\n with pytest.raises(error):\n rank.snake_case_split(token)\n\n#\n# text_into_chunks\n#\n\n@pytest.mark.text_preprocessing\n@pytest.mark.parametrize('text, chunk_size', [\n ('Just an example string, which should remain one sentence', 1000),\n ('Just an example string, which should not remain one sentence', 10),\n])\ndef test_text_into_chunks(text, chunk_size):\n chunks = rank.text_into_chunks(text, chunk_size)\n for chunk in chunks:\n assert len(chunk) <= chunk_size\n assert ''.join(chunks) == text\n \n@pytest.mark.text_preprocessing\ndef test_text_into_chunks_with_commit(example_commit_content):\n '''\n The function should be able to handle real commit content, where the message and diff are provided as list\n '''\n # larger text than the chunk size specified\n chunks = rank.text_into_chunks(text=example_commit_content['diff'], chunk_size=100)\n for chunk in chunks:\n assert len(chunk) <= 100\n assert len(chunks) == 6\n assert ''.join(chunks) == ' '.join(example_commit_content['diff'])\n \n # smaller text than the chunk size specified\n chunks = rank.text_into_chunks(text=example_commit_content['message'], chunk_size=100)\n assert len(chunks) == 1\n assert len(chunks[0]) == 40\n\n@pytest.mark.exception_handling\n@pytest.mark.parametrize('text, error', [\n (['Check what happens', 12345, 'When there are integers in the list'], TypeError),\n])\ndef test_text_into_chunks_errors(text, error):\n with pytest.raises(error):\n rank.text_into_chunks(text)\n\n#\n# filter_text\n#\n\n@pytest.mark.text_preprocessing\ndef test_filter_text_2():\n text = 'This is an example sentence to test the functionalities of filtered_text'\n assert rank.filter_text(text) == 'example sentence test functionality filtered_text filter text'\n assert type(rank.filter_text(text, as_tokens=True)[0]) == spacy.tokens.token.Token\n assert rank.filter_text(text, as_list=True) == ['example', 'sentence', 'test', 'functionality', 'filtered_text', 'filter', 'text']\n\n@pytest.mark.text_preprocessing\n@pytest.mark.parametrize('text, remove_duplicates, case_sensitive, lemmatize, result', [\n ('This is an example.', True, False, True, 'example'),\n ('This is an example: Example.', False, True, False, 'example Example'),\n ('This is an example. In this example, example occurs more than once.', True, False, True, 'example occur'),\n ('This is an example. In this example, example occurs more than once.', False, False, True, 'example example example occur'),\n (['This is an example.', 'In this example, example occurs more than once.'], False, False, True, 'example example example occur'),\n])\ndef test_filter_text(text, remove_duplicates, case_sensitive, lemmatize, result):\n assert result == rank.filter_text(text, as_tokens=False, as_list=False, remove_duplicates=remove_duplicates, case_sensitive=case_sensitive, lemmatize=lemmatize)\n\n#\n# filter_doc\n#\n\n@pytest.mark.text_preprocessing\ndef test_filter_doc(example_commit_content):\n '''\n The function should be able to handle real commit content, where the message and diff are provided as list\n '''\n text = ' '.join(example_commit_content['message'])\n doc = nlp(text)\n assert rank.filter_doc(doc=doc) == 'add changelog merge'\n\n@pytest.mark.exception_handling\ndef test_filter_doc_errors(example_commit_content):\n '''\n The doc provided should be a spacy.tokens.doc.Doc\n '''\n with pytest.raises(TypeError):\n rank.text_into_chunks(doc=example_commit_content['message'])\n\n#\n# simpler_filter_text\n#\n\n@pytest.mark.text_preprocessing\ndef test_simpler_filter_text(example_commit_content):\n '''\n The function should be able to handle real commit content, where the message and diff are provided as list\n '''\n assert rank.simpler_filter_text(text=example_commit_content['message']) == 'add changelog merge'\n assert rank.simpler_filter_text(text=' '.join(example_commit_content['message'])) == 'add changelog merge'\n assert rank.simpler_filter_text(text='This is an example sentence to test the functionalities of filtered_text') == 'example sentence test functionality filtered_text filter text'\n\n#\n# extract_relevant_lines_from_commit_diff\n#\n@pytest.mark.text_preprocessing\ndef test_extract_relevant_lines_from_commit_diff(example_commit_content):\n assert len(rank.extract_relevant_lines_from_commit_diff(git_diff=example_commit_content['diff'], max_lines=10000)) == 2\n assert len(rank.extract_relevant_lines_from_commit_diff(git_diff=example_commit_content['diff'], max_lines=1)) == 1\n assert rank.extract_relevant_lines_from_commit_diff(git_diff=example_commit_content['diff'])[1] == '+* Enhancement: templates can now specify cpu period and cpu quota [#795](https://github.com/jenkinsci/docker-plugin/issues/795)'\n\n@pytest.mark.exception_handling\ndef test_extract_relevant_lines_from_commit_errors(example_commit_content):\n '''\n The doc provided should be a spacy.tokens.doc.Doc\n '''\n with pytest.raises(TypeError):\n rank.extract_relevant_lines_from_commit_diff(git_diff=' '.join(example_commit_content['diff']))\n\n#\n# extract_n_most_occurring_words\n#\n\n@pytest.mark.text_preprocessing\ndef test_extract_n_most_occurring_words(example_commit_content):\n assert rank.extract_n_most_occurring_words(rank.simpler_filter_text('Messages contain fix indicating words like fixing, fix or fixes, can also contain a lot of different words. And we do not want a lot of stopwords! From this description, fix should be the returned word and and and not not not a stopword.'), n=1) == 'fix'\n assert rank.extract_n_most_occurring_words(rank.simpler_filter_text(example_commit_content['message']), n=1) == 'add'\n assert rank.extract_n_most_occurring_words(rank.simpler_filter_text(' '.join(example_commit_content['message'])), n=1) == 'add'\n\n@pytest.mark.exception_handling\n@pytest.mark.parametrize('text, error', [\n (['Check what happens', 12345, 'When there are integers in the list'], TypeError),\n])\ndef test_extract_n_most_occurring_words(text, error):\n with pytest.raises(error):\n rank.extract_n_most_occurring_words(text)\n\n#\n# find_references\n#\n\n@pytest.mark.text_preprocessing\ndef test_find_references(example_commit_content):\n assert len(rank.find_references('No reference here!')) == 0\n assert type(rank.find_references(example_commit_content['message'])) == list\n assert rank.find_references(example_commit_content['message']) == ['#795']\n assert len(rank.find_references(example_commit_content['diff'])) == 7\n assert 'https://github.com/jenkinsci/docker-plugin/issues/802' in rank.find_references(example_commit_content['diff'])\n\n# @pytest.mark.text_preprocessing\n# def test_remove_project_name():\n# project_name = 'jpcertcc LogonTracer logon tracer'\n# description = 'LogonTracer logon tracer early allow remote attacker conduct xml external entity xxe attack unspecified vector'\n# assert rank.remove_project_name_from_string(project_name, description) == 'early allow remote attacker conduct xml external entity xxe attack unspecified vector'\n\n##################################\n###\n### RANKING\n###\n##################################\n\n# @pytest.mark.ranking","sub_path":"prospector/tests/test_prospector_rank.py","file_name":"test_prospector_rank.py","file_ext":"py","file_size_in_byte":9798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"126722797","text":"# local imports\nfrom . import nxadapter\nfrom . import community\nfrom . import centrality\nfrom _NetworKit import ParallelPartitionCoarsening\nfrom .support import MissingDependencyError\n\n# external imports\ntry:\n\timport networkx\nexcept ImportError:\n\thave_nx = False\nelse:\n\thave_nx = True\n\ndef save(name, dir=\".\"):\n\t\"\"\" Save a figure \"\"\"\n\tsavefig(os.path.join(dir, \"{0}.pdf\".format(name)), bbox_inches=\"tight\", transparent=True)\n\n\ndef coloringToColorList(G, coloring):\n\tclist = []\n\n\tnColors = len(coloring.keys())\n\n\tfor v in G.nodes():\n\t\tclist.append(float(coloring[v]) / nColors)\n\n\treturn clist\n\n\ndef drawGraph(G, **kwargs):\n\t\"\"\" Draws a graph via networkX. Passes additional arguments beyond the graph to networkx.draw(...).\n\t By default, node sizes are scaled between 30 and 300 by node degree.\n\t\"\"\"\n\tif not have_nx:\n\t\traise MissingDependencyError(\"networkx\")\n\tnxG = nxadapter.nk2nx(G)\n\tif not \"node_size\" in kwargs:\n\t\tkwargs[\"node_size\"] =[30+270*s for s in centrality.DegreeCentrality(G,True).run().scores()],\n\tnetworkx.draw(nxG, **kwargs)\n\ndef drawCommunityGraph(G, zeta, **kwargs):\n\t\"\"\" Draws the community graph for a given graph and partition. Passes any additional arguments to networkx.draw(...).\n\t By default, node sizes are scaled between 30 and 500 by community size.\n\t\"\"\"\n\tif not have_nx:\n\t\traise MissingDependencyError(\"networkx\")\n\tcg = ParallelPartitionCoarsening(G,zeta)\n\tcg.run() # convert communities to nodes\n\tgraph = cg.getCoarseGraph()\n\tcomGraph = nxadapter.nk2nx(graph)\n\tif not \"node_size\" in kwargs:\n\t\tsizes = list(zeta.subsetSizeMap().values())\n\t\tmax_size = max(sizes)\n\t\tsizes = [elem/max_size for elem in sizes]\n\t\tkwargs[\"node_size\"] = [30+470*s for s in sizes]\n\tnetworkx.draw(comGraph, **kwargs)\n","sub_path":"networkit/viztasks.py","file_name":"viztasks.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"72877100","text":"import pygame\nfrom .settings import *\nfrom random import choice\n\nclass Comida():\n def __init__(self, x, y, c=RED):\n self.x = x \n self.y = y\n self.width = PIXEL_LEN\n self.height = PIXEL_LEN\n self.color = c\n\n def draw(self, win):\n pygame.draw.rect(win, self.color, (self.x * PIXEL_LEN, self.y * PIXEL_LEN + TOPBAR, self.width, self.height))\n \n def update(self, player):\n if self.x == player.x and self.y == player.y:\n player.len += 1\n self.change_place(player)\n \n def change_place(self, player):\n possible_places = [(i, j) for i in range(ROWS) for j in range(COLS)]\n possible_places.pop(possible_places.index((player.x, player.y)))\n for piece in player.cauda:\n possible_places.pop(possible_places.index((piece.x, piece.y)))\n if len(possible_places) > 0:\n self.x, self.y = choice(possible_places)\n","sub_path":"win10/utils/comida.py","file_name":"comida.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"203250038","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\nclass Solution(object):\n def get_left_boundary(self, root):\n ret = [root]\n if root.left is None:\n return ret\n cur = root.left\n while True:\n ret.append(cur)\n if cur.left:\n cur = cur.left\n elif cur.right:\n cur = cur.right\n else:\n return ret\n\n def get_right_boundary(self, root):\n ret = [root]\n if root.right is None:\n return ret\n cur = root.right\n while True:\n ret.append(cur)\n if cur.right:\n cur = cur.right\n elif cur.left:\n cur = cur.left\n else:\n return ret[::-1]\n\n def dfs(self, root, leaves):\n if root is None:\n return\n self.dfs(root.left, leaves)\n self.dfs(root.right, leaves)\n if root.left is None and root.right is None:\n leaves.append(root)\n\n def get_leaves(self, root):\n leaves = list()\n self.dfs(root, leaves)\n return leaves\n\n def boundaryOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if root is None:\n return []\n boundary = self.get_left_boundary(root) + self.get_leaves(root) + self.get_right_boundary(root)\n total = set()\n ret = list()\n for node in boundary:\n if node in total:\n continue\n total.add(node)\n ret.append(node.val)\n return ret\n\n","sub_path":"google/545_boundary_of_binary_tree.py","file_name":"545_boundary_of_binary_tree.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"17637180","text":"import RPi.GPIO as gp\nimport numpy as np\nimport time\n\npins = [10, 9, 11, 5, 6, 13, 19, 26]\ngp.setmode(gp.BCM)\ngp.setup(pins, gp.OUT)\ngp.setup(17, gp.OUT)\ngp.setup(4, gp.IN)\n\n\ndef dec_to_bin_list(val):\n out = [0] * 8\n for i in range(7, -1, -1):\n if val // 2 ** i != 0:\n out[i] = 1\n val %= 2 ** i\n return out\n\n\ndef num_dac(val):\n array = dec_to_bin_list(val)\n gp.output(pins, array)\n # print(array)\n\n\nnum_dac(0)\ngp.output(17, True)\n\ntry:\n while True:\n l = 0\n r = 255\n for i in range(9): \n m = (l + r) // 2\n num_dac(m)\n time.sleep(0.001)\n if not gp.input(4):\n r = m\n else:\n l = m\n print('Voltage: {:.1f}, digital value: {}'.format(3.3 * m /255, m))\n \n \nfinally:\n num_dac(0)\n gp.cleanup()\n","sub_path":"gpio/bins_adc.py","file_name":"bins_adc.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"140710660","text":"import discord\r\nfrom discord.ext import commands\r\nimport random\r\nimport bs4 as bs\r\nimport urllib.request\r\nfrom urllib.request import Request, urlopen\r\nimport time, threading\r\n\r\nclient = discord.Client()\r\n\r\ndescription = '''An example bot to showcase the discord.ext.commands extension\r\nmodule.\r\nThere are a number of utility commands being showcased here.'''\r\nbot = commands.Bot(command_prefix='.', description=description)\r\n\r\n@bot.command(pass_context=True)\r\nasync def delete(ctx, num):\r\n\r\n if ctx.message.author.id == '159271060582301698':\r\n channel = ctx.message.channel\r\n deleted = await bot.purge_from(channel,limit=int(num))\r\n await bot.send_message(channel, 'Deleted {} message(s)'.format(len(deleted)))\r\n else:\r\n await bot.say('You do not have the permission to use this command')\r\n\r\n\r\n@bot.event\r\nasync def on_message(message):\r\n\r\n if message.content.startswith('$guess'):\r\n await bot.send_message(message.channel, 'Guess a number between 1 to 10')\r\n\r\n def guess_check(m):\r\n return m.content.isdigit()\r\n\r\n guess = await bot.wait_for_message(timeout=5.0, author=message.author, check=guess_check)\r\n answer = random.randint(1, 10)\r\n if guess is None:\r\n fmt = 'Sorry, you took too long. It was {}.'\r\n await bot.send_message(message.channel, fmt.format(answer))\r\n return\r\n if int(guess.content) == answer:\r\n await bot.send_message(message.channel, 'You are right!')\r\n else:\r\n await bot.send_message(message.channel, 'Sorry. It is actually {}.'.format(answer))\r\n\r\n await bot.process_commands(message)\r\n\r\n\r\n \r\n@bot.event\r\nasync def on_ready():\r\n print('Logged in as')\r\n print(bot.user.name)\r\n print(bot.user.id)\r\n print('------')\r\n\r\n\r\n@bot.command()\r\nasync def ping():\r\n await bot.say('Pong!')\r\n\r\n\r\n@bot.command()\r\nasync def helpp():\r\n await bot.say('''**Commands**\\n\r\n`.subs`: Subsciber Count of Kristoffer. Updates every 5 minutes and shows what youtube.com shows\\n\r\n`.views`: Total Views Count of Kristoffer. Updates every 5 minutes and shows what youtube.com shows\\n\r\n`.helpp`: Help Message\r\n''')\r\n\r\n\r\n@bot.command()\r\nasync def subs():\r\n global final\r\n await bot.say('**{}** Glorious Subscribers'.format(final))\r\n\r\n\r\n@bot.command()\r\nasync def views():\r\n global bold\r\n await bot.say('**{}** Legendary Views'.format(bold[1].replace('.',',')))\r\n\r\n \r\nbold = []\r\nfinal = ''\r\ndef loadviews():\r\n global bold\r\n req2 = Request('https://www.youtube.com/channel/UCGQQOuwK6KDOUjLPylTM3KQ/about', headers={'User-Agent': 'Mozilla/5.0'})\r\n webpage2 = urlopen(req2).read()\r\n soup2 = bs.BeautifulSoup(webpage2,'lxml')\r\n classes = []\r\n bold = []\r\n num = 0\r\n for span in soup2.findAll('span', attrs={'class':\"about-stat\"}):\r\n num += 1\r\n if num == 1 or num == 2:\r\n btags = span.find('b')\r\n bold.append(btags.text)\r\n elif num == 3:\r\n pass\r\n threading.Timer(300, loadviews).start()\r\n\r\n\r\ndef loadsubs():\r\n global final\r\n req = Request('https://www.youtube.com/channel/UCGQQOuwK6KDOUjLPylTM3KQ', headers={'User-Agent': 'Mozilla/5.0'})\r\n webpage = urlopen(req).read()\r\n soup = bs.BeautifulSoup(webpage,'lxml')\r\n span = soup.find('span', attrs={'class':\"yt-subscription-button-subscriber-count-branded-horizontal subscribed yt-uix-tooltip\"})\r\n final = span.text.replace('.',',')\r\n threading.Timer(300, loadsubs).start()\r\n \r\nloadviews()\r\nprint('views loaded')\r\nloadsubs()\r\nprint('subs loaded')\r\n \r\n\r\nbot.run('token')\r\n","sub_path":"randomdiscord.py","file_name":"randomdiscord.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"302102102","text":"# -*- coding: utf-8 -*-\n\nimport multiprocessing\nimport time\nimport random\n\nvector_B = []\n\ndef fatorial(n):\n fat = n\n for i in range(n-1, 1, -1):\n fat = fat * i\n return(fat)\n\ndef calc_fatorial(q1, q2):\n factorial_list = q1.get()\n vector = []\n for item in factorial_list:\n factorial = fatorial(item)\n vector.append(factorial)\n q2.put(vector)\n\n\nif __name__ == \"__main__\":\n\n print('===' * 25, 'Questão 09-c'.center(75), '===' * 25, sep='\\n')\n\n vector_size = int(input(\"Entre com o tamanho do vetor(0-20): \"))\n\n start_time = float(time.time())\n\n vector_A = []\n for i in range(vector_size):\n vector_A.append(random.randint(0, 20))\n\n process_number = 4\n\n queue_in = multiprocessing.Queue()\n queue_out = multiprocessing.Queue()\n\n lista_proc = []\n for i in range(process_number):\n start = i * int(vector_size/process_number)\n end = (i + 1) * int(vector_size/process_number)\n queue_in.put(vector_A[start:end])\n m = multiprocessing.Process(target=calc_fatorial, args=(queue_in,\n queue_out))\n m.start()\n lista_proc.append(m)\n\n for m in lista_proc:\n m.join()\n\n # for i in range(0, process_number):\n # for item in queue_out.get():\n # vector_B.append(item)\n\n end_time = float(time.time())\n print('{}Tempo de multi processamento: {}'.format(' '*2, end_time - start_time))","sub_path":"questao09_c.py","file_name":"questao09_c.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"381723400","text":"#_*_ coding: utf-8 _*_\nimport MySQLdb\nimport MySQLdb.cursors\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nclass Dota2Pipeline(object):\n def __init__(self):\n self.conn = MySQLdb.connect(\n host = \"localhost\",\n user = \"root\",\n passwd = \"433280\",\n db = \"dota2\",\n charset = \"utf8\",\n use_unicode = True\n )\n self.cursor = self.conn.cursor()\n\n #加载数据钱先清空表\n self.cursor.execute(\"delete from Heros\")\n self.cursor.execute(\"delete from Skills\")\n self.cursor.execute(\"delete from Equipments\")\n self.conn.commit()\n\n\n def process_item(self, item, spider):\n\n # 加载数据钱先清空表\n # self.cursor.execute(\"delete from Heros\")\n # self.cursor.execute(\"delete from Skills\")\n # self.cursor.execute(\"delete from Equipments\")\n\n str_equipments = 'insert into Equipments ' \\\n '(HeroID,HeroNameCN,InitialEquip,EarlyEquip,CoreEquip,GodEquip) ' \\\n 'values (%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")' % \\\n (\n item[\"hero_ID\"][0],\n item[\"hero_name_cn\"][0],\n item[\"initial_equip\"][0],\n item[\"early_equip\"][0],\n item[\"core_equip\"][0],\n item[\"god_equip\"][0]\n )\n str_heros = 'insert into Heros ' \\\n '(HeroID,HeroNameCN,HeroNameEN,AttackType,Role,Camp,OtherName,' \\\n 'AttributePower,AttributeAgile,AttributeIntelligence,InitialAttack,' \\\n 'InitialArmor,InitialSpeed,VisionField,AttackField,AttackSpeed,' \\\n 'Background,Skill,CoHero,SimilarHero) ' \\\n 'values (%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")' % \\\n (\n item[\"hero_ID\"][0],\n item[\"hero_name_cn\"][0],\n item[\"hero_name_en\"][0],\n item[\"attack_type\"][0],\n item[\"role\"][0],\n item[\"camp\"][0],\n item[\"other_name\"][0],\n item[\"attribute_power\"][0],\n item[\"attribute_agile\"][0],\n item[\"attribute_intelligence\"][0],\n item[\"initial_attack\"][0],\n item[\"initial_armor\"][0],\n item[\"initial_speed\"][0],\n item[\"vision_field\"][0],\n item[\"attack_field\"][0],\n item[\"attack_speed\"][0],\n item[\"background\"][0],\n item[\"skill\"][0],\n item[\"co_hero\"][0],\n item[\"similar_hero\"][0]\n )\n str_skills = 'insert into Skills (HeroID,HeroNameCN,' \\\n 'Skill_Name_1,Skill_Describe_1,Skill_Tip_1,Skill_Magic_1,Skill_CD_1,Skill_Infos_1,Skill_Story_1,' \\\n 'Skill_Name_2,Skill_Describe_2,Skill_Tip_2,Skill_Magic_2,Skill_CD_2,Skill_Infos_2,Skill_Story_2,' \\\n 'Skill_Name_3,Skill_Describe_3,Skill_Tip_3,Skill_Magic_3,Skill_CD_3,Skill_Infos_3,Skill_Story_3,' \\\n 'Skill_Name_4,Skill_Describe_4,Skill_Tip_4,Skill_Magic_4,Skill_CD_4,Skill_Infos_4,Skill_Story_4,' \\\n 'Skill_Name_5,Skill_Describe_5,Skill_Tip_5,Skill_Magic_5,Skill_CD_5,Skill_Infos_5,Skill_Story_5,' \\\n 'Skill_Name_6,Skill_Describe_6,Skill_Tip_6,Skill_Magic_6,Skill_CD_6,Skill_Infos_6,Skill_Story_6,' \\\n 'Skill_Name_7,Skill_Describe_7,Skill_Tip_7,Skill_Magic_7,Skill_CD_7,Skill_Infos_7,Skill_Story_7,' \\\n 'Skill_Name_8,Skill_Describe_8,Skill_Tip_8,Skill_Magic_8,Skill_CD_8,Skill_Infos_8,Skill_Story_8,' \\\n 'Skill_Name_9,Skill_Describe_9,Skill_Tip_9,Skill_Magic_9,Skill_CD_9,Skill_Infos_9,Skill_Story_9,' \\\n 'Skill_Name_10,Skill_Describe_10,Skill_Tip_10,Skill_Magic_10,Skill_CD_10,Skill_Infos_10,Skill_Story_10,' \\\n 'Skill_Name_11,Skill_Describe_11,Skill_Tip_11,Skill_Magic_11,Skill_CD_11,Skill_Infos_11,Skill_Story_11,' \\\n 'Skill_Name_12,Skill_Describe_12,Skill_Tip_12,Skill_Magic_12,Skill_CD_12,Skill_Infos_12,Skill_Story_12,' \\\n 'Skill_Name_13,Skill_Describe_13,Skill_Tip_13,Skill_Magic_13,Skill_CD_13,Skill_Infos_13,Skill_Story_13,' \\\n 'Skill_Name_14,Skill_Describe_14,Skill_Tip_14,Skill_Magic_14,Skill_CD_14,Skill_Infos_14,Skill_Story_14' \\\n ') values (%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")' % \\\n (\n item[\"hero_ID\"][0],\n item[\"hero_name_cn\"][0],\n item[\"skill_name_1\"][0],\n item[\"skill_describe_1\"][0],\n item[\"skill_tip_1\"][0],\n item[\"skill_magic_1\"][0],\n item[\"skill_CD_1\"][0],\n item[\"skill_infos_1\"][0],\n item[\"skill_story_1\"][0],\n item[\"skill_name_2\"][0],\n item[\"skill_describe_2\"][0],\n item[\"skill_tip_2\"][0],\n item[\"skill_magic_2\"][0],\n item[\"skill_CD_2\"][0],\n item[\"skill_infos_2\"][0],\n item[\"skill_story_2\"][0],\n item[\"skill_name_3\"][0],\n item[\"skill_describe_3\"][0],\n item[\"skill_tip_3\"][0],\n item[\"skill_magic_3\"][0],\n item[\"skill_CD_3\"][0],\n item[\"skill_infos_3\"][0],\n item[\"skill_story_3\"][0],\n item[\"skill_name_4\"][0],\n item[\"skill_describe_4\"][0],\n item[\"skill_tip_4\"][0],\n item[\"skill_magic_4\"][0],\n item[\"skill_CD_4\"][0],\n item[\"skill_infos_4\"][0],\n item[\"skill_story_4\"][0],\n item[\"skill_name_5\"][0],\n item[\"skill_describe_5\"][0],\n item[\"skill_tip_5\"][0],\n item[\"skill_magic_5\"][0],\n item[\"skill_CD_5\"][0],\n item[\"skill_infos_5\"][0],\n item[\"skill_story_5\"][0],\n item[\"skill_name_6\"][0],\n item[\"skill_describe_6\"][0],\n item[\"skill_tip_6\"][0],\n item[\"skill_magic_6\"][0],\n item[\"skill_CD_6\"][0],\n item[\"skill_infos_6\"][0],\n item[\"skill_story_6\"][0],\n item[\"skill_name_7\"][0],\n item[\"skill_describe_7\"][0],\n item[\"skill_tip_7\"][0],\n item[\"skill_magic_7\"][0],\n item[\"skill_CD_7\"][0],\n item[\"skill_infos_7\"][0],\n item[\"skill_story_7\"][0],\n item[\"skill_name_8\"][0],\n item[\"skill_describe_8\"][0],\n item[\"skill_tip_8\"][0],\n item[\"skill_magic_8\"][0],\n item[\"skill_CD_8\"][0],\n item[\"skill_infos_8\"][0],\n item[\"skill_story_8\"][0],\n item[\"skill_name_9\"][0],\n item[\"skill_describe_9\"][0],\n item[\"skill_tip_9\"][0],\n item[\"skill_magic_9\"][0],\n item[\"skill_CD_9\"][0],\n item[\"skill_infos_9\"][0],\n item[\"skill_story_9\"][0],\n item[\"skill_name_10\"][0],\n item[\"skill_describe_10\"][0],\n item[\"skill_tip_10\"][0],\n item[\"skill_magic_10\"][0],\n item[\"skill_CD_10\"][0],\n item[\"skill_infos_10\"][0],\n item[\"skill_story_10\"][0],\n item[\"skill_name_11\"][0],\n item[\"skill_describe_11\"][0],\n item[\"skill_tip_11\"][0],\n item[\"skill_magic_11\"][0],\n item[\"skill_CD_11\"][0],\n item[\"skill_infos_11\"][0],\n item[\"skill_story_11\"][0],\n item[\"skill_name_12\"][0],\n item[\"skill_describe_12\"][0],\n item[\"skill_tip_12\"][0],\n item[\"skill_magic_12\"][0],\n item[\"skill_CD_12\"][0],\n item[\"skill_infos_12\"][0],\n item[\"skill_story_12\"][0],\n item[\"skill_name_13\"][0],\n item[\"skill_describe_13\"][0],\n item[\"skill_tip_13\"][0],\n item[\"skill_magic_13\"][0],\n item[\"skill_CD_13\"][0],\n item[\"skill_infos_13\"][0],\n item[\"skill_story_13\"][0],\n item[\"skill_name_14\"][0],\n item[\"skill_describe_14\"][0],\n item[\"skill_tip_14\"][0],\n item[\"skill_magic_14\"][0],\n item[\"skill_CD_14\"][0],\n item[\"skill_infos_14\"][0],\n item[\"skill_story_14\"][0]\n )\n\n try:\n self.cursor.execute(str_equipments)\n self.cursor.execute(str_heros)\n self.cursor.execute(str_skills)\n self.conn.commit()\n except MySQLdb.Error as err:\n print(\"Error %d : %s\" % (err.args[0],err.args[1]))\n\n return item\n","sub_path":"dota2/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":11221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"580620279","text":"import sys\nimport torch \nimport torch.nn as nn\nfrom .loss import * \nfrom .ae_loss import AELoss\n\ndef Get_loss_function(cfgs):\n \"\"\" return given loss function\n \"\"\"\n loss_fun = {}\n \n if(cfgs.Loss_set['HeatMap_type'] == 'Softmax'):\n function = nn.CrossEntropyLoss()\n loss_fun['heat_loss'] = function\n elif(cfgs.Loss_set['HeatMap_type'] =='Focal'):\n function = FocalLoss()\n loss_fun['heat_loss'] = function\n else:\n print('the function name you have entered is not supported yet')\n sys.exit()\n\n if(cfgs.Loss_set['Reg_type'] == 'SmoothL1'):\n function = SmoothL1Loss()\n loss_fun['reg_loss'] = function\n else:\n print('the function name you have entered is not supported yet')\n sys.exit()\n\n if(cfgs.Loss_set['Tag_type'] == 'AELoss'):\n function = AELoss('max')\n loss_fun['tag_loss'] = function\n else:\n print('the function name you have entered is not supported yet')\n sys.exit()\n\n if(cfgs.Loss_set['AE_type'] == 'AELoss'):\n function = AELoss('max')\n loss_fun['ae_loss'] = function\n else:\n print('the function name you have entered is not supported yet')\n sys.exit()\n\n if(cfgs.Loss_set['WH_type'] == 'SmoothL1'):\n function = SmoothL1Loss()\n loss_fun['wh_loss'] = function\n else:\n print('the function name you have entered is not supported yet')\n sys.exit()\n \n return loss_fun","sub_path":"losses/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"262804560","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns(\n 'Instanssi.main2014.views',\n url(r'^$', 'pageloader', {'templatename': 'index'}, name=\"index\"),\n\turl(r'^info/', 'pageloader', {'templatename': 'info'}, name=\"info\"),\n url(r'^english/', 'pageloader', {'templatename': 'english'}, name=\"english\"),\n url(r'^yhteystiedot/', 'pageloader', {'templatename': 'info'}, name=\"yhteystiedot\"), # Show Info page\n url(r'^kompot/', 'pageloader', {'templatename': 'kompot'}, name=\"kompot\"),\n url(r'^kilpailusopimus/', 'pageloader', {'templatename': 'kilpailusopimus'}, name=\"kilpailusopimus\"),\n)\n","sub_path":"Instanssi/main2014/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"591734648","text":"# -*- coding: utf8 -*-\n\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom logging import getLogger\nfrom pathlib import Path\nfrom typing import List\n\nfrom . import basedetector\nfrom . import mozyaml\nfrom . import python\nfrom . import retirejs\nfrom . import rust\nfrom . import thirdpartyalert\nfrom . import thirdpartypaths\nfrom ..knowledgegraph import KnowledgeGraph\n\nlogger = getLogger(__name__)\n\n\ndef __subclasses_of(cls):\n sub_classes = cls.__subclasses__()\n sub_sub_classes = []\n for sub_cls in sub_classes:\n sub_sub_classes += __subclasses_of(sub_cls)\n return sub_classes + sub_sub_classes\n\n\n__all__ = [\"run\", \"run_all\", \"all_detectors\"]\n\n# Keep a record of all DependencyDetector subclasses\nall_detectors = dict([(detector.name(), detector) for detector in __subclasses_of(basedetector.DependencyDetector)])\n# all_detector_names = sorted(list(all_detectors.keys()))\n\n\ndef run(detector: str, tree: Path, graph: KnowledgeGraph) -> bool:\n global logger\n\n try:\n current_detector = all_detectors[detector](tree, graph)\n except KeyError:\n logger.critical(f\"Unknown detector `{detector}`\")\n raise Exception(\"まさか!\")\n\n logger.debug(f\"Running `{detector}` .setup()\")\n if not current_detector.setup():\n logger.error(f\"Detector `{detector}` .setup() failed\")\n return False\n\n logger.debug(f\"Running `{detector}` .run()\")\n current_detector.run()\n logger.debug(f\"Running `{detector}` .teardown()\")\n current_detector.teardown()\n logger.debug(f\"Detector `{detector}` finished\")\n\n return True\n\n\ndef run_all(tree: Path, graph: KnowledgeGraph, *, choice: List[str] or None = None) -> bool:\n\n sorted_detectors = list(all_detectors.values())\n sorted_detectors.sort(key=lambda x: x.priority(), reverse=True)\n sorted_detector_names = [d.name() for d in sorted_detectors]\n\n if choice is None or len(choice) == 0:\n choice = sorted_detector_names\n for detector_name in choice:\n if detector_name not in sorted_detector_names:\n logger.error(f\"Ignoring unknown detector {detector_name}\")\n\n ret = True\n for detector in sorted_detectors:\n if detector.name() not in choice:\n logger.warning(f\"Not running detector {detector.name()}\")\n continue\n ret = run(detector.name(), tree, graph)\n if not ret:\n logger.critical(f\"Detector `{detector.name}` failed. Aborting\")\n break\n\n return ret\n","sub_path":"utils/mozdep/detectors/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"103638833","text":"import torch\nimport torch.nn as nn\nimport torch.utils\nimport torch.utils.data\n\nimport os\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport random\nimport datetime\nimport csv\nfrom preprocessing.calculateError import *\nfrom fileprocessor import *\n\n\n\n#torch.manual_seed(0)\n\n\n\n\n#Preprocessng\nfrom sklearn.preprocessing import MinMaxScaler\n\n\nparser = argparse.ArgumentParser(description='The Embedded Topic Model')\n\nparser.add_argument('--data_path', type=str, default='./Data/With_Features/fire.csv', help='Path where the files are located')\nparser.add_argument('--save_path', type=str, default='./Results/', help='path to save results')\nparser.add_argument('--percentage', type=float, default=0.75, metavar='TP', help='training percentage. Rest is splitted in validation and testing sets')\nparser.add_argument('--x-length', type=int, default=15, metavar='XL', help='previous time steps (default: 15)')\nparser.add_argument('--y-length', type=int, default=5, metavar='YL', help='Time steps to predict (default: 5)')\nparser.add_argument('--mini_batch', type=int, default=55, metavar='MB', help='Size of the mini_batch')\nparser.add_argument('--epochs', type=int, default=1000, metavar='XL', help='previous time steps (default: 20)')\nparser.add_argument('--input_dim', type=int, default=1, metavar='ID',help='steps to predict (default: 10)')\nparser.add_argument('--output_dim', type=int, default=1, metavar='OD', help='steps to predict (default: 10)')\nparser.add_argument('--hidden_layer', type=int, default=100, metavar='HL',help='number of hidden layers (default: 20)')\nparser.add_argument('--type_training', type=str, default='AD', metavar='TT',help='Random mini batches (RB), all data (AD), fixed mini batches (FB)')\nparser.add_argument('--learning_rate', type=float, default=0.0001, metavar='LR', help='learning rate')\nparser.add_argument('--type_rnn', type=str, default='lstm', metavar='TT',help='Random mini batches (RB), all data (AD), fixed mini batches (FB)')\nparser.add_argument('--type_actifun', type=str, default='relu', metavar='AF',help='Select the activation function to the very last layer')\n\nparser.add_argument('--bestIter', type=str, default='', metavar='BI',help='Iteration with std greater than quantile and smallest error')\nparser.add_argument('--type_group', type=str, default='law', metavar='TG',help='TypeGroup')\n\n\nclip = 0.01\n\nargs = parser.parse_args()\n\n#Setting parameters\nbestIter = args.bestIter\npercentage = args.percentage\nfile_name = args.data_path\nx_length = args.x_length\ny_length = args.y_length\nx_dim = args.input_dim\ny_dim = args.output_dim\nmini_batch_size = args.mini_batch\nepochs = args.epochs\ntype_training = args.type_training\nlearning_rate = args.learning_rate\nincident_group = args.type_group\n\n\n\n\n\n#Create windows of sequences\ndef create_inout_sequences(input_data, xw, yw):\n\t'''\n\tInput: Sequence or dataFrame of one column\n\tOutput: lists of X and list of Y\n\t'''\n\tin_seq = []\n\tout_seq = []\n\tL = len(input_data)\n\tfor i in range(L-xw-yw):\n\t\ttrain_seq = input_data[i:i+xw]\n\t\ttrain_label = input_data[i+xw:i+xw+yw]\n\t\tin_seq.append(train_seq )\n\t\tout_seq.append(train_label)\n\treturn in_seq, out_seq\n\n\n\ndef splitData(all_data, scaler):\n\n\ttrain_data_size = int(percentage*len(all_data))#431\n\tvalidation_data_size = train_data_size + int(0.5*(1-percentage)*len(all_data))\n\ttrain_data = all_data[:train_data_size]\n\tvalid_data = all_data[train_data_size : validation_data_size]\n\ttest_data = all_data[validation_data_size:]\n\t#print(len(train_data),len(valid_data), len(test_data))\n\n\n\t#Preprocessing\n\t\n\tscaler.fit(train_data.reshape(-1, 1))\n\ttrain_normalized = scaler.transform(train_data.reshape(-1, 1))\n\tvalid_normalized = scaler.transform(valid_data.reshape(-1,1))\n\ttest_normalized = scaler.transform(test_data.reshape(-1, 1))\n\n\n\t#Creating containers or pytorch variables\n\ttrain_data_normalized = torch.FloatTensor(train_normalized).view(-1)\n\tvalid_data_normalized = torch.FloatTensor(valid_normalized).view(-1)\n\ttest_data_normalized = torch.FloatTensor(test_normalized).view(-1)\n\n\n\ttrain_in, train_out = create_inout_sequences(train_data_normalized, x_length, y_length)\n\tval_in, val_out = create_inout_sequences(valid_data_normalized, x_length, y_length)\n\ttest_in, test_out = create_inout_sequences(test_data_normalized, x_length, y_length)\n\n\tsizeTrain = len(train_in) \n\tsizeTest = len(test_in)\n\tif type_training=='AD':\n\t\tmini_batch_size = sizeTrain\n\tnum_batches = int(sizeTrain/mini_batch_size) \n\n\n\tallIdx = range(sizeTrain)\n\t#Transform lists of x-y in arrays and move length to first dimension: torch.Size([len, batch_size, 1])\n\tseq_inOr_tra = torch.stack(train_in).transpose(0,1)[:,:,None]\n\tseq_outOr_tra = torch.stack(train_out).transpose(0,1)[:,:,None]\n\n\tval_size = len(val_in)\n\t#print(val_size, np.quantile(train_normalized,0.9), np.quantile(valid_normalized,0.9), np.quantile(test_normalized,0.9))\n\tseq_inOr_val = torch.stack(val_in).transpose(0,1)[:,:,None]#torch.Size([15, 1334, 1])\n\tseq_outOr_val = torch.stack(val_out).transpose(0,1)[:,:,None]\n\n\ttest_size = len(test_in)\n\tseq_inOr_tst = torch.stack(test_in).transpose(0,1)[:,:,None]#torch.Size([15, 1334, 1])\n\tseq_outOr_tst = torch.stack(test_out).transpose(0,1)[:,:,None]\n\n\treturn seq_inOr_tst, seq_outOr_tst, np.quantile(valid_normalized,0.5), test_size, np.quantile(test_normalized,0.9)\n\n\n\n\nclass RNN(nn.Module):\n\tdef __init__(self, input_size=1, output_size=1, hidden_layer_size=200, type_actifun='relu'):\n\t\tsuper().__init__()\n\t\tself.hidden_layer_size = hidden_layer_size\n\t\tself.output_size = output_size\n\t\tself.rnn = nn.RNN(input_size, hidden_layer_size)\n\n\t\tif type_actifun=='relu':\n\t\t\tself.linear = nn.Sequential(nn.Linear(hidden_layer_size, output_size), nn.ReLU())\n\t\telse:#Sigmoid\n\t\t\tself.linear = nn.Sequential(nn.Linear(hidden_layer_size, output_size), nn.Sigmoid())\n\n\tdef forward(self, input_seq, batch_size,hidden_cell, pred_length):\n\t\t#only h, not c\n\t\thidden_cell = hidden_cell[0]\n\t\tlstm_out, hidden_cell = self.rnn(input_seq.view(len(input_seq) ,batch_size, -1), hidden_cell)\n\n\t\tpredictions = self.linear(lstm_out.view(-1, self.hidden_layer_size))\n\n\t\tpredictions = predictions.reshape(len(input_seq),batch_size, self.output_size)\n\t\treturn predictions[-pred_length:]\n\n\nclass LSTM(nn.Module):\n\tdef __init__(self, input_size=1, output_size=1, hidden_layer_size=200, type_actifun='relu'):\n\t\tsuper().__init__()\n\t\tself.hidden_layer_size = hidden_layer_size\n\t\tself.output_size = output_size\n\t\tself.lstm = nn.LSTM(input_size, hidden_layer_size)\n\n\t\tself.rnnDec = nn.RNN(input_size, hidden_layer_size)\n\n\n\n\t\tif type_actifun=='relu':\n\t\t\tself.linear = nn.Sequential(nn.Linear(hidden_layer_size, output_size), nn.ReLU())\n\t\telse:#Sigmoid\n\t\t\tself.linear = nn.Sequential(nn.Linear(hidden_layer_size, output_size), nn.Sigmoid())\n\n\tdef forward(self, input_seq, batch_size,hidden_cell, pred_length):\n\t\tlstm_out, hidden_cell = self.lstm(input_seq.view(len(input_seq) ,batch_size, -1), hidden_cell)\n\n\t\tpredictions = self.linear(lstm_out.view(-1, self.hidden_layer_size))\n\n\t\tpredictions = predictions.reshape(len(input_seq),batch_size, self.output_size)\n\t\treturn predictions[-pred_length:], hidden_cell\n\n\tdef sample(self, dec_input,hidden_cellEnc, pred_length, batch_size):\n\t\tpredictions = []\n\t\t\n\t\thidden_cellDec = hidden_cellEnc[0]#h,c\n\t\tfor step in range(pred_length):\n\t\t\tlstm_outDec, hidden_cellDec = self.rnnDec(dec_input.view(1,batch_size, -1), hidden_cellDec)\n\t\t\tdec_input = self.linear(lstm_outDec)\n\t\t\tpredictions.append(dec_input)\n\n\t\treturn torch.cat(predictions[-pred_length:])\n\n\ndef testing(seq_inOr, seq_outOr, size):\n\tmodel.eval()\n\tlist_preds = []\n\tloss_test_batch = 0\n\n\t#TEST BATCH GUIDED\n\n\t####### REVIEW IF IT BATCH AND INDIVIDUAL TESTING GIVE SAME RESULTS, THEY DID\n\ttest_preds = []\n\twith torch.no_grad():\n\n\n\t\thidden = (torch.zeros(1, size, model.hidden_layer_size), torch.zeros(1, size, model.hidden_layer_size))\n\t\tpreds_batch, hiddenEnc = model(seq_inOr,size,hidden, y_length)\n\t\tpreds_batch = model.sample(seq_inOr[-1], hiddenEnc, y_length, size)\n\t\tsingle_loss = loss_function(preds_batch, seq_outOr)\n\n\t\t##### single_loss = single_loss + torch.sum(seq_outOr)\n\n\t\tloss_test_batch += single_loss\n\n\t#print(loss_test_batch)\n\t\n\t# if RMSE boxplot, make inverse scale transform first\n\tlossBoxPlot = ((preds_batch-seq_outOr) **2 ).transpose(1,0).numpy().squeeze() # sequeeze to get rid of 3rd dimension = 1\n\n\n\n\tloss_test = 0\n\t#INDIVIDUAL GUIDED\n\tfor i in range(size):\n\n\t\ttest_preds = []\n\t\twith torch.no_grad():\n\n\n\t\t\thidden = (torch.zeros(1, 1, model.hidden_layer_size), torch.zeros(1, 1, model.hidden_layer_size))\n\n\t\t\tpreds, hiddenEnc =model(seq_inOr[:,i,:],1,hidden, y_length)\n\t\t\tpreds = model.sample(seq_inOr[-1,i,:], hiddenEnc, y_length, 1)\n\n\t\t\t#preds=model(seq_in,1,hiddien, y_length)\n\t\t\tsingle_loss = loss_function(preds, seq_outOr[:,i,:,None])\n\t\t\t\n\t\t\t##### single_loss = single_loss + torch.sum(seq_outOr)\n\n\n\t\t\tloss_test += single_loss\n\n\t\t#Adding as many lists as steps\n\t\tfor step in range(y_length):\n\t\t\ttest_preds.append(preds[step].detach().numpy().reshape((y_dim)))\n\n\t\tlist_preds.append(test_preds)\n\n\tpredsMetric = np.transpose(np.asarray(list_preds),[1,0,2])\n\n\n\t#### CALCULATING MAE, MSE TO SAVE THEM TO FILE\n\tpred_test_save = scaler.inverse_transform(predsMetric.squeeze().reshape(-1,1))#to flat the data\n\tpred_test_save= pred_test_save.reshape(y_length,-1).transpose(1,0)#to recover shape length,size -> size, lenght\n\treal_test_save = scaler.inverse_transform(seq_outOr.squeeze().detach().numpy().reshape(-1,1))\n\treal_test_save = real_test_save.reshape(y_length,-1).transpose(1,0)\n\n\t#### FIRST REVERS SCALE TRANSFORMATION\n\terr = RMSE(real_test_save,pred_test_save)\n\tmaerr = MAE(real_test_save,pred_test_save)\n\n\n\n\t#print(preds[step].detach().numpy().squeeze().shape, np.asarray(list_preds).shape)\n\treturn loss_test/size,predsMetric , loss_test_batch.item(), lossBoxPlot, np.mean(err)\n\n\n\ndef NUMPEAK(real_test_save, pred_test_save, qTest90):\n\n\tflgPeaksReal = np.where(real_test_save>=qTest90)\n\tnumPeaksReal = np.sum(flgPeaksReal,axis=1)\n\n\tflgPeaksPred = np.where(pred_test_save>=qTest90)\n\tnumPeaksPred = np.sum(flgPeaksPred,axis=1)\n\n\tratioPeaks = np.mean(numPeaksPred/numPeaksReal)\n\treturn ratioPeaks\n\n\n\ndef testModel(seq_inOr_tst, seq_outOr_tst, test_size, qTest90, save_path):\n\tloss_tst, pred_test, loss_tst_batch , loss_box_tst, err_avg= testing(seq_inOr_tst, seq_outOr_tst, test_size)\n\tdiffMaxMin = pred_test.max() - pred_test.min()\n\tstdPreds = np.std(pred_test)\n\tloss_tst = loss_tst.item()#to bring from graph network space\n\n\n\tstep_plot = 0\n\tplt.plot(np.concatenate((pred_test[step_plot],seq_outOr_tst[step_plot]),axis =1))\n\tplt.savefig(\"{}/bestV_PredvsReal_Test\".format(save_path), bbox_inches='tight')#self.savedFolder+'/'+ch.name+str(numfig)\n\tplt.clf()\n\n\t#Plot boxplot of losses\n\tdfBox = pd.DataFrame(loss_box_tst)\n\tdfBox.boxplot()\n\tplt.savefig(os.path.join(save_path,'bestV_boxplot'))\n\tplt.clf()\n\n\t#### CALCULATING MAE, MSE TO SAVE THEM TO FILE\n\tpred_test_save = scaler.inverse_transform(pred_test.squeeze().reshape(-1,1))#to flat the data\n\tpred_test_save= pred_test_save.reshape(y_length,-1).transpose(1,0)#to recover shape length,size -> size, lenght\n\treal_test_save = scaler.inverse_transform(seq_outOr_tst.squeeze().detach().numpy().reshape(-1,1))\n\treal_test_save = real_test_save.reshape(y_length,-1).transpose(1,0)\n\n\t#### FIRST REVERS SCALE TRANSFORMATION\n\n\terr = RMSE(real_test_save,pred_test_save)\n\tmaerr = MAE(real_test_save,pred_test_save)\n\tratioPeaks = NUMPEAK(real_test_save,pred_test_save, qTest90)\n\n\n\twritetofile(os.path.join(save_path,\"bestV_pred.txt\"),pred_test_save)\n\twritetofile(os.path.join(save_path,\"bestV__real.txt\"),real_test_save)\n\twriteErrResult(os.path.join(save_path,\"bestV__test_rmse.txt\"),err) # y_length\n\twriteErrResult(os.path.join(save_path,\"bestV__test_mae.txt\"),maerr)\n\n\t#Final log\n\tprint(f'Test loss: {loss_tst:10.4f} {err_avg:10.4f} Diff Max-Min :{diffMaxMin:10.4f} Std: {stdPreds:2.4f}')\n\n\n\t#Global log - among runs\n\ttype_rnn = args.type_rnn + \"_unguided\"\n\treturn loss_tst, err_avg, stdPreds, ratioPeaks\n\n\n\n\n\n#modelType\t epochs\tinputDim\t xLength\t yLength\t learningRate\t unitsHiddenLayer\t typeTraining\t trainingSize\tminiBatchSize\t typeAF\t lossTraint\t lossTest\t\n#RMSE\tDiffMaxMin\tstdDev\tBestPrevIteration\tBestLoss\tBestStd\tratioPeaks\t folder\tComments\tpreproFile\n\ndfResults = pd.read_csv(os.path.join(args.save_path,args.type_rnn,incident_group+\"/LogResultsTests.csv\"))\n\n\nprint(dfResults.columns)\n###### ITERATE OVER ALL THE FOLDERS OF FINAL RESULTS\nfor index, row in dfResults.iterrows():\n\tfolder = row['folder']\n\tbestIter = row['BestPrevIteration']\n\thidden_units = int(row[\"unitsHiddenLayer\"])\n\tpreproFile = str(row[\"preproFile\"])\n\tx_length = int(row[\"xLength\"])\n\ty_length = int(row[\"yLength\"])\n\tmodelType = str(row[\"modelType\"])\n\n\t### SPLIT THE TRAIN, TEST AND VAL WITH THAT FILE\n\t\n\tif preproFile == 'nan' or modelType!='lstm_guided':\n\t#if np.isnan(preproFile):\n\t\tcontinue\n\tdf = pd.read_csv(preproFile, delimiter=',')\n\n\t# stop test of 100\n\tall_data = df['Response Time'].values.astype(float)#[:500]\n\tscaler = MinMaxScaler()#feature_range=(-1, 1)\n\tseq_inOr_tst, seq_outOr_tst, qVal50, test_size, qTest90 = splitData(all_data, scaler)\n\n\tbestStd = 0.0\n\tsave_path = os.path.join(args.save_path,args.type_rnn,incident_group,folder)\n\tif np.isnan(bestIter):\n\t\t#Look for the folder and open Log.csv\n\t\t\n\t\tdfLogExp = pd.read_csv(os.path.join(save_path,\"Log.csv\"))\n\n\t\tbestLossVal = float('Inf')\n\t\tfor idLogExp, rowLogExp in dfLogExp.iterrows():\n\t\t\t#Epoch\tlossTrain\tlossVal\tstdDev or standarDeviation\n\t\t\tif 'stdDev' in dfLogExp.columns:\n\t\t\t\tstdev = rowLogExp[\"stdDev\"]\n\t\t\telse:\n\t\t\t\tstdev = rowLogExp[\"standarDeviation\"]\n\n\t\t\tif float(rowLogExp[\"lossVal\"])< bestLossVal and float(stdev)>= qVal50:\n\t\t\t\tbestLossVal = float(rowLogExp[\"lossVal\"])\n\t\t\t\tbestIter = int(rowLogExp[\"Epoch\"])\n\t\t\t\tbestStd = float(stdev)\n\telse:\n\t\tbestIter = int(bestIter)\n\n\t### CREATE THE MODEL WITH THOS UNITS AND LOAD THE MODEL\n\tif args.type_rnn == 'rnn':\n\t\tmodel = RNN(x_dim, y_dim, hidden_units, args.type_actifun)\n\telse:#lstm\n\t\tmodel = LSTM(x_dim, y_dim, hidden_units, args.type_actifun)\n\n\t#If we did not find a better solution\n\tif np.isnan(bestIter):\n\t\tcontinue\n\tprint(index, folder, preproFile, modelType, bestStd,qVal50, test_size, qTest90)\n\n\tfn = os.path.join(save_path,'vrnn_state_dict_'+str(bestIter)+'.pth')\n\tmodel.load_state_dict(torch.load(fn))\n\n\tloss_function = nn.MSELoss()\n\tBestLossTest, BestRMSE, BestStdTest, ratioPeaksTest = testModel(seq_inOr_tst, seq_outOr_tst, test_size, qTest90, save_path)\n\n\tdfResults[\"BestPrevIteration\"].loc[index] = bestIter\n\tdfResults[\"BestLoss\"].loc[index] = round(BestRMSE,0)\n\tdfResults[\"BestStd\"].loc[index] = round(BestStdTest,4)\n\tdfResults[\"ratioPeaks\"].loc[index] = round(ratioPeaksTest,4)\n\ndfResults.to_csv(os.path.join(args.save_path,args.type_rnn,incident_group+\"/LogResultsTests.csv\"), index=False)\n\n\n\n\n","sub_path":"emergency_model_running/emergency_model/model/Pytorch_prevVersions/pytorchRNN_guided_testBest.py","file_name":"pytorchRNN_guided_testBest.py","file_ext":"py","file_size_in_byte":14813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"218555371","text":"#%%\nfrom utils import *\nfrom utils.metrics import regression_report\nfrom data_processing import Data, evaluate_by_label, fill_label\n\nimport pandas as pd\nfrom sklearn.experimental import enable_hist_gradient_boosting\nfrom sklearn.ensemble import HistGradientBoostingRegressor\n\n\n# data\ndata = Data(use_dummies=False, normalize=False)\nX_train_df, X_test_df, y_train_df, y_test_df = data.train_test_split_by_date(\n [\"actual_adr\"], test_ratio=0.3\n)\ntrain_df = pd.concat([X_train_df, y_train_df], axis=1)\ncreated_df = data.duplicate_data((2015, 6, 1), (2016, 3, 31), ratio=1)\n# created_df = data.create_data((2016, 6, 1), (2017, 3, 31), ratio=1, offset=5)\naugmented_df = pd.concat([train_df, created_df[train_df.columns]], axis=0)\ny_train_df = augmented_df[[\"actual_adr\"]]\nX_train_df = augmented_df.drop([\"actual_adr\"], axis=1)\n\n#%%\nX_train, X_test, y_train, y_test = (\n X_train_df.to_numpy(),\n X_test_df.to_numpy(),\n y_train_df[\"actual_adr\"].to_numpy(),\n y_test_df[\"actual_adr\"].to_numpy(),\n)\nprint(f\"X_train shape {X_train.shape}, y_train shape {y_train.shape}\")\nprint(f\"X_test shape {X_test.shape}, y_test shape {y_test.shape}\")\n\n#%% evaluate performance with training data\neval_reg = HistGradientBoostingRegressor(random_state=1126)\neval_reg.fit(X_train, y_train)\n\nprint(\"-\" * 10, \"regression report\", \"-\" * 10)\nreport = regression_report(y_test, eval_reg.predict(X_test), X_test.shape[1])\nprint(report)\n\nprint(\"-\" * 10, \"evaluation of label\", \"-\" * 10)\nlabel_df = data.get_true_label(columns=[\"adr\", \"revenue\", \"is_canceled\", \"label\"])\npred_label_df = data.predict_label(eval_reg, X_test_df, reg_out=\"adr\")\n\n#%%\nprint(\"[ label evaluation ]\")\nreport_label = evaluate_by_label(pred_label_df, label_df, target=\"label\")\nprint(report_label)\nprint(\"[ revenue_per_day evaluation ]\")\nreport_revenue = evaluate_by_label(pred_label_df, label_df, target=\"revenue\")\nprint(report_revenue)\n\n#%% training with all data\nX_df, y_df = data.processing([\"actual_adr\"])\ntrain_df = pd.concat([X_df, y_df], axis=1)\ncreated_df = data.duplicate_data(ratio=0.8)\naugmented_df = pd.concat([train_df, created_df[train_df.columns]], axis=0)\ny_df = augmented_df[[\"actual_adr\"]]\nX_df = augmented_df.drop([\"actual_adr\"], axis=1)\n\nreg = HistGradientBoostingRegressor(random_state=1126)\nreg.fit(X_df.to_numpy(), y_df[\"actual_adr\"].to_numpy())\n\n#%% fill predict label to csv\ntest_X_df = data.processing_test_data(\"data/test.csv\")\npred_label_df = data.predict_label(reg, test_X_df, reg_out=\"adr\")\nfill_label(pred_label_df, \"data/test_nolabel.csv\")\n\n#%%\n","sub_path":"mae_0.43(0.35)_data_augmentation(duplicate).py","file_name":"mae_0.43(0.35)_data_augmentation(duplicate).py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"228344979","text":"import sys\nfrom typing import List\nfrom math import sqrt\n\n# input\nF1_score = sys.argv[1]\n# RMSE = sys.argv[1]\n# Pearson_correlation = sys.argv[1]\n# output\nanalysis_F1_score_deleted_files = sys.argv[2]\n# analysis_RMSE_deleted_files = sys.argv[2]\n# analysis_Pearson_correlation_deleted_files = sys.argv[2]\n\nwith open(F1_score) as f:\n lines = f.readlines()\n f.close()\n mean = 0\n for line in lines:\n number = float(line)\n mean = mean + number\n\n mean = mean / len(lines)\n\nwith open(F1_score) as f:\n lines = f.readlines()\n f.close()\n sum = 0\n for line in lines:\n x = float(line)\n sum = sum + (x-mean)\n power = (sum) ** 2\n variance = power / len(lines)\n stddev = variance ** 0.5\n\nmy_list = [mean, stddev]\n\nwith open(analysis_F1_score_deleted_files, 'w') as output:\n for item in my_list:\n output.write(\"%s\\n\" % item)\n\n# Por o seguinte código na linha de comando:\n # python analysis.py F1_score.txt analysis_F1_score_deleted_files.txt\n# Por o seguinte código na linha de comando:\n # python analysis.py RMSE.txt analysis_RMSE_deleted_files.txt\n# Por o seguinte código na linha de comando:\n # python analysis.py Pearson_correlation.txt analysis_Pearson_correlation_deleted_files.txt","sub_path":"Scenario_Modified/Analysis_average/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"14218673","text":"\n### one code one day\n### 2020/03/29\n### 2020年百度实习生 算法岗 笔试\n### 题目具体忘记了 这里只存个 代码\n\n### 给 n 个数对, 如(10,4), (20, 5), (50, 8), (40, 7), (30, 6)\n### m回合 ,每回合抽一对,你会获得你抽到的那一对的第一个值,但是其他的数对的第一个值都要减去\n### 这个抽到的数对的第二个值 比如抽到(10,4),你会获得10分,但是剩下的数对会减去4,如果抽完(10,4)\n### 剩下另4个,那么会变为(20-4,5),(50-4,8),(40-4,7),(30-4, 6)\n### 求m回合所抽到的最大分数\n\n\nn = int(input())\nm = int(input())\na = [int(num) for num in input().split(' ')]\nb = [int(num) for num in input().split(' ')]\n\nnew = []\nfor i in range(n):\n new.append([b[i], a[i]])\nnew.sort()\n\ndp = []\nfor i in range(n):\n dp.append([new[i][1], new[i][0]])\n\nfor turn in range(1, m):\n for i in range(n-1, turn-1, -1):\n res = -1\n r = 0\n for j in range(turn-1, i):\n if(r < dp[j][0] - dp[j][1]):\n r = dp[j][0] - dp[j][1]\n res = j\n if(res != -1):\n dp[i][0] = new[i][1] + dp[res][0] - dp[res][1]\n dp[i][1] = new[i][0] + dp[res][1]\n print(dp)\n","sub_path":"动态规划/maxSUM.py","file_name":"maxSUM.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"470710103","text":"import numpy as np\nimport numba as nb\nXF = 1.\n\n# Convective Differentiation function, approximates du/dx\n#@nb.jit\ndef convective_dudt(un, dx, strategy='4c'):\n duconv = np.zeros(un.size)\n #duconv = np.zeros(un.size, dtype=np.float128)\n if strategy=='2c':\n duconv[1:-1] = -1 * un[1:-1] * (un[2:] - un[:-2]) / (2 * dx)\n elif strategy == '4c':\n #duconv[1] = -1 * un[1] * (-10 * un[0] - 77 * un[1] + 150 * un[2] - 100 * un[3] + 50 * un[4] -15 * un[5] + 2 * un[6]) / 60 / dx\n #duconv[-2] = -1 * un[-2] * (10 * un[-1] + 77 * un[-2] - 150 * un[-3] + 100 * un[-4] - 50 * un[-5] + 15 * un[-6] - 2 * un[6]) / 60 / dx\n #duconv[1] = -1 * un[1] * (un[2] - un[0]) / (2 * dx)\n #duconv[-2] = -1 * un[-2] * (un[-1] - un[-3]) / (2 * dx) \n duconv[1] = -1 * un[1] * ( - 25./12. * un[1] + 4 * un[2] - 3 * un[3] + 4./3. * un[4] - un[5]/4.) / dx\n # I made this negative negative \\|/\n duconv[-2] = un[-2] * ( - 25./12. * un[-2] + 4 * un[-3] - 3 * un[-4] + 4./3. * un[-5] - un[-6]/4.) / dx\n duconv[2:-2] = -1 * un[2:-2] * (-1./12. * un[4:] + 8./12. * un[3:-1] - 8/12. * un[1:-3] + 1./12. * un[:-4]) / (dx)\n #duconv[2:-2] = -1 * un[2:-2] * (-1 * un[4:] + 8 * un[3:-1] - 8 * un[1:-3] + un[:-4]) / ( 12 * dx)\n return duconv\n\n# Diffustive Differentiation function, approximates nu d^2 u /dx^2\n#@nb.jit\ndef diffusive_dudt(un, nu, dx, strategy='5c'):\n dundiff = np.zeros(un.size)\n #dundiff = np.zeros(un.size, dtype=np.float128)\n\n # O(h^2)\n if strategy == '3c':\n dundiff[1:-1] = nu * (un[2:] - 2 * un[1:-1] + un[:-2]) / dx**2\n\n # O(h^4)\n elif strategy == '5c':\n # http://web.media.mit.edu/~crtaylor/calculator.html\n #dundiff[1] = nu * (137 * un[0] - 147 * un[1] - 255 * un[2] + 470 * un[3] - 285 * un[4] + 93 * un[5] - 13 * un[6]) / 180 / dx**2\n #dundiff[-2] = nu * (137 * un[-1] - 147 * un[-2] - 255 * un[-3] + 470 * un[-4] - 285 * un[-5] + 93 * un[-6] - 13 * un[-7]) / (180 * dx**2)\n\n # second order\n #dundiff[1] = nu * (un[0] - 2 * un[1] + un[2]) / dx ** 2\n #dundiff[-2] = nu * ( un[-1] - 2 * un[-2] + un[-3]) / dx ** 2\n dundiff[1] = nu * (15./4. * un[1] - 77./6. * un[2] + 107./6. * un[3] - 13 * un[4] + (61./12.) * un[5] - 5./6. * un[6]) / dx ** 2\n dundiff[-2] = nu * (15./4. * un[-2] - 77./6. * un[-3] + 107./6. * un[-4] - 13 * un[-5] + (61./12.) * un[-6] - 5./6. * un[-7]) / dx ** 2\n dundiff[2:-2] = nu * (-1 * un[4:] + 16 * un[3:-1] - 30 * un[2:-2] + 16 * un[1:-3] - un[:-4]) / (12 * dx**2 )\n else: raise(IOError(\"Invalid diffusive strategy\")) ; quit()\n return dundiff\n\n# Velocity Evolution Function. Accepts initial and boundary conditions, returns time evolution history.\n#@nb.jit\ndef geturec(x, nu=.05, evolution_time=1, u0=None, n_save_t=50, ubl=0., ubr=0., diffstrategy='5c', convstrategy='4c', timestrategy='fe', dt=None, returndt=False):\n\n dx = x[1] - x[0]\n\n # Prescribde cfl=0.05 and ftcs=0.02\n if dt is not None: pass\n else: dt = min(.02 * dx / 1., .02 / nu * dx ** 2)\n if returndt: return dt\n\n # Determine the interval, \"divider\", to record time with\n nt = int(evolution_time / dt)\n dt = evolution_time / nt\n print('t is ', nt * dt)\n divider = int(nt / float(n_save_t))\n if divider ==0: raise(IOError(\"not enough time steps to save %i times\"%n_save_t))\n\n # The default initial condition is a half sine wave.\n u_initial = ubl + np.sin(x)\n #u_initial = ubl + np.sin(x * np.pi)\n if u0 is not None: u_initial = u0\n u = u_initial\n u[0] = ubl\n u[-1] = ubr\n\n # insert ghost cells; extra cells on the left and right\n # for the edge cases of the finite difference scheme\n #x = np.insert(x, 0, x[0]-dx)\n #x = np.insert(x, -1, x[-1]+dx)\n #u = np.insert(u, 0, ubl)\n #u = np.insert(u, -1, ubr)\n\n # u_record holds all the snapshots. They are evenly spaced in time,\n # except the final and initial states\n u_record = np.zeros((x.size, int(nt / divider + 2)))\n #u_record = np.zeros((x.size, int(nt / divider + 2)), dtype=np.float128)\n\n # Evolve through time\n ii = 1\n u_record[:, 0] = u\n for _ in range(nt):\n un = u.copy()\n #dudt = diffusive_dudt(un, nu, dx, strategy=diffstrategy) \n dudt = diffusive_dudt(un, nu, dx, strategy=diffstrategy) + convective_dudt(un, dx, strategy=convstrategy)\n\n # forward euler time step\n if timestrategy == 'fe':\n u = un + dt * dudt\n elif timestrategy == 'rk2':\n uhalfn = un + dt * dudt / 2.\n duhalfn_dt1 = diffusive_dudt(uhalfn, nu, dx, strategy=diffstrategy) + convective_dudt(uhalfn, dx, strategy=convstrategy)\n u = un + dt * duhalfn_dt1\n #u = 0.5 * (un + dt * dudt + uhalfn + duhalfn_dt1 * dt)\n if _ == 0: print('hey!')\n\n # RK 4 time step\n elif timestrategy == 'rk4':\n uhalfn = un + dt * dudt / 2.\n duhalfn_dt1 = diffusive_dudt(uhalfn, nu, dx, strategy=diffstrategy) + convective_dudt(uhalfn, dx, strategy=convstrategy)\n uhalfk2 = un + duhalfn_dt1 * dt / 2\n duhalfk2_dt = diffusive_dudt(uhalfk2, nu, dx, strategy=diffstrategy) + convective_dudt(uhalfk2, dx, strategy=convstrategy)\n ufull = un + duhalfk2_dt * dt\n dufull_dt = diffusive_dudt(ufull, nu, dx, strategy=diffstrategy)+ convective_dudt(ufull, dx, strategy=convstrategy)\n u = un + (dt / 6.) * (dudt + 2 * duhalfn_dt1 + 2 * duhalfk2_dt + dufull_dt)\n else: raise(Exception(\"Error\"))\n\n # Save every mth time step\n #return u\n if _ % divider == 0:\n u_record[:, ii] = u.copy()\n ii += 1\n u_record[:, -1] = u\n return u_record\n #return u_record[1:-1, :]\n\nif __name__==\"__main__\":\n x = np.linspace(0, np.pi, 801)\n u = geturec(x, nu=0.1, dt=5e-9, evolution_time=0.00002, n_save_t=1)[:, -1]\n fl = open('mine.dat', 'w')\n fl.write(' '.join([str(s) for s in u]))\n #fl.write(' '.join([str(s) for s in u[:, -1]]))\n fl.close()\n","sub_path":"burgers/mysolver.py","file_name":"mysolver.py","file_ext":"py","file_size_in_byte":6020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"130165146","text":"'''\nCopyright (2019, ) Institute of Software, Chinese Academy of Sciences\n\n@author: wuyuewen@otcaix.iscas.ac.cn\n@author: wuheng@otcaix.iscas.ac.cn\n\nhttps://pypi.org/project/json2xml/\nhttps://github.com/kubernetes/kubernetes/issues/51046\n'''\n\n'''\nImport python libs\n'''\nimport re\nfrom xml.dom import minidom\nfrom StringIO import StringIO as _StringIO\n\n'''\nImport third party libs\n'''\ntry:\n import libvirt\n HAS_LIBVIRT = True\nexcept ImportError:\n HAS_LIBVIRT = False\n# import yaml\n\n\nVIRT_STATE_NAME_MAP = {0: 'running',\n 1: 'running',\n 2: 'running',\n 3: 'paused',\n 4: 'shutdown',\n 5: 'shutdown',\n 6: 'crashed'}\n\n\n'''\n VM lifecycle\n'''\n\ndef __get_conn():\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n try:\n conn = libvirt.open('qemu:///system')\n except Exception:\n raise Exception(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software'\n )\n return conn\n\n\ndef _get_dom(vm_):\n '''\n Return a domain object for the named vm\n '''\n conn = __get_conn()\n if vm_ not in list_vms():\n raise Exception('The specified vm is not present(%s).' % vm_)\n return conn.lookupByName(vm_)\n\ndef _get_pool(pool_):\n conn = __get_conn()\n if pool_ not in list_pools():\n raise Exception('The specified pool is not present(%s).' % pool_)\n pool = conn.storagePoolLookupByName(pool_)\n pool.refresh()\n return pool\n\ndef _get_vol(pool_, vol_):\n pool = _get_pool(pool_)\n return pool.storageVolLookupByName(vol_)\n\ndef _get_all_snapshots(vm_):\n vm = _get_dom(vm_)\n return vm.snapshotListNames()\n\ndef _get_snapshot(vm_, snap_):\n vm = _get_dom(vm_)\n return vm.snapshotLookupByName(snap_)\n\ndef is_vm_exists(vm_):\n if vm_ in list_vms():\n return True\n return False\n\ndef is_vm_active(vm_):\n if vm_ in list_active_vms():\n return True\n return False\n\ndef list_vms():\n '''\n Return a list of virtual machine names on the minion\n\n CLI Example::\n\n salt '*' virt.list_vms\n '''\n vms = []\n vms.extend(list_active_vms())\n vms.extend(list_inactive_vms())\n return vms\n\ndef list_active_vms():\n '''\n Return a list of names for active virtual machine on the minion\n\n CLI Example::\n\n salt '*' virt.list_active_vms\n '''\n conn = __get_conn()\n vms = []\n for id_ in conn.listDomainsID():\n vms.append(conn.lookupByID(id_).name())\n return vms\n\n\ndef list_inactive_vms():\n '''\n Return a list of names for inactive virtual machine on the minion\n\n CLI Example::\n\n salt '*' virt.list_inactive_vms\n '''\n conn = __get_conn()\n vms = []\n for id_ in conn.listDefinedDomains():\n vms.append(id_)\n return vms\n\n# def vm_info(vm_=None):\n# '''\n# Return detailed information about the vms on this hyper in a\n# list of dicts::\n# \n# [\n# 'your-vm': {\n# 'cpu': ,\n# 'maxMem': ,\n# 'mem': ,\n# 'state': '',\n# 'cputime' \n# },\n# ...\n# ]\n# \n# If you pass a VM name in as an argument then it will return info\n# for just the named VM, otherwise it will return all VMs.\n# \n# CLI Example::\n# \n# salt '*' virt.vm_info\n# '''\n# def _info(vm_):\n# dom = _get_dom(vm_)\n# raw = dom.info()\n# return {'cpu': raw[3],\n# 'cputime': int(raw[4]),\n# 'disks': get_disks(vm_),\n# 'graphics': get_graphics(vm_),\n# 'nics': get_nics(vm_),\n# 'maxMem': int(raw[1]),\n# 'mem': int(raw[2]),\n# 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')}\n# info = {}\n# if vm_:\n# info[vm_] = _info(vm_)\n# else:\n# for vm_ in list_vms():\n# info[vm_] = _info(vm_)\n# return info\n\n\ndef vm_state(vm_=None):\n '''\n Return list of all the vms and their state.\n\n If you pass a VM name in as an argument then it will return info\n for just the named VM, otherwise it will return all VMs.\n\n CLI Example::\n\n salt '*' virt.vm_state |