',\n \"\",\n )\n .replace(\n '
',\n \"\",\n )\n .replace(\n '
',\n \"\",\n )\n .replace(\"
\", \"\")\n )\n dates = list(dict.fromkeys(dates))\n for i in range(len(dates)):\n dates[i] = dates[i].replace(\" \", \" \")\n dates[i] = f\"{dates[i][:len(dates[i]) - 3]}, {dates[i][len(dates[i]) - 3:]}\"\n\n time_template = {\n \"Midnight\": 0,\n \"1 AM\": 1,\n \"2 AM\": 2,\n \"3 AM\": 3,\n \"4 AM\": 4,\n \"5 AM\": 5,\n \"6 AM\": 6,\n \"7 AM\": 7,\n \"8 AM\": 8,\n \"9 AM\": 9,\n \"10 AM\": 10,\n \"11 AM\": 11,\n \"Noon\": 12,\n \"1 PM\": 13,\n \"2 PM\": 14,\n \"3 PM\": 15,\n \"4 PM\": 16,\n \"5 PM\": 17,\n \"6 PM\": 18,\n \"7 PM\": 19,\n \"8 PM\": 20,\n \"9 PM\": 21,\n \"10 PM\": 22,\n \"11 PM\": 23,\n }\n raw_times = soup.find_all(\n \"div\",\n attrs={\n \"style\": \"text-align:right;width:44px;font-size:10px;margin:4px 4px 0px 0px;\"\n },\n )\n times = []\n for each in raw_times:\n each = re.findall(\n r\"
(.*?)
\",\n str(each),\n )\n if not each:\n continue\n this = each[0].strip(\"\\xa0\")\n if this in time_template.keys():\n this = time_template[this]\n times.append(this)\n times = list(dict.fromkeys(times))\n\n group_grid = []\n for i in range(len(dates)):\n group_grid.append([[] for j in range((len(times) * 4))])\n\n raw_attendant = re.findall(\n r\"PeopleNames\\[\\d\\] = '(.*?)';PeopleIDs\\[\\d\\] = (.*?);\", str(response.text)\n )\n raw_attendant = list(dict.fromkeys(raw_attendant))\n attendant = dict()\n for each in raw_attendant:\n attendant[each[1]] = each[0]\n\n availables = re.findall(\n r\"AvailableAtSlot\\[(\\d*?)\\]\\.push\\((\\d*?)\\);\", str(response.text)\n )\n availables = list(dict.fromkeys(availables))\n\n for each in availables:\n time_slot = int(each[0]) % (len(times) * 4)\n date_slot = int(each[0]) // (len(times) * 4)\n group_grid[date_slot][time_slot].append(str(each[1]))\n\n grid_count = []\n for each in group_grid:\n grid_count.append(list(map(len, each)))\n\n datetimes = dict()\n for i in range(len(group_grid)):\n for j in range(len(group_grid[i])):\n attendant_name = tuple(map(lambda s: attendant[s], group_grid[i][j]))\n if attendant_name not in datetimes.keys() and attendant_name:\n datetimes[attendant_name] = dict()\n datetimes[attendant_name][dates[i]] = list()\n elif attendant_name:\n datetimes[attendant_name][dates[i]] = list()\n\n for i in range(len(group_grid)):\n for j in range(len(group_grid[i])):\n attendant_name = tuple(map(lambda s: attendant[s], group_grid[i][j]))\n try:\n if attendant_name:\n datetimes[attendant_name][dates[i]].append(j)\n except:\n pass\n try:\n group_amount = list(map(len, dict.fromkeys(datetimes)))\n max_people = max(group_amount)\n except ValueError:\n return \"還沒有人投票哦!\"\n\n result = dict()\n for i, amount in enumerate(group_amount):\n if amount == max_people:\n for j, datetime in enumerate(datetimes):\n if i == j:\n result[datetime] = datetimes[datetime]\n\n def time_segment(raw_time: list):\n time_dict = {\n 0: \"00:00\",\n 1: \"00:15\",\n 2: \"00:30\",\n 3: \"00:45\",\n 4: \"01:00\",\n 5: \"01:15\",\n 6: \"01:30\",\n 7: \"01:45\",\n 8: \"02:00\",\n 9: \"02:15\",\n 10: \"02:30\",\n 11: \"02:45\",\n 12: \"03:00\",\n 13: \"03:15\",\n 14: \"03:30\",\n 15: \"03:45\",\n 16: \"04:00\",\n 17: \"04:15\",\n 18: \"04:30\",\n 19: \"04:45\",\n 20: \"05:00\",\n 21: \"05:15\",\n 22: \"05:30\",\n 23: \"05:45\",\n 24: \"06:00\",\n 25: \"06:15\",\n 26: \"06:30\",\n 27: \"06:45\",\n 28: \"07:00\",\n 29: \"07:15\",\n 30: \"07:30\",\n 31: \"07:45\",\n 32: \"08:00\",\n 33: \"08:15\",\n 34: \"08:30\",\n 35: \"08:45\",\n 36: \"09:00\",\n 37: \"09:15\",\n 38: \"09:30\",\n 39: \"09:45\",\n 40: \"10:00\",\n 41: \"10:15\",\n 42: \"10:30\",\n 43: \"10:45\",\n 44: \"11:00\",\n 45: \"11:15\",\n 46: \"11:30\",\n 47: \"11:45\",\n 48: \"12:00\",\n 49: \"12:15\",\n 50: \"12:30\",\n 51: \"12:45\",\n 52: \"13:00\",\n 53: \"13:15\",\n 54: \"13:30\",\n 55: \"13:45\",\n 56: \"14:00\",\n 57: \"14:15\",\n 58: \"14:30\",\n 59: \"14:45\",\n 60: \"15:00\",\n 61: \"15:15\",\n 62: \"15:30\",\n 63: \"15:45\",\n 64: \"16:00\",\n 65: \"16:15\",\n 66: \"16:30\",\n 67: \"16:45\",\n 68: \"17:00\",\n 69: \"17:15\",\n 70: \"17:30\",\n 71: \"17:45\",\n 72: \"18:00\",\n 73: \"18:15\",\n 74: \"18:30\",\n 75: \"18:45\",\n 76: \"19:00\",\n 77: \"19:15\",\n 78: \"19:30\",\n 79: \"19:45\",\n 80: \"20:00\",\n 81: \"20:15\",\n 82: \"20:30\",\n 83: \"20:45\",\n 84: \"21:00\",\n 85: \"21:15\",\n 86: \"21:30\",\n 87: \"21:45\",\n 88: \"22:00\",\n 89: \"22:15\",\n 90: \"22:30\",\n 91: \"22:45\",\n 92: \"23:00\",\n 93: \"23:15\",\n 94: \"23:30\",\n 95: \"23:45\",\n }\n\n base_time = times[0] * 4\n all_day_time = []\n time_session = f\"{time_dict[base_time + raw_time[0]]}\"\n\n for i in range(len(raw_time)):\n this_time = base_time + raw_time[i]\n if i < len(raw_time) - 1 and raw_time[i] + 1 == raw_time[i + 1]:\n continue\n else:\n time_session += f\"~{time_dict[this_time + 1]}\"\n all_day_time.append(time_session)\n if i < len(raw_time) - 1:\n time_session = f\"{time_dict[base_time + raw_time[i + 1]]}\"\n\n return all_day_time\n\n wrapped_result = {\n \"event_name\": str(\n re.findall(r\"
(.*?) - When2meet\", str(soup))[0]\n ),\n \"candidates\": [],\n }\n\n for key_1, item_1 in result.items():\n candidate = {\n \"participants\": key_1,\n \"available_time\": list(),\n }\n for key_2, item_2 in item_1.items():\n this_date = dict()\n this_date[\"date\"] = key_2\n this_date[\"time\"] = time_segment(result[key_1][key_2])\n candidate[\"available_time\"].append(this_date)\n\n wrapped_result[\"candidates\"].append(candidate)\n\n # 餐廳選擇結果\n choose_result = \"\"\n like_list = []\n event_data = config.db.vote_pull.find_one({\"_id\": event_id})\n for each_participant, like in event_data[\"participants\"].items():\n like_list += like\n occurence_count = Counter(like_list)\n for restaurant_index, count in occurence_count.most_common(3):\n restaurant_name = event_data[\"restaurants\"][restaurant_index][\"name\"]\n choose_result += f\"{restaurant_name} : {count}票\\n\"\n\n message = f'投票結果出爐啦!\\n\\n【{wrapped_result[\"event_name\"]}】\\n------------------\\n{choose_result}'\n for each in wrapped_result[\"candidates\"]:\n message += f'參與者:{each[\"participants\"]}\\n'\n for each_available in each[\"available_time\"]:\n message += f'日期:{each_available[\"date\"]}\\n'\n message += f\"時間:\"\n for i, each_time in enumerate(each_available[\"time\"]):\n if i == 0:\n message += f\"{each_time}\\n\"\n else:\n message += f\"------{each_time}\\n\"\n message += \"------------------\\n\"\n\n return message\n","sub_path":"project/vote/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"653376785","text":"# -*- coding: utf-8 -*-\n\nfrom logging import getLogger\n\nfrom ..web.models import InfoSite\n\nlog = getLogger('django')\n\n\ndef get_info():\n\t# Obtiene o crea una instancia de InfoSite en caso de que no exista.\n\n\tinfo = InfoSite.objects.all()\n\tif info:\n\t\treturn info[0]\n\telse:\n\t\tinfo = InfoSite(email='chevarrias@gmail.com',\n\t\t\ttelefono='5555555', direccion='Av. Sin Nombre #123',\n\t\t\tfacebook='http://facebook.com/', site='http://127.0.0.1:8000')\n\t\tinfo.save()\n\t\treturn info\n\ndef get_coors():\n\timport random, decimal\n\tnum_1_min = -11.942884\n\tnum_1_max = -12.112792\n\tnum_2_min = -76.835941\n\tnum_2_max = -77.042962\n\treturn str(round(random.random()*(num_1_min-num_1_max)+num_1_max, 12))+\",\"+str(round(random.random()*(num_2_min-num_2_max)+num_2_max, 12))","sub_path":"src/apps/cursos/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"119397949","text":"import os\nimport sys\nimport random\nimport math\nimport re\nimport time\nimport numpy as np\nimport cv2\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport skimage\nfrom skimage.segmentation import slic,watershed, quickshift, mark_boundaries\nimport itertools\nimport logging\nimport json\nimport re\nimport random\nfrom collections import OrderedDict\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.lines as lines\nfrom matplotlib.patches import Polygon\n\n\n# import ssd\nfrom ssd_tf.model import Model\n\n\nclass TomatoProcessing():\n \"\"\"Class that does the post processing\"\"\"\n def __init__(self, image=None, r=None, depth_image=None, intrinsics=None):\n \"\"\"Initialize parameters for post processing\"\"\"\n self.size_image = (480, 640)\n\n # max number of tomato returned\n self.n_tomato_max = 10\n\n # workspace setting\n self.l_lim = self.size_image[1] / 3\n self.r_lim = 2 * self.size_image[1] /3\n\n # color for sub_segmentation\n self.red_level = 200\n self.proportion_min_red = 50\n self.distance_max_r = 3400 # deltaE_ciede94 distance\n\n # class input\n self.image = image\n self.results = r\n self.depth_image = depth_image\n self.intrinsics = intrinsics\n\n\n # class output\n self.data = None\n\n\n # result sorting variables\n self.detection_thresh = 0.8\n\n def set_input(self, image=None, results=None, depth_image=None, intrinsics=None, size_image=None):\n \"\"\"setter for the input of the class\"\"\"\n if image is not None: self.image = image\n if results is not None: self.results = results\n if depth_image is not None:\n self.depth_image = depth_image\n self.depth_image_3d = np.dstack((self.depth_image, self.depth_image, self.depth_image))\n if intrinsics is not None: self.intrinsics = intrinsics\n if size_image is not None :\n self.height = size_image[0]\n self.width = size_image[1]\n return 0\n\n def get_output(self):\n \"\"\"getter for the output of the class\"\"\"\n return {'data' : self.data, 'scores': self.scores}\n\n\n def processed_image(self, t0=None):\n \"\"\"Compute an image usefull for visualization, can print the fps preprocess time is given\"\"\"\n\n if self.image is None or self.results is None: return None\n initial_img = np.copy(self.image)\n image_masks = np.zeros((self.height, self.width, 3), dtype=np.uint8)\n\n\n\n\n in_ws_scores = self.in_ws_data['scores']\n in_ws_n_tomato = min(len(in_ws_scores), self.n_tomato_max)\n\n print_height = 20\n if in_ws_n_tomato == 0:\n cv2.putText(initial_img, 'NO TOMATO DETECTED IN WORKSPACE', (10, print_height), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), thickness=2)\n print_height += 20\n\n out_ws_scores = self.out_ws_data['scores']\n out_ws_n_tomato = min(len(out_ws_scores), self.n_tomato_max)\n\n\n if self.depth_image is None:\n final_img = np.hstack([(initial_img).astype(np.uint8), image_masks])\n else:\n depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(self.depth_image, alpha=255 / self.depth_image.max()), cv2.COLORMAP_JET)\n final_img = np.hstack([(initial_img).astype(np.uint8), image_masks, (depth_colormap * 255).astype(np.uint8)])\n\n\n if self.depth_image is not None:\n depth_colormap = (cv2.applyColorMap(cv2.convertScaleAbs(self.depth_image, alpha=255 / self.depth_image.max()), cv2.COLORMAP_JET)*255).astype(np.uint8)\n\n in_ws_rois = self.in_ws_data['rois']\n in_ws_ids_pixels = self.in_ws_data['id_pixel_masks']\n in_ws_centers = self.in_ws_data['centers']\n\n color1 = (255, 0, 0)\n\n # inside workspace\n for n in range(in_ws_n_tomato-1, -1, -1):\n\n\n [y1, x1, y2, x2] = in_ws_rois[n]\n id = in_ws_ids_pixels[n]\n center = in_ws_centers[n]\n score = in_ws_scores[n]\n image_masks[y1:y2 ,x1:x2, :][id == 1] = (0, 0, 255)\n image_masks[y1:y2, x1:x2, :][id == 2] = (0, 255, 0)\n\n # draw roi\n if n == 0:\n line_width = 6\n else:\n line_width = 2\n\n cv2.rectangle(initial_img, tuple((x1, y1)), tuple((x2, y2)), color1, line_width, lineType=4)\n cv2.rectangle(image_masks, tuple((x1, y1)), tuple((x2, y2)), color1, line_width, lineType=4)\n if self.depth_image is not None:\n cv2.rectangle(depth_colormap, tuple((x1, y1)), tuple((x2, y2)), color1, line_width, lineType=4)\n\n\n # draw detection score\n cv2.putText(initial_img, '{:6d}'.format(int(score)), tuple((x1, y1)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))\n\n # draw depth\n if self.in_ws_data['depths'] is not None:\n depth = self.in_ws_data['depths'][n]\n cv2.putText(initial_img, 'd={:1.3f}m'.format(depth), tuple((x1, y2)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))\n\n # draw center\n cv2.circle(initial_img, tuple(center), 5, (255, 0, 0), -1)\n\n out_ws_rois = self.out_ws_data['rois']\n out_ws_ids_pixels = self.out_ws_data['id_pixel_masks']\n out_ws_centers = self.out_ws_data['centers']\n\n color1 = (0, 0, 255)\n\n # outside workspace\n for n in range(out_ws_n_tomato-1, -1, -1):\n\n\n [y1, x1, y2, x2] = out_ws_rois[n]\n id = out_ws_ids_pixels[n]\n center = out_ws_centers[n]\n score = out_ws_scores[n]\n image_masks[y1:y2 ,x1:x2, :][id == 1] = (0, 0, 255)\n image_masks[y1:y2, x1:x2, :][id == 2] = (0, 255, 0)\n\n\n line_width = 1\n\n cv2.rectangle(initial_img, tuple((x1, y1)), tuple((x2, y2)), color1, line_width, lineType=4)\n cv2.rectangle(image_masks, tuple((x1, y1)), tuple((x2, y2)), color1, line_width, lineType=4)\n if self.depth_image is not None:\n cv2.rectangle(depth_colormap, tuple((x1, y1)), tuple((x2, y2)), color1, line_width, lineType=4)\n\n\n # draw detection score\n cv2.putText(initial_img, '{:6d}'.format(int(score)), tuple((x1, y1)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))\n\n # draw depth\n if self.out_ws_data['depths'] is not None:\n depth = self.out_ws_data['depths'][n]\n cv2.putText(initial_img, 'd={:1.3f}m'.format(depth), tuple((x1, y2)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))\n\n # draw center\n cv2.circle(initial_img, tuple(center), 5, (255, 0, 0), -1)\n\n g_scores = self.g_data['scores']\n g_n_tomato = min(len(g_scores), self.n_tomato_max)\n g_rois = self.g_data['rois']\n g_ids_pixels = self.g_data['id_pixel_masks']\n g_centers = self.g_data['centers']\n\n color1 = (255, 255, 255)\n\n # green tomato\n for n in range(g_n_tomato - 1, -1, -1):\n\n [y1, x1, y2, x2] = g_rois[n]\n id = g_ids_pixels[n]\n center = g_centers[n]\n score = g_scores[n]\n image_masks[y1:y2, x1:x2, :][id == 1] = (0, 0, 255)\n image_masks[y1:y2, x1:x2, :][id == 2] = (0, 255, 0)\n\n\n\n cv2.rectangle(initial_img, tuple((x1, y1)), tuple((x2, y2)), color1, 2, lineType=4)\n cv2.line(initial_img, tuple((x1, y2)), tuple((x2, y1)), color1, 1, lineType=4)\n cv2.line(initial_img, tuple((x1, y1)), tuple((x2, y2)), color1, 1, lineType=4)\n cv2.rectangle(image_masks, tuple((x1, y1)), tuple((x2, y2)), color1, 2, lineType=4)\n cv2.line(image_masks, tuple((x1, y2)), tuple((x2, y1)), color1, 1, lineType=4)\n cv2.line(image_masks, tuple((x1, y1)), tuple((x2, y2)), color1, 1, lineType=4)\n if self.depth_image is not None:\n cv2.rectangle(depth_colormap, tuple((x1, y1)), tuple((x2, y2)), color1, 2, lineType=4)\n cv2.line(depth_colormap, tuple((x1, y2)), tuple((x2, y1)), color1, 1, lineType=4)\n cv2.line(depth_colormap, tuple((x1, y1)), tuple((x2, y2)), color1, 1, lineType=4)\n\n # draw detection score\n cv2.putText(initial_img, '{:6d}'.format(int(score)), tuple((x1, y1)), cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n (255, 255, 255))\n\n # draw depth\n if self.out_ws_data['depths'] is not None:\n depth = self.g_data['depths'][n]\n cv2.putText(initial_img, 'd={:1.3f}m'.format(depth), tuple((x1, y2)), cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n (255, 255, 255))\n\n # draw center\n cv2.circle(initial_img, tuple(center), 5, color1, -1)\n\n\n if self.depth_image is None:\n final_img = np.hstack([initial_img, image_masks])\n else:\n final_img = np.hstack([initial_img, image_masks, depth_colormap])\n\n t = time.time() - t0\n cv2.putText(final_img, 'FPS : {:2.0f}'.format(1/t), (10, print_height), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), thickness=2)\n if print_height != 20:print_height-=15\n else: print_height=0\n\n color1 = (255,0,0)\n cv2.line(final_img, (int(self.l_lim), print_height), (int(self.l_lim), self.height), color1, 2)\n cv2.line(final_img, (int(self.r_lim), print_height), (int(self.r_lim), self.height), color1, 2)\n\n line_height_min = int(self.size_image[0] / 2 + 10)\n line_height_max = int(self.size_image[0] / 2 - 10)\n cv2.line(final_img, (int(self.l_lim), line_height_min), (int(self.l_lim) - 20, line_height_min), color1, 2)\n cv2.line(final_img, (int(self.l_lim), line_height_max), (int(self.l_lim) - 20, line_height_max), color1, 2)\n\n cv2.line(final_img, (int(self.r_lim), line_height_min), (int(self.r_lim) + 20, line_height_min), color1, 2)\n cv2.line(final_img, (int(self.r_lim), line_height_max), (int(self.r_lim) + 20, line_height_max), color1, 2)\n\n return final_img\n\n\n def pixel_id(self, sub_img):\n # matrix of boolean, telling if it is red but not green\n red_mat = np.zeros((sub_img.shape))\n red_mat[:,:,0] = self.red_level\n d_r = skimage.color.deltaE_ciede94(skimage.color.rgb2lab(sub_img), skimage.color.rgb2lab(red_mat)) < self.distance_max_r\n # range between 2000 and 4000\n return d_r\n\n def sub_segmentation(self):\n \"\"\"Does the complet post processing\n :param image: initial image\n :param r: output of the mrcnn\n :return n: number of tomato detected\n :return score_detection: given by the network for each tomato\n :return rois: rois given by the network\"\"\"\n\n if self.image is None or self.results is None: return None\n\n\n scores = self.results['scores']\n n_tomato = min(len(scores), self.n_tomato_max)\n if n_tomato == 0: return None\n in_ws_n_tomato_out = 0\n out_ws_n_tomato_out = 0\n g_n_tomato_out = 0\n\n rois = self.results['boxes']\n in_ws_rois_out = []\n in_ws_centers = []\n in_ws_red_scores = []\n in_ws_ids_pixels = []\n if self.depth_image is not None: in_ws_depths = []\n else: in_ws_depths = None\n\n out_ws_rois_out = []\n out_ws_centers = []\n out_ws_red_scores = []\n out_ws_ids_pixels = []\n if self.depth_image is not None:\n out_ws_depths = []\n else:\n out_ws_depths = None\n\n g_rois_out = []\n g_centers = []\n g_red_scores = []\n g_ids_pixels = []\n if self.depth_image is not None:\n g_depths = []\n else:\n g_depths = None\n\n\n for n in range(n_tomato):\n if scores[n]
self.r_lim:\n\n out_ws_rois_out.append([y1, x1, y2, x2])\n out_ws_n_tomato_out += 1\n out_ws_centers.append((int(centertmp[1]), int(centertmp[0])))\n out_ws_red_scores.append(int(number_r_pixel))\n out_ws_ids_pixels.append(id)\n if self.depth_image is not None :\n sub_depth = self.depth_image[y1:y2, x1:x2]\n depth = np.sum(sub_depth[np.nonzero(id)]) / (number_r_pixel + sys.float_info.epsilon)\n out_ws_depths.append(depth)\n\n # inside workspace\n else:\n in_ws_rois_out.append([y1, x1, y2, x2])\n in_ws_n_tomato_out += 1\n in_ws_centers.append((int(centertmp[1]), int(centertmp[0])))\n in_ws_red_scores.append(int(number_r_pixel))\n in_ws_ids_pixels.append(id)\n if self.depth_image is not None:\n sub_depth = self.depth_image[y1:y2, x1:x2]\n depth = np.sum(sub_depth[np.nonzero(id)]) / (number_r_pixel + sys.float_info.epsilon)\n in_ws_depths.append(depth)\n\n\n\n self.g_data = {'tomato_count' : g_n_tomato_out, 'scores' : g_red_scores, 'rois' : g_rois_out, 'centers' : g_centers,\\\n 'depths': g_depths, 'id_pixel_masks' : g_ids_pixels}\n\n self.in_ws_data = {'tomato_count' : in_ws_n_tomato_out, 'scores' : in_ws_red_scores, 'rois' : in_ws_rois_out, 'centers' : in_ws_centers,\\\n 'depths': in_ws_depths, 'id_pixel_masks' : in_ws_ids_pixels}\n\n self.out_ws_data = {'tomato_count': out_ws_n_tomato_out, 'scores': out_ws_red_scores, 'rois': out_ws_rois_out, 'centers': out_ws_centers, \\\n 'depths': out_ws_depths, 'id_pixel_masks': out_ws_ids_pixels}\n\n\n\n return self.in_ws_data, self.out_ws_data, self.g_data\n\n def deprojection(self):\n \"\"\"Compute 3D data\"\"\"\n\n if self.depth_image is None:\n self.data.update({'points_3d' : None})\n return None\n\n if self.in_ws_data is None:\n self.sub_segmentation()\n\n in_ws_n_tomato = self.in_ws_data['tomato_count']\n out_ws_n_tomato = self.out_ws_data['tomato_count']\n g_n_tomato = self.g_data['tomato_count']\n if in_ws_n_tomato == 0 and out_ws_n_tomato == 0 and g_n_tomato == 0: return -1\n\n ppx = self.intrinsics.ppx\n ppy = self.intrinsics.ppy\n fx = self.intrinsics.fx\n fy = self.intrinsics.fy\n\n in_ws_points = []\n out_ws_points = []\n g_points = []\n\n for n in range(in_ws_n_tomato):\n depth = self.in_ws_data['depths'][n]\n center = self.in_ws_data['centers'][n]\n\n in_ws_points.append([depth * (center[0] - ppx) / fx, depth * (center[1] - ppy) / fy, depth])\n\n for n in range(out_ws_n_tomato):\n depth = self.out_ws_data['depths'][n]\n center = self.out_ws_data['centers'][n]\n\n out_ws_points.append([depth * (center[0] - ppx) / fx, depth * (center[1] - ppy) / fy, depth])\n\n for n in range(g_n_tomato):\n depth = self.g_data['depths'][n]\n center = self.g_data['centers'][n]\n\n g_points.append([depth * (center[0] - ppx) / fx, depth * (center[1] - ppy) / fy, depth])\n\n self.in_ws_data.update({'points_3d': in_ws_points})\n self.out_ws_data.update({'points_3d': out_ws_points})\n self.g_data.update({'points_3d': g_points})\n\n return 0\n\n\n def sort_by_depth(self):\n \"\"\"sort the data by depth\"\"\"\n if self.out_ws_data is not None and self.out_ws_data['tomato_count'] != 0:\n depth = self.out_ws_data['depths']\n index_list = [i for i in range(len(depth))]\n combined = zip(index_list, depth)\n zipped_sorted = sorted(combined, key=lambda x: x[1])\n index_list, depth = map(list, zip(*zipped_sorted))\n data_sorted = {name: [] for name in self.out_ws_data if name != 'tomato_count'}\n for name in data_sorted:\n for ind in index_list:\n data_sorted[name].append(self.out_ws_data[name][ind])\n data_sorted.update({'tomato_count': self.out_ws_data['tomato_count']})\n self.out_ws_data = data_sorted\n\n\n if self.in_ws_data is not None and self.in_ws_data['tomato_count'] != 0:\n depth = self.in_ws_data['depths']\n index_list = [i for i in range(len(depth))]\n combined = zip(index_list, depth)\n zipped_sorted = sorted(combined, key=lambda x: x[1])\n index_list, depth = map(list, zip(*zipped_sorted))\n data_sorted = {name: [] for name in self.in_ws_data if name != 'tomato_count'}\n for name in data_sorted:\n for ind in index_list:\n data_sorted[name].append(self.in_ws_data[name][ind])\n data_sorted.update({'tomato_count': self.in_ws_data['tomato_count']})\n self.in_ws_data = data_sorted\n\n\n\n","sub_path":"Tomato/Tomato_ssd.py","file_name":"Tomato_ssd.py","file_ext":"py","file_size_in_byte":18253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"640795462","text":"from django.shortcuts import redirect, get_object_or_404,render_to_response\nfrom django.template import RequestContext\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic.simple import direct_to_template\nfrom django.contrib.auth.models import User\n\n\nfrom accounts.forms import SignupForm\n\n\ndef signup(request, signup_form=SignupForm, template_name='accounts/signup.html', success_url=None, extra_context=None):\n\n form = signup_form()\n if request.method == 'POST':\n form = signup_form(request.POST)\n if form.is_valid():\n user = form.save()\n\n if success_url: redirect_to = success_url\n else: redirect_to = reverse('accounts_signup_complete',\n kwargs={'username': user.username})\n return redirect(redirect_to)\n\n data = { 'form': form, }\n return render_to_response(template_name, data, context_instance=RequestContext(request))\n\n\ndef direct_to_user_template(request, username, template_name, extra_context=None):\n\n user = get_object_or_404(User, username__iexact=username)\n\n if not extra_context: extra_context = dict()\n extra_context['viewed_user'] = user\n return direct_to_template(request,\n template_name,\n extra_context=extra_context)\n","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"449015732","text":"from django.contrib.auth.models import AbstractUser\nfrom django.db import models\n\n\nclass User(AbstractUser):\n follow = models.ManyToManyField(\n 'self', symmetrical=False, related_name='follower',\n blank=True, verbose_name='на кого подписан'\n )\n\n class Meta:\n verbose_name = 'пользователь'\n verbose_name_plural = 'пользователи'\n","sub_path":"src/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"492855067","text":"\"\"\"\nTODO: brief description of filters.py\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom backtester.common_algos import swingpoints\n\n\nclass SwarmFilter(object):\n @staticmethod\n def filter_equity(equity, gf_function, gf_context):\n\n is_picked, gf_data = gf_function(equity, gf_context)\n\n # Litte bit future referencing but without entry point bug\n # Unusable in production (real-time environments)\n eqty_chg = equity.shift(-1) - equity\n return eqty_chg[is_picked].cumsum().ffill(), gf_data\n\n\n @staticmethod\n def rolling_mean(avg_swarm_eqty, context):\n period = context['ma_period']\n ma = avg_swarm_eqty.rolling(period).mean()\n return avg_swarm_eqty > ma, {'values': ma, 'name': 'GF: Moving average ({0} periods)'.format(period)}\n\n\n @staticmethod\n def volatility_chandelier(avg_swarm_eqty, context):\n period = context['period']\n down_factor = context['down_factor']\n up_factor = context['up_factor']\n\n vola = avg_swarm_eqty.diff(periods=period).abs().rolling(60).median()\n\n swing_point = pd.Series(np.nan, index=avg_swarm_eqty.index)\n swing_point_regime = pd.Series(0, index=avg_swarm_eqty.index)\n\n # Swing point bullish regime\n swing_switch = 1\n\n # Swing point start index\n sw_i = -1\n\n # Min/Max prices for swings\n sw_h_max = avg_swarm_eqty[0]\n sw_l_min = avg_swarm_eqty[0]\n\n for i in range(len(avg_swarm_eqty)):\n if i == 0:\n continue\n if np.isnan(avg_swarm_eqty[i]):\n continue\n if np.isnan(vola.values[i]):\n continue\n elif sw_i == -1 and vola.values[i] > 0:\n sw_h_max = sw_l_min = avg_swarm_eqty[i]\n sw_i = i\n\n if swing_switch == 1:\n #\n # We have a bullish swing\n #\n sw_h_max = max(sw_h_max, avg_swarm_eqty[i])\n\n # Check for reversion\n if avg_swarm_eqty[i] <= sw_h_max - vola[sw_i] * down_factor:\n # Reverse swing\n swing_switch = -1\n sw_l_min = avg_swarm_eqty.values[i]\n sw_h_max = avg_swarm_eqty.values[i]\n swing_point.values[i] = sw_l_min + vola[sw_i] * up_factor\n\n sw_i = i\n else:\n swing_point.values[i] = sw_h_max - vola[sw_i] * down_factor\n\n\n else:\n #\n # We have a bearish swing\n #\n sw_l_min = min(sw_l_min, avg_swarm_eqty.values[i])\n\n # Check for reversion\n if avg_swarm_eqty.values[i] >= sw_l_min + vola[sw_i] * up_factor:\n # Reverse swing\n swing_switch = 1\n sw_l_min = avg_swarm_eqty.values[i]\n sw_h_max = avg_swarm_eqty.values[i]\n sw_i = i\n swing_point.values[i] = sw_h_max - vola[sw_i] * down_factor\n else:\n swing_point.values[i] = sw_l_min + vola[sw_i] * up_factor\n\n swing_point_regime.values[i] = swing_switch\n\n return swing_point_regime == 1, {'values': swing_point,\n 'input_equity': avg_swarm_eqty,\n 'name': 'GF: SwingPoint ({0} chg-periods, {1} up, {2} down)'.format(period, up_factor, down_factor)}\n\n\n @staticmethod\n def swingpoint_daily(avg_swarm_eqty, context):\n down_factor = context['down_factor']\n up_factor = context['up_factor']\n\n\n spreadSeries = avg_swarm_eqty\n\n data = pd.DataFrame({'exo': spreadSeries, 'volume': pd.Series(0, index=spreadSeries.index) })\n sp_df = swingpoints(up_factor, down_factor, data)\n\n\n BULLISH = 1\n BEARISH = -1\n UNDEFINED = 0\n lastSWPHigh = np.inf # intmax('int32');\n lastSWPLow = -np.inf # intmin('int32');\n EPSILON = 0.000000000001\n\n nDays = len(sp_df)\n currentState = UNDEFINED\n nBase = 0 # nDays - length(spreadSeries);\n marketState = np.zeros(nDays, dtype=np.int8) # zeros(1, nDays);\n\n sphIndicator = sp_df['sphIndicator'].values\n splIndicator = sp_df['splIndicator'].values\n sphLevel = sp_df['sphLevel'].values\n splLevel = sp_df['splLevel'].values\n\n for dd in range(1, nDays):\n if dd <= nBase:\n continue\n if sphIndicator[dd - nBase]:\n lastSWPHigh = sphLevel[dd - nBase]\n if splIndicator[dd - nBase]:\n lastSWPLow = splLevel[dd - nBase]\n\n if currentState == BULLISH:\n pass\n if (spreadSeries[dd - nBase] - lastSWPLow <= -EPSILON and\n spreadSeries[dd - nBase - 1] - lastSWPLow > -EPSILON) \\\n or \\\n (lastSWPLow - lastSWPHigh >= EPSILON and\n spreadSeries[dd - nBase] - lastSWPHigh <= -EPSILON and\n spreadSeries[dd - nBase - 1] - lastSWPHigh > -EPSILON):\n currentState = BEARISH\n\n elif currentState == BEARISH:\n if (spreadSeries[dd - nBase] - lastSWPHigh >= EPSILON and\n spreadSeries[dd - nBase - 1] - lastSWPHigh < EPSILON) \\\n or \\\n (lastSWPLow - lastSWPHigh >= EPSILON and\n spreadSeries[dd - nBase] - lastSWPLow >= EPSILON and\n spreadSeries[dd - nBase - 1] - lastSWPLow < EPSILON):\n currentState = BULLISH\n\n else: # currentState == UNDEFINED\n if spreadSeries[dd] - lastSWPHigh >= EPSILON:\n currentState = BULLISH\n if spreadSeries[dd] - lastSWPLow <= -EPSILON:\n currentState = BEARISH\n\n marketState[dd] = currentState\n\n return pd.Series(marketState == BULLISH, index=spreadSeries.index, dtype=np.uint8), \\\n {\n 'values': pd.Series(marketState, index=spreadSeries.index),\n 'input_equity': avg_swarm_eqty,\n 'name': 'GF: SwingPoint Daily ({0} up, {1} down)'.format(up_factor,\n down_factor)\n }","sub_path":"backtester/swarms/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":6534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"448211781","text":"from auto_test.YH.common.base import get_response\nfrom auto_test.YH.common.logger import Log\nfrom auto_test.YH.case.fresh_purchase.apis_test.app_api.get_key import getKey\nfrom auto_test.YH.test_data.read_data import get_test_data\nfrom auto_test.YH.case.fresh_purchase.apis_test.app_api.app_login import getAppToken\n\n\n\nclass makeOrder(object):\n def __init__(self):\n self.log = Log() # 初始化日志\n self.token = getAppToken().get_token() # 获取token\n self.key = getKey().get_key() # 获取key\n self.test_data = get_test_data('/fresh_data.xlsx', 'app', 2) # 初始化测试数据\n\n def get_order(self):\n \"\"\"\n 制单\n :return:\n \"\"\"\n headers = eval(self.test_data.get('header'))\n headers['login-token'] = getAppToken().get_token()\n url = self.test_data.get('route') + self.key\n try:\n res = get_response(url, self.test_data.get('method'),\n data=self.test_data.get('data').encode('utf-8'),\n headers=headers)\n return res\n except Exception as e:\n self.log.error('请求异常%s' % e)\n\n\n","sub_path":"auto_test/YH/case/fresh_purchase/apis_test/app_api/make_order.py","file_name":"make_order.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"272215018","text":"#!/usr/bin/python3\n\n\nimport sys\nfrom time import sleep\ndata =sys.argv[1:]\nsum = 0\nfor i in data:\n sum = sum +int(i)\n\nprint (\" The sum of the numbers is \",sum)\n\n","sub_path":"Day1_P5.py","file_name":"Day1_P5.py","file_ext":"py","file_size_in_byte":163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"187494168","text":"\n\nfrom xai.brain.wordbase.nouns._librarian import _LIBRARIAN\n\n#calss header\nclass _LIBRARIANS(_LIBRARIAN, ):\n\tdef __init__(self,): \n\t\t_LIBRARIAN.__init__(self)\n\t\tself.name = \"LIBRARIANS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"librarian\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_librarians.py","file_name":"_librarians.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"412404456","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom ast import literal_eval\nfrom copy import deepcopy\nfrom lxml import etree\n\nimport odoo\nfrom odoo import http, _\nfrom odoo.http import content_disposition, request\nfrom odoo.exceptions import UserError, AccessError, ValidationError\nfrom odoo.addons.web_studio.controllers import export\nfrom odoo.tools import ustr\n\n\nclass WebStudioController(http.Controller):\n\n @http.route('/web_studio/chatter_allowed', type='json', auth='user')\n def is_chatter_allowed(self, model):\n \"\"\" Returns True iff a chatter can be activated on the model's form views, i.e. if\n - it is a custom model (since we can make it inherit from mail.thread), or\n - it already inherits from mail.thread.\n \"\"\"\n Model = request.env[model]\n return Model._custom or isinstance(Model, type(request.env['mail.thread']))\n\n @http.route('/web_studio/get_studio_action', type='json', auth='user')\n def get_studio_action(self, action_name, model, view_id=None, view_type=None):\n view_type = 'tree' if view_type == 'list' else view_type # list is stored as tree in db\n model = request.env['ir.model'].search([('model', '=', model)], limit=1)\n\n action = None\n if hasattr(self, '_get_studio_action_' + action_name):\n action = getattr(self, '_get_studio_action_' + action_name)(model, view_id=view_id, view_type=view_type)\n\n return action\n\n def _get_studio_action_acl(self, model, **kwargs):\n return {\n 'name': _('Access Control Lists'),\n 'type': 'ir.actions.act_window',\n 'res_model': 'ir.model.access',\n 'views': [[False, 'list'], [False, 'form']],\n 'target': 'current',\n 'domain': [],\n 'context': {\n 'default_model_id': model.id,\n 'search_default_model_id': model.id,\n },\n 'help': _(\"\"\"\n Add a new access control list\n
\n \"\"\"),\n }\n\n def _get_studio_action_automations(self, model, **kwargs):\n return {\n 'name': _('Automated Actions'),\n 'type': 'ir.actions.act_window',\n 'res_model': 'base.automation',\n 'views': [[False, 'list'], [False, 'form']],\n 'target': 'current',\n 'domain': [],\n 'context': {\n 'default_model_id': model.id,\n 'search_default_model_id': model.id,\n },\n 'help': _(\"\"\" \n Add a new automated action\n
\n \"\"\"),\n }\n\n def _get_studio_action_filters(self, model, **kwargs):\n return {\n 'name': _('Filter Rules'),\n 'type': 'ir.actions.act_window',\n 'res_model': 'ir.filters',\n 'views': [[False, 'list'], [False, 'form']],\n 'target': 'current',\n 'domain': [],\n 'context': { # model_id is a Selection on ir.filters\n 'default_model_id': model.model,\n 'search_default_model_id': model.model,\n },\n 'help': _(\"\"\" \n Add a new filter\n
\n \"\"\"),\n }\n\n def _get_studio_action_reports(self, model, **kwargs):\n return {\n 'name': _('Reports'),\n 'type': 'ir.actions.act_window',\n 'res_model': 'ir.actions.report',\n 'views': [[False, 'kanban'], [False, 'form']],\n 'target': 'current',\n 'domain': [(\"binding_model_id.transient\",\"=\",False)],\n 'context': {\n 'default_model': model.model,\n 'search_default_model': model.model,\n },\n 'help': _(\"\"\" \n Add a new report\n
\n \"\"\"),\n }\n\n def _get_studio_action_translations(self, model, **kwargs):\n \"\"\" Open a view for translating the field(s) of the record (model, id). \"\"\"\n domain = ['|', ('name', '=', model.model), ('name', 'ilike', model.model + ',')]\n\n # search view + its inheritancies\n views = request.env['ir.ui.view'].search([('model', '=', model.model)])\n domain = ['|', '&', ('name', '=', 'ir.ui.view,arch_db'), ('res_id', 'in', views.ids)] + domain\n\n def make_domain(fld, rec):\n name = \"%s,%s\" % (fld.model_name, fld.name)\n return ['&', ('res_id', '=', rec.id), ('name', '=', name)]\n\n def insert_missing(fld, rec):\n if not fld.translate:\n return []\n\n if fld.related:\n try:\n # traverse related fields up to their data source\n while fld.related:\n rec, fld = fld.traverse_related(rec)\n if rec:\n return ['|'] + domain + make_domain(fld, rec)\n except AccessError:\n return []\n\n assert fld.translate and rec._name == fld.model_name\n request.env['ir.translation'].insert_missing(fld, rec)\n return []\n\n # insert missing translations of views\n for view in views:\n for name, fld in view._fields.items():\n domain += insert_missing(fld, view)\n\n # insert missing translations of model, and extend domain for related fields\n record = request.env[model.model].search([], limit=1)\n if record:\n for name, fld in record._fields.items():\n domain += insert_missing(fld, record)\n\n action = {\n 'name': _('Translate view'),\n 'type': 'ir.actions.act_window',\n 'res_model': 'ir.translation',\n 'view_mode': 'tree',\n 'views': [[request.env.ref('base.view_translation_dialog_tree').id, 'list']],\n 'target': 'current',\n 'domain': domain,\n }\n\n return action\n\n @http.route('/web_studio/create_new_menu', type='json', auth='user')\n def create_new_menu(self, app_name=False, menu_name=False, model_id=False, is_app=False, parent_id=None, icon=None):\n \"\"\" Create a new menu @menu_name, linked to a new action associated to the model_id\n @param model_id: if not set, the action associated to this menu is the home menu\n except if @is_app is True that will create a new model\n @param is_app: if True, create an extra menu (app, without parent)\n @param parent_id: the parent of the new menu.\n To be set if is_app is False.\n @param icon: the icon of the new app.\n It can either be:\n - the ir.attachment id of the uploaded image\n - if the icon has been created, an array containing: [icon_class, color, background_color]\n To be set if is_app is True.\n \"\"\"\n model = None\n if model_id:\n model = request.env['ir.model'].browse(model_id)\n elif is_app:\n # create a new model\n model = request.env['ir.model'].studio_name_create(menu_name)\n\n # create the action\n if model:\n action = request.env['ir.actions.act_window'].create({\n 'name': menu_name,\n 'res_model': model.model,\n 'help': \"\"\"\n \n This is your new action ; by default, it contains a list view and a form view.\n
\n \n You can start customizing these screens by clicking on the Studio icon on the\n top right corner (you can also customize this help message there).\n
\n \"\"\",\n })\n action_ref = 'ir.actions.act_window,' + str(action.id)\n else:\n action = request.env.ref('base.action_open_website')\n action_ref = 'ir.actions.act_url,' + str(action.id)\n\n if is_app:\n # create the menus (app menu + first submenu)\n menu_values = {\n 'name': app_name,\n 'child_id': [(0, 0, {\n 'name': menu_name,\n 'action': action_ref,\n })]\n }\n\n menu_values.update(self._get_icon_fields(icon))\n\n new_context = dict(request.context)\n new_context.update({'ir.ui.menu.full_list': True}) # allows to create a menu without action\n new_menu = request.env['ir.ui.menu'].with_context(new_context).create(menu_values)\n\n else:\n # create the submenu\n new_menu = request.env['ir.ui.menu'].create({\n 'name': menu_name,\n 'action': action_ref,\n 'parent_id': parent_id,\n })\n\n return {\n 'menu_id': new_menu.id,\n 'action_id': action.id,\n }\n\n @http.route('/web_studio/edit_menu_icon', type='json', auth='user')\n def edit_menu_icon(self, menu_id, icon):\n values = self._get_icon_fields(icon)\n request.env['ir.ui.menu'].browse(menu_id).write(values)\n\n def _get_icon_fields(self, icon):\n \"\"\" Get icon related fields (depending on the @icon received). \"\"\"\n if isinstance(icon, int):\n icon_id = request.env['ir.attachment'].browse(icon)\n if not icon_id:\n raise UserError(_('The icon is not linked to an attachment'))\n return {'web_icon_data': icon_id.datas}\n elif isinstance(icon, list) and len(icon) == 3:\n return {'web_icon': ','.join(icon)}\n else:\n raise UserError(_('The icon has not a correct format'))\n\n @http.route('/web_studio/set_background_image', type='json', auth='user')\n def set_background_image(self, attachment_id):\n attachment = request.env['ir.attachment'].browse(attachment_id)\n if attachment:\n request.env.user.sudo(request.uid).company_id.background_image = attachment.datas\n\n @http.route('/web_studio/reset_background_image', type='json', auth='user')\n def reset_background_image(self):\n request.env.user.sudo(request.uid).company_id.background_image = None\n\n def create_new_field(self, values):\n \"\"\" Create a new field with given values.\n In some cases we have to convert \"id\" to \"name\" or \"name\" to \"id\"\n - \"model\" is the current model we are working on. In js, we only have his name.\n but we need his id to create the field of this model.\n - The relational widget doesn't provide any name, we only have the id of the record.\n This is why we need to search the name depending of the given id.\n \"\"\"\n # Get current model\n model = request.env['ir.model'].search([('model', '=', values.pop('model_name'))])\n values['model_id'] = model.id\n\n # Field type is called ttype in the database\n if values.get('type'):\n values['ttype'] = values.pop('type')\n\n # For many2one and many2many fields\n if values.get('relation_id'):\n values['relation'] = request.env['ir.model'].browse(values.pop('relation_id')).model\n # For related one2many fields\n if values.get('related') and values.get('ttype') == 'one2many':\n field_name = values.get('related').split('.')[-1]\n field = request.env['ir.model.fields'].search([\n ('name', '=', field_name),\n ('model', '=', values.pop('relational_model')),\n ])\n field.ensure_one()\n values.update(\n relation=field.relation,\n relation_field=field.relation_field,\n )\n # For one2many fields\n if values.get('relation_field_id'):\n field = request.env['ir.model.fields'].browse(values.pop('relation_field_id'))\n values.update(\n relation=field.model_id.model,\n relation_field=field.name,\n )\n # For selection fields\n if values.get('selection'):\n values['selection'] = ustr(values['selection'])\n\n # Optional default value at creation\n default_value = values.pop('default_value', False)\n\n # Create new field\n new_field = request.env['ir.model.fields'].create(values)\n\n if default_value:\n if new_field.ttype == 'selection':\n if default_value is True:\n selection_values = literal_eval(new_field.selection)\n # take the first selection value as default one in this case\n default_value = len(selection_values) and selection_values[0][0]\n self.set_default_value(new_field.model, new_field.name, default_value)\n\n return new_field\n\n @http.route('/web_studio/add_view_type', type='json', auth='user')\n def add_view_type(self, action_type, action_id, res_model, view_type, args):\n view_type = 'tree' if view_type == 'list' else view_type # list is stored as tree in db\n try:\n request.env[res_model].fields_view_get(view_type=view_type)\n except UserError:\n return False\n self.edit_action(action_type, action_id, args)\n return True\n\n @http.route('/web_studio/edit_action', type='json', auth='user')\n def edit_action(self, action_type, action_id, args):\n\n action_id = request.env[action_type].browse(action_id)\n if action_id:\n if 'groups_id' in args:\n args['groups_id'] = [(6, 0, args['groups_id'])]\n\n if 'view_mode' in args:\n args['view_mode'] = args['view_mode'].replace('list', 'tree') # list is stored as tree in db\n\n # As view_id and view_ids have precedence on view_mode, we need to correctly set them\n if action_id.view_id or action_id.view_ids:\n view_modes = args['view_mode'].split(',')\n\n # add new view_mode\n missing_view_modes = [x for x in view_modes if x not in [y.view_mode for y in action_id.view_ids]]\n for view_mode in missing_view_modes:\n vals = {\n 'act_window_id': action_id.id,\n 'view_mode': view_mode,\n }\n if action_id.view_id and action_id.view_id.type == view_mode:\n # reuse the same view_id in the corresponding view_ids record\n vals['view_id'] = action_id.view_id.id\n\n request.env['ir.actions.act_window.view'].create(vals)\n\n for view_id in action_id.view_ids:\n if view_id.view_mode in view_modes:\n # resequence according to new view_modes\n view_id.sequence = view_modes.index(view_id.view_mode)\n else:\n # remove old view_mode\n view_id.unlink()\n\n action_id.write(args)\n\n return True\n\n @http.route('/web_studio/set_another_view', type='json', auth='user')\n def set_another_view(self, action_id, view_mode, view_id):\n\n action_id = request.env['ir.actions.act_window'].browse(action_id)\n window_view = request.env['ir.actions.act_window.view'].search([('view_mode', '=', view_mode), ('act_window_id', '=', action_id.id)])\n if not window_view:\n window_view = request.env['ir.actions.act_window.view'].create({'view_mode': view_mode, 'act_window_id': action_id.id})\n\n window_view.view_id = view_id\n\n return True\n\n def _get_studio_view(self, view):\n domain = [('inherit_id', '=', view.id), ('name', '=', self._generate_studio_view_name(view))]\n return view.search(domain, order='priority desc, name desc, id desc', limit=1)\n\n def _set_studio_view(self, view, arch):\n studio_view = self._get_studio_view(view)\n if studio_view and len(arch):\n studio_view.arch_db = arch\n elif studio_view:\n studio_view.unlink()\n elif len(arch):\n self._create_studio_view(view, arch)\n\n def _generate_studio_view_name(self, view):\n return \"Odoo Studio: %s customization\" % (view.name)\n\n @http.route('/web_studio/get_studio_view_arch', type='json', auth='user')\n def get_studio_view_arch(self, model, view_type, view_id=False):\n view_type = 'tree' if view_type == 'list' else view_type # list is stored as tree in db\n\n if not view_id:\n # TOFIX: it's possibly not the used view ; see fields_get_view\n # try to find the lowest priority matching ir.ui.view\n view_id = request.env['ir.ui.view'].default_view(request.env[model]._name, view_type)\n # We have to create a view with the default view if we want to customize it.\n view = self._get_or_create_default_view(model, view_type, view_id)\n studio_view = self._get_studio_view(view)\n\n return {\n 'studio_view_id': studio_view and studio_view.id or False,\n 'studio_view_arch': studio_view and studio_view.arch_db or \"\",\n }\n\n @http.route('/web_studio/edit_view', type='json', auth='user')\n def edit_view(self, view_id, studio_view_arch, operations=None):\n IrModelFields = request.env['ir.model.fields']\n view = request.env['ir.ui.view'].browse(view_id)\n\n parser = etree.XMLParser(remove_blank_text=True)\n arch = etree.fromstring(studio_view_arch, parser=parser)\n model = view.model\n\n # Determine whether an operation is associated with\n # the creation of a binary field\n def create_binary_field(op):\n node = op.get('node')\n if node and node.get('tag') == 'field' and node.get('field_description'):\n ttype = node['field_description'].get('type')\n is_image = node['attrs'].get('widget') == 'image'\n return ttype == 'binary' and not is_image\n return False\n\n # Every time the creation of a binary field is requested,\n # we also create an invisible char field meant to contain the filename.\n # The char field is then associated with the binary field\n # via the 'filename' attribute of the latter.\n for op in [op for op in operations if create_binary_field(op)]:\n filename = op['node']['field_description']['name'] + '_filename'\n\n # Create an operation adding an additional char field\n char_op = deepcopy(op)\n char_op['node']['field_description'].update({\n 'name': filename,\n 'type': 'char',\n 'field_description': _('Filename for %s') % op['node']['field_description']['name'],\n })\n char_op['node']['attrs']['invisible'] = '1'\n operations.append(char_op)\n\n op['node']['attrs']['filename'] = filename\n\n for op in operations:\n # create a new field if it does not exist\n if 'node' in op:\n if op['node'].get('tag') == 'field' and op['node'].get('field_description'):\n model = op['node']['field_description']['model_name']\n # Check if field exists before creation\n field = IrModelFields.search([\n ('name', '=', op['node']['field_description']['name']),\n ('model', '=', model),\n ], limit=1)\n if not field:\n field = self.create_new_field(op['node']['field_description'])\n op['node']['attrs']['name'] = field.name\n if op['node'].get('tag') == 'filter' and op['target']['tag'] == 'group' and op['node']['attrs'].get('create_group'):\n op['node']['attrs'].pop('create_group')\n create_group_op = {\n 'node': {\n 'tag': 'group',\n 'attrs': {\n 'name': 'studio_group_by',\n }\n },\n 'empty': True,\n 'target': {\n 'tag': 'search',\n },\n 'position': 'inside',\n }\n self._operation_add(arch, create_group_op, model)\n # set a more specific xpath (with templates//) for the kanban view\n if view.type == 'kanban':\n if op.get('target') and op['target'].get('tag') == 'field':\n op['target']['tag'] = 'templates//field'\n\n # call the right operation handler\n getattr(self, '_operation_%s' % (op['type']))(arch, op, model)\n\n # Save or create changes into studio view, identifiable by xmlid\n # Example for view id 42 of model crm.lead: web-studio_crm.lead-42\n new_arch = etree.tostring(arch, encoding='unicode', pretty_print=True)\n self._set_studio_view(view, new_arch)\n\n # Normalize the view\n studio_view = self._get_studio_view(view)\n try:\n normalized_view = studio_view.normalize()\n self._set_studio_view(view, normalized_view)\n except ValidationError: # Element '<...>' cannot be located in parent view\n # If the studio view is not applicable after normalization, let's\n # just ignore the normalization step, it's better to have a studio\n # view that is not optimized than to prevent the user from making\n # the change he would like to make.\n self._set_studio_view(view, new_arch)\n\n ViewModel = request.env[view.model]\n fields_view = ViewModel.with_context({'studio': True}).fields_view_get(view.id, view.type)\n view_type = 'list' if view.type == 'tree' else view.type\n\n return {\n 'fields_views': {view_type: fields_view},\n 'fields': ViewModel.fields_get(),\n 'studio_view_id': studio_view.id,\n }\n\n @http.route('/web_studio/rename_field', type='json', auth='user')\n def rename_field(self, studio_view_id, studio_view_arch, model, old_name, new_name):\n studio_view = request.env['ir.ui.view'].browse(studio_view_id)\n\n # a field cannot be renamed if it appears in a view ; we thus reset the\n # studio view before all operations to be able to rename the field\n studio_view.arch_db = studio_view_arch\n\n field_id = request.env['ir.model.fields']._get(model, old_name)\n field_id.write({'name': new_name})\n\n def _create_studio_view(self, view, arch):\n # We have to play with priorities. Consider the following:\n # View Base: \n # View Standard inherits Base: \n # View Custo inherits Base: \n # We want x,x2,z,y, because that's what we did in studio, but the order of xpath\n # resolution is sequence,name, not sequence,id. Because \"Custo\" < \"Standard\", it\n # would first resolve in x,x2,y, then resolve \"Standard\" with x,z,x2,y as result.\n return request.env['ir.ui.view'].create({\n 'type': view.type,\n 'model': view.model,\n 'inherit_id': view.id,\n 'mode': 'extension',\n 'priority': 99,\n 'arch': arch,\n 'name': self._generate_studio_view_name(view),\n })\n\n @http.route('/web_studio/edit_field', type='json', auth='user')\n def edit_field(self, model_name, field_name, values):\n field = request.env['ir.model.fields'].search([('model', '=', model_name), ('name', '=', field_name)])\n field.write(values)\n\n # remove default value if the value is not acceptable anymore\n if field.ttype == 'selection':\n current_default = request.env['ir.default'].get(model_name, field_name, company_id=True)\n if current_default:\n selection_values = literal_eval(field.selection)\n if current_default not in [x[0] for x in selection_values]:\n request.env['ir.default'].discard_values(model_name, field_name, [current_default])\n\n @http.route('/web_studio/edit_view_arch', type='json', auth='user')\n def edit_view_arch(self, view_id, view_arch):\n view = request.env['ir.ui.view'].browse(view_id)\n\n if view:\n view.write({'arch': view_arch})\n ViewModel = request.env[view.model]\n try:\n fields_view = ViewModel.with_context({'studio': True}).fields_view_get(view.id, view.type)\n view_type = 'list' if view.type == 'tree' else view.type\n return {\n 'fields_views': {\n view_type: fields_view,\n },\n 'fields': ViewModel.fields_get(),\n }\n except Exception:\n return False\n\n @http.route('/web_studio/export', type='http', auth='user')\n def export(self, token):\n \"\"\" Exports a zip file containing the 'studio_customization' module\n gathering all customizations done with Studio (customizations of\n existing apps and freshly created apps).\n \"\"\"\n studio_module = request.env['ir.module.module'].get_studio_module()\n data = request.env['ir.model.data'].search([('studio', '=', True)])\n content = export.generate_archive(studio_module, data)\n\n return request.make_response(content, headers=[\n ('Content-Disposition', content_disposition('customizations.zip')),\n ('Content-Type', 'application/zip'),\n ('Content-Length', len(content)),\n ], cookies={'fileToken': token})\n\n @http.route('/web_studio/create_default_view', type='json', auth='user')\n def create_default_view(self, model, view_type, attrs):\n attrs['string'] = \"Default %s view for %s\" % (view_type, model)\n # The grid view arch has the attributes set as children nodes and not in\n # the view node\n if view_type == 'grid':\n arch = self._get_default_grid_view(attrs)\n else:\n arch = self._get_default_view(view_type, attrs)\n request.env['ir.ui.view'].create({\n 'type': view_type,\n 'model': model,\n 'arch': arch,\n 'name': attrs['string'],\n })\n\n def _get_default_view(self, view_type, attrs):\n arch = etree.Element(view_type, attrs)\n return etree.tostring(arch, encoding='unicode', pretty_print=True, method='html')\n\n def _get_or_create_default_view(self, model, view_type, view_id=False):\n View = request.env['ir.ui.view']\n # If we have no view_id to inherit from, it's because we are adding\n # fields to the default view of a new model. We will materialize the\n # default view as a true view so we can keep using our xpath mechanism.\n if view_id:\n view = View.browse(view_id)\n else:\n arch = request.env[model].fields_view_get(view_id, view_type)['arch']\n view = View.create({\n 'type': view_type,\n 'model': model,\n 'arch': arch,\n 'name': \"Default %s view for %s\" % (view_type, model),\n })\n return view\n\n def _node_to_expr(self, node):\n if not node.get('attrs') and node.get('xpath_info'):\n # Format of expr is /form/tag1[]/tag2[]/[...]/tag[]\n expr = ''.join(['/%s[%s]' % (parent['tag'], parent['indice']) for parent in node.get('xpath_info')])\n else:\n # Format of expr is //tag[@attr1_name=attr1_value][@attr2_name=attr2_value][...]\n expr = '//' + node['tag']\n for k, v in node.get('attrs', {}).items():\n if k == 'class':\n # Special case for classes which usually contain multiple values\n expr += '[contains(@%s,\\'%s\\')]' % (k, v)\n else:\n expr += '[@%s=\\'%s\\']' % (k, v)\n\n # Avoid matching nodes in sub views.\n # Example with field as node:\n # A field should be defined only once in a view but in some cases,\n # a view can be composed by some other views where a field with\n # the same name may exist.\n # Here, we want to generate xpath based on the nodes in the parent view only.\n if not node.get('subview_xpath'):\n expr = expr + '[not(ancestor::field)]'\n\n # If we receive a more specific xpath because we are editing an inline\n # view, we add it in front of the generated xpath.\n if node.get('subview_xpath'):\n xpath = node.get('subview_xpath')\n if node.get('isSubviewAttr'):\n expr = xpath\n # Hack to check if the last subview xpath element is not the same than expr\n # E.g when we add a field in an empty subview list the expr computed\n # by studio will be only '/tree' but this is useless since the\n # subview xpath already specify this element. So in this case,\n # we don't add the expr computed by studio.\n elif len(xpath) - len(expr) != xpath.find(expr):\n expr = xpath + expr\n return expr\n\n # Create a new xpath node based on an operation\n # TODO: rename it in master\n def _get_xpath_node(self, arch, operation):\n expr = self._node_to_expr(operation['target'])\n position = operation['position']\n\n return etree.SubElement(arch, 'xpath', {\n 'expr': expr,\n 'position': position\n })\n\n def _operation_remove(self, arch, operation, model=None):\n expr = self._node_to_expr(operation['target'])\n\n # We have to create a brand new xpath to remove this field from the view.\n # TODO: Sometimes, we have to delete more stuff than just a single tag !\n etree.SubElement(arch, 'xpath', {\n 'expr': expr,\n 'position': 'replace'\n })\n\n def _operation_add(self, arch, operation, model):\n node = operation['node']\n xpath_node = self._get_xpath_node(arch, operation)\n\n # Take a xml_node and put columns on it:\n # If the xml_node is not a group, this function will create a group node\n # to add two columns on it.\n def add_columns(xml_node, title=False):\n # Get the random key generated is JS.\n # Expected value: 'studio__\n name = 'studio_group_' + xml_node.get('name').split('_')[2]\n\n if xml_node.tag != 'group':\n xml_node_group = etree.SubElement(xml_node, 'group', {'name': name})\n else:\n xml_node_group = xml_node\n\n xml_node_page_left = etree.SubElement(xml_node_group, 'group', {'name': name + '_left'})\n xml_node_page_right = etree.SubElement(xml_node_group, 'group', {'name': name + '_right'})\n if title:\n xml_node_page_left.attrib['string'] = _('Left Title')\n xml_node_page_right.attrib['string'] = _('Right Title')\n\n # Create the actual node inside the xpath. It needs to be the first\n # child of the xpath to respect the order in which they were added.\n xml_node = etree.Element(node['tag'], node.get('attrs'))\n if node['tag'] == 'notebook':\n name = 'studio_page_' + node['attrs']['name'].split('_')[2]\n xml_node_page = etree.Element('page', {'string': 'New Page', 'name': name})\n add_columns(xml_node_page)\n xml_node.insert(0, xml_node_page)\n elif node['tag'] == 'page':\n add_columns(xml_node)\n elif node['tag'] == 'group':\n if 'empty' not in operation:\n add_columns(xml_node, title=True)\n elif node['tag'] == 'button':\n # To create a stat button, we need\n # - a many2one field (1) that points to this model\n # - a field (2) that counts the number of records associated with the current record\n # - an action to jump in (3) with the many2one field (1) as domain/context\n #\n # (1) [button_field] the many2one field\n # (2) [button_count_field] is a non-stored computed field (to always have the good value in the stat button, if access rights)\n # (3) [button_action] an act_window action to jump in the related model\n button_field = request.env['ir.model.fields'].browse(node['field'])\n button_count_field, button_action = self._get_or_create_fields_for_button(model, button_field, node['string'])\n\n # the XML looks like \n \n \n \n \n \n \"\"\" % {'field': color_field_name})\n etree.SubElement(arch, 'xpath', {\n 'expr': '//div/*[1]',\n 'position': 'before',\n }).append(dropdown_node)\n\n # set the corresponding color attribute on the kanban record\n xpath_node = etree.SubElement(arch, 'xpath', {\n 'expr': '//div',\n 'position': 'attributes',\n })\n xml_node = xpath_node.find('attribute[@name=\"%s\"]' % ('color'))\n if xml_node is None:\n xml_node = etree.Element('attribute', {'name': 'color'})\n xml_node.text = color_field_name\n xpath_node.insert(0, xml_node)\n else:\n xml_node.text = color_field_name\n\n def _operation_kanban_image(self, arch, operation, model):\n \"\"\" Insert a image and its corresponding needs in an kanban view arch\n Implied modifications:\n - add the field in the view\n - add a section (kanban_right) in the view\n - add the field with `kanban_image` in this section\n \"\"\"\n model_id = request.env['ir.model'].search([('model', '=', model)])\n if not model_id:\n raise UserError(_('The model %s does not exist.') % model)\n\n if not operation.get('field'):\n raise UserError(_('Please specify a field.'))\n\n field_id = request.env['ir.model.fields'].search([\n ('model', '=', model),\n ('name', '=', operation['field'])\n ])\n if not field_id:\n raise UserError(_('The field %s does not exist.') % operation['field'])\n\n # add field at the beginning\n etree.SubElement(arch, 'xpath', {\n 'expr': 'templates',\n 'position': 'before',\n }).append(etree.Element('field', {'name': field_id.name}))\n\n # add the image inside the view\n etree.SubElement(arch, 'xpath', {\n 'expr': '//div',\n 'position': 'inside',\n }).append(\n etree.fromstring(\"\"\"\n
\n
![]()
\n
\n \"\"\" % {'model': field_id.relation, 'field': field_id.name})\n )\n\n def _operation_kanban_priority(self, arch, operation, model):\n \"\"\" Insert a priority and its corresponding needs in an kanban view arch\n Implied modifications:\n - create a selection field x_priority in the model if it doesn't exist\n - add a section (kanban_left) in the view\n - add the field x_priority with the widget priority in this section\n \"\"\"\n model_id = request.env['ir.model'].search([('model', '=', model)])\n if not model_id:\n raise UserError(_('The model %s does not exist.') % model)\n\n if operation.get('field'):\n field_id = request.env['ir.model.fields'].search([\n ('model', '=', model),\n ('name', '=', operation['field'])\n ])\n if not field_id:\n raise UserError(_('The field %s does not exist.') % operation['field'])\n\n else:\n field_id = request.env['ir.model.fields'].search([\n ('model_id', '=', model_id.id),\n ('name', '=', 'x_priority'),\n ('ttype', '=', 'selection')\n ])\n # create a field selection x_priority if it doesn't exist in the model\n if not field_id:\n field_id = request.env['ir.model.fields'].create({\n 'model': model,\n 'model_id': model_id.id,\n 'name': 'x_priority',\n 'field_description': 'Priority',\n 'ttype': 'selection',\n 'selection': \"[('0', 'Low'), ('1', 'Normal'), ('2', 'High')]\",\n })\n\n # add priority inside the view\n etree.SubElement(arch, 'xpath', {\n 'expr': '//div',\n 'position': 'inside',\n }).append(\n etree.fromstring(\"\"\"\n
\n \n
\n \"\"\" % (field_id.name))\n )\n\n def _operation_statusbar(self, arch, operation, model=None):\n \"\"\" Create and insert a header as the first child of the form. \"\"\"\n xpath_node = etree.SubElement(arch, 'xpath', {\n 'expr': '//form/*[1]',\n 'position': 'before'\n })\n xpath_node.append(etree.Element('header'))\n\n @http.route('/web_studio/get_email_alias', type='json', auth='user')\n def get_email_alias(self, model_name):\n \"\"\" Returns the email alias associated to the model @model_name if both exist\n \"\"\"\n result = {'alias_domain': request.env['ir.config_parameter'].get_param('mail.catchall.domain')}\n model = request.env['ir.model'].search([('model', '=', model_name)], limit=1)\n if model:\n email_alias = request.env['mail.alias'].search([('alias_model_id', '=', model.id)], limit=1)\n if email_alias:\n result['email_alias'] = email_alias.alias_name\n return result\n\n @http.route('/web_studio/set_email_alias', type='json', auth='user')\n def set_email_alias(self, model_name, value):\n \"\"\" Set the email alias associated to the model @model_name\n - if there is no email alias, it will be created\n - if there is one and the value is empty, it will be unlinked\n \"\"\"\n model = request.env['ir.model'].search([('model', '=', model_name)], limit=1)\n if model:\n email_alias = request.env['mail.alias'].search([('alias_model_id', '=', model.id)], limit=1)\n if email_alias:\n if value:\n email_alias.alias_name = value\n else:\n email_alias.unlink()\n else:\n request.env['mail.alias'].create({\n 'alias_model_id': model.id,\n 'alias_name': value,\n })\n\n @http.route('/web_studio/get_default_value', type='json', auth='user')\n def get_default_value(self, model_name, field_name):\n \"\"\" Return the default value associated to the given field. \"\"\"\n return {\n 'default_value': request.env['ir.default'].get(model_name, field_name, company_id=True)\n }\n\n @http.route('/web_studio/set_default_value', type='json', auth='user')\n def set_default_value(self, model_name, field_name, value):\n \"\"\" Set the default value associated to the given field. \"\"\"\n request.env['ir.default'].set(model_name, field_name, value, company_id=True)\n\n @http.route('/web_studio/create_stages_model', type='json', auth='user')\n def create_stages_model(self, model_name):\n \"\"\" Create a new model if it does not exist\n \"\"\"\n stages_model = model_name + '_stage'\n if not model_name.startswith('x_'):\n stages_model = 'x_' + stages_model\n model_id = request.env['ir.model'].search([\n ('model', '=', stages_model),\n ])\n if not model_id:\n model = request.env['ir.model'].search([('model', '=', model_name)])\n model_id = request.env['ir.model'].create({\n 'model': stages_model,\n 'name': model.name + ' ' + _('stages'),\n })\n return model_id.id\n\n @http.route('/web_studio/create_inline_view', type='json', auth='user')\n def create_inline_view(self, model, view_id, field_name, subview_type, subview_xpath):\n inline_view = request.env[model].load_views([[False, subview_type]])\n view = request.env['ir.ui.view'].browse(view_id)\n studio_view = self._get_studio_view(view)\n if not studio_view:\n studio_view = self._create_studio_view(view, '
')\n parser = etree.XMLParser(remove_blank_text=True)\n arch = etree.fromstring(studio_view.arch_db, parser=parser)\n expr = \"//field[@name='%s']\" % field_name\n if subview_xpath:\n expr = subview_xpath + expr\n position = 'inside'\n xpath_node = arch.find('xpath[@expr=\"%s\"][@position=\"%s\"]' % (expr, position))\n if xpath_node is None: # bool(node) == False if node has no children\n xpath_node = etree.SubElement(arch, 'xpath', {\n 'expr': expr,\n 'position': position\n })\n view_arch = inline_view['fields_views'][subview_type]['arch']\n xml_node = etree.fromstring(view_arch)\n xpath_node.insert(0, xml_node)\n studio_view.arch_db = etree.tostring(arch, encoding='utf-8', pretty_print=True)\n return studio_view.arch_db\n","sub_path":"addons13/web_studio/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":52625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"35559200","text":"import sys\nsys.path.append('src/util')\nimport requests\nimport pandas as pd\nimport numpy as np\nimport os\nfrom pytz import timezone\nfrom datetime import datetime, date, timedelta\nfrom dateutil.relativedelta import *\nfrom dotenv import load_dotenv\nimport logging\nimport logging.config\nimport math\nfrom utils import *\nimport json\nimport schedule\nimport time\n\nnp.seterr(divide='ignore', invalid='ignore')\nload_dotenv(dotenv_path='stock.env')\n\nlogging.config.fileConfig(fname='log.conf', disable_existing_loggers=False)\nlogger = logging.getLogger()\n\ndata_location = os.getenv(\"data\")\ndata_realtime = os.getenv(\"data\") + os.getenv(\"data_realtime\")\ntz = os.getenv(\"timezone\")\ndate_format = os.getenv(\"date_format\")\ndatetime_format = os.getenv(\"datetime_format\")\n\ndef isDown(df):\n fiveRedCandle = True\n for i in range(0, 5):\n # print(df.iloc[i].Close, df.iloc[i].Open)\n if df.iloc[i].Close >= df.iloc[i].Open:\n fiveRedCandle = False\n break\n maxHigh = max(list(df.loc[0:15].High))\n changedPercent = (maxHigh - df.iloc[0].Low)/df.iloc[0].Low\n reducedTwentyPercent = changedPercent > 20\n # print(fiveRedCandle, changedPercent, reducedTwentyPercent)\n return fiveRedCandle or reducedTwentyPercent\n\ndef scan(stocks):\n downStocks = []\n downBelowMA200Stocks = []\n for stock in stocks:\n df = pd.read_csv(\"{}{}.csv\".format(data_realtime, stock))\n getIndicators(df)\n if isDown(df):\n if df.iloc[0].Close < df.iloc[0].MA200:\n downBelowMA200Stocks.append(stock)\n else:\n downStocks.append(stock)\n if len(downStocks) > 0:\n print(\"Stock on down trend above MA200:\")\n print(\",\".join(downStocks))\n if len(downBelowMA200Stocks) > 0:\n print(\"Stock on down trend under MA200:\")\n print(\",\".join(downBelowMA200Stocks))\n\nif __name__ == \"__main__\":\n stocks = list(pd.read_csv(data_location + os.getenv('all_stocks'), header=None)[0])\n # stocks = ['MST']\n if len(sys.argv) == 2:\n if sys.argv[1] == 'down':\n scan(stocks)\n","sub_path":"src/scan/trends.py","file_name":"trends.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"650459773","text":"# Dangling comment placement in empty lists\n# Regression test for https://github.com/python/cpython/blob/03160630319ca26dcbbad65225da4248e54c45ec/Tools/c-analyzer/c_analyzer/datafiles.py#L14-L16\na1 = [ # a\n]\na2 = [ # a\n # b\n]\na3 = [\n # b\n]\n\n# Add magic trailing comma only if there is more than one entry, but respect it if it's\n# already there\nb1 = [\n aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa\n]\nb2 = [\n aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa,\n]\nb3 = [\n aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa,\n aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa\n]\n\n# Comment placement in non-empty lists\nc1 = [ # trailing open bracket\n # leading item\n 1,\n\n # between\n\n 2, # trailing item\n # leading close bracket\n] # trailing close bracket\n","sub_path":"crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"211128178","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n'''\n@author: Tengwei Yuan\n'''\n\nimport re\nfrom urllib import request\nfrom urllib.request import urlopen\n\nfrom bs4 import BeautifulSoup\n\n\ndef httpCrawler(url):\n '''\n @summary: 网页抓取\n '''\n content = httpRequest(url)\n title = parseHtml(content)\n saveData(title)\n\n\ndef httpRequest(url):\n '''\n @summary: 网络请求\n '''\n try:\n ret = None\n SockFile = None\n req = request.Request(url)\n req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)')\n req.add_header('Pragma', 'no-cache')\n\n SockFile = urlopen(req)\n ret = SockFile.read()\n finally:\n if SockFile:\n SockFile.close()\n\n return ret\n\n\ndef saveHtml(source, file_name):\n f = open(file_name, 'w', encoding='utf8')\n f.write(BeautifulSoup(source, 'lxml').prettify())\n f.close()\n\n\ndef parseHtml(html):\n '''\n @summary: 抓取结构化数据\n '''\n\n content = None\n pattern = '
([^<]*?)'\n temp = re.findall(pattern, html)\n if temp:\n content = temp[0]\n\n print(content)\n return content\n\n\n### get all needed urls from current search page and also url to next page\ndef get_urls(start_url):\n html = urlopen(start_url)\n\n base_url = 'http://place.qyer.com'\n bsObj = BeautifulSoup(html, 'lxml')\n\n for link in bsObj.findAll(\"a\", attrs={'class': 'ui_page_item ui_page_next'}):\n if 'href' in link.attrs:\n next_page_link = base_url + link.attrs['href']\n print(next_page_link)\n get_urls(next_page_link)\n return\n\n\n### get all needed items in current page with required methods like selenium\ndef get_items():\n return\n\n\nfrom lxml import html\nimport requests\n\n\ndef clean(item):\n return '. '.join(item).lstrip('\\n').lstrip(' ').rstrip(' ').rstrip('\\n')\n\n\ndef getInfo():\n page = requests.get('http://place.qyer.com/poi/V2YJY1FiBzBTZVI3/')\n tree = html.fromstring(page.content)\n title_xpath = '//*[@class=\"poiDet-largeTit\"]/h1[@class=\"en\"]/a/text()'\n body_xpath = '//*[@class=\"poiDet-detail\"]/text()'\n rank_title_xpath = '//div[@class=\"infos\"]/div[1]/ul/li[@class=\"rank\"]/text()'\n rank_info_xpath = '//div[@class=\"infos\"]/div[1]/ul/li[@class=\"rank\"]/span/text()'\n\n tips_xpath = '//*[@class=\"poiDet-tips\"]/li[*]/div[@class=\"content\"]/p/text()'\n\n rank_info = ''\n\n title = tree.xpath(title_xpath)\n body = tree.xpath(body_xpath)\n rank_title = tree.xpath(rank_title_xpath)\n rank_info = tree.xpath(rank_info_xpath)\n\n tips = tree.xpath(tips_xpath)\n\n title = clean(title)\n body = clean(body)\n rank_title = clean(rank_title)\n rank_info = clean(rank_info)\n tips = clean(tips)\n\n print(title)\n print(rank_title, rank_info)\n print(body)\n\n print(tips)\n\n\ndef getReview():\n # url = 'http://place.qyer.com/poi/V2UJYlFkBzBTZFI-/'\n #\n # review_title_xpath = \"//*[@class='poiDet-largeTit']/h1[@class='en']/a/text()\"\n # review_info_xpath = '//*[@id=\"commentTar\"]/div[2]/div[*]/text()'\n # page = requests.get('http://place.qyer.com/poi/V2UJYlFkBzBTZFI-/')\n\n url = 'https://cn.tripadvisor.com/Restaurant_Review-g154943-d4041836-Reviews-Cactus_Club_Cafe-Vancouver_British_Columbia.html'\n source = httpRequest(url)\n saveHtml(source, 'test.html')\n\n review_title_xpath = '//*[@id=\"HEADING\"]/text()'\n review_info_xpath = '//*[@id=\"review_*\"]/div/div[2]/div/div/div[4]/p/text()'\n page = requests.get(url)\n\n tree = html.fromstring(page.content)\n\n review_title = tree.xpath(review_title_xpath)\n review_info = tree.xpath(review_info_xpath)\n\n print(review_title)\n print(review_info)\n\n\nfrom selenium import webdriver\nimport time\n\n\ndef getReview_JS():\n driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')\n # driver.set_window_size(1120, 550)\n\n # driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')\n # driver.get(\"http://pythonscraping.com/pages/javascript/ajaxDemo.html\")\n driver.get(\n \"https://cn.tripadvisor.com/Restaurant_Review-g154943-d4041836-Reviews-Cactus_Club_Cafe-Vancouver_British_Columbia.html\")\n time.sleep(1)\n # review_xpath = '//*[@id=\"review_338052777\"]//p'\n # review_xpath = '//p[@class=\"partial_entry\"]'\n review_xpath = '//*[@id=\"REVIEWS\"]//p[@class=\"partial_entry\"]'\n reviews = driver.find_elements_by_xpath(review_xpath)\n for review in reviews:\n print(review.text)\n driver.close()\n\n\ndef get_review_pages():\n start_url = 'https://cn.tripadvisor.com/Restaurant_Review-g154943-d4041836-Reviews-Cactus_Club_Cafe-Vancouver_British_Columbia.html#REVIEWS'\n driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')\n driver.get(start_url)\n links = driver.find_elements_by_link_text(u'//a[contains(text(), \"下一页\")]')\n for link in links:\n # link.click()\n print(link.text)\n\n return\n\n\ndef saveData(data):\n '''\n @summary: 数据存储\n '''\n f = open('test', 'w', encoding='utf-16')\n f.write(data)\n f.close()\n\n\nif __name__ == '__main__':\n # url = 'http://www.amazon.com'\n # #httpCrawler(url)\n # source = httpRequest(url)\n # saveHtml(source, 'test1.html')\n\n # getInfo()\n # getReview_JS()\n # get_review_pages()\n\n # test_1()\n\n start_url = 'http://place.qyer.com/vancouver/food/?page=1'\n get_urls(start_url)\n","sub_path":"spider/SpiderTripAdvisor.py","file_name":"SpiderTripAdvisor.py","file_ext":"py","file_size_in_byte":5422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"189253598","text":"from pyramid.config import Configurator\n\n\ndef main(global_config, **settings):\n config = Configurator(settings=settings)\n config.include('pyramid_chameleon')\n config.add_route('index', '/')\n config.add_route('chat', '/chat')\n config.scan()\n return config.make_wsgi_app()\n\n\ndef meinheld_server_runner(wsgi_app, global_config, **settings):\n from meinheld import server, middleware\n host = settings.get('host', '0.0.0.0')\n port = int(settings.get('port', 8080))\n\n server.listen((host, port))\n server.set_access_logger(None)\n server.set_error_logger(None)\n\n print('Starting HTTP server on http://%s:%s' % (host, port))\n server.run(middleware.WebSocketMiddleware(wsgi_app))\n","sub_path":"wsocket/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"22081783","text":"import inspect, numpy, os, random, sys, transforms\nfrom baseforms import MoebiusBase, SphericalBase\nfrom click import progressbar\nfrom image import Image\nfrom math import log10, isnan\n\n\ndef safelog10(x):\n try:\n return log10(x)\n except ValueError:\n return 0.0\n\ndef test_seed(num_transforms, moebius_chance, spherical_chance, seed):\n \"\"\"\n Test whether the IFS seed will be both non-degenerate and interesting by\n rendering a low-resolution version\n \"\"\"\n lowres = IFSI(150, 150, 1000, 1000, num_transforms, moebius_chance, spherical_chance, seed)\n if lowres.iterate(range(1000)):\n if lowres.im.interest_factor() >= 120:\n return True\n return False\n\n\ndef get_seed(num_transforms, moebius_chance, spherical_chance):\n while True:\n seed = random.randrange(sys.maxsize)\n if test_seed(num_transforms, moebius_chance, spherical_chance, seed):\n return seed\n\n\nclass IFSI: # IFS Image\n def __init__(self, width, height, iterations, num_points, num_transforms, moebius_chance, spherical_chance, seed, exclude=[], include=[], filename=None):\n self.seed = seed\n self.rng = random.Random(seed)\n self.ifs = IFS(self.rng, num_transforms, moebius_chance, spherical_chance, exclude, include)\n self.im = Image(width, height, max(1, (num_points * iterations) / (width * height)))\n self.iterations = iterations\n self.num_points = num_points\n self.name = \"-\".join([t.get_name() for w,t in self.ifs.transforms])\n if filename == None:\n self.filename = os.path.join(\"im\", self.name + \"_\" + str(self.seed))\n self.filename += \"_\" + str(self.im.width) + \"x\" + str(self.im.height)\n self.filename += \".png\"\n else:\n self.filename = filename\n\n def render(self, bar=True):\n if bar is True:\n label = \"Rendering \" + self.name\n with progressbar(length=self.num_points, label=label, width=0) as iter:\n if self.iterate(iter):\n return self\n else:\n if hasattr(bar, \"UpdateBar\"):\n guibar = bar\n else:\n guibar = None\n if self.iterate(range(self.num_points), guibar=guibar):\n return self\n return False\n\n def iterate(self, iterator, guibar=None):\n for i in iterator:\n\n # Start with a random point, and the color black\n px = self.rng.uniform(-1, 1)\n py = self.rng.uniform(-1, 1)\n r, g, b = 0.0, 0.0, 0.0\n zero_count, cont_count = 0, 0\n\n # Run the starting point through the system repeatedly\n for j in range(self.iterations):\n t = self.ifs.choose_transform()\n try:\n px, py = t.transform(px, py)\n except ZeroDivisionError:\n zero_count += 1\n if zero_count >= 10:\n cont_count +=1\n if cont_count >= 10:\n # Degenerate form. Abort render.\n return False\n continue\n r, g, b = t.transform_colour(r, g, b)\n\n # Apply final transform for every iteration\n fx, fy = self.ifs.final_transform(px, py)\n x = int((fx + 1) * self.im.width / 2)\n y = int((fy + 1) * self.im.height / 2)\n\n # Plot the point in the image buffer\n self.im.add_radiance(x, y, [r, g, b])\n\n if guibar:\n guibar.UpdateBar(i+1)\n return self\n\n def save_image(self):\n if not os.path.exists(\"im\"):\n os.makedirs(\"im\")\n self.im.save(self.filename)\n return self\n\n def get_image(self):\n a = numpy.array([safelog10(x) for x in self.im.data])\n return numpy.reshape(a / max(a), (self.im.width, self.im.height, 3))\n\nclass IFS:\n def __init__(self, rng, num_transforms, moebius_chance, spherical_chance, exclude, include):\n self.transforms = []\n self.total_weight = 0\n self.rng = rng\n\n transform_choices = []\n transform_list = inspect.getmembers(sys.modules[\"transforms\"], inspect.isclass)\n name_list = [name for (name, obj) in transform_list]\n name_list = list(set(name_list) - set(exclude))\n\n if include != []:\n name_list = list(set(name_list) & set(include))\n for (name, obj) in transform_list:\n if name in name_list:\n transform_choices.append(obj)\n\n for n in range(num_transforms):\n # Pick a transform, and possibly either a Moebius and/or Spherical baseform\n xform = self.rng.choice(transform_choices)(self.rng)\n if self.rng.random() < moebius_chance:\n xform = MoebiusBase(self.rng, xform)\n if self.rng.random() < spherical_chance:\n xform = SphericalBase(self.rng, xform)\n self.add_transform(xform)\n\n def add_transform(self, transform):\n weight = self.rng.gauss(1, 0.2) * self.rng.gauss(1, 0.2)\n self.total_weight += weight\n self.transforms.append((weight, transform))\n\n def choose_transform(self):\n w = self.rng.random() * self.total_weight\n running_total = 0\n for weight, transform in self.transforms:\n running_total += weight\n if w <= running_total:\n return transform\n\n def final_transform(self, px, py):\n \"\"\"\n Final transform to be applied after each iteration\n \"\"\"\n a = 0.5\n b = 0\n c = 0\n d = 1\n z = complex(px, py)\n z2 = (a * z + b) / (c * z + d)\n return z2.real, z2.imag\n","sub_path":"ifs.py","file_name":"ifs.py","file_ext":"py","file_size_in_byte":5781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"264628367","text":"# Make a dictionary where the key is a worker’s name, and the value is a list\n# where the first element is the clock in time, second element is the clock\n# out time, and the third element is the total hours worked that day. Each\n# worker’s list starts at [0, 0, 0]. Create functions for clock_in and\n# clock_out.\n#\n# clock_in takes the dictionary of workers, the name of the worker, and the\n# clock in time as parameters. When the worker clocks in, enter and save\n# their clock in time as the first element in the associated list value.\n#\n# clock_out takes the same parameters, but with a clock out time instead\n# of clock in time. When the worker clocks out, enter and save their clock\n# out time and calculate the hours worked for that day and store it as the\n# third element in the list.\n#\n# To make this program a little easier, we’re entering the clock in and\n# clock out times as integers. As a bonus mission, try adding the times as\n# strings representing the 24 hour clock (e.g., \"08:00\"), and then figure out\n# how to calculate the time worked. And you can do this exercise either by\n# aliasing or copying the dictionary.\n\n\ndef clock_in(dict, worker_name, clock_in_time):\n dict[worker_name] = [clock_in_time, 0, 0]\n\n\ndef clock_out(dict, worker_name, clock_out_time):\n dict[worker_name][1] = clock_out_time\n dict[worker_name][2] = clock_out_time - dict[worker_name][0]\n\n\ndef main():\n workers = {\n \"George Spelvin\": [0, 0, 0],\n \"Jane Doe\": [0, 0, 0],\n \"John Smith\": [0, 0, 0]}\n print(workers.get(\"George Spelvin\")) # should print [0,0,0]\n clock_in(workers, \"George Spelvin\", 8)\n clock_out(workers, \"George Spelvin\", 17)\n print(workers.get(\"George Spelvin\")) # should print [8, 17, 9]\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"unit1/Chapter 11 - Dictionaries and Tuples/Chapter 11 - Exercise 04.py","file_name":"Chapter 11 - Exercise 04.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"58475339","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\ntry:\n from email.MIMEMultipart import MIMEMultipart\n from email.MIMEText import MIMEText\nexcept ImportError: #Python3\n from email.mime.multipart import MIMEMultipart\n from email.mime.text import MIMEText\nimport smtplib\nimport os\nfrom webbreaker.notifiers.notifier import Notifier\nfrom webbreaker.webbreakerlogger import Logger\nfrom subprocess import CalledProcessError\ntry:\n import ConfigParser as configparser\nexcept ImportError: #Python3\n import configparser\n\ntry: # Python 2\n config = configparser.SafeConfigParser()\nexcept NameError: # Python 3\n config = configparser.ConfigParser()\n\nclass EmailNotifier(Notifier):\n def __init__(self, emailer_settings=None):\n if emailer_settings:\n self.emailer_settings = emailer_settings\n else:\n self.is_agent = True\n self.__read_agent_settings__()\n Notifier.__init__(self, \"EmailNotifier\")\n\n def notify(self, event):\n try:\n msg = MIMEMultipart()\n msg['From'] = self.emailer_settings['from_address']\n msg['To'] = self.emailer_settings['to_address']\n msg['Subject'] = \"{0} {1}\".format(event['subject'], event['scanname'])\n\n html = str(self.emailer_settings['email_template']).format(event['server'],\n event['scanname'],\n event['scanid'],\n event['subject'],\n \"\".join(\n [\"
{0}\".format(t) for t in event['targets']]))\n msg.attach(MIMEText(html, 'html'))\n\n mail_server = smtplib.SMTP(self.emailer_settings['smtp_host'], self.emailer_settings['smtp_port'])\n mail_server.sendmail(msg['From'], msg['To'], msg.as_string())\n\n mail_server.quit()\n except (Exception, AttributeError) as e: # we don't want email failure to stop us, just log that it happened\n Logger.app.error(\"Error sending email. {}\".format(e.message))\n Logger.console.error(\"Error sending email, see log: {}!\".format(Logger.app_logfile))\n\n def cloudscan_notify(self, recipient, subject, git_url, ssc_url, state, scan_id, scan_name):\n try:\n msg = MIMEMultipart()\n msg['From'] = self.from_address\n msg['To'] = recipient\n msg['Subject'] = subject\n\n html = str(self.email_template).format(git_url, ssc_url, scan_name, scan_id, state, self.chatroom)\n msg.attach(MIMEText(html, 'html'))\n\n mail_server = smtplib.SMTP(self.smtp_host, self.smtp_port)\n mail_server.sendmail(msg['From'], msg['To'], msg.as_string())\n\n mail_server.quit()\n except (Exception, AttributeError) as e: # we don't want email failure to stop us, just log that it happened\n Logger.app.error(\"Error sending email. {}\".format(e.message))\n Logger.console.error(\"Error sending email, see log: {}!\".format(Logger.app_logfile))\n\n\n def __read_agent_settings__(self):\n settings_file = os.path.abspath(os.path.join('webbreaker', 'etc', 'email.ini'))\n try:\n config.read(settings_file)\n self.smtp_host = config.get(\"agent_emailer\", \"smtp_host\")\n self.smtp_port = config.get(\"agent_emailer\", \"smtp_port\")\n self.from_address = config.get(\"agent_emailer\", \"from_address\")\n self.email_template = config.get(\"agent_emailer\", \"email_template\")\n self.default_to_address = config.get(\"agent_emailer\", \"default_to_address\")\n self.chatroom = config.get(\"agent_emailer\", \"chatroom\")\n\n except (configparser.NoOptionError, CalledProcessError) as noe:\n Logger.console.error(\"{} has incorrect or missing values {}\".format(settings_file, noe))\n except configparser.Error as e:\n Logger.app.error(\"Error reading {} {}\".format(settings_file, e))\n\n def __str__(self):\n return \"EmailNotifier\"\n","sub_path":"webbreaker/notifiers/emailer.py","file_name":"emailer.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"384162572","text":"from __future__ import division\nimport numpy as np\n\nclass Invest(object):\n \"\"\" Investment instrument class \"\"\"\n def __init__(self, asset):\n \"\"\" Constructor of the class. \n\n Args:\n asset (int): Total asset possessed. \n\n \"\"\"\n self.asset = asset\n\n def simulate(self, ntrials, position):\n \"\"\" Simulate the investment given number of shares to purchase.\n\n Args:\n ntrials (int): number of trials to simulate.\n position (int): number of shares to purchase.\n\n Returns:\n (float): daily return rate calculated from the simulation results.\n\n \"\"\"\n position_value = self.asset / position # Value per share given position\n cumu_ret = []\n for trial in xrange(ntrials):\n gain = np.random.uniform(size=position) > 0.49 # Gain money?\n cumu_ret.append(gain.sum() * position_value * 2)\n\n daily_ret = [ret/1000-1 for ret in cumu_ret]\n return daily_ret\n\n \n","sub_path":"yx887/invest/investment.py","file_name":"investment.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"50926739","text":"\n# Import Libraries\nimport sys\nimport getopt\nfrom time import strftime, gmtime\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Convolution1D, Flatten, MaxPooling1D, Dropout, PReLU\nfrom keras.optimizers import RMSprop, Adam, Nadam\nfrom keras.regularizers import l2\nfrom keras.models import load_model, Model\n\nfrom learning_utils import *\n\n\nPHOVECT_COLS = ['consonant', 'speaker', 'vowel', 'token']\nNAMES = ['Jonny', 'Ira', 'Anna', 'Dani', 'Theresa']\nCONS = ['g', 'b']\nVOWS = ['I', 'o', 'a', 'ae', 'e', 'u']\nPHONEME_DIR = '/Users/Jonny/Github/SVN-ComboPack/ratrixSounds/phonemes/'\n\nMAPBACK = {'g':1,'b':2,\n 'Jonny':1,'Ira':2,'Anna':3,'Dani':4,'Theresa':5,\n 'I':1,'o':2,'a':3,'ae':4,'e':5,'u':6}\n\nSPEC_TYPE = \"mel\" # or \"spec\"\n\nMEL_PARAMS = {\n \"n_fft\" : 960,\n \"hop_length\" : 960,\n \"n_mels\" : 64,\n \"fmin\" : 1000,\n \"htk\" : True\n}\n\nSPEC_PARAMS = {\n \"window\" : \"hamming\",\n \"nperseg\" : 960,\n \"noverlap\" : 480,\n \"return_onesided\" : True,\n \"scaling\" : \"spectrum\"\n}\n\nLOAD_PARAMS = {\n \"scale\" : True,\n \"prop_train\" : 0.9,\n \"as_row\" : False,\n\n # What form should the data be in?\n # possible vals:\n # \"regression\" - fit spectrograms to continuous predictions\n # \"trials\" - fit spectrograms to record of trials\n \"net_type\" : \"regression\",\n\n # Weight training by what?\n # possible vals:\n # None - don't weight\n # \"correct\" - weight by accuracy\n \"weight_by\" : None\n}\n\n\nDATA_DIR = '/Users/Jonny/Documents/fixSpeechData/'\nN_CONV_FILTERS = 64\nFILT_LEN = 32\nLEARN_RATE = 0.005\nL2_WEIGHT = 0.001\nOPTIMIZER_TYPE = \"adam\" # nadam, adam, or rmsprop\nNET_TYPE = LOAD_PARAMS[\"net_type\"]\n\n# Jitter audio so all don't start at same time\nN_JIT = 1\nJIT_AMT = 0.1 # In seconds\n\n\n##########################################\n\nphovect_idx, phovect_xdi, file_idx, file_loc = (\n make_phoneme_iterators(NAMES, CONS, VOWS, MAPBACK, PHONEME_DIR)\n )\n\nX_train,cons_train,speak_train,vow_train = audio_from_files(file_loc, phovect_idx, N_JIT, JIT_AMT)\n\n\n\n\n##########################################\n# Check if we were passed a model string or if we are training fresh\ntry:\n opts,args = getopt.getopt(sys.argv[1:],\"p:\")\nexcept:\n opts = None\n args = None\n\nloaded = False\nfor opt, arg in opts:\n if opt == '-p':\n print('Loading model {}'.format(arg))\n model = load_model(arg)\n loaded = True\n\nif not loaded:\n print('Building model')\n\n if OPTIMIZER_TYPE == \"nadam\":\n optimizer = Nadam(lr=LEARN_RATE)\n elif OPTIMIZER_TYPE == \"adam\":\n optimizer = Adam(lr=LEARN_RATE)\n else:\n optimizer = RMSprop(lr=LEARN_RATE, clipnorm=1.)\n\n #Build model\n #Convolution layers\n #As per https://arxiv.org/pdf/1412.6806v3.pdf\n model = Sequential()\n # FIRST 2 CONV LAYERS\n model.add(Convolution1D(N_CONV_FILTERS, FILT_LEN,\n init='he_normal',\n border_mode='same',\n W_regularizer=l2(L2_WEIGHT),\n activation='relu',\n #activity_regularizer=activity_l2(L2_WEIGHT),\n batch_input_shape=X_train.shape))\n # model.add(PReLU())\n model.add(Dropout(0.1))\n model.add(Convolution1D(N_CONV_FILTERS, FILT_LEN,\n init='he_normal',\n border_mode='same',\n activation='relu',\n W_regularizer=l2(L2_WEIGHT)))\n #activity_regularizer=activity_l2(L2_WEIGHT),))\n # model.add(PReLU())\n model.add(Dropout(0.1))\n # model.add(Convolution1D(N_CONV_FILTERS, FILT_LEN,\n # init='he_normal',\n # border_mode='same',\n # # activation=PReLU(),\n # W_regularizer=l2(L2_WEIGHT)))\n # #activity_regularizer=activity_l2(L2_WEIGHT),\n # model.add(Dropout(0.1))\n model.add(MaxPooling1D(pool_length=4))\n\n model.add(Convolution1D(N_CONV_FILTERS*2, FILT_LEN,\n init='he_normal',\n border_mode='same',\n activation='relu',\n #activity_regularizer=activity_l2(L2_WEIGHT),\n W_regularizer=l2(L2_WEIGHT)))\n # model.add(PReLU())\n model.add(Dropout(0.1))\n model.add(Convolution1D(N_CONV_FILTERS*2, FILT_LEN,\n init='he_normal',\n border_mode='same',\n W_regularizer=l2(L2_WEIGHT),\n #activity_regularizer=activity_l2(L2_WEIGHT),\n activation='relu'))\n # model.add(PReLU())\n model.add(Dropout(0.1))\n model.add(MaxPooling1D(pool_length=4))\n\n model.add(Convolution1D(N_CONV_FILTERS*2, FILT_LEN,\n init='he_normal',\n border_mode='same',\n W_regularizer=l2(L2_WEIGHT),\n activation='relu'))\n # model.add(PReLU())\n #model.add(Dropout(0.1))\n model.add(Convolution1D(N_CONV_FILTERS*2, FILT_LEN,\n init='he_normal',\n border_mode='same',\n W_regularizer=l2(L2_WEIGHT),\n activation='relu'))\n # model.add(PReLU())\n model.add(Dropout(0.1))\n model.add(MaxPooling1D(pool_length=4))\n\n # model.add(Convolution1D(N_CONV_FILTERS*4, 1,\n # init='he_normal',\n # border_mode='same',\n # W_regularizer=l2(L2_WEIGHT),\n # #activity_regularizer=activity_l2(L2_WEIGHT),\n # # activation=PReLU()))\n model.add(Dropout(0.1))\n\n model.add(Flatten())\n model.add(Dense(2,\n activation='softmax',\n init=\"he_uniform\",\n W_regularizer=l2(L2_WEIGHT)\n ))\n model.add(Dropout(0.1))\n model.compile(loss='binary_crossentropy',\n optimizer=optimizer,\n metrics=['binary_accuracy'])\n\n for i in range(100):\n X_train,y_train = audio_from_files(file_loc,phovect_idx,N_JIT,JIT_AMT)\n model.fit(X_train, y_train, batch_size=2, nb_epoch=1)\n model_str = '/Users/Jonny/Documents/Speech_Models/raw_conv_{}_N{}'.format(strftime(\"%m%d%H%M\", gmtime()),N_CONV_FILTERS)\n model.save(model_str)\n\n\n","sub_path":"analysis/speech/stim_properties/raw_conv_classifier_standalone.py","file_name":"raw_conv_classifier_standalone.py","file_ext":"py","file_size_in_byte":6678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"121308670","text":"from django.contrib.auth.models import User\nfrom django.test import TestCase\n\nfrom wiki.models import Page\n\n\n\n\nclass PageListViewTests(TestCase):\n def test_multiple_pages(self):\n # Make some test data to be displayed on the page.\n user = User.objects.create()\n\n Page.objects.create(title=\"My Test Page\", content=\"test\", author=user)\n Page.objects.create(title=\"Another Test Page\", content=\"test\", author=user)\n\n # Issue a GET request to the MakeWiki homepage.\n # When we make a request, we get a response back.\n response = self.client.get('/')\n\n # Check that the response is 200 OK.\n self.assertEqual(response.status_code, 200)\n\n # Check that the number of pages passed to the template\n # matches the number of pages we have in the database.\n responses = response.context['pages']\n self.assertEqual(len(responses), 2)\n\n self.assertQuerysetEqual(\n responses,\n ['
', ''],\n ordered=False\n )\n\n","sub_path":"wiki/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"391880845","text":"#!/usr/bin/env python3\n\nimport argparse\nimport datetime\nimport os\nimport sys\nimport threading\nimport urllib.request\nimport math\nimport json\n\n\ndef record_interval(stop_rec, stream_url, target_dir, station, interval):\n file_extension = \".mp3\"\n\n conn = urllib.request.urlopen(stream_url)\n content_type = conn.getheader('Content-Type')\n if content_type == 'application/ogg' or content_type == 'audio/ogg':\n file_extension = '.ogg'\n elif content_type == 'audio/x-mpegurl':\n print('Sorry, M3U playlists are currently not supported')\n sys.exit()\n elif content_type != \"audio/mpeg\":\n print('Unknown content type \"' + content_type + '\". Assuming mp3.')\n\n # Ignoring buffered content\n timestamp = datetime.datetime.now().timestamp()\n timestamp = math.floor(timestamp + 0.5)\n\n while not conn.close and datetime.datetime.now().timestamp() - timestamp < 2:\n conn.read(1024)\n\n # Start recording\n timestamp = datetime.datetime.now().timestamp()\n timestamp = math.floor(timestamp + 0.5)\n\n filename = os.path.join(target_dir, station.lower().replace(\" \", \"\").replace(\"-\", \"\") + '-')\n tmp_filename = filename + \".downloading\"\n with open(tmp_filename, \"wb\") as target:\n while not stop_rec.is_set() and not conn.closed and datetime.datetime.now().timestamp() - timestamp < interval:\n target.write(conn.read(1024))\n\n conn.close()\n filename = filename + str(timestamp) + file_extension\n os.rename(tmp_filename, filename)\n return filename\n\n\ndef record_worker(stop_rec, stream_url, target_dir, station, interval):\n while not stop_rec.is_set():\n try:\n record_interval(stop_rec, stream_url, target_dir, station, interval)\n except Exception as e:\n print(e, file=sys.stderr)\n\n\ndef record(stations, target_dir, interval):\n stop_rec = threading.Event()\n\n recording_threads = []\n for station in stations:\n record_thread = threading.Thread(target=record_worker,\n args=(stop_rec, station['endpoint'], target_dir, station['name'], interval))\n recording_threads.append(record_thread)\n\n for record_thread in recording_threads:\n record_thread.setDaemon(True)\n record_thread.start()\n\n for record_thread in recording_threads:\n record_thread.join()\n\n stop_rec.set()\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description='This script record internet streaming live stations.')\n\n parser.add_argument('-df', \"--data_folder\", type=str, help=\"Destination folder for recorded audios.\",\n default=\"data\")\n parser.add_argument('-i', \"--interval\", type=int, help=\"Interval time to reset recording\", default=10 * 60)\n parser.add_argument('-f', \"--stations\", type=str, help=\"Json file with stations list\", default=\"stations.json\")\n\n return parser.parse_args()\n\n\ndef main():\n args = parse_arguments()\n\n stations = []\n try:\n with open(args.stations) as target:\n stations.extend(json.loads(target.read()))\n except Exception as e:\n print(\"Error loading config file: \", e, file=sys.stderr)\n\n if not os.path.isdir(args.data_folder):\n print('Folder to save data does not exist', file=sys.stderr)\n exit(0)\n\n record(stations, args.data_folder, args.interval)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"s1-record-stream.py","file_name":"s1-record-stream.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"589768133","text":"import copy\nfrom typing import Dict, Union, List\nfrom pathlib import Path\n\nfrom typeguard import typechecked\nfrom zsvision.zs_utils import memcache, concat_features\n\nfrom utils import memory_summary\nfrom base.base_dataset import BaseDataset\n\n\nclass DiDeMo(BaseDataset):\n\n @staticmethod\n @typechecked\n def dataset_paths(training_file=None) -> Dict[str, Union[Path, str, Dict, List[str]]]:\n subset_paths = {}\n test_splits = {\n \"val\": \"val_list.txt\",\n \"test\": \"test_list.txt\",\n \"public_server_val\": \"public_server_val.txt\",\n \"public_server_test\": \"public_server_test.txt\",\n }\n for split_name, fname in test_splits.items():\n if training_file is None:\n subset_paths[split_name] = {\"train\": \"train_list.txt\", \"val\": fname}\n else:\n subset_paths[split_name] = {\"train\": training_file, \"val\": fname}\n\n feature_names = BaseDataset.common_feat_names()\n custom_paths = {\n \"audio\": [\"aggregated_audio_feats/vggish-audio-raw.pickle\"],\n \"ocr\": [\"aggregated_ocr_feats/ocr-feats.pkl\"],\n \"speech\": [\"aggregated_speech_feats/stt_w2v.pickle\"],\n \"face\": [\"aggregated_facefeats_25fps_256px_stride1/face-avg.pickle\"],\n }\n\n text_feat_paths = BaseDataset.common_text_feat_paths()\n # include non-standard text features\n text_feat_paths[\"openai\"] = \"openai-feats.pkl\"\n text_feat_paths = {key: Path(\"aggregated_text_feats\") / fname\n for key, fname in text_feat_paths.items()}\n\n challenge_text_feat_paths = {\n key: Path(\"aggregated_text_feats\") / f\"{key}{fname.suffix}\"\n for key, fname in text_feat_paths.items()\n }\n feature_info = {\n \"custom_paths\": custom_paths,\n \"feature_names\": feature_names,\n \"subset_list_paths\": subset_paths,\n \"text_feat_paths\": text_feat_paths,\n \"challenge_text_feat_paths\": challenge_text_feat_paths,\n \"raw_captions_path\": \"raw-captions.pkl\",\n }\n return feature_info\n\n def load_features(self):\n root_feat = Path(self.root_feat)\n if self.distil_params is not None:\n self.distil_features = {}\n d_base_path = self.distil_params['base_path']\n\n teachers = list(map(lambda x: root_feat / Path(d_base_path + x), self.distil_params['teachers']))\n\n for i, f_name in enumerate(teachers):\n self.distil_features[i] = memcache(f_name)\n\n feat_names = {key: self.visual_feat_paths(key) for key in\n self.paths[\"feature_names\"]}\n feat_names.update(self.paths[\"custom_paths\"])\n features = {}\n for expert, rel_names in feat_names.items():\n if expert not in self.ordered_experts:\n continue\n feat_paths = tuple([root_feat / rel_name for rel_name in rel_names])\n if len(feat_paths) == 1:\n features[expert] = memcache(feat_paths[0])\n else:\n # support multiple forms of feature (e.g. max and avg pooling). For\n # now, we only support direct concatenation\n msg = f\"{expert}: Only direct concatenation of muliple feats is possible\"\n print(f\"Concatenating aggregates for {expert}....\")\n assert self.feat_aggregation[expert][\"aggregate\"] == \"concat\", msg\n axis = self.feat_aggregation[expert][\"aggregate-axis\"]\n x = concat_features.cache_info() # pylint: disable=no-value-for-parameter\n print(f\"concat cache info: {x}\")\n features_ = concat_features(feat_paths, axis=axis)\n memory_summary()\n\n # Make separate feature copies for each split to allow in-place filtering\n features[expert] = copy.deepcopy(features_)\n\n self.features = features\n if self.challenge_mode:\n self.load_challenge_text_features()\n else:\n self.raw_captions = memcache(root_feat / self.paths[\"raw_captions_path\"])\n text_feat_path = root_feat / self.paths[\"text_feat_paths\"][self.text_feat]\n self.text_features = memcache(text_feat_path)\n\n def sanity_checks(self):\n msg = (f\"Expected to have single test caption for DiDemo, since we assume\"\n f\"that the captions are fused (but using {self.num_test_captions})\")\n assert self.num_test_captions == 1, msg\n","sub_path":"data_loader/DiDeMo_dataset.py","file_name":"DiDeMo_dataset.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"613931041","text":"import bluetooth\nfrom bluetooth import lookup_name\nimport time\nimport RPi.GPIO as GPIO\nfrom Arduino import arduino\n\nboard = arduino('9600')\n\nwhile True:\n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(40, GPIO.OUT)\n\n def RPIbluetooth():\n print(\"Checking \" + time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.gmtime()))\n result = bluetooth.lookup_name('A0:10:81:91:E8:EF', timeout=1)\n if (result is not None):\n print(\"User present\")\n GPIO.output(40, True)\n time.sleep(3)\n GPIO.output(40, False)\n else: \n GPIO.output(40, False)\n print(\"User out of range\")\n time.sleep(2)\n RPIbluetooth()\n\n if arduino.digitalRead(12) == \"HIGH\":\n print('High')\n RPIbluetooth()\n time.sleep(1)\n else:\n print('fail')\n time.sleep(2)\n","sub_path":"RPiBluetooth.py","file_name":"RPiBluetooth.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"51981583","text":"from bbfreeze import Freezer #@UnresolvedImport\n\nfolder_name =\"SysInterceptor\" \n\nf = Freezer(folder_name, includes=())\nf.addScript(\"..\\\\interceptor_tray.py\", gui_only=True)\nf.use_compression = 0\nf.include_py = True\nf() # starts the freezing proces\n\nimport os;\nos.system(\"copy ..\\\\CARRIER.ICO .\\\\SysInterceptor\")\nos.system(\"copy .\\\\SysInterceptor\\\\*.* ..\\\\..\\\\..\\\\..\\\\output\\\\final_release\")\nos.system(\"xcopy /E/Y ..\\\\calculator\\\\*.* ..\\\\..\\\\..\\\\..\\\\output\\\\final_release\\\\calculator\\\\\")\n","sub_path":"kb_codes/eclipse/py/syscarrier/src/interceptor/exe_generator/bbfreeze_exec_generator.py","file_name":"bbfreeze_exec_generator.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"632441767","text":"# Simple Linear Regression\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\n\n# Importing the dataset\ndataset = pd.read_csv('../data/Salary_Data.csv')\nX = dataset.loc[:, 'YearsExperience'].values.reshape(-1, 1)\ny = dataset.loc[:, 'Salary'].values.reshape(-1, 1)\n\n# Splitting the dataset into the Training set and Test set\nX_train, X_test, y_train, y_test = train_test_split(X, y,\n test_size=1/3,\n random_state=0)\n\n# Feature Scaling\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\nsc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train)\"\"\"\n\n# Fitting Simple Linear Regression to the Training set\nregressor = LinearRegression(fit_intercept=True,\n normalize=False,\n copy_X=True,\n n_jobs=None)\nregressor.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_pred = regressor.predict(X_test)\n\n# Visualising the Training set results\nfig = plt.figure(figsize=(16, 8))\nplt.scatter(X_train, y_train, color='red')\nplt.plot(X_train, regressor.predict(X_train), color='blue')\nplt.title('Salary vs Experience (Training set)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary')\n# plt.show()\nplt.savefig('../img/linreg_training_set.png')\n\n# Visualising the Test set results\nfig = plt.figure(figsize=(16, 8))\nplt.scatter(X_test, y_test, color='red')\nplt.plot(X_train, regressor.predict(X_train), color='blue')\nplt.title('Salary vs Experience (Test set)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary')\n# plt.show()\nplt.savefig('../img/linreg_test_set.png')\n","sub_path":"src/simple_linear_regression.py","file_name":"simple_linear_regression.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"219806495","text":"import numpy as np\nimport pandas as pd\nfrom time import time\nimport shutil\nimport os\nimport sys\nimport inspect\nimport unittest\n\ncurrentdir = os.path.dirname(\n os.path.abspath(\n inspect.getfile(\n inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0, parentdir)\n\nfrom src.lr.models.transformers.processor import filter_df_by_label, clean_df # noqa\nfrom src.lr.models.transformers.XLNetWrapper import XLNetWrapper # noqa\n\n\nbase_path = parentdir + \"/src/data/toy/\"\n\n\nclass BasicXLNetTraining(unittest.TestCase):\n\n @classmethod\n def tearDown(cls):\n if os.path.exists(\"example.log\"):\n os.remove(\"example.log\")\n\n if os.path.exists(\"xlnet\"):\n shutil.rmtree(\"xlnet\")\n\n paths = [\"cached_dev_to_eval_200\", \"cached_test_200\", \"cached_train_200\",\n \"cached_train_to_eval_200\"]\n\n for path in paths:\n path = parentdir + path\n if os.path.exists(path):\n os.remove(path)\n\n def test_xlnet_training(self):\n\n hyperparams = {\"local_rank\": -1,\n \"max_seq_length\": 200,\n \"overwrite_cache\": False,\n \"num_train_epochs\": 1.0,\n \"per_gpu_train_batch_size\": 32,\n \"per_gpu_eval_batch_size\": 32,\n \"gradient_accumulation_steps\": 1,\n \"learning_rate\": 5e-5,\n \"weight_decay\": 0.0,\n \"adam_epsilon\": 1e-8,\n \"max_grad_norm\": 1.0,\n \"max_steps\": 7,\n \"warmup_steps\": 0,\n \"save_steps\": 6,\n \"no_cuda\": False,\n \"n_gpu\": 1,\n \"model_name_or_path\": \"xlnet\",\n \"output_dir\": \"xlnet\",\n \"random_state\": 42,\n \"fp16\": False,\n \"fp16_opt_level\": \"01\",\n \"device\": \"cpu\",\n \"verbose\": False,\n \"model_type\": \"xlnet\",\n \"pad_on_left\": False,\n \"pad_token\": 0,\n \"pad_token_segment_id\": 0,\n \"mask_padding_with_zero\": True,\n \"eval_sample_size\": 100,\n \"n_cores\": 7,\n \"base_path\": base_path + \"cached_\",\n \"pretrained_weights\": 'xlnet-base-cased'}\n\n # ## loading base model\n\n my_xlnet = XLNetWrapper(hyperparams)\n\n # ## Loading DFs\n\n train_path = base_path + \"train.csv\"\n test_path = base_path + \"dev.csv\"\n df = pd.read_csv(train_path)\n test = pd.read_csv(test_path)\n test = test.sample(100, random_state=hyperparams[\"random_state\"])\n df = clean_df(df, 7)\n test = clean_df(test, 7)\n\n # ### Eval 1\n\n pred = my_xlnet.predict(test, transform=True, mode=\"test\")\n lmap = my_xlnet.processor.get_label_map()\n filtered = filter_df_by_label(test.dropna()).reset_index(drop=True)\n before_acc = np.mean(filtered.label.map(lambda x: lmap[x]) == pred)\n\n # ### Fit\n\n global_step, tr_loss, train_time = my_xlnet.fit(df)\n\n # ### Eval 2\n\n eval_path = base_path + \"cached_test_200\"\n pred = my_xlnet.predict(None, transform=False, path=eval_path)\n lmap = my_xlnet.processor.get_label_map()\n filtered = filter_df_by_label(test.dropna()).reset_index(drop=True)\n after_acc = np.mean(filtered.label.map(lambda x: lmap[x]) == pred)\n\n self.assertTrue(np.round(tr_loss, 3) == 1.134)\n self.assertTrue(before_acc == 0.25)\n self.assertTrue(after_acc == 0.32)\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","sub_path":"tests/BasicXLNetTraining.py","file_name":"BasicXLNetTraining.py","file_ext":"py","file_size_in_byte":3856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"621586988","text":"#Frontend\n\nfrom tkinter import *\nimport tkinter.messagebox\nimport pshop_backend\nimport mysql.connector\n\n\nroot = Tk()\nroot.title(\"Petshop Database Management System\")\nroot.geometry(\"1200x700\")\n#root.config(bg=\"grey\")\n\nTitleFrame = Frame(root, bd=2, padx=5, pady=8, relief=RIDGE)\nTitleFrame.pack(side = TOP)\n\nLabel(TitleFrame ,font=('arial', 20, 'bold'), text=\"Petshop Database Management\").grid()\n\n\n#===============================================================================\ndef est_conn():\n pshop_backend.connect_to_database(hostname.get(), username.get(), password.get(), databasename.get())\n tkinter.messagebox.showinfo(\"Register\", \"Connected to database\")\n ConnectFrame.destroy()\n DisplayData()\n\ndef connect_to_database():\n global ConnectFrame\n ConnectFrame = Toplevel(root)\n ConnectFrame.title(\"Connect to database\")\n ConnectFrame.geometry(\"300x300\")\n\n global hostname, username, password, databasename\n\n hostname = StringVar()\n username = StringVar()\n password = StringVar()\n databasename = StringVar()\n\n hostname.set(\"localhost\")\n databasename.set(\"my_petshop_gui2\") # sets the default value\n\n\n Label(ConnectFrame, text = \"Please enter details below\").pack()\n Label(ConnectFrame, text =\"\").pack()\n Label(ConnectFrame, text =\"Mysql server address\").pack()\n mysql_add = Entry(ConnectFrame, textvariable = hostname)\n mysql_add.pack()\n Label(ConnectFrame, text =\" Mysql Username\").pack()\n mysql_uname = Entry(ConnectFrame, textvariable = username)\n mysql_uname.pack()\n Label(ConnectFrame, text =\"Mysql Password\").pack()\n mysql_pass = Entry(ConnectFrame, textvariable = password, show=\"*\")\n mysql_pass.pack()\n Label(ConnectFrame, text =\"Database Name\").pack()\n mysql_pass = Entry(ConnectFrame, textvariable = databasename)\n mysql_pass.pack()\n Label(ConnectFrame, text =\"\").pack()\n Button(ConnectFrame, text=\"Connect\", command = est_conn).pack()\n\n#=========================Functions======================================\ndef DisplayData():\n info_list.delete(0,END)\n #info_list.insert(0, \"PetID PetType NumInStock NumSold Price PetSubType\")\n rows = pshop_backend.viewDataAll()\n #info_list.insert(END, rows[0][1], rows[2])\n for row in rows:\n info_list.insert(END, str(row[0]) + '%15s' % str(row[1]) + '%15s' % str(row[2])\\\n + '%15s' % str(row[3]) + '%18s' % str(row[4]) + '%15s' % str(row[5]) + '%25s' % str(row[6]) + '%15s' % str(row[7])\\\n + '%15s' % str(row[8]) + '%15s' % str(row[9]), str(\"\"))\n\n\ndef m_exit():\n root.destroy()\n\n\n#====================================================================================\n\nMesgFrame = LabelFrame(root, font=('arial', 20, 'bold'), text=\"Pet & Client Info\\n\")\nMesgFrame.pack(side = TOP)\n\ninfo_list = Listbox(MesgFrame, width = 100, height = 20)\ninfo_list.grid(row = 0, column = 0, padx = 20)\n\n#================================Pet Table=============================================\n#========================================================================================================\n#========================================================================================================\n#========================================================================================================\ndef pet_table():\n\n PetFrame = Toplevel(root)\n PetFrame.title(\"Pet Info\")\n PetFrame.geometry(\"600x700\")\n\n Label(PetFrame).grid(row=0, column=1)\n Label(PetFrame).grid(row=1, column=1)\n Label(PetFrame, text = \"Pet Input\").grid(row=2, column=2)\n lblPetType = Label(PetFrame, text = \"Pet Type\")\n lblPetType.grid(row=3, column = 0, columnspan = 2)\n txtPetType = Entry(PetFrame, width = 20)\n txtPetType.grid(row=3, column = 2, columnspan = 2)\n\n lblPetSubType = Label(PetFrame, text = \"Pet Sub Type\")\n lblPetSubType.grid(row=4, column = 0, columnspan = 2)\n txtPetSubType = Entry(PetFrame, width = 20)\n txtPetSubType.grid(row=4, column = 2, columnspan = 2)\n\n lblNumStock = Label(PetFrame, text = \"Number In Stock\")\n lblNumStock.grid(row=5, column = 0, columnspan = 2)\n txtNumStock = Entry(PetFrame, width = 20)\n txtNumStock.grid(row=5, column = 2, columnspan = 2)\n\n lblNumSold = Label(PetFrame, text = \"Number Sold\")\n lblNumSold.grid(row=6, column = 0, columnspan = 2)\n txtNumSold = Entry(PetFrame, width = 20)\n txtNumSold.grid(row=6, column = 2, columnspan = 2)\n\n lblPetPrice = Label(PetFrame, text = \"Price in USD\")\n lblPetPrice.grid(row=7, column = 0, columnspan = 2)\n txtPetPrice = Entry(PetFrame, width = 20)\n txtPetPrice.grid(row=7, column = 2, columnspan = 2)\n\n Label(PetFrame).grid(row=8, column=1)\n Label(PetFrame).grid(row=9, column=1)\n Label(PetFrame, text = \"Pet Table\").grid(row=10, column=2)\n\n #=======Functions for the Function===============\n def display_pet():\n pet_list.delete(0,END)\n #info_list.insert(0, \"PetID PetType NumInStock NumSold Price PetSubType\")\n rows = pshop_backend.viewData('pet_info')\n #info_list.insert(END, rows[0][1], rows[2])\n for row in rows:\n #pet_list.insert(END, str(row[0]) + '%15s' % str(row[1]) + '%15s' % str(row[2])\\\n # + '%15s' % str(row[3]) + '%18s' % str(row[4]) + '%15s' % str(row[5]), str(\"\"))\n pet_list.insert(END, row)\n\n\n def clearData():\n txtPetType.delete(0,END)\n txtPetSubType.delete(0,END)\n txtNumStock.delete(0,END)\n txtNumSold.delete(0,END)\n txtPetPrice.delete(0,END)\n\n def add_data():\n pass\n\n def pet_Rec(event):\n global psd\n searchStd = pet_list.curselection()[0]\n psd = pet_list.get(searchStd)\n\n txtPetType.delete(0,END)\n txtPetType.insert(END, psd[1])\n txtPetSubType.delete(0,END)\n txtPetSubType.insert(END,psd[2])\n txtNumStock.delete(0,END)\n txtNumStock.insert(END,psd[3])\n txtNumSold.delete(0,END)\n txtNumSold.insert(END,psd[4])\n txtPetPrice.delete(0,END)\n txtPetPrice.insert(END,psd[5])\n\n def addData():\n if(len(txtPetType.get())!=0):\n pshop_backend.addPetRec(txtPetType.get(), txtPetSubType.get(), txtNumStock.get(), txtNumSold.get(), txtPetPrice.get())\n pet_list.delete(0,END)\n pet_list.insert(END, (txtPetType.get(), txtPetSubType.get(), txtNumStock.get(), txtNumSold.get(), txtPetPrice.get()))\n print(txtPetType.get())\n\n def DeleteData():\n if(len(txtPetSubType.get())!=0):\n pshop_backend.deleteRec('pet_info', 'pet_id', psd[0])\n clearData()\n display_pet()\n\n\n def searchDatabase():\n pet_list.delete(0,END)\n for row in pshop_backend.searchData(txtPetType.get(), txtPetSubType.get(), txtNumStock.get(), txtNumSold.get(), txtPetPrice.get()):\n pet_list.insert(END, row, str(\"\"))\n\n\n def update():\n if len(txtPetType.get()) != 0:\n pshop_backend.dataUpdate(psd[0], txtPetType.get(), txtPetSubType.get(), txtNumStock.get(), txtNumSold.get(), txtPetPrice.get())\n display_pet()\n\n\n\n#===========Listbox & ScrollBar=======================\n\n scrollbar = Scrollbar(PetFrame)\n scrollbar.grid(row=11, column=9, sticky='ns')\n\n pet_list = Listbox(PetFrame, width = 60, height = 20, yscrollcommand = scrollbar.set)\n pet_list.bind('<>', pet_Rec)\n pet_list.grid(row=11, column=0, columnspan=9, padx=15)\n scrollbar.config(command = pet_list.yview)\n\n\n #=========Buttons=============================\n petAddData = Button(PetFrame, text=\"Add New\", command = addData)\n petAddData.grid(row=12, column=0)\n\n petDisplayData = Button(PetFrame, text=\"Display\", command = display_pet)\n petDisplayData.grid(row=12, column=1)\n\n petClearData = Button(PetFrame, text=\"Clear\", command = clearData)\n petClearData.grid(row=12, column=2)\n\n petDeleteData = Button(PetFrame, text=\"Delete\", command = DeleteData)\n petDeleteData.grid(row=12, column=3)\n\n petSearchData = Button(PetFrame, text=\"Search\", command = searchDatabase)\n petSearchData.grid(row=12, column=4)\n\n petUpdateData = Button(PetFrame, text=\"Update\", command = update)\n petUpdateData.grid(row=12, column=5)\n\n petExit = Button(PetFrame, text=\"Exit\", command = lambda: pshop_backend.close_win(PetFrame))\n petExit.grid(row=12, column=6)\n\n\n#================================Transaction Table=============================================\n#========================================================================================================\n#========================================================================================================\n#========================================================================================================\ndef tran_table():\n\n tranFrame = Toplevel(root)\n tranFrame.title(\"Transaction Info\")\n tranFrame.geometry(\"600x700\")\n\n Label(tranFrame).grid(row=0, column=1)\n Label(tranFrame).grid(row=1, column=1)\n Label(tranFrame, text = \"Transaction Input\").grid(row=2, column=2)\n lblDate = Label(tranFrame, text = \"Date\")\n lblDate.grid(row=3, column = 0, columnspan = 2)\n txtDate = Entry(tranFrame, width = 20)\n txtDate.grid(row=3, column = 2, columnspan = 2)\n\n lblCustomer = Label(tranFrame, text = \"Customer Name\")\n lblCustomer.grid(row=4, column = 0, columnspan = 2)\n txtCustomer = Entry(tranFrame, width = 20)\n txtCustomer.grid(row=4, column = 2, columnspan = 2)\n\n lblPetId = Label(tranFrame, text = \"PetId\")\n lblPetId.grid(row=5, column = 0, columnspan = 2)\n txtPetId = Entry(tranFrame, width = 20)\n txtPetId.grid(row=5, column = 2, columnspan = 2)\n\n lblQuantity = Label(tranFrame, text = \"Quantity\")\n lblQuantity.grid(row=6, column = 0, columnspan = 2)\n txtQuantity = Entry(tranFrame, width = 20)\n txtQuantity.grid(row=6, column = 2, columnspan = 2)\n\n lblTotalPrice = Label(tranFrame, text = \"Total Price in USD\")\n lblTotalPrice.grid(row=7, column = 0, columnspan = 2)\n txtTotalPrice = Entry(tranFrame, width = 20)\n txtTotalPrice.grid(row=7, column = 2, columnspan = 2)\n\n Label(tranFrame).grid(row=8, column=1)\n Label(tranFrame).grid(row=9, column=1)\n Label(tranFrame, text = \"Transaction Table\").grid(row=10, column=2)\n\n\n #=============================Functions============================\n #=======Functions for the Function===============\n def display_tran():\n tran_list.delete(0,END)\n #info_list.insert(0, \"PetID PetType NumInStock NumSold Price PetSubType\")\n rows = pshop_backend.viewData('transaction_info')\n #info_list.insert(END, rows[0][1], rows[2])\n for row in rows:\n #tran_list.insert(END, str(row[0]) + '%15s' % str(row[1]) + '%15s' % str(row[2])\\\n # + '%15s' % str(row[3]) + '%18s' % str(row[4]) + '%15s' % str(row[5]), str(\"\"))\n tran_list.insert(END, row)\n\n\n def clearData():\n txtDate.delete(0,END)\n txtCustomer.delete(0,END)\n txtPetId.delete(0,END)\n txtQuantity.delete(0,END)\n txtTotalPrice.delete(0,END)\n\n\n\n def tran_Rec(event):\n global sd\n searchStd = tran_list.curselection()[0]\n sd = tran_list.get(searchStd)\n\n txtDate.delete(0,END)\n txtDate.insert(END, sd[1])\n txtCustomer.delete(0,END)\n txtCustomer.insert(END,sd[2])\n txtPetId.delete(0,END)\n txtPetId.insert(END,sd[3])\n txtQuantity.delete(0,END)\n txtQuantity.insert(END,sd[4])\n txtTotalPrice.delete(0,END)\n txtTotalPrice.insert(END,sd[5])\n\n\n def addData():\n if(len(txtCustomer.get())!=0):\n pshop_backend.addTranRec(str(txtDate.get()), txtCustomer.get(), txtPetId.get(), txtQuantity.get(), txtTotalPrice.get())\n tran_list.delete(0,END)\n tran_list.insert(END, (txtDate.get(), txtCustomer.get(), txtPetId.get(), txtQuantity.get(), txtTotalPrice.get()))\n\n\n def DeleteData():\n if(len(txtCustomer.get())!=0):\n pshop_backend.deleteRec('transaction_info', 'tran_id', sd[0])\n clearData()\n display_tran()\n\n def searchDatabase():\n tran_list.delete(0,END)\n for row in pshop_backend.searchTranData(txtDate.get(), txtCustomer.get(), txtPetId.get(), txtQuantity.get(), txtTotalPrice.get()):\n tran_list.insert(END,row,str(\"\"))\n\n def update():\n if len(txtDate.get()) != 0:\n pshop_backend.tran_dataUpdate(sd[0], txtDate.get(), txtCustomer.get(), txtPetId.get(), txtQuantity.get(), txtTotalPrice.get())\n display_tran()\n\n\n #===========Listbox & ScrollBar=======================\n\n scrollbar = Scrollbar(tranFrame)\n scrollbar.grid(row=11, column=9, sticky='ns')\n\n tran_list = Listbox(tranFrame, width = 60, height = 20, yscrollcommand = scrollbar.set)\n tran_list.bind('<>', tran_Rec)\n tran_list.grid(row=11, column=0, columnspan=9, padx=15)\n scrollbar.config(command = tran_list.yview)\n\n #===================Buttons=========================\n tranAddData = Button(tranFrame, text=\"Add New\", command = addData)\n tranAddData.grid(row=12, column=0)\n\n tranDisplayData = Button(tranFrame, text=\"Display\", command = display_tran)\n tranDisplayData.grid(row=12, column=1)\n\n tranClearData = Button(tranFrame, text=\"Clear\", command = clearData)\n tranClearData.grid(row=12, column=2)\n\n tranDeleteData = Button(tranFrame, text=\"Delete\", command = DeleteData)\n tranDeleteData.grid(row=12, column=3)\n\n tranSearchData = Button(tranFrame, text=\"Search\", command = searchDatabase)\n tranSearchData.grid(row=12, column=4)\n\n tranUpdateData = Button(tranFrame, text=\"Update\", command = update)\n tranUpdateData.grid(row=12, column=5)\n\n tranExit = Button(tranFrame, text=\"Exit\", command = lambda: pshop_backend.close_win(tranFrame))\n tranExit.grid(row=12, column=6)\n #========================================================================================================\n #========================================================================================================\n #========================================================================================================\n\n\n\n\n\n#===========================================================================\nBotFrame = Frame(root)\nBotFrame.pack(side=TOP)\nbot0 = Button(BotFrame, text=\"Connect to Database\", command = connect_to_database)\nbot0.grid(row=0, column=0)\nbot4 = Button(BotFrame, text=\"Display Database\", command = DisplayData)\nbot4.grid(row=0, column=1)\nbot1 = Button(BotFrame, text=\"Show Pet Database\", command = pet_table)\nbot1.grid(row=0, column=2)\nbot2 = Button(BotFrame, text=\"Show Customer Database\", command = tran_table)\nbot2.grid(row=0, column=3)\nbot3 = Button(BotFrame, text=\"Exit\", command = m_exit)\nbot3.grid(row=0, column=4)\n\n\n\nroot.mainloop()\n","sub_path":"petshop_gui/pshop_frontend.py","file_name":"pshop_frontend.py","file_ext":"py","file_size_in_byte":15021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"283188327","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom mainApp.models import Customers, CustomerBankAccount, CustomerCreditCard, CustomerAndroidPay, CustomerApplePay, CustomerPaypal\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.exceptions import ValidationError\n\nclass UserForm(forms.ModelForm):\n password = forms.CharField(widget=forms.PasswordInput())\n\n class Meta:\n model = User\n # The username should match the Customer ID\n fields = ('username', 'email', 'password')\n\nclass CustomersForm(forms.ModelForm):\n class Meta:\n model = Customers\n fields = (\n 'customerid',\n 'companyname',\n 'contactname',\n 'contacttitle',\n 'address',\n 'city',\n 'region',\n 'postalcode',\n 'country',\n 'phone',\n 'fax'\n )\n\n labels = {\n 'customerid' : _('CustomerID'),\n 'companyname' : _('Company Name'),\n 'contactname' : _('Contact Name'),\n 'contacttitle' : _('Contact Title'),\n 'address' : _('Address'),\n 'city' : _('City'),\n 'region' : _('Region'),\n 'postalcode' : _('Postal Code'),\n 'country' : _('Country'),\n 'phone' : _('Phone'),\n 'fax' : _('Fax')\n }\n\nclass AdvancedSearchForm(forms.Form):\n productname = forms.CharField(label='Product Name', max_length=100, required=False)\n suppliername = forms.CharField(label='Supplier Name', max_length=100, required=False)\n\n CATEGORIES = (\n (None, '------------'),\n (1, 'Beverages'),\n (2, 'Condiments'),\n (3, 'Confections'),\n (4, 'Dairy Products'),\n (5, 'Grains/Cereals'),\n (6, 'Meat/Poultry'),\n (7, 'Produce'),\n (8, 'Seafood')\n )\n\n categoryid = forms.ChoiceField(label='Category', choices=CATEGORIES, required=False)\n\n SUPPLIERS = (\n (None, '------------'),\n (1, 'Exotic Liquids'),\n (2, 'New Orleans Cajun Delights'),\n (3, \"Grandma Kelly's Homestead\"),\n (4, 'Tokyo Traders'),\n (5, \"Cooperativa de Quesos 'Las Cabras'\"),\n (6, \"Mayumi's\"),\n (7, 'Pavlova, Ltd.'),\n (8, 'Specialty Biscuits, Ltd.'),\n (9, 'PB Knckebrd AB'),\n (10, 'Refrescos Americanas LTDA'),\n (11, 'Heli Swaren GmbH & Co. KG'),\n (12, 'Plutzer Lebensmittelgromrkte AG'),\n (13, 'Nord-Ost-Fisch Handelsgesellschaft mbH'),\n (14, 'Formaggi Fortini s.r.l.'),\n (15, 'Norske Meierier'),\n (16, 'Bigfoot Breweries'),\n (17, 'Svensk Sjfda AB'),\n (18, 'Aux joyeux ecclsiastiques'),\n (19, 'New England Seafood Cannery'),\n (20, 'Leka Trading'),\n (21, 'Lyngbysild'),\n (22, 'Zaanse Snoepfabriek'),\n (23, 'Karkki Oy'),\n (24, \"G'day, Mate\"),\n (25, 'Ma Maison'),\n (26, 'Pasta Buttini s.r.l.'),\n (27, 'Escargots Nouveaux'),\n (28, 'Gai pturage'),\n (29, \"Forts d'rables\"),\n )\n\n supplierid = forms.ChoiceField(label='Supplier', choices=SUPPLIERS, required=False)\n\n def clean(self):\n cleaned_data = super(AdvancedSearchForm, self).clean()\n productname = cleaned_data.get(\"productname\")\n suppliername = cleaned_data.get(\"suppliername\")\n categoryid = cleaned_data.get(\"categoryid\")\n supplierid = cleaned_data.get(\"supplierid\")\n\n if not (productname or suppliername or categoryid or supplierid):\n raise ValidationError(\"You must specify at least one field\")\n\n # This list holds the keys with null values from cleaned_data\n validKeys = [k for k,v in cleaned_data.items() if v is not '']\n\n cleaned_data[\"validKeys\"] = validKeys\n\n return cleaned_data\n\nclass QuickSearchForm(forms.Form):\n productname = forms.CharField(label='Product Name', max_length=100, required=False)\n\n CATEGORIES = (\n (None, '------------'),\n (1, 'Beverages'),\n (2, 'Condiments'),\n (3, 'Confections'),\n (4, 'Dairy Products'),\n (5, 'Grains/Cereals'),\n (6, 'Meat/Poultry'),\n (7, 'Produce'),\n (8, 'Seafood')\n )\n\n categoryid = forms.ChoiceField(label='Category', choices=CATEGORIES, required=False)\n\n def clean(self):\n cleaned_data = super(QuickSearchForm, self).clean()\n productname = cleaned_data.get(\"productname\")\n categoryid = cleaned_data.get(\"categoryid\")\n\n if not (productname or categoryid):\n raise ValidationError(\"You must specify at least one field\")\n\n # This list holds the keys with null values from cleaned_data\n validKeys = [k for k,v in cleaned_data.items() if v is not '']\n\n cleaned_data[\"validKeys\"] = validKeys\n\n return cleaned_data\n\nclass CustomerBankAccountForm(forms.ModelForm):\n class Meta:\n model = CustomerBankAccount\n fields = (\n 'customerid',\n 'routingno',\n 'accountno',\n )\n\n labels = {\n 'customerid' : _('CustomerID'),\n 'routingno' : _('Routing Number'),\n 'accountno' : _('Account Number'),\n }\n\nclass CustomerCreditCardForm(forms.ModelForm):\n CARD_TYPE_CHOICES = (\n ('visa', 'Visa'),\n ('mastercard', 'Mastercard'),\n )\n cardtype = forms.ChoiceField(label='Category', choices=CARD_TYPE_CHOICES)\n cardno = forms.IntegerField(label='Card Number')\n cvv = forms.IntegerField(label='CVV')\n expiration = forms.DateField(widget=forms.SelectDateWidget())\n\n def clean(self):\n cleaned_data = super(CustomerCreditCardForm, self).clean()\n cardtype = cleaned_data.get(\"cardtype\")\n cardno = cleaned_data.get(\"cardno\")\n cvv = cleaned_data.get(\"cvv\")\n expiration = cleaned_data.get(\"expiration\")\n\n # List of validation errors\n errors = []\n\n # Add the CVV and CardNo length errors\n if cvv and cardno:\n cardno_length = len(str(cardno))\n cvv_length = len(str(cvv))\n if cardno_length > 19 or cardno_length < 16:\n errors.append(_(\"Card number must be between 16 and 19 digits\"))\n if cvv_length != 3:\n errors.append(_(\"CVV must be 3 digits\"))\n\n # Raise all validation errors\n if len(errors) > 0:\n raise ValidationError(errors)\n\n return cleaned_data\n\n class Meta:\n model = CustomerCreditCard\n fields = (\n 'customerid',\n 'cardtype',\n 'cardno',\n 'cvv',\n 'expiration',\n )\n\n labels = {\n 'customerid' : _('CustomerID'),\n 'cardtype' : _('Card Type'),\n 'cardno' : _('Card Number'),\n 'cvv' : _('CVV'),\n 'expiration' : _('Expiration'),\n }\n\nclass CustomerAndroidPayForm(forms.ModelForm):\n email = forms.EmailField(label='Email address')\n\n class Meta:\n model = CustomerAndroidPay\n fields = (\n 'customerid',\n 'email',\n )\n\n labels = {\n 'customerid' : _('CustomerID'),\n 'email' : _('Email address'),\n }\n\nclass CustomerApplePayForm(forms.ModelForm):\n email = forms.EmailField(label='Email address')\n\n class Meta:\n model = CustomerApplePay\n fields = (\n 'customerid',\n 'email',\n )\n\n labels = {\n 'customerid' : _('CustomerID'),\n 'email' : _('Email address'),\n }\n\nclass CustomerPaypalForm(forms.ModelForm):\n email = forms.EmailField(label='Email address')\n\n class Meta:\n model = CustomerPaypal\n fields = (\n 'customerid',\n 'email',\n )\n\n labels = {\n 'customerid' : _('CustomerID'),\n 'email' : _('Email address'),\n }\n\nclass ShipmentTypeForm(forms.Form):\n shipment_choices = (\n (1, 'Ground'),\n (2, 'Air'),\n (3, 'Sea'),\n )\n\n shipmentType = forms.ChoiceField(label='Shipment Method', choices=shipment_choices)\n\ndef getAvailablePaymentTypes(customerid):\n # Get a list of the payment options that a given user has\n # CustomerBankAccount, CustomerCreditCard, CustomerAndroidPay, CustomerApplePay, CustomerPaypal\n bank_account_exists = CustomerBankAccount.objects.filter(customerid=customerid).exists()\n credit_card_exists = CustomerCreditCard.objects.filter(customerid=customerid).exists()\n android_pay_exists = CustomerAndroidPay.objects.filter(customerid=customerid).exists()\n apple_pay_exists = CustomerApplePay.objects.filter(customerid=customerid).exists()\n paypal_exists = CustomerPaypal.objects.filter(customerid=customerid).exists()\n\n bank_account_choice = ('bank_account', 'Bank Account')\n credit_card_choice = ('credit_card', 'Credit Card')\n android_pay_choice = ('android_pay', 'Android Pay')\n apple_pay_choice = ('apple_pay', 'Apple Pay')\n paypal_choice = ('paypal', 'Paypal')\n\n # Pair up the boolean that checks if the payment type exists with its choice tuple\n exists_choices_pairs = [\n [bank_account_exists, bank_account_choice],\n [credit_card_exists, credit_card_choice],\n [android_pay_exists, android_pay_choice],\n [apple_pay_exists, apple_pay_choice],\n [paypal_exists, paypal_choice],\n ]\n\n choices_list = []\n\n for pair in exists_choices_pairs:\n if pair[0]:\n # If the payment type exists, add the tuple to the choices list\n choices_list.append(pair[1])\n\n # Cast the choices list to a proper choices tuple\n choices = tuple(choices_list)\n\n return choices\n\nclass PaymentTypeForm(forms.Form):\n def __init__(self, customerid, *args, **kwargs):\n super(PaymentTypeForm, self).__init__(*args, **kwargs)\n self.fields['paymentType'] = forms.ChoiceField(label='Payment Type', choices=getAvailablePaymentTypes(customerid))\n\nclass ShippingAddressForm(forms.Form):\n address = forms.CharField(label='Address', widget=forms.TextInput(attrs={'placeholder': 'Street Address'}), max_length=60, required=True)\n city = forms.CharField(label='City', widget=forms.TextInput(attrs={'placeholder': 'City'}), max_length=15, required=True)\n region = forms.CharField(label='Region', widget=forms.TextInput(attrs={'placeholder': 'Region'}), max_length=15, required=True)\n postalcode = forms.CharField(label='Postal Code', widget=forms.TextInput(attrs={'placeholder': 'Postal Code'}), max_length=10, required=True)\n country = forms.CharField(label='Country', widget=forms.TextInput(attrs={'placeholder': 'Country'}), max_length=15, required=True)\n\n def clean(self):\n cleaned_data = super(ShippingAddressForm, self).clean()\n\n address = cleaned_data.get(\"address\")\n city = cleaned_data.get(\"city\")\n region = cleaned_data.get(\"region\")\n postalcode = cleaned_data.get(\"postalcode\")\n country = cleaned_data.get(\"country\")\n\n if not (address and city and region and postalcode and country):\n raise ValidationError(\"You must specify all address fields\")\n\n return cleaned_data\n\nclass InventoryReportingForm(forms.Form):\n productname = forms.CharField(label='Product Name', max_length=100, required=False)\n suppliername = forms.CharField(label='Supplier Name', max_length=100, required=False)\n\n CATEGORIES = (\n (None, '------------'),\n (1, 'Beverages'),\n (2, 'Condiments'),\n (3, 'Confections'),\n (4, 'Dairy Products'),\n (5, 'Grains/Cereals'),\n (6, 'Meat/Poultry'),\n (7, 'Produce'),\n (8, 'Seafood')\n )\n\n categoryid = forms.ChoiceField(label='Category', choices=CATEGORIES, required=False)\n unitprice = forms.DecimalField(label='Unit Price', max_digits=10, decimal_places=4, required=False)\n unitsinstock__lte = forms.IntegerField(label='In Stock (Upper)', required=False)\n unitsinstock__gte = forms.IntegerField(label='In Stock (Lower)', required=False)\n reorderlevel__lte = forms.IntegerField(label='ReorderLevel (Upper)', required=False)\n reorderlevel__gte = forms.IntegerField(label='ReorderLevel (Lower)', required=False)\n discontinued = forms.CharField(label='Discontinued', required=False)\n\n def clean(self):\n cleaned_data = super(InventoryReportingForm, self).clean()\n productname = cleaned_data.get(\"productname\")\n suppliername = cleaned_data.get(\"suppliername\")\n categoryid = cleaned_data.get(\"categoryid\")\n unitprice = cleaned_data.get(\"unitprice\")\n unitsinstock__lte = cleaned_data.get(\"unitsinstock__lte\")\n unitsinstock__gte = cleaned_data.get(\"unitsinstock__gte\")\n reorderlevel__lte = cleaned_data.get(\"reorderlevel__lte\")\n reorderlevel__gte = cleaned_data.get(\"reorderlevel__gte\")\n discontinued = cleaned_data.get(\"discontinued\")\n if discontinued:\n discontinued = ord(discontinued)\n\n if not (productname or suppliername or categoryid or unitprice or (unitsinstock__lte and unitsinstock__gte) or (reorderlevel__lte and reorderlevel__gte) or discontinued):\n raise ValidationError(\"You must specify at least one field\")\n if unitsinstock__lte or unitsinstock__gte:\n if unitsinstock__lte and unitsinstock__gte:\n if unitsinstock__lte > unitsinstock__gte:\n raise ValidationError(\"Upper means the field must be the upper bound\")\n else:\n # One is there but not the other\n raise ValidationError(\"You must specify both in stock fields if you specify one\")\n if reorderlevel__lte or reorderlevel__gte:\n if reorderlevel__lte and reorderlevel__gte:\n if reorderlevel__lte > reorderlevel__gte:\n raise ValidationError(\"Upper means the field must be the upper bound\")\n else:\n raise ValidationError(\"You must specify both reorder level fields if you specify one\")\n\n # This list holds the keys with null values from cleaned_data\n validKeys = [k for k,v in cleaned_data.items() if (v is not '') and (v is not None)]\n\n cleaned_data[\"validKeys\"] = validKeys\n\n return cleaned_data\n","sub_path":"mainApp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":14498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"332252852","text":"import numpy as np\nimport torch\nimport collections\nimport elf\nimport wandb\nimport matplotlib.pyplot as plt\nfrom elf.segmentation.multicut import multicut_kernighan_lin\nfrom elf.segmentation.features import project_node_labels_to_pixels\nfrom rag_utils import find_dense_subgraphs\n\nimport rewards\nfrom utils.graphs import collate_edges, get_edge_indices\nfrom utils.general import random_label_cmap\n\nState = collections.namedtuple(\"State\", [\"raw\", \"sp_seg\", \"edge_ids\", \"edge_feat\", \"node_feat\", \"subgraph_indices\",\n \"sep_subgraphs\", \"gt_edge_weights\"])\n\n\nclass MulticutEmbeddingsEnv:\n\n def __init__(self, cfg, device):\n super(MulticutEmbeddingsEnv, self).__init__()\n\n self.reset()\n self.cfg = cfg\n self.device = device\n self.max_p = torch.nn.MaxPool2d(3, padding=1, stride=1)\n self.reward_function = eval(\"rewards.\" + self.cfg.reward_function)(cfg.s_subgraph)\n\n\n def execute_action(self, actions, logg_vals=None, post_stats=False, post_images=False, tau=None, train=True):\n self.current_edge_weights = actions.squeeze()\n self.current_soln = self.get_current_soln(self.current_edge_weights)\n\n self.sg_current_edge_weights = []\n for i, sz in enumerate(self.cfg.s_subgraph):\n self.sg_current_edge_weights.append(\n self.current_edge_weights[self.subgraph_indices[i].view(-1, sz)])\n\n reward = self.reward_function(prediction_segmentation=self.current_soln.long(),\n gt=self.sg_gt_edges, dir_edges=self.dir_edge_ids,\n superpixel_segmentation=self.init_sp_seg.long(),\n actions=actions,\n subgraph_indices=self.subgraph_indices)\n\n if post_stats:\n tag = \"train/\" if train else \"validation/\"\n wandb.log({tag + \"avg_return\": reward[-1].item()})\n if post_images:\n mc_soln = self.gt_soln[-1].cpu() if self.gt_edge_weights is not None else torch.zeros(self.raw.shape[-2:])\n wandb.log({tag + \"pred_mean\": wandb.Histogram(self.current_edge_weights.view(-1).cpu().numpy())})\n fig, axes = plt.subplots(2, 3, sharex='col', sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0})\n axes[0, 0].imshow(self.gt_seg[-1].cpu().squeeze(), cmap=random_label_cmap(), interpolation=\"none\")\n axes[0, 0].set_title('gt')\n if self.raw.ndim == 3:\n axes[0, 1].imshow(self.raw[-1, 0])\n else:\n axes[0, 1].imshow(self.raw[-1])\n axes[0, 1].set_title('raw image')\n axes[0, 2].imshow(self.init_sp_seg[-1].cpu(), cmap=random_label_cmap(), interpolation=\"none\")\n axes[0, 2].set_title('superpixels')\n axes[1, 0].imshow(mc_soln, cmap=random_label_cmap(), interpolation=\"none\")\n axes[1, 0].set_title('mc_gt')\n axes[1, 1].imshow(self.init_sp_seg[-1].cpu())\n axes[1, 1].set_title('embed')\n axes[1, 2].imshow(self.current_soln[-1].cpu(), cmap=random_label_cmap(), interpolation=\"none\")\n axes[1, 2].set_title('prediction')\n wandb.log({tag: [wandb.Image(fig, caption=\"state\")]})\n plt.close('all')\n if logg_vals is not None:\n for key, val in logg_vals.items():\n wandb.log({tag + key: val})\n\n self.acc_reward.append(reward[-1].item())\n return reward\n\n def get_state(self):\n return State(self.raw, self.batched_sp_seg, self.edge_ids, self.edge_feat, self.node_feat,\n self.subgraph_indices, self.sep_subgraphs, self.gt_edge_weights)\n\n def update_data(self, raw, gt, edge_ids, gt_edges, sp_seg, rags, edge_feat, node_feat, *args, **kwargs):\n bs = raw.shape[0]\n dev = raw.device\n for _sp_seg in sp_seg:\n assert all(_sp_seg.unique() == torch.arange(_sp_seg.max() + 1, device=dev))\n\n self.rags = rags\n self.gt_seg, self.init_sp_seg = gt.squeeze(1), sp_seg.squeeze(1)\n self.raw = raw\n self.node_feat = node_feat if node_feat is None else torch.cat(node_feat, 0)\n self.edge_feat = edge_feat if edge_feat is None else torch.cat(edge_feat, 0)\n\n subgraphs, self.sep_subgraphs = [], []\n _subgraphs, _sep_subgraphs = find_dense_subgraphs([eids.transpose(0, 1).cpu().numpy() for eids in edge_ids], self.cfg.s_subgraph)\n _subgraphs = [torch.from_numpy(sg.astype(np.int64)).to(dev).permute(2, 0, 1) for sg in _subgraphs]\n _sep_subgraphs = [torch.from_numpy(sg.astype(np.int64)).to(dev).permute(2, 0, 1) for sg in _sep_subgraphs]\n\n self.dir_edge_ids = [torch.cat([_edge_ids, torch.stack([_edge_ids[1], _edge_ids[0]], dim=0)], dim=1) for _edge_ids in edge_ids]\n self.n_nodes = [eids.max() + 1 for eids in edge_ids]\n self.edge_ids, (self.n_offs, self.e_offs) = collate_edges(edge_ids)\n for i in range(len(self.cfg.s_subgraph)):\n subgraphs.append(torch.cat([sg + self.n_offs[i] for i, sg in enumerate(_subgraphs[i*bs:(i+1)*bs])], -2).flatten(-2, -1))\n self.sep_subgraphs.append(torch.cat(_sep_subgraphs[i*bs:(i+1)*bs], -2).flatten(-2, -1))\n\n self.subgraphs = subgraphs\n self.subgraph_indices = get_edge_indices(self.edge_ids, subgraphs)\n\n batched_sp = []\n for sp, off in zip(self.init_sp_seg, self.n_offs):\n batched_sp.append(sp + off)\n self.batched_sp_seg = torch.stack(batched_sp, 0)\n\n self.gt_edge_weights = gt_edges\n if self.gt_edge_weights is not None:\n self.gt_edge_weights = torch.cat(self.gt_edge_weights)\n self.gt_soln = self.get_current_soln(self.gt_edge_weights)\n self.sg_gt_edges = [self.gt_edge_weights[sg].view(-1, sz) for sz, sg in\n zip(self.cfg.s_subgraph, self.subgraph_indices)]\n\n self.current_edge_weights = torch.ones(self.edge_ids.shape[1], device=self.edge_ids.device) / 2\n\n return\n\n def get_current_soln(self, edge_weights):\n p_min = 0.001\n p_max = 1.\n segmentations = []\n for i in range(1, len(self.e_offs)):\n probs = edge_weights[self.e_offs[i-1]:self.e_offs[i]]\n probs -= probs.min()\n probs /= probs.max()\n costs = (p_max - p_min) * probs + p_min\n costs = (torch.log((1. - costs) / costs)).detach().cpu().numpy()\n node_labels = elf.segmentation.multicut.multicut_decomposition(self.rags[i-1], costs, internal_solver='greedy-additive', n_threads=4)\n mc_seg = project_node_labels_to_pixels(self.rags[i-1], node_labels).squeeze()\n\n mc_seg = torch.from_numpy(mc_seg.astype(np.long)).to(self.device)\n # mask = mc_seg[None] == torch.unique(mc_seg)[:, None, None]\n # mc_seg = (mask * (torch.arange(len(torch.unique(mc_seg)), device=mc_seg.device)[:, None, None] + 1)).sum(0) - 1\n\n segmentations.append(mc_seg)\n return torch.stack(segmentations, dim=0)\n\n def reset(self):\n self.acc_reward = []\n","sub_path":"environments/multicut.py","file_name":"multicut.py","file_ext":"py","file_size_in_byte":7354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"244394334","text":"\nimport random\ndef main():\n print('***********************************')\n print('** Welcome to BlackJack! **')\n print('***********************************')\n\n\n\n player()\n dealer()\n\ndef hit():\n first = random.randint(1,13)\n if first == 11 or first == 12 or first == 13:\n first = 10\n return first\n\ndef player():\n player_hand = hit()\n print('Your first card is: %d' % player_hand)\n \n print()\n answer = 'y'\n while player_hand < 21 and answer == 'y':\n print('Do you want another card?')\n answer = input('Type y for Yes, n for No: ')\n print()\n if answer == 'y':\n draw = random.randint(1,13)\n if draw == 11 or draw == 12 or draw == 13:\n draw = 10\n player_hand = player_hand + draw\n print('Your next card is: %d' % draw)\n print('Your combined value is %d' % player_hand)\n print()\n if answer == 'n':\n player_hand = player_hand\n print('Your combined value is %d' % player_hand)\n break\n if player_hand > 21:\n print('Bust')\n break\n if player_hand == 21:\n print('21!')\n break\n return player_hand\n\ndef dealer():\n dealer_hand = 0\n if dealer_hand < 17:\n while dealer_hand < 17:\n print('Dealer draws another card.')\n dealer_hand = hit()\n print('Dealer\\'s card is: %d' % dealer_hand)\n dealer_hand = dealer_hand + hit()\n print('Dealer\\'s value is %d, you have %d' % (dealer_hand,dealer_hand)) #how to get player_hand here\n if dealer_hand >= 17:\n print('Stand')\n return dealer_hand\nmain()\n","sub_path":"Blackjack.py","file_name":"Blackjack.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"522604784","text":"from twisted.internet import reactor,protocol\nfrom twisted.protocols import basic\nclass EchoProtocol(basic.LineReceiver):\n def lineReceived(self, line):\n if line.decode() == 'quit':\n self.sendLine(\"Goodbye.\".encode())\n self.transport.loseConnection()\n else:\n say=\"You said: \" + line.decode()\n self.sendLine(say.encode())\n\nclass EchoServerFactory(protocol.ServerFactory):\n protocol = EchoProtocol\n\nif __name__==\"__main__\":\n port = 5001\n reactor.listenTCP(port, EchoServerFactory())\n reactor.run()\n","sub_path":"base_python/t_1019.py","file_name":"t_1019.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"306516885","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import validation_curve, cross_val_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.feature_selection import SelectKBest, chi2\nfrom sklearn.pipeline import make_pipeline\n\n# Separate dataset into training/test set\ndf = pd.read_csv(\"code/diabetic_retinopathy.csv\", header=None)\n\nX = df.iloc[:, :-1]\ny = df.iloc[:,-1]\nX_train, X_test = np.split(X, [900], axis = 0)\ny_train, y_test = np.split(y, [900], axis = 0)\n\nX_train.shape\n\n\n# Part (a)\nprint(\"Part (a)\")\nprint(\"Training set - Label count\")\nprint(y_train.value_counts())\n\nmajority_label = y_train.mode()[0] # Find majority label\ny_test_pred = pd.Series(majority_label, index=np.arange(len(y_test)))\ny_train_pred = pd.Series(majority_label, index=np.arange(len(y_train)))\n\nprint(\"Accuracy score (train): \",accuracy_score(y_train, y_train_pred))\nprint(\"Accuracy score (test): \",accuracy_score(y_test, y_test_pred))\n\n# Part (b)\nprint(\"Part (b)\")\n\nclassifier = DecisionTreeClassifier(random_state = 347)\nclassifier.fit(X_train, y_train)\n\ny_test_pred = classifier.predict(X_test)\ny_train_pred = classifier.predict(X_train)\n\nprint(\"Accuracy score (train): \",accuracy_score(y_train, y_train_pred))\nprint(\"Accuracy score (test): \",accuracy_score(y_test, y_test_pred))\n\n# Part (c)\nprint(\"Part (c)\")\nprint(\"Max depth: \", classifier.tree_.max_depth)\n\nmax_depth = range(1,11)\n\nval_score = []\ntrain_score = []\n\nfor i in max_depth:\n classifier = DecisionTreeClassifier(max_depth = i, random_state = 347).fit(X_train, y_train)\n y_test_pred, y_train_pred = classifier.predict(X_test), classifier.predict(X_train)\n train_score.append(accuracy_score(y_train, y_train_pred))\n val_score.append(accuracy_score(y_test, y_test_pred))\n\nfig1 = plt.figure()\nax1 = plt.axes()\nax1.plot(max_depth, train_score, color ='blue', label = 'training score')\nax1.plot(max_depth, val_score, color ='red', label = 'prediction score')\nax1.set_xlabel('max depth')\nax1.set_ylabel('score')\nax1.legend(loc='best');\n\nfig1.savefig('fig_1.png')\n\nplt.plot(max_depth, train_score, color ='blue', label = 'training score')\nplt.plot(max_depth, val_score, color ='red', label = 'training score')\n\n# Part (d)\nprint(\"Part (d)\")\n\n# Part (e)\nprint(\"Part (e)\")\ntrain_score, val_score = validation_curve(classifier, X_train, y_train, 'max_depth', max_depth, cv = 4)\n\nfig2 = plt.figure()\nax2 = plt.axes()\nax2.plot(max_depth, np.mean(train_score,1), color = 'blue', label = 'training score')\nax2.plot(max_depth, np.mean(val_score,1), color = 'red', label = 'validation score')\nax2.legend(loc='best')\nax2.set_xlabel('max depth')\nax2.set_ylabel('score');\nfig2.savefig('fig_2.png')\n\nmax_depth\nval_score\nnp.mean(val_score,1)\n\nmax_depth_best = max_depth[np.argmax(np.mean(val_score,1))]\nprint(\"Max depth with best performance: \", max_depth_best)\n\nclassifier = DecisionTreeClassifier(max_depth = max_depth_best, random_state = 347).fit(X_train, y_train)\ny_test_pred, y_train_pred = classifier.predict(X_test), classifier.predict(X_train)\nprint(\"Accuracy score (train): \",accuracy_score(y_train, y_train_pred))\nprint(\"Accuracy score (test): \",accuracy_score(y_test, y_test_pred))\n\n\n# Part (f)\nprint(\"Part (f)\")\n\nmodel = make_pipeline(SelectKBest(chi2),\n DecisionTreeClassifier(max_depth = 10, random_state = 347))\nfeatures = range(1,11)\n\ntrain_score, val_score = validation_curve(model, X_train, y_train, param_name = \"selectkbest__k\", param_range = features, cv = 4)\nfig3 = plt.figure()\nax3 = plt.axes()\nax3.plot(features, np.mean(train_score,1), color = 'blue', label = 'training score')\nax3.plot(features, np.mean(val_score,1), color = 'red', label = 'validation score')\nax3.legend(loc='best')\nax3.set_xlabel('features')\nax3.set_ylabel('score');\nfig3.savefig('fig_3.png')\n\n\nfeatures_best = features[np.argmax(np.mean(val_score,1))]\nprint(\"Number features with best performance: \", features_best)\n\nmodel.set_params(selectkbest__k = features_best)\nmodel.fit(X_train, y_train)\ny_test_pred, y_train_pred = model.predict(X_test), model.predict(X_train)\nprint(\"Accuracy score (train): \",accuracy_score(y_train, y_train_pred))\nprint(\"Accuracy score (test): \",accuracy_score(y_test, y_test_pred))\n","sub_path":"Problem Set 1/code/question_2.py","file_name":"question_2.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"33710092","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom . models import Book\n\nfrom django.contrib.auth import login\nfrom django.contrib.auth.decorators import login_required\n\nfrom django.urls import resolve\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\n\nfrom django.core.mail import send_mail\nfrom django.template.loader import render_to_string\nfrom django.views.decorators.cache import cache_control\n\n\n\n\n\n# Create your views here.\n\n@login_required\ndef addBook(request):\n return render(request,\"list.html\")\n\n@login_required\ndef book(request):\n return render(request,\"addBookButton.html\")\n\n\n \n@login_required\ndef sell(request):\n return render(request,\"book_registration.html\")\n# def donate(request):\n# return HttpResponseRedirect(\"/addbook\")\n\n@login_required\ndef donate(request):\n return render(request,\"donate_book_register.html\")\n\n\n\n\n@cache_control(no_cache=True, must_revalidate=True)\n@login_required\ndef added(request):\n book_name=request.POST['book_name']\n bookowner=request.user.id\n category=request.POST['category']\n writer=request.POST['writer']\n desc=request.POST['description']\n image=request.FILES['book_photo']\n condition=request.POST['condition']\n actualPrice=int(request.POST['actual_price'])\n sellingPrice=int(request.POST['selling_price'])\n publication=request.POST['publication']\n\n displaySellingPrice=sellingPrice+(10*sellingPrice/100)\n\n # url_name=resolve(request.path).url_name\n # if(url_name == 'added_sell'):\n # donation=request.POST['false']\n # else:\n # donation=request.POST['true']\n\n \n\n book=Book(bname=book_name, bookowner=bookowner, category=category, writer=writer, description=desc, image=image, condition=condition, actual_price=actualPrice, selling_price=sellingPrice, publication=publication, display_selling_price=displaySellingPrice)\n book.save()\n return render(request,\"book_registration.html\")\n\n\n\n\n@login_required\ndef added(request):\n book_name=request.POST['book_name']\n bookowner=request.user.id\n category=request.POST['category']\n writer=request.POST['writer']\n desc=request.POST['description']\n image=request.FILES['book_photo']\n condition=request.POST['condition']\n actualPrice=int(request.POST['actual_price'])\n sellingPrice=int(request.POST['selling_price'])\n publication=request.POST['publication']\n user=request.user.username\n\n\n displaySellingPrice=sellingPrice+(10*sellingPrice/100)\n\n # url_name=resolve(request.path).url_name\n # if(url_name == 'added_sell'):\n # donation=request.POST['false']\n # else:\n # donation=request.POST['true']\n \n book=Book(bookowner=bookowner,bname=book_name, category=category, writer=writer, description=desc, image=image, condition=condition, actual_price=actualPrice, selling_price=sellingPrice, publication=publication, display_selling_price=displaySellingPrice)\n book.save()\n\n # subject = 'Book Uploaded'\n # message = render_to_string('bookaddedmail.html', {\n # 'user': user,\n # 'Book_Name' : book_name,\n # 'Author' : writer,\n # 'Price' : sellingPrice,\n # 'Publication' : publication,\n # })\n # from_email=[settings.EMAIL_HOST_USER]\n # to_email=[request.user.email]\n # send_mail(subject=subject,from_email=from_email,recipient_list=to_email,message=message,fail_silently=False)\n return render(request,\"book_registration.html\",{'msg':'success'})\n \n\n \n\n\n\n\n\n@login_required\ndef addeddonate(request):\n book_name=request.POST['book_name']\n bookowner=request.user.id\n category=request.POST['category']\n writer=request.POST['writer']\n desc=request.POST['description']\n image=request.FILES['book_photo']\n condition=request.POST['condition']\n publication=request.POST['publication']\n\n donation=True\n\n\n\n\n book=Book(bname=book_name, bookowner=bookowner, category=category, writer=writer,donation=donation, description=desc, image=image, condition=condition, actual_price=0, selling_price=0, publication=publication, display_selling_price=0)\n book.save()\n return render(request,\"donate_book_register.html\")\n\n\n\n\n\n","sub_path":"last_this_is_last_final_testing_code-master/addBook/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"443915970","text":"# from bs4 import BeautifulSoup\nimport requests\nimport json\nimport csv\nfrom utils import convert_epoch, hash_file, check_duplicate\n\n# Must use API becuse we cannot extract data through HTMl\nsource = requests.get(\"https://www.nyse.com/api/ipo-center/calendar\").text\n\n# Open a CSV file to save the entries\ncsv_file = open('IPO_Filings.csv', 'w')\ncsv_output = csv.writer(csv_file)\ncsv_output.writerow([\"Date Filed\", \"Company\", \"Ticker\", \"Industry\", \"Price\"])\n\n# Traverse JSON payload to get information\ndata_dict = json.loads(source)\ncompanies_list = data_dict['calendarList']\nfor company in companies_list:\n # Get useful information from the filings\n issuer = company['issuer_nm']\n ticker = company['symbol']\n industry = company['custom_group_industry_nm']\n price_range = company['current_file_price_range_usd']\n date_filed = convert_epoch(company['init_file_dt']) # Change this to expected?\n\n if company['deal_status_desc'] == 'Filed': # This will need to be 'Expected' I think\n csv_output.writerow([date_filed, issuer, ticker, industry, price_range])\n\n# Close the file\ncsv_file.close()\n\n# Call function to hash current file\nhash_number = hash_file()\n\n# Call function to check if this hash already exists\ncheck_duplicate(hash_number)\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"52620936","text":"# Copyright 2021 The Feast Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport logging\nimport multiprocessing\nimport socket\nfrom contextlib import closing\nfrom datetime import datetime, timedelta\nfrom multiprocessing import Process\nfrom sys import platform\nfrom typing import Any, Dict, List\n\nimport pandas as pd\nimport pytest\nfrom _pytest.nodes import Item\n\nfrom feast import FeatureStore\nfrom feast.wait import wait_retry_backoff\nfrom tests.data.data_creator import create_dataset\nfrom tests.integration.feature_repos.integration_test_repo_config import (\n IntegrationTestRepoConfig,\n)\nfrom tests.integration.feature_repos.repo_configuration import (\n AVAILABLE_OFFLINE_STORES,\n AVAILABLE_ONLINE_STORES,\n Environment,\n TestData,\n construct_test_environment,\n construct_universal_test_data,\n)\nfrom tests.integration.feature_repos.universal.data_sources.file import (\n FileDataSourceCreator,\n)\n\nlogger = logging.getLogger(__name__)\n\n\ndef pytest_configure(config):\n if platform in [\"darwin\", \"windows\"]:\n multiprocessing.set_start_method(\"spawn\")\n else:\n multiprocessing.set_start_method(\"fork\")\n config.addinivalue_line(\n \"markers\", \"integration: mark test that has external dependencies\"\n )\n config.addinivalue_line(\"markers\", \"benchmark: mark benchmarking tests\")\n config.addinivalue_line(\n \"markers\", \"goserver: mark tests that use the go feature server\"\n )\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"--integration\",\n action=\"store_true\",\n default=False,\n help=\"Run tests with external dependencies\",\n )\n parser.addoption(\n \"--benchmark\", action=\"store_true\", default=False, help=\"Run benchmark tests\",\n )\n parser.addoption(\n \"--goserver\",\n action=\"store_true\",\n default=False,\n help=\"Run tests that use the go feature server\",\n )\n\n\ndef pytest_collection_modifyitems(config, items: List[Item]):\n should_run_integration = config.getoption(\"--integration\") is True\n should_run_benchmark = config.getoption(\"--benchmark\") is True\n should_run_goserver = config.getoption(\"--goserver\") is True\n\n integration_tests = [t for t in items if \"integration\" in t.keywords]\n if not should_run_integration:\n for t in integration_tests:\n items.remove(t)\n else:\n items.clear()\n for t in integration_tests:\n items.append(t)\n\n benchmark_tests = [t for t in items if \"benchmark\" in t.keywords]\n if not should_run_benchmark:\n for t in benchmark_tests:\n items.remove(t)\n else:\n items.clear()\n for t in benchmark_tests:\n items.append(t)\n\n goserver_tests = [t for t in items if \"goserver\" in t.keywords]\n if should_run_goserver:\n items.clear()\n for t in goserver_tests:\n items.append(t)\n\n\n@pytest.fixture\ndef simple_dataset_1() -> pd.DataFrame:\n now = datetime.utcnow()\n ts = pd.Timestamp(now).round(\"ms\")\n data = {\n \"id_join_key\": [1, 2, 1, 3, 3],\n \"float_col\": [0.1, 0.2, 0.3, 4, 5],\n \"int64_col\": [1, 2, 3, 4, 5],\n \"string_col\": [\"a\", \"b\", \"c\", \"d\", \"e\"],\n \"ts_1\": [\n ts,\n ts - timedelta(hours=4),\n ts - timedelta(hours=3),\n ts - timedelta(hours=2),\n ts - timedelta(hours=1),\n ],\n }\n return pd.DataFrame.from_dict(data)\n\n\n@pytest.fixture\ndef simple_dataset_2() -> pd.DataFrame:\n now = datetime.utcnow()\n ts = pd.Timestamp(now).round(\"ms\")\n data = {\n \"id_join_key\": [\"a\", \"b\", \"c\", \"d\", \"e\"],\n \"float_col\": [0.1, 0.2, 0.3, 4, 5],\n \"int64_col\": [1, 2, 3, 4, 5],\n \"string_col\": [\"a\", \"b\", \"c\", \"d\", \"e\"],\n \"ts_1\": [\n ts,\n ts - timedelta(hours=4),\n ts - timedelta(hours=3),\n ts - timedelta(hours=2),\n ts - timedelta(hours=1),\n ],\n }\n return pd.DataFrame.from_dict(data)\n\n\ndef start_test_local_server(repo_path: str, port: int):\n fs = FeatureStore(repo_path)\n fs.serve(\"localhost\", port, no_access_log=True)\n\n\n@pytest.fixture(scope=\"session\")\ndef environment(request, worker_id):\n e = construct_test_environment(\n request.param, worker_id=worker_id, fixture_request=request\n )\n\n yield e\n\n e.feature_store.teardown()\n e.data_source_creator.teardown()\n if e.online_store_creator:\n e.online_store_creator.teardown()\n\n\n_config_cache = {}\n\n\ndef pytest_generate_tests(metafunc: pytest.Metafunc):\n \"\"\"\n This function receives each test function (wrapped in Metafunc)\n at the collection stage (before tests started).\n Here we can access all fixture requests made by the test as well as its markers.\n That allows us to dynamically parametrize the test based on markers and fixtures\n by calling metafunc.parametrize(...).\n\n See more examples at https://docs.pytest.org/en/6.2.x/example/parametrize.html#paramexamples\n\n We also utilize indirect parametrization here. Since `environment` is a fixture,\n when we call metafunc.parametrize(\"environment\", ..., indirect=True) we actually\n parametrizing this \"environment\" fixture and not the test itself.\n Moreover, by utilizing `_config_cache` we are able to share `environment` fixture between different tests.\n In order for pytest to group tests together (and share environment fixture)\n parameter should point to the same Python object (hence, we use _config_cache dict to store those objects).\n \"\"\"\n if \"environment\" in metafunc.fixturenames:\n markers = {m.name: m for m in metafunc.definition.own_markers}\n\n if \"universal_offline_stores\" in markers:\n offline_stores = AVAILABLE_OFFLINE_STORES\n else:\n # default offline store for testing online store dimension\n offline_stores = [(\"local\", FileDataSourceCreator)]\n\n online_stores = None\n if \"universal_online_stores\" in markers:\n # Online stores are explicitly requested\n if \"only\" in markers[\"universal_online_stores\"].kwargs:\n online_stores = [\n AVAILABLE_ONLINE_STORES.get(store_name)\n for store_name in markers[\"universal_online_stores\"].kwargs[\"only\"]\n if store_name in AVAILABLE_ONLINE_STORES\n ]\n else:\n online_stores = AVAILABLE_ONLINE_STORES.values()\n\n if online_stores is None:\n # No online stores requested -> setting the default or first available\n online_stores = [\n AVAILABLE_ONLINE_STORES.get(\n \"redis\",\n AVAILABLE_ONLINE_STORES.get(\n \"sqlite\", next(iter(AVAILABLE_ONLINE_STORES.values()))\n ),\n )\n ]\n\n extra_dimensions: List[Dict[str, Any]] = [{}]\n\n if \"python_server\" in metafunc.fixturenames:\n extra_dimensions.extend(\n [\n {\"python_feature_server\": True},\n {\"python_feature_server\": True, \"provider\": \"aws\"},\n ]\n )\n\n if \"goserver\" in markers:\n extra_dimensions.append({\"go_feature_retrieval\": True})\n\n configs = []\n for provider, offline_store_creator in offline_stores:\n for online_store, online_store_creator in online_stores:\n for dim in extra_dimensions:\n config = {\n \"provider\": provider,\n \"offline_store_creator\": offline_store_creator,\n \"online_store\": online_store,\n \"online_store_creator\": online_store_creator,\n **dim,\n }\n # temporary Go works only with redis\n if config.get(\"go_feature_retrieval\") and (\n not isinstance(online_store, dict)\n or online_store[\"type\"] != \"redis\"\n ):\n continue\n\n # aws lambda works only with dynamo\n if (\n config.get(\"python_feature_server\")\n and config.get(\"provider\") == \"aws\"\n and (\n not isinstance(online_store, dict)\n or online_store[\"type\"] != \"dynamodb\"\n )\n ):\n continue\n\n c = IntegrationTestRepoConfig(**config)\n\n if c not in _config_cache:\n _config_cache[c] = c\n\n configs.append(_config_cache[c])\n\n metafunc.parametrize(\n \"environment\", configs, indirect=True, ids=[str(c) for c in configs]\n )\n\n\n@pytest.fixture(scope=\"session\")\ndef python_server(environment):\n proc = Process(\n target=start_test_local_server,\n args=(environment.feature_store.repo_path, environment.get_local_server_port()),\n daemon=True,\n )\n if (\n environment.python_feature_server\n and environment.test_repo_config.provider == \"local\"\n ):\n proc.start()\n # Wait for server to start\n wait_retry_backoff(\n lambda: (\n None,\n _check_port_open(\"localhost\", environment.get_local_server_port()),\n ),\n timeout_secs=10,\n )\n\n yield\n\n if proc.is_alive():\n proc.kill()\n\n\ndef _check_port_open(host, port) -> bool:\n with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:\n return sock.connect_ex((host, port)) == 0\n\n\n@pytest.fixture(scope=\"session\")\ndef universal_data_sources(environment) -> TestData:\n return construct_universal_test_data(environment)\n\n\n@pytest.fixture(scope=\"session\")\ndef e2e_data_sources(environment: Environment):\n df = create_dataset()\n data_source = environment.data_source_creator.create_data_source(\n df, environment.feature_store.project, field_mapping={\"ts_1\": \"ts\"},\n )\n\n return df, data_source\n","sub_path":"sdk/python/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":10663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"50219982","text":"# -*- coding : utf-8 -*-\r\n\r\nfrom pymongo import MongoClient\r\nimport pymongo\r\nimport copy\r\n\r\nclient = MongoClient(\"mongodb://localhost\")\r\nmongo_db = client.zhihu_spider\r\n\r\ncols = ['user', 'answer']\r\n\r\ndef set_data_to_db(col,data):\r\n if col in cols is False:\r\n return \"Invalid collections name\"\r\n\r\n users = mongo_db[col]\r\n _d = {}\r\n\r\n if col == 'user' and data:\r\n _d['username'] = data.get('username','0')\r\n else:\r\n _d['url'] = data.get('url','0')\r\n\r\n if users.find(_d).count():\r\n return \"data has exists in database\"\r\n\r\n users.insert_one(data)\r\n\r\ndef get_data_from_db(col):\r\n if col in cols is False:\r\n return \"Invalid collections name\"\r\n\r\n users = mongo_db[col]\r\n\r\n datas = users.find({}).sort('agree_num',pymongo.DESCENDING)\r\n\r\n result = []\r\n\r\n for data in datas :\r\n\r\n del data['_id']\r\n result.append(data)\r\n\r\n return result\r\n","sub_path":"dbtool.py","file_name":"dbtool.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"169012598","text":"from ftplib import FTP\nimport os\n\nclass FTPService:\n\n def __init__(self, report, server, user, pswd):\n self.server = server\n self.user = user\n self.pswd = pswd\n self.report = report\n self.ftp = FTP(server)\n\n def download_files(self, local_path, path_in_ftp_server):\n if not os.path.isdir(local_path):\n os.makedirs(local_path)\n os.chdir(local_path)\n\n r = self.ftp.login(self.user, self.pswd)\n self.report.write(r, True, False, True)\n \n downloaded_files = self.download_files_of_subdir(local_path, path_in_ftp_server, False)\n\n r = self.ftp.close()\n self.report.write('ftp finished', True, False, True)\n\n print(';\\n'.join(downloaded_files))\n return downloaded_files\n \n def download_files_of_subdir(self, local_path, path_in_ftp_server, delete_path_in_ftp_server = False):\n levels = len(path_in_ftp_server.split('/'))\n downloaded_files = []\n # go to ftp directory\n self.report.write('go to ' + path_in_ftp_server, True, False, True)\n r = self.ftp.cwd(path_in_ftp_server)\n self.report.write(r, True, False, True)\n\n # download files\n files_or_folders = self.ftp.nlst()\n self.report.write('Files/Folders to download:\\n' + '\\n'.join(files_or_folders) + '\\n' + str(len(files_or_folders)) + ' files/folders', True, False, True)\n \n for folder_or_file in files_or_folders:\n if os.path.isfile( path_in_ftp_server + '/' + folder_or_file):\n # must be a file\n print('test file')\n downloaded_file = self.download_and_delete_file(local_path, folder_or_file)\n if len(downloaded_file)>0:\n downloaded_files.append(downloaded_file)\n elif os.path.isdir( path_in_ftp_server + '/' + folder_or_file):\n print('test dir')\n # supposed to be a folder\n downloaded_files += self.download_files_of_subdir(local_path, folder_or_file, False)\n elif folder_or_file.endswith('.zip') or folder_or_file.endswith('.tgz'):\n print('test .zip')\n # must be a file\n downloaded_file = self.download_and_delete_file(local_path, folder_or_file)\n if len(downloaded_file)>0:\n downloaded_files.append(downloaded_file)\n else:\n # supposed to be a folder\n print('test nothing')\n downloaded_files += self.download_files_of_subdir(local_path, folder_or_file, False)\n\n\n # up level\n for i in range(0,levels):\n r = self.ftp.cwd('..')\n self.report.write(r, True, False, True)\n\n if delete_path_in_ftp_server:\n r = self.ftp.rmd(path_in_ftp_server)\n self.report.write(r, True, False, True)\n return downloaded_files\n \n \n def download_and_delete_file(self, local_path, file):\n downloaded_file = ''\n r = self.ftp.retrbinary('RETR ' + file, open(file, 'wb').write)\n self.report.write(r, True, False, True)\n if os.path.exists(local_path + '/' + file):\n\n statinfo = os.stat(local_path + '/' + file)\n self.report.write(str(statinfo.st_size), True, False, True)\n\n downloaded_file = file\n r = self.ftp.delete(file)\n self.report.write(r, True, False, True)\n return downloaded_file\n\n def list_content(self, path_in_ftp_server):\n \n r = self.ftp.login(self.user, self.pswd)\n self.report.write(r, True, False, True)\n \n files_list = self.list_content_of_files_of_subdir(path_in_ftp_server)\n\n r = self.ftp.close()\n self.report.write('ftp finished', True, False, True)\n\n print(';\\n'.join(files_list))\n return files_list\n \n def list_content_of_files_of_subdir(self, path_in_ftp_server):\n levels = len(path_in_ftp_server.split('/'))\n items_in_ftp = []\n # go to ftp directory\n self.report.write('go to ' + path_in_ftp_server, True, False, True)\n r = self.ftp.cwd(path_in_ftp_server)\n self.report.write(r, True, False, True)\n\n # download files\n files_or_folders = self.ftp.nlst()\n self.report.write('Files/Folders in FTP:' + '\\n'.join(files_or_folders) + '\\n' + str(len(files_or_folders)) + ' files/folders', True, False, True)\n \n for folder_or_file in files_or_folders:\n if os.path.isdir(folder_or_file):\n items_in_ftp += self.list_content_of_files_of_subdir(folder_or_file)\n else:\n items_in_ftp.append(folder_or_file)\n \n # up level\n for i in range(0,levels):\n r = self.ftp.cwd('..')\n self.report.write(r, True, False, True)\n\n \n self.report.write(r, True, False, True)\n return items_in_ftp\n","sub_path":"src/xml_converter/src/reuse/services/ftp_service/ftp_service.py","file_name":"ftp_service.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"128705952","text":"\"\"\"\nCode was copied from https://github.com/VHellendoorn/ICLR20-Great\nAuthor: https://github.com/VHellendoorn\n\nMIT License\n\nCopyright (c) 2020 Vincent Hellendoorn\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport tensorflow as tf\n\nfrom . import util\n\n\nclass AttentionLayer(tf.keras.layers.Layer):\n \"\"\"Implementation of multi-headed attention with optional edge-bias.\n\n This class supports self-attention and key-value attention, with (non-optional) masks. If bias_dim is not None, the attention computation(s) assumes that a (sparse) bias vector is provided, formatted like: (edge_type, batch_index, key_index, query_index). Bias edge types are embedded in the same dimension as each head's attention and projected to a scalar before being inserted into the attention computation as (q + b) * k.\n \"\"\"\n\n def __init__(self, attention_dim, num_heads=8, hidden_dim=None, bias_dim=None):\n super(AttentionLayer, self).__init__()\n self.attention_dim = attention_dim\n self.hidden_dim = hidden_dim if hidden_dim is not None else self.attention_dim\n self.num_heads = 1 if num_heads is None else num_heads\n self.attention_dim_per_head = self.attention_dim // self.num_heads\n self.bias_dim = bias_dim\n\n def build(self, _):\n self.attn_query = self.add_weight(name='q',\n shape=(self.hidden_dim, self.num_heads, self.attention_dim_per_head),\n initializer='glorot_uniform')\n self.attn_keys = self.add_weight(name='k', shape=(self.hidden_dim, self.num_heads, self.attention_dim_per_head),\n initializer='glorot_uniform')\n self.attn_values = self.add_weight(name='v',\n shape=(self.hidden_dim, self.num_heads, self.attention_dim_per_head),\n initializer='glorot_uniform')\n self.weight_out = self.add_weight(name='o',\n shape=(self.num_heads, self.attention_dim_per_head, self.hidden_dim),\n initializer='glorot_uniform')\n if self.bias_dim is not None:\n self.bias_embs = self.add_weight(name='e1', shape=(self.bias_dim, self.attention_dim_per_head),\n initializer='glorot_uniform')\n self.bias_scalar = self.add_weight(name='e2', shape=(self.attention_dim_per_head, 1),\n initializer='glorot_uniform')\n\n @tf.function(input_signature=[tf.TensorSpec(shape=(None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, 4), dtype=tf.int32)])\n def call(self, states, key_states, masks, attention_bias):\n # Compute key, query and value vectors, reshaped to [Batch, Heads, Time, Dim] where Dim is attention_dim//num_heads.\n query, keys, values = self.compute_qkv(states, key_states)\n\n # Compute attention weights, and context from these.\n alpha = self.get_attention_weights(query, keys, masks, attention_bias)\n\n # Compute weigthed context and project out.\n context = tf.einsum('bhqk,bkha->bqha', alpha, values)\n context = tf.einsum('btha,had->btd', context, self.weight_out)\n return context\n\n # Compute key, query and value vectors.\n @tf.function(input_signature=[tf.TensorSpec(shape=(None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, None, None), dtype=tf.float32)])\n def compute_qkv(self, states, key_states):\n query = tf.einsum('btd,dha->btha', states, self.attn_query) # Queries are always computed on states\n keys = tf.einsum('btd,dha->btha', key_states, self.attn_keys)\n values = tf.einsum('btd,dha->btha', key_states, self.attn_values)\n return query, keys, values\n\n # Compute attention weights from cross-product between keys and queries (scaled, masked, softmaxed).\n @tf.function(input_signature=[tf.TensorSpec(shape=(None, None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, 4), dtype=tf.int32)])\n def get_attention_weights(self, query, keys, masks, attention_bias):\n alpha = tf.einsum('bkha,bqha->bhqk', keys, query)\n\n # If bias_dim is set, assume that a bias vector is provided.\n if self.bias_dim is not None:\n # Embed edge types in per-head-attention dimension. Experimentally, mat-mul tends to be faster here, but regular embedding is equally valid.\n bias = tf.matmul(tf.one_hot(attention_bias[:, 0], self.bias_dim), self.bias_embs)\n # Project down to a scalar.\n bias = tf.squeeze(tf.matmul(bias, self.bias_scalar), -1)\n alpha_shape = tf.shape(alpha)\n bias_shape = tf.stack([alpha_shape[0], alpha_shape[2], alpha_shape[3]])\n # Scatter edge biases to their [batch_index, key_index, query_index] positions.\n bias = tf.scatter_nd(attention_bias[:, 1:], bias, bias_shape)\n\n # Since bias is a scalar, we can reduce memory cost by rewriting the attention from (q + b) * k to q*k + b*reduce_sum(k, -1)\n summed_keys = tf.reduce_sum(keys, -1) # bkh\n bias = tf.einsum('bqk,bkh->bhqk', bias, summed_keys)\n # Accordingly, simply add the bias as a residual to standard dot-product attention.\n alpha += bias\n\n # Scale and apply mask\n alpha *= tf.math.rsqrt(tf.cast(self.attention_dim_per_head, 'float32'))\n alpha = alpha * masks + (1.0 - tf.math.ceil(masks)) * tf.float32.min\n alpha = tf.nn.softmax(alpha)\n alpha *= masks\n return alpha\n\n\nclass LayerNormalization(tf.keras.layers.Layer):\n def __init__(self, hidden_dim):\n super(LayerNormalization, self).__init__()\n self.hidden_dim = hidden_dim\n\n def build(self, _):\n self.scale = tf.Variable(tf.ones(self.hidden_dim))\n self.bias = tf.Variable(tf.zeros(self.hidden_dim))\n self.build = True\n\n @tf.function(input_signature=[tf.TensorSpec(shape=(None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(), dtype=tf.float32)])\n def call(self, x, epsilon=1e-3):\n mean, variance = tf.nn.moments(x, -1, keepdims=True)\n norm_x = (x - mean) * tf.math.rsqrt(variance + epsilon)\n return norm_x * self.scale + self.bias\n\n\nclass Transformer(tf.keras.layers.Layer):\n \"\"\"Transformer language model: converts indices into hidden states through layers of multi-headed attention and feed-forward dense layers.\n\n Augments a generic Transformer with attentional bias, if bias_dim is provided. See documentation on AttentionLayer for more details.\n To generate language from the resulting states, pass the states to the 'predict' function. Note that it assumes that the input vocabulary is output vocabulary (i.e., it reuses the model's embedding table).\n \"\"\"\n NOOP_BIAS = tf.zeros((0, 4), 'int32')\n\n default_config = {\n 'hidden_dim': 128,\n 'dropout_rate': 0.1,\n 'num_edge_types': 9,\n 'ff_dim': 2048,\n 'num_layers': 6,\n 'attention_dim': 128,\n 'num_heads': 8,\n }\n\n def __init__(self, model_config=None, shared_embedding=None, vocab_dim=None, is_encoder_decoder=False):\n super(Transformer, self).__init__()\n if model_config is None:\n model_config = Transformer.default_config\n self.is_encoder_decoder = is_encoder_decoder\n self.bias_dim = model_config['num_edge_types']\n self.hidden_dim = model_config['hidden_dim']\n self.ff_dim = model_config['ff_dim']\n self.attention_dim = model_config['attention_dim']\n self.num_layers = model_config['num_layers']\n self.num_heads = model_config['num_heads']\n self.dropout_rate = model_config['dropout_rate']\n\n # Initialize embedding variable in constructor to allow reuse by other models\n if shared_embedding is not None:\n self.embed = shared_embedding\n elif vocab_dim is None:\n raise ValueError('Pass either a vocabulary dimension or an embedding Variable')\n else:\n random_init = tf.random_normal_initializer(stddev=self.hidden_dim ** -0.5)\n self.embed = tf.Variable(random_init([vocab_dim, self.hidden_dim]), dtype=tf.float32)\n\n # Initialize default positional encoding for very long sequences. Can make this a parameter if necessary.\n self.pos_enc = util.positional_encoding(self.hidden_dim, 5000)\n\n def build(self, _):\n # Set up multi-headed attention, and feed-forward layers.\n make_att = lambda: AttentionLayer(self.attention_dim, self.num_heads, self.hidden_dim, self.bias_dim)\n self.attention = [make_att() for _ in range(self.num_layers)] # make_att_deprecated\n if self.is_encoder_decoder:\n self.enc_attention = [make_att() for _ in range(self.num_layers)]\n\n # Layer normalization for every residual layer\n self.ln = [[LayerNormalization(self.hidden_dim) for _ in range(3 if self.is_encoder_decoder else 2)] for _ in\n range(self.num_layers)]\n self.ln_out = LayerNormalization(self.hidden_dim)\n\n # Two-layer feed-forward with wide layer in the middle\n self.ff_1 = [tf.keras.layers.Dense(self.ff_dim, activation='relu') for _ in range(self.num_layers)]\n self.ff_2 = [tf.keras.layers.Dense(self.hidden_dim) for _ in range(self.num_layers)]\n\n # Default 'call' applies standard self-attention, with dropout if training=True.\n @tf.function(input_signature=[tf.TensorSpec(shape=(None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, 4), dtype=tf.int32),\n tf.TensorSpec(shape=(), dtype=tf.bool)])\n def call(self, states, masks, attention_bias, training):\n real_dropout_rate = self.dropout_rate * tf.cast(training,\n 'float32') # Easier for distributed training than an explicit conditional\n for ix in range(self.num_layers):\n new_states = self.ln[ix][0](states)\n new_states = self.attention[ix](new_states, new_states, masks, attention_bias)\n new_states = tf.nn.dropout(new_states, rate=real_dropout_rate)\n states += new_states\n\n new_states = self.ff_1[ix](self.ln[ix][1](states))\n new_states = tf.nn.dropout(new_states, rate=real_dropout_rate)\n new_states = self.ff_2[ix](new_states)\n new_states = tf.nn.dropout(new_states, rate=real_dropout_rate)\n states += new_states\n return self.ln_out(states)\n\n # Standard encoder-decoder attention, with dropout if training=True.\n # NOTE: tentatively does not support attention bias within the query itself; extending this should be straightforward.\n @tf.function(input_signature=[tf.TensorSpec(shape=(None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, None, None, None), dtype=tf.float32),\n tf.TensorSpec(shape=(None, 4), dtype=tf.int32),\n tf.TensorSpec(shape=(), dtype=tf.bool)])\n def enc_dec_attention(self, states, masks, key_states, key_masks, attention_bias, training):\n real_dropout_rate = self.dropout_rate * tf.cast(training,\n 'float32') # Easier for distributed training than an explicit conditional\n for ix in range(self.num_layers):\n new_states = self.ln[ix][0](states)\n new_states = self.attention[ix](new_states, new_states, masks, tf.zeros((0, 4), dtype='int32'))\n new_states = tf.nn.dropout(new_states, rate=real_dropout_rate)\n states += new_states\n\n new_states = self.ln[ix][2](states)\n new_states = self.enc_attention[ix](new_states, key_states, key_masks, attention_bias)\n new_states = tf.nn.dropout(new_states, rate=real_dropout_rate)\n states += new_states\n\n new_states = self.ff_1[ix](self.ln[ix][1](states))\n new_states = tf.nn.dropout(new_states, rate=real_dropout_rate)\n new_states = self.ff_2[ix](new_states)\n new_states = tf.nn.dropout(new_states, rate=real_dropout_rate)\n states += new_states\n return self.ln_out(states)\n\n # Embed inputs. Note: applies scaling before positional encoding.\n @tf.function(input_signature=[tf.TensorSpec(shape=(None, None), dtype=tf.int32)])\n def embed_inputs(self, inputs):\n states = tf.nn.embedding_lookup(self.embed, inputs)\n states *= tf.math.sqrt(tf.cast(tf.shape(states)[-1], 'float32'))\n states += self.pos_enc[:tf.shape(states)[1]]\n return states\n\n # Generates tokens from transformer states using the transposed embedding layer.\n @tf.function(input_signature=[tf.TensorSpec(shape=(None, None, None), dtype=tf.float32)])\n def predict(self, states):\n return tf.matmul(states, self.embed, transpose_b=True)\n\n # Convenience function: returns a sequence mask in which each token can only see states up to its own position. Useful for generative language modeling (e.g. decoding).\n @tf.function\n def get_sequence_mask(self, seq_len):\n return tf.sequence_mask(lengths=tf.range(1, seq_len + 1), maxlen=seq_len, dtype=tf.float32)\n","sub_path":"src/encoders/utils/great_transformer_network.py","file_name":"great_transformer_network.py","file_ext":"py","file_size_in_byte":15202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"573120225","text":"# -*-coding:utf-8 -*-\n\"\"\"统计维修单\"\"\"\n\nfrom pymongo import MongoClient, ReturnDocument\nfrom datetime import datetime, timedelta\nfrom app.base_class import CodeTable\nfrom app.commontools import create_day_list, in_date\n\n\ndef statistics_maintenaces(citycode, startdate='2016-01-01'):\n \"\"\"\n\n :param startdate: 统计开始的日期 '2016-01-01'\n :param citycode: 城市代码\n :return: None\n \"\"\"\n mongo_client = MongoClient(host='127.0.0.1', port=27017)\n today = datetime.today().strftime('%Y-%m-%d')\n\n # 获取某个城市的维修单数据\n maintenaces = mongo_client.spv1.maintenaces.aggregate(\n [\n {'$lookup': {'from': 'companies', 'localField': 'companyId', 'foreignField': '_id', 'as': 'company'}},\n {'$project': {'_id': 0, 'company': 1}}\n ])\n target_maintenaces = []\n for maintenace in maintenaces:\n if str(int(maintenace.get('company')[0].get('cityCode'))) == citycode:\n target_maintenaces.append(maintenace)\n\n # 获取辖区列表\n province_code_abbr = citycode[0:2]\n city_code_abbr = citycode[2:4]\n codetable = CodeTable()\n countylist = codetable.get_belong_county_info(province_code_abbr, city_code_abbr) # 获取市内区域代码列表\n\n # 按照辖区分类维修数据\n area_relatived_maintenaces = {}\n for county_info in countylist:\n temp_maintenace_list = []\n for tmaintenace in target_maintenaces:\n if str(int(tmaintenace.get('company')[0].get('countyCode'))) == county_info[1]:\n temp_maintenace_list.append(tmaintenace)\n area_relatived_maintenaces[(county_info[0], county_info[1])] = temp_maintenace_list\n\n # 按照每天统计\n for k, v in area_relatived_maintenaces.items():\n # 生成按照天的时间段\n days = create_day_list(startdate, today)\n if len(v) == 0: # 如果某个地区的投诉为0,则全部置为0\n for day in days:\n daily_data = {\n 'provinceCode': citycode[0:2] + '0000',\n 'cityCode': citycode,\n 'countyCode': k[1], # 辖区代码\n 'date': day[0],\n 'maintenaceQty': 0, # 维修量\n }\n\n updated_data = mongo_client.statistics.maintenacesstatistics.find_one_and_update(\n {'cityCode': citycode, 'provinceCode': citycode[0:2] + '0000', 'date': day[0], 'countyCode': k[1]},\n {\n '$set': daily_data}, upsert=True, return_document=ReturnDocument.AFTER)\n print(updated_data)\n else:\n for day in days:\n count = 0 # 记数\n for maintenace in v:\n if in_date(day, maintenace.get('created')):\n count += 1\n if count > 0:\n daily_data = {\n 'provinceCode': citycode[0:2] + '0000',\n 'cityCode': citycode,\n 'countyCode': k[1], # 辖区代码\n 'date': day[0],\n 'maintenaceQty': count, # 维修单量\n }\n else:\n daily_data = {\n 'provinceCode': citycode[0:2] + '0000',\n 'cityCode': citycode,\n 'countyCode': k[1], # 辖区代码\n 'date': day[0],\n 'maintenaceQty': 0, # 维修单量\n }\n updated_data = mongo_client.statistics.maintenacesstatistics.find_one_and_update(\n {'cityCode': citycode, 'provinceCode': citycode[0:2] + '0000', 'date': day[0], 'countyCode': k[1]},\n {\n '$set': daily_data}, upsert=True, return_document=ReturnDocument.AFTER)\n print(updated_data)\n\nif __name__ == '__main__':\n statistics_maintenaces('371100')\n","sub_path":"statistics/statistics_maintenaces.py","file_name":"statistics_maintenaces.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"540822715","text":"import sklearn.utils.linear_assignment_ as su\nimport numpy as np\nimport sys\nimport os\nfrom nltk.parse import stanford\nimport nltk\nfrom nltk.tree import ParentedTree\nfrom zss import simple_distance, Node\nimport random\nnumnodes =0\n\nclass Cassim:\n def __init__(self):\n self.sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')\n os.environ['STANFORD_PARSER'] = 'jars/stanford-parser.jar'\n os.environ['STANFORD_MODELS'] = 'jars/stanford-parser-3.5.2-models.jar'\n self.parser = stanford.StanfordParser(model_path=\"jars/englishPCFG.ser.gz\")\n\n def convert_mytree(self, nltktree,pnode):\n global numnodes\n for node in nltktree:\n numnodes+=1\n if type(node) is nltk.ParentedTree:\n tempnode = Node(node.label())\n pnode.addkid(tempnode)\n self.convert_mytree(node,tempnode)\n return pnode\n\n def minweight_edit_distance(self, doc1, doc2):\n global numnodes\n doc1sents = self.sent_detector.tokenize(doc1.strip())\n doc2sents = self.sent_detector.tokenize(doc2.strip())\n doc1parsed = self.parser.raw_parse_sents((doc1sents))\n doc2parsed = self.parser.raw_parse_sents((doc2sents))\n costMatrix = []\n doc1parsed = list(doc1parsed)\n for i in range(len(doc1parsed)):\n doc1parsed[i] = list(doc1parsed[i])[0]\n doc2parsed = list(doc2parsed)\n for i in range(len(doc2parsed)):\n doc2parsed[i] = list(doc2parsed[i])[0]\n for i in range(len(doc1parsed)):\n numnodes = 0\n sentencedoc1 = ParentedTree.convert(doc1parsed[i])\n tempnode = Node(sentencedoc1.root().label())\n new_sentencedoc1 = self.convert_mytree(sentencedoc1,tempnode)\n temp_costMatrix = []\n sen1nodes = numnodes\n for j in range(len(doc2parsed)):\n numnodes=0.0\n sentencedoc2 = ParentedTree.convert(doc2parsed[j])\n tempnode = Node(sentencedoc2.root().label())\n new_sentencedoc2 = self.convert_mytree(sentencedoc2,tempnode)\n ED = simple_distance(new_sentencedoc1, new_sentencedoc2)\n ED = ED / (numnodes + sen1nodes)\n temp_costMatrix.append(ED)\n costMatrix.append(temp_costMatrix)\n costMatrix = np.array(costMatrix)\n rownum= costMatrix.shape[0]\n colnum = costMatrix.shape[1]\n if rownum > colnum:\n costMatrixRandom = costMatrix[np.random.randint(rownum, size=colnum),:]\n else:\n costMatrixRandom = costMatrix[:,np.random.randint(colnum, size=rownum)]\n \n indexes = su.linear_assignment(costMatrix)\n total = 0\n minWeight = 0\n rowMarked = [0] * len(doc1parsed)\n colMarked = [0] * len(doc2parsed)\n for row, column in indexes:\n total += costMatrix[row][column]\n rowMarked[row] = 1\n colMarked [column] = 1\n minWeight = total\n \n for k in range(len(rowMarked)):\n if rowMarked[k]==0:\n total+= np.min(costMatrix[k])\n for c in range(len(colMarked)):\n if colMarked[c]==0:\n total+= np.min(costMatrix[:,c])\n maxlengraph = max(len(doc1parsed),len(doc2parsed))\n minlengraph = min(len(doc1parsed),len(doc2parsed))\n \n indexes = su.linear_assignment(costMatrixRandom)\n randtotal = 0\n for row, column in indexes:\n randtotal +=costMatrixRandom[row][column]\n lengraph = costMatrixRandom.shape[0]\n \n return total/maxlengraph#, minWeight/minlengraph, randtotal/lengraph\n","sub_path":"Cassim.py","file_name":"Cassim.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"219408442","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Branch',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=40)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Course',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=40)),\n ('course_id', models.CharField(unique=True, max_length=10)),\n ('branch', models.ForeignKey(to='basic.Branch')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Membership',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('course', models.ForeignKey(to='basic.Course')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Notification',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('type', models.CharField(max_length=100)),\n ('object_id', models.IntegerField(blank=True)),\n ('user_name', models.CharField(max_length=50)),\n ('link', models.CharField(max_length=100)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Register',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('code', models.CharField(unique=True, max_length=32)),\n ('email', models.EmailField(unique=True, max_length=75)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SetNotification',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('keyword', models.CharField(max_length=100)),\n ('notification', models.ForeignKey(to='basic.Notification')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('reg', models.CharField(unique=True, max_length=12, blank=True)),\n ('website', models.URLField(blank=True)),\n ('picture', models.ImageField(upload_to=b'profile_images', blank=True)),\n ('role', models.CharField(default=b'Student', max_length=20)),\n ('branch', models.ForeignKey(to='basic.Branch', blank=True)),\n ('courses', models.ManyToManyField(to='basic.Course', through='basic.Membership')),\n ('notifications', models.ManyToManyField(to='basic.Notification', through='basic.SetNotification')),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='setnotification',\n name='user',\n field=models.ForeignKey(to='basic.UserProfile'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='membership',\n name='member',\n field=models.ForeignKey(to='basic.UserProfile'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='course',\n name='students',\n field=models.ManyToManyField(to='basic.UserProfile', through='basic.Membership'),\n preserve_default=True,\n ),\n ]\n","sub_path":"src/basic/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"316903959","text":"import requests\nimport json\nimport PythonTokenGenerator\n\n# Test environment URL\nurl = 'https://biblio-qa1.dev.rosettastone.com'\nactivity_set = '839ca07b-d2bb-4d2b-aa79-215c8f201e28'\n\n# Set service end point, user, environment\nend_point = '/content/activity_set/' + activity_set + '/aggregate/'\nuser = 'mhotchkiss-qa1@rosettastone.com'\nenvironment = 'qa1'\n\n# Get the generated userId and auth_token\nresponse = PythonTokenGenerator.get_token(environment, user)\nuser_id = response[0]\nauth_token = response[1]\nprint('auth_token = ' + auth_token + '\\n')\n\nheaders = {\n 'Authorization': 'Bearer ' + auth_token\n}\n\n# Make the request\nr = requests.get(url + end_point + user_id, headers=headers)\n\n# Process and format the response\nresults = json.loads(r.text)\npretty = json.dumps(results, indent=2)\nprint(pretty)\n\n#{\n# \"error_description\": \"not_found: missing:https://db-host-5/biblio/839ca07b-d2bb-4d2b-aa79-215c8f201e28%2Faggregate%2Fc6e3f3dd-b9dd-4c98-96a1-126190ec4927\",\n# \"error\": \"Entity Not Found\"\n#}\n","sub_path":"RoStoneIssues/AEB6286/AEB6286.py","file_name":"AEB6286.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"412472803","text":"from enum import Enum\n\nfrom sqlalchemy import create_engine, Column, DateTime, func, Integer, BigInteger, Text\nfrom sqlalchemy.dialects.postgresql import JSON, JSONB\nfrom sqlalchemy.exc import DatabaseError\nfrom flask_sqlalchemy import Model\nfrom sqlalchemy.orm import sessionmaker\n\nfrom dukepy.config import Config\nfrom dukepy.traces import print_exception_traces\n\n\nclass DBType(Enum):\n sqlite = 1\n mysql = 2\n postgres = 3\n\n\ndb_type = DBType.sqlite # Default\nif \"sqlite\" == Config()[\"database\"][\"active\"]:\n db_type = DBType.sqlite\nif \"mysql\" == Config()[\"database\"][\"active\"]:\n db_type = DBType.mysql\nif \"postgres\" == Config()[\"database\"][\"active\"]:\n db_type = DBType.postgres\n\n\n## Init session\nclass DBSession():\n def uri(self, type):\n db_uri = None\n\n if type == DBType.sqlite:\n db_uri = \"sqlite:///\" + Config()[\"database\"][\"sqlite\"][\"path\"]\n\n if type == DBType.mysql:\n config = Config()[\"database\"][\"mysql\"]\n db_uri = \"mysql+pymysql://{0}:{1}@{2}:3306/{3}\".format(config[\"user\"], config[\"password\"], config[\"host\"],\n config[\"db\"])\n\n if type == DBType.postgres:\n config = Config()[\"database\"][\"postgres\"]\n db_uri = \"postgresql://{0}:{1}@{2}:{3}/{4}\".format(config[\"user\"], config[\"password\"], config[\"host\"],\n config[\"port\"], config[\"db\"])\n\n return db_uri\n\n def create_session(self, db_uri):\n engine = create_engine(db_uri)\n Session = sessionmaker(bind=engine)\n session = Session()\n session._model_changes = {}\n return session\n\n\ndb_session_helper = DBSession()\ndb_uri = db_session_helper.uri(db_type)\ndb_session = db_session_helper.create_session(db_uri)\n\n\n## Declare base\nclass AlchemyBase(Model):\n \"\"\"\n ref: https://chase-seibert.github.io/blog/2016/03/31/flask-sqlalchemy-sessionless.html\n \"\"\"\n\n id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)\n if db_type == DBType.sqlite:\n json_data = Column(Text, nullable=True)\n if db_type == DBType.mysql:\n json_data = Column(Text, nullable=True)\n if db_type == DBType.postgres:\n json_data = Column(JSONB, nullable=True)\n\n # https://stackoverflow.com/a/12155686/973425\n created_at = Column(DateTime, nullable=False,\n server_default=func.now())\n updated_at = Column(DateTime, nullable=False,\n server_default=func.now(),\n server_onupdate=func.now())\n\n def save(self):\n local_object = db_session.merge(self)\n db_session.add(local_object)\n # try:\n self._flush()\n db_session.commit()\n # except DatabaseError as e:\n # code = e.orig.args[0]\n # if code == 1062:\n # raise\n # return None\n return local_object\n\n def update(self, **kwargs):\n for attr, value in kwargs.items():\n setattr(self, attr, value)\n return self.save()\n\n def delete(self):\n local_object = db_session.merge(self) # https://stackoverflow.com/a/47663833/973425\n db_session.delete(local_object)\n self._flush()\n db_session.commit()\n\n def _flush(self):\n try:\n db_session.flush()\n # db_session.refresh(self)\n except DatabaseError as e:\n db_session.rollback()\n print_exception_traces(e)\n raise\n\n @staticmethod\n def session():\n return db_session\n","sub_path":"src/dukepy/sql_alchemy/tables/alchemy_base.py","file_name":"alchemy_base.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"245831410","text":"import re # for regular expressions\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\nfrom spellchecker import SpellChecker\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nimport pickle\n\nnltk.download('punkt')\nnltk.download('stopwords')\n\nwords_removed= ['collect', 'part', 'promote', 'review', 'really', 'product']\n\nstemmer = PorterStemmer()\n\nspell = SpellChecker()\n\nwith open('logisticReg_final_model.pkl', 'rb') as file:\n model = pickle.load(file)\n \nwith open('tf_idf_vectorizer_new.pkl', 'rb') as file:\n tf_idf = pickle.load(file)\n \n\nclass get_sentiment():\n \n def __init__(self):\n \n return None\n \n def clean_review(self, review_text):\n review_text = re.sub(r\"http\\S+|www.\\S+\", \"\", review_text) \n review_text = re.sub(\"[^a-zA-Z]\", \" \", review_text) \n review_text = str(review_text).lower() \n review_text = word_tokenize(review_text) \n review_text = [i for i in review_text if len(i)>2] \n review_text = [i for i in review_text if i not in stopwords.words('english')] \n review_text = [i for i in review_text if i not in words_removed]\n review_text = [stemmer.stem(i) for i in review_text] \n review_text = [spell.correction(i) for i in review_text] \n review_text = ' '.join(review_text)\n \n return(review_text)\n \n def sentiment (self, review_text):\n \n review_text = self.clean_review(review_text)\n \n X = tf_idf.transform([review_text])\n \n y= model.predict(X)\n \n return(int(y))\n \n\n \nimport pandas as pd\nimport numpy as np\nimport random\n\nitem_based_reco = pd.read_csv('item_based_reco.csv')\nitem_based_reco.set_index('reviews_username', inplace=True)\n\ndataset = pd.read_csv('sample30.csv')\n\nid_name= pd.read_csv('id_name.csv')\n\nclass pdt_recommendation(get_sentiment):\n \n def __init__(self):\n \n #self.username= username\n return None\n \n \n def recom_using_item_based(self, username): ##takes username as input and returns 20 reco pdts\n \n d = item_based_reco.loc[username].sort_values(ascending=False)[0:20]\n top_20 = list(d.index)\n \n return top_20\n \n def pdt_overall_sentiment(self, pdt_id): ##takes a pdt id as input serach the reviews and give the sentiment_score\n \n filt_df= dataset.loc[dataset['id']== pdt_id, ['reviews_title', 'reviews_text']]\n filt_df['merge']= filt_df['reviews_title']+ str(' ')+ filt_df['reviews_text']\n all_reviews = list(filt_df['merge'])\n \n if len(all_reviews)>300:\n all_reviews= random.sample(all_reviews, 300)\n \n #print(len(all_reviews))\n \n sentiment_score= sum([self.sentiment(str(review)) for review in all_reviews])\n \n return (round(sentiment_score/len(all_reviews),2))\n \n def predict(self, username):\n \n top_20_pdt_id= self.recom_using_item_based(username)\n top_20_pdt_sent={}\n for id in top_20_pdt_id:\n top_20_pdt_sent[id] = self.pdt_overall_sentiment(id)\n \n top_20_pdt_sent= dict(sorted(top_20_pdt_sent.items(), key= (lambda x: -x[1])))\n\n top_5_pdt_id= list(top_20_pdt_sent.keys())[0:5]\n \n \n top_5_pdt_name= [id_name.loc[id_name['id']==x , 'name_by_brand'].values[0] for x in top_5_pdt_id]\n \n \n return(top_5_pdt_name)\n \n\n ","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"509933111","text":"import pygame\nimport random\n\nfrom os import path\n\nimg_dir=path.join(path.dirname(__file__),'img')\n\nwidth=600\nheight=600\n\n\nwhite=(255,255,255)\nblack=(0,0,0)\nred=(255,0,0)\ngreen=(0,255,0)\nblue=(0,255,0)\n\n\n#initialize pygame and create window\n\npygame.init()\npygame.mixer.init()\nscreen=pygame.display.set_mode((width,height))\npygame.display.set_caption(\"my game\")\n\nclass Player(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image=pygame.transform.scale(player_img,(40,40))\n self.image.set_colorkey(black)\n #self.image.fill(green)\n self.rect=self.image.get_rect()\n self.rect.centerx=width/2\n self.rect.bottom=height-10\n self.speedx=0\n\n def update(self):\n self.speedx=0\n keystate=pygame.key.get_pressed()\n if keystate[pygame.K_LEFT]:\n self.speedx=-5\n if keystate[pygame.K_RIGHT]:\n self.speedx=5\n self.rect.x+=self.speedx\n if self.rect.right>width:\n self.rect.right=width\n if self.rect.left<0:\n self.rect.left=0\n #print(self.speedx,self.rect.x)\n\n def shoot(self):\n bullet=Bullet(self.rect.centerx,self.rect.top)\n all_sprites.add(bullet)\n bullets.add(bullet)\n\nclass Mob(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image=pygame.transform.scale(monstor_img,(40,30))\n self.image.set_colorkey(black)\n self.rect=self.image.get_rect()\n self.rect.x=random.randrange(width-self.rect.width)\n self.rect.y=random.randrange(-100,-40)\n self.speedy=random.randrange(1,4)\n\n def update(self):\n self.rect.y+=self.speedy\n if self.rect.top>height+10:\n self.rect.x=random.randrange(width-self.rect.width)\n self.rect.y=random.randrange(-100,-40)\n self.speedy=random.randrange(1,4)\n\nclass Bullet(pygame.sprite.Sprite):\n def __init__(self,x,y):\n pygame.sprite.Sprite.__init__(self)\n self.image=bullet_img\n self.image.set_colorkey(black)\n \n self.rect=self.image.get_rect()\n self.rect.bottom=y\n self.rect.centerx=x\n self.speedy=-5\n\n def update(self):\n self.rect.y+=self.speedy\n if self.rect.bottom<0:\n self.kill()\n \n\n#load all game images\n\nplayer_img=pygame.image.load(path.join(img_dir,'ship-medium.png')).convert()\nbullet_img=pygame.image.load(path.join(img_dir,'laserRed16.png')).convert()\nmonstor_img=pygame.image.load(path.join(img_dir,'monstor.png')).convert()\n\nall_sprites=pygame.sprite.Group()\n\nmobs=pygame.sprite.Group()\n\nbullets=pygame.sprite.Group()\n\nplayer=Player()\nall_sprites.add(player)\n\nfor i in range(10):\n m=Mob()\n all_sprites.add(m)\n mobs.add(m)\n \ndone=True\n\nwhile done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = False\n elif event.type==pygame.KEYDOWN:\n if event.key==pygame.K_SPACE:\n player.shoot()\n\n all_sprites.update()\n\n hits=pygame.sprite.groupcollide(mobs,bullets,True,True)\n for hit in hits:\n m=Mob()\n all_sprites.add(m)\n mobs.add(m)\n\n hits=pygame.sprite.spritecollide(player,mobs,False)\n if hits:\n print('lost game')\n done=False\n \n screen.fill(black)\n all_sprites.draw(screen)\n pygame.display.flip()\n pygame.time.delay(10)\n \n","sub_path":"player_shoot.py","file_name":"player_shoot.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"122363554","text":"from mwclient import Site\nimport pandas as pd\nimport re\nimport src.local # create a file called local.py with your credentials\n\n\ndef site_login():\n \"\"\"\n Log-in to the Semantic MediaWiki using a USERNAME and PASSWORD\n Create a file called local.py with your credentials\n \"\"\"\n site = Site(('http', 'beta.floranorthamerica.org'))\n site.login(src.local.USERNAME, src.local.PASSWORD)\n return site\n\n\ndef extract_property_text(printouts, property):\n \"\"\"\n Extract property data from the data returned by the API (=\"printouts\") for a property\n\n Parameters\n ----------\n printouts: query results returned by the site.ask query function\n property: property name (e.g., Illustrator, Distribution, etc.)\n\n Returns\n -------\n property_text: isolated property text string for the property in question\n\n \"\"\"\n property_text = printouts[property]\n if len(property_text) == 1:\n property_text = property_text[0] # property_text comes as a list, even with one value\n if isinstance(property_text, dict): # If the property is a page type, it returns a dictionary\n property_text = property_text['fulltext'] # with namespace, url, etc. 'fulltext' is what we want\n # if property_text contains more than one value, it is useful to simply return it as a list!\n if len(property_text) > 1 and isinstance(property_text[0], dict): # UNLESS property_text is a dictionary, in the\n # case of page properties. In this case we need to extract the 'fulltext' property values and return them as a list,\n # similar to string type properties TODO: return Series instead of list here\n prop_value_list = list()\n prop_value_list.append([prop_value['fulltext'] for prop_value in property_text]) #\n property_text = prop_value_list[0]\n return property_text\n\n\ndef extract_taxon_properties(site, query_string, properties):\n \"\"\"\n Return taxa names matched by a query string, as well as the property data asked for in a list\n using the mwclient function \"ask\".\n\n Parameters\n ----------\n site: a logged-in Site object of the flora\n query_string: a query string to run ask SMW ask query API\n properties: a list of the properties you'd like to return\n\n Returns\n -------\n taxon_names: a list of the taxon name returned to match to the property data returned\n property_texts: a list of property text data asked for by the query string\n \"\"\"\n properties_texts = []\n taxon_names = []\n\n for answer in site.ask(query_string): # use a for loop to collect properties and other things we want to store!\n for title, data in answer.items():\n if title == 'printouts':\n properties_texts.append([extract_property_text(data, property) for property in properties])\n if title == 'fulltext':\n taxon_names.append(data)\n print(\"Appending {} data\".format(data))\n\n return taxon_names, properties_texts\n\n\ndef ask_query(query_string, output_file_name):\n \"\"\"\n Run an ask query against the API module \"ask\" using the mwclient function \"ask\".\n\n Parameters\n ----------\n output_file_name: output file name\n query_string: a query string to run ask SMW ask query API, e.g.:\n\n Examples:\n query_string = \"[[Authority::Linnaeus]][[Distribution::Nunavut]]|?Taxon family\"\n query_string = \"[[Authority::Miller]]|?Taxon family|?Volume\"\n query_string = \"[[Distribution::Ont.]][[Author::Geoffrey A. Levin]]|?Taxon family|?Volume|?Illustration|?Distribution\"\n query_string = \"[[Distribution::Ont.]][[Author::Geoffrey A. Levin]]|?Taxon family|?Volume|?Distribution\"\n query_string = \"[[Illustrator::+]][[Illustration::Present]]\"\n\n Returns\n -------\n properties_texts_data_frame: a pandas dataframe with matched taxa names and properties\n\n \"\"\"\n site = site_login()\n properties = re.split(r'\\|\\?', query_string)[1:]\n taxon_names, properties_texts = extract_taxon_properties(site, query_string, properties)\n properties_texts = pd.DataFrame(properties_texts, columns=properties)\n properties_texts_data_frame = pd.concat([pd.Series(taxon_names), properties_texts], axis=1)\n properties_texts_data_frame = properties_texts_data_frame.rename(columns={0: \"Taxon name\"})\n properties_texts_data_frame.to_csv(output_file_name, index=False)\n return properties_texts_data_frame","sub_path":"python/src/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"178535603","text":"from django.shortcuts import render\nfrom django.http import Http404\nfrom .models import Shows,Reservation,Category\nfrom datetime import datetime\nfrom django.contrib.auth.decorators import login_required\n\nfrom django.contrib.auth.forms import UserCreationForm\n\n# Create your views here.\n\n\ndef index(request):\n return render( request,'reservations/index.html')\n\n\n\ndef detail(request,id_spectacle):\n try:\n spectacle = Shows.objects.get(pk=id_spectacle)\n except Shows.DoesNotExist:\n raise Http404(\"Ce spectacle n existe pas !\")\n if request.method=='POST':\n nombre_place=int(request.POST.get(\"nombre_place\"))\n place_dispo= spectacle.location.get_available_places()\n if (place_dispo >= nombre_place):\n total= nombre_place*spectacle.get_price()\n current_user=request.user\n location=spectacle.location\n booking=Reservation.objects.create(\n user=current_user,\n nombre_place=nombre_place,\n prix_total=total,\n spectacle=spectacle,\n location=location\n )\n\n\n\n return render(request,'reservations/detail.html', {'spectacle': spectacle})\n\n\ndef spectacles(request):\n spectacle_dispo = Shows.objects.filter(bookable=True)\n return render(request,'reservations/spectacles.html',{'spectacle_dispo':spectacle_dispo})\n\n\n\n@login_required(login_url='/utilisateur/connexion/')\ndef reservation(request):\n spectacle_dispo=Shows.objects.filter(bookable=True)\n return render(request,'reservations/reservations.html',{'spectacle_dispo':spectacle_dispo})\n\ndef categorie(request):\n categories=Category.objects.all()\n return render(request,'reservations/categories.html',{'categories':categories})\n\ndef spectacle_categu(request,id_categorie):\n spectacles=Shows.objects.filter(category=id_categorie)\n return render(request, 'reservations/spectacle_category.html', {'spectacles': spectacles})\n\ndef modif_bookable(request,data):\n\n pass","sub_path":"reservations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"387202412","text":"# -*- coding: utf-8 -*-\n\"\"\"\n===============================================================================\nNanoGen view controllers (:mod:`sknano.apps.nanogen_gui._nanogen_controllers`)\n===============================================================================\n\n.. currentmodule:: sknano.apps.nanogen_gui._nanogen_controllers\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\nfrom __future__ import unicode_literals\n__docformat__ = 'restructuredtext en'\n\n\ntry:\n from PyQt5.QtWidgets import QApplication\nexcept ImportError:\n from PyQt4.QtGui import QApplication\n\nfrom ._nanogen_views import NanoGenView, SWNTGeneratorView, \\\n MWNTGeneratorView, GrapheneGeneratorView, \\\n FullereneGeneratorView, BulkStructureGeneratorView\n\n__all__ = ['NanoGenController', 'SWNTGeneratorController',\n 'MWNTGeneratorController', 'GrapheneGeneratorController',\n 'BulkStructureGeneratorController', 'ViewControllerMixin',\n 'GeneratorViewController']\n\n\nclass ViewControllerMixin:\n def refresh_view(self):\n \"\"\"Refresh `NanoGenView`.\"\"\"\n self.view.update_app_view()\n\n\nclass NanoGenController(ViewControllerMixin):\n \"\"\":mod:`~sknano.apps.nanogen_gui` MVC controller class.\n\n Parameters\n ----------\n args : :attr:`python:sys.argv`\n model : :class:`~sknano.apps.nanogen_gui._nanogen_model.NanoGenModel`\n An instance of\n :class:`~sknano.apps.nanogen_gui._nanogen_model.NanoGenModel`.\n\n \"\"\"\n def __init__(self, args, model=None):\n app = QApplication(args)\n self.model = model\n self.view = NanoGenView(self, self.model)\n self.model.notify_observers()\n self.view.show()\n app.exec_()\n\n\nclass GeneratorViewController(ViewControllerMixin):\n def __init__(self, model=None, view=None, **kwargs):\n self.model = model\n self.view = view(self, self.model, **kwargs)\n self.model.notify_observers()\n self.view.show()\n\n def get_generator_parameters(self):\n return self.view.get_generator_parameters()\n\n\nclass SWNTGeneratorController(GeneratorViewController):\n def __init__(self, model=None, **kwargs):\n super().__init__(model=model, view=SWNTGeneratorView, **kwargs)\n\n\nclass MWNTGeneratorController(GeneratorViewController):\n def __init__(self, model=None, **kwargs):\n super().__init__(model=model, view=MWNTGeneratorView, **kwargs)\n\n\nclass GrapheneGeneratorController(GeneratorViewController):\n def __init__(self, model=None, **kwargs):\n super().__init__(model=model, view=GrapheneGeneratorView, **kwargs)\n\n\nclass FullereneGeneratorController(GeneratorViewController):\n def __init__(self, model=None, **kwargs):\n super().__init__(model=model, view=FullereneGeneratorView, **kwargs)\n\n\nclass BulkStructureGeneratorController(GeneratorViewController):\n def __init__(self, model=None, **kwargs):\n super().__init__(model=model, view=BulkStructureGeneratorView,\n **kwargs)\n","sub_path":"sknano/apps/nanogen_gui/_nanogen_controllers.py","file_name":"_nanogen_controllers.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"235323483","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nfrom sys import version_info\nif version_info.major == 3:\n pass\nelif version_info.major == 2:\n input = raw_input\nelse:\n print (\"Unknown python version - input function not safe\")\n\nfrom os import environ\n#from collections import deque\nfrom sys import stdin\n#from statistics import median\n#from sys import setrecursionlimit\n#setrecursionlimit (11000)\n\n\"\"\"\ntc 1\nanswer: 633\n9 5\n2 3 4 2 3 6 8 4 5\nanswer: 2\n6 3\n2 2 2 9 1 15\nanswer: 2\n10 3\n4 5 6 2 7 1 8 0 9 3\nanswer: 2\n14 4\n5 5 5 5 10 1 1 1 4 0 2 8 3 14\nanswer: 5\n50 8\n34 26 83 26 66 26 34 83 56 88 1 5 8 8 5 1 2 35 65 33 31 30 0 200 156 22 22 22 22 33 33 33 44 4 44 44 12 82 48 25 22 22 21 12 12 33 1 1 1 9\nanswer: 7\n\n\"\"\"\n\ndef countSort (n, l):\n mxVal = 201\n c = [0] * mxVal\n for i in range (n):\n c [l [i]] += 1\n res = []\n for i in range (mxVal):\n if c [i]:\n res += [i] * c [i]\n return res\n\nclass CSM: # count sort median\n def __init__(self, lst, n):\n mxVal = 201\n self.lst_size = n\n self.odd = n % 2\n self.nh = n // 2\n self.csm_size = mxVal\n self.data = [0] * mxVal\n self.fill (lst, n)\n self.init_csm ()\n def fill (self, lst, n):\n for i in range (n):\n self.data [lst [i]] += 1\n def init_csm (self):\n hc = 0\n brk = False\n for i in range (self.csm_size):\n if self.data [i]:\n if hc + self.data [i] <= self.nh:\n hc += self.data [i]\n continue\n hc += self.data [i]\n for ix in range (self.data [i],0,-1):\n hc -= 1\n if hc <= self.nh: # hc half counter\n self.nhdf = ix # diff2nh\n self.nhnr = i # nh number (in half of list)\n brk = True\n break\n if brk: break\n def csm (self):\n if self.odd:\n return self.nhnr\n else:\n if self.nhdf > 1: nh_1 = self.nhnr\n else: # nh_1 is number in nh - 1\n nh_1 = self.nhnr - 1\n while not self.data [nh_1]: nh_1 -= 1\n return (nh_1 + self.nhnr) / 2\n def qu_csm (self, fst, new): # queue - drop fst, add new\n self.data [fst] -= 1\n self.data [new] += 1\n if (fst == new or fst < self.nhnr and new < self.nhnr or\n fst > self.nhnr and new >= self.nhnr or\n fst == self.nhnr and new > self.nhnr \n and self.data [self.nhnr] >= self.nhdf): pass\n elif (fst < self.nhnr and new >= self.nhnr or\n fst == self.nhnr and new > self.nhnr):\n if self.nhdf < self.data [self.nhnr]: self.nhdf += 1\n else:\n self.nhnr += 1\n while not self.data [self.nhnr]: self.nhnr += 1\n self.nhdf = 1\n elif (fst >= self.nhnr and new < self.nhnr):\n if self.nhdf > 1: self.nhdf -= 1\n else:\n self.nhnr -= 1\n while not self.data [self.nhnr]: self.nhnr -= 1\n self.nhdf = self.data [self.nhnr]\n def median (self): # via creating sorted list (O (n))\n l = self.srt_lst ()\n nh = self.nh\n odd = self.odd\n return l [nh] if odd else (l [nh - 1] + l [nh]) / 2\n # fill a list to 'count array'\n def srt_lst (self):\n res = []\n for i in range (self.csm_size):\n if self.data [i]:\n res += [i] * self.data [i]\n return res\n\ndef activityNotifications (exptr, n, d):\n odd = d % 2\n dh = d // 2\n def get_med (seq):\n return seq [dh] if odd else (seq [dh - 1] + seq [dh]) / 2\n act = 0\n if n < 100 and d < 100:\n for i in range (d, n):\n md = get_med (sorted (exptr [i - d : i]))\n if exptr [i] >= md * 2:\n act += 1\n return act\n else:\n lst = CSM (exptr [ : d], d)\n for i in range (d, n):\n md = lst.csm ()\n if exptr [i] >= md * 2: #lst.median () * 2: # md * 2:\n act += 1\n lst.qu_csm (exptr [i - d], exptr [i])\n return act\n\ndef main ():\n fptr = open (environ ['OUTPUT_PATH'], 'w')\n [n, d] = map (int, input ().split ())\n #expenditure = list (map (int, stdin.readline ().rstrip ().split ()))\n expenditure = [int (x) for x in stdin.readline ().split ()]\n result = activityNotifications (expenditure, n, d)\n print (result)\n fptr.write (str (result) + '\\n')\n fptr.close ()\n\nif __name__ == '__main__':\n main ()\n","sub_path":"2017/hackerrank/activityNotifications.py","file_name":"activityNotifications.py","file_ext":"py","file_size_in_byte":4679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"62717339","text":"import logging\nimport models.backbone.resnet_cifar as resnet\nlogger = logging.getLogger('base')\n\ndef define_net(arch, block_name, num_classes=100, pretrained=False):\n if arch.startswith(\"resnet\"):\n depth = int(arch.split('-')[-1])\n net = resnet.ResNet(depth=depth, num_classes=num_classes, block_name=block_name)\n else:\n raise NotImplementedError('The model [{}] is not implemented.'.format(arch))\n logger.info('The network [{}] has created.'.format(arch))\n return net","sub_path":"models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"438008892","text":"##import rospy\nimport atexit\nimport ray\n#from ray.rllib.agents.ddpg.apex import ApexDDPGTrainer\nfrom ray import tune\nfrom ray.tune import run_experiments, grid_search\nimport gym\n\n\nnum_of_workers = 12\nhorizon = 40\n\n#ray.init()\n#ray.init(redis_address=\"localhost:48842\")\n#ray.init(redis_address=\"localhost:14458\",huge_pages= True, plasma_directory='/mnt/hugepages')\n#ray.init(plasma_directory='/tmp/plasma')\nray.init(object_store_memory=175000000000, redis_max_memory=20000000000)\n\n\ndef on_episode_start(info):\n episode = info[\"episode\"]\n print(\"episode {} started\".format(episode.episode_id))\n\n\n\ndef on_episode_end(info):\n episode = info[\"episode\"]\n print(episode.episode_id, episode.length)\n\n\ndef on_sample_end(info):\n print(\"returned sample batch of size {}\".format(info[\"samples\"].count))\n\n\ndef on_train_result(info):\n print(\"trainer.train() result: {} -> {} episodes\".format(\n info[\"trainer\"], info[\"result\"][\"episodes_this_iter\"]))\n # you can mutate the result dict to add new fields to return\n info[\"result\"][\"callback_ok\"] = True\n\n\ndef on_postprocess_traj(info):\n episode = info[\"episode\"]\n batch = info[\"batch\"]\n print(\"postprocessed {} steps\".format(batch.count))\n if \"num_batches\" not in episode.custom_metrics:\n episode.custom_metrics[\"num_batches\"] = 0\n episode.custom_metrics[\"num_batches\"] += 1\n\n\nrun_experiments({\n \"Our_results\": {\n \"run\": \"APEX_DDPG\",\n \"env\": 'FetchPickAndPlace-v1',\n \"stop\": {\"episode_reward_mean\": 20,},\n #\"resources_per_trial\":{\"cpu\": 10, \"gpu\": 1},\n \"config\": {\n \"n_step\":2, \n \"compress_observations\": True, \"prioritized_replay\": False,\n \"timesteps_per_iteration\": 1500, \"min_iter_time_s\":30,\n \"horizon\":horizon, \"parameter_noise\": True,\n \"num_workers\": 4, \"collect_metrics_timeout\":1600,\n \"buffer_size\":200000, \"lr\": 1e-3, # to try different learning rates #\"per_worker_exploration\": True,\n \"num_cpus_per_worker\": 1.5,\n \"num_cpus_for_driver\":1,\n \"batch_mode\": \"complete_episodes\",\n \"per_worker_exploration\" : True,\n \"callbacks\": {\n #\"on_episode_start\": tune.function(on_episode_start),\n #\"on_episode_step\": None,\n #\"on_episode_end\": tune.function(on_episode_end),\n #\"on_sample_end\": tune.function(on_sample_end),\n \"on_train_result\": tune.function(on_train_result),\n #\"on_postprocess_traj\": tune.function(on_postprocess_traj),\n }\n },\n },\n })\n","sub_path":"train_ee.py","file_name":"train_ee.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"634090987","text":"\"\"\" Compiled: 2020-09-18 10:38:49 \"\"\"\n\n#__src_file__ = \"extensions/advanced_corporate_actions/./etc/FCorpActionSetup.py\"\n\"\"\"----------------------------------------------------------------------------\n MODULE\n FCorpActionSetup - Module which create the additional infos needed for the corporate\n action processing. \n\n DESCRIPTION\n This module set up all the necessary additional infos for the advanced \n corporate action processing.\n ---------------------------------------------------------------------------\"\"\"\nimport FBDPCommon\nimport acm\nimport FBDPCurrentContext\nimport FCorpActionElectionStatesSetup\n \ndef CreateAdditionalInfo():\n FBDPCommon.CreateAdditionalInfo('Position', 'CorpActionElection',\n 'Standard', 'Integer', description='Reference to Position', subTypes=[])\n FBDPCommon.CreateAdditionalInfo('PositionInstance', 'CorpActionElection',\n 'Standard', 'Integer', description='Position', subTypes=[])\n FBDPCommon.CreateAdditionalInfo('RollbackElection', 'CorpActionElection',\n 'Standard', 'String', description='RollbackElection', subTypes=[])\n FBDPCommon.CreateAdditionalInfo('TaxRate', 'CorpActionElection',\n 'Standard', 'Double', description='Tax Rate Applicable', \n subTypes=[], defaultValue=1.0)\n FBDPCommon.CreateAdditionalInfo('SuggestedBy', 'CorpActionElection',\n 'Standard', 'String', description='Suggested By Trader', subTypes=[])\n FBDPCommon.CreateAdditionalInfo('TraderElection', 'CorpActionElection',\n 'Standard', 'String', description='Elected By Trader', subTypes=[], defaultValue='N/A')\n FBDPCommon.CreateAdditionalInfo('TraderInterestedIn', 'CorpAction',\n 'Standard', 'String', description='Intererted By Trader', subTypes=[])\n FBDPCommon.CreateAdditionalInfo('MarkitCAStatus', 'CorpAction',\n 'Standard', 'String', description='Workflow Status', subTypes=[])\n FBDPCommon.CreateAdditionalInfo('CADefinitionFile', 'CorpAction',\n 'Standard', 'String', description='File defines the Corporate Action', subTypes=[])\n\ndef CreateMarketPlaces():\n MarketNames = ['ExDate', 'RecordDate']\n for mktName in MarketNames:\n if not acm.FMarketPlace[mktName]:\n mkt = acm.FMarketPlace()\n mkt.Name(mktName)\n mkt.Commit()\n\ndef CreatePositionSepcification():\n spec = acm.FPositionSpecification[\"Corporate Actions\"]\n if spec:\n return\n\n specification= acm.FPositionSpecification()\n specification.Name(\"Corporate Actions\")\n specification.Commit()\n attributes = ['Counterparty.Name', 'Portfolio.Name', 'Instrument.Name', 'Instrument.Underlying.Name']\n for attr in attributes:\n definition = acm.FPositionAttributeDefinition()\n definition.Definition(attr)\n definition.Specification(specification)\n definition.Commit()\n\ndef Setup():\n FBDPCurrentContext.CreateLog(\"FCorpActionSetup\", 1, 1, 0, 0,\n False, \"\", \"\")\n CreateAdditionalInfo()\n CreatePositionSepcification()\n CreateMarketPlaces()\n FCorpActionElectionStatesSetup.CreateCorporateActionElectionStateChart()\n\nSetup()","sub_path":"Extensions/Advanced Corporate Actions/FPythonCode/FCorpActionSetup.py","file_name":"FCorpActionSetup.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"347250356","text":"import traceback\n\n\"\"\"######\nGrades\n\n* Try not to worry.\n* I don't normalize grades until the end.\n* And I will be \"curving\" things at that point.\n\n* On assignment 3: 75 is good, 65 is OK. You are \n all writing reasonabl code. But almost all of \n you could improve.\n\nI grade hard so you can learn. I will not be\nassigning letter grades in the same way.\nI'm aware this is a one credit hour course.\n\n\"\"\"\n\n\n\n\n\n\n\n\"\"\"######\nExceptions\n\"\"\"\n\ndef f():\n return \"str\" + 1\n\n#print(int(f()))\n\n\"\"\"\nExceptions propogate up the call stack.\n\"Unroll\" the stack.\n\"\"\"\n\n\n\n\n\n\"\"\"######\nRaising exceptions\n\nMany operations can raise exceptions.\nAnd we can do it explicitly.\n\"\"\"\n\n#raise TypeError(\"...\")\n#raise KeyError(\"test\")\n#raise RuntimeError()\n#raise RuntimeError\n\n\n\n\n\n\n\"\"\"######\nCatching exceptions\n\"\"\"\ntry:\n raise RuntimeError(\"test\")\nexcept RuntimeError:\n # Handle error\n traceback.print_exc()\n\n\ntry:\n d = {}\n d[101]\nexcept LookupError as e:\n print(type(e), e.args)\n\n\n\n\n\"\"\"######\nFinally\n\"\"\"\n#del code\n#def code():\n# pass\ntry:\n code()\nexcept NameError:\n print(\"Error\")\nfinally:\n print(\"Done\")\n\n\n\n\n\n\"\"\"######\nBuilt-in exceptions\n\nBaseException\n +-- SystemExit\n +-- KeyboardInterrupt\n +-- GeneratorExit\n +-- Exception\n +-- StopIteration\n +-- ArithmeticError\n | +-- FloatingPointError\n | +-- OverflowError\n | +-- ZeroDivisionError\n +-- AssertionError\n +-- AttributeError\n +-- BufferError\n +-- EOFError\n +-- ImportError\n +-- LookupError\n | +-- IndexError\n | +-- KeyError\n +-- MemoryError\n +-- NameError\n | +-- UnboundLocalError\n +-- OSError\n | +-- BlockingIOError\n | +-- ChildProcessError\n | +-- ConnectionError\n | | +-- BrokenPipeError\n | | +-- ConnectionAbortedError\n | | +-- ConnectionRefusedError\n | | +-- ConnectionResetError\n | +-- FileExistsError\n | +-- FileNotFoundError\n | +-- InterruptedError\n | +-- IsADirectoryError\n | +-- NotADirectoryError\n | +-- PermissionError\n | +-- ProcessLookupError\n | +-- TimeoutError\n +-- ReferenceError\n +-- RuntimeError\n | +-- NotImplementedError\n +-- SyntaxError\n | +-- IndentationError\n | +-- TabError\n +-- SystemError\n +-- TypeError\n +-- ValueError\n | +-- UnicodeError\n | +-- UnicodeDecodeError\n | +-- UnicodeEncodeError\n | +-- UnicodeTranslateError\n +-- Warning\n +-- DeprecationWarning\n +-- PendingDeprecationWarning\n +-- RuntimeWarning\n +-- SyntaxWarning\n +-- UserWarning\n +-- FutureWarning\n +-- ImportWarning\n +-- UnicodeWarning\n +-- BytesWarning\n +-- ResourceWarning\n\"\"\"\n\n\n\"\"\"######\nUser-defined exceptions\n\"\"\"\n\nclass MyError(Exception):\n def __init__(self, error_code, msg):\n self.code = error_code\n self.msg = msg\n\n def __repr__(self):\n return \"{}({!r}, {!r})\".format(type(self).__name__, self.code, self.msg)\n \n def __str__(self):\n return \"{} ({})\".format(self.msg, self.code)\n\ndef func():\n raise MyError(500, \"Server error\")\n\n#func()\n\ntry:\n func()\nexcept MyError as e:\n print(e)\n\n\ntry:\n func()\nexcept Exception:\n print(\"error\")\n\n\n\n\n\n\"\"\"######\nAdditional control constructs that python has:\n* Else on try/except\n* Else on loops\n\"\"\"\n\ntry:\n #raise Exception\n pass\nexcept RuntimeError:\n print(\"Raise\")\nelse:\n print(\"No raise\")\nfinally:\n print(\"Always\")\n\n\n# Example from Python Manual (https://docs.python.org/3.4/tutorial/controlflow.html)\nfor n in range(2, 10):\n for x in range(2, n):\n if n % x == 0:\n print(n, 'equals', x, '*', n//x)\n break\n else:\n # loop fell through without finding a factor\n print(n, 'is a prime number')\n\n\ndone = False\nwhile not done:\n #break\n done = True\nelse:\n print(\"Done normally\")\n\n\n\n\"\"\"######\nGenerators with input\n\"\"\"\n\ndef generateSets():\n s = set()\n while True:\n s.add((yield frozenset(s)))\n\ng = generateSets()\ng.send(None)\nprint(g.send(1))\nprint(g.send(\"a\"))\nprint(g.send(42))\ng.close()\n\n\n\"\"\"######\nyield from\n\nA way to yield everything that would be yielded from another\ngenerator. It totally integrates the sub interator into this one\nincluding if the user of the iterator uses .send(v).\n\"\"\"\n\ndef g(iterable):\n yield from iterable\n # Roughly the same as\n # for v in iterable: yield v\n\n\"\"\"We can use this to build something odd. A generator with multiple\nlevels that takes input somewhere deep inside.\n\nThis is a form of coroutine.\n\"\"\"\n\ndef collect():\n acc = 0\n while True:\n v = yield\n if v is None:\n break\n acc += v\n return acc\n\ndef g():\n print((yield from collect()), (yield from collect()))\n # To prevent exception\n yield \n\nx = g()\nx.send(None)\nx.send(1)\nx.send(2)\nx.send(None)\nx.send(30)\nx.send(1)\nx.send(None)\nx.close()\n\n# What is x? What does it represent?\n\n\n\n\"\"\"######\nCoroutines\n\nCooperative concurrency.\n\"\"\"\n\ndef reader(filename, sink):\n with open(filename, \"r\") as fi:\n sink.send(None)\n for line in fi:\n if sink.send(line.strip()):\n print(\"Matched!\")\n sink.close()\n\ndef matcher(pat):\n isLastMatch = False\n while True:\n v = (yield isLastMatch)\n if pat in v:\n print(v)\n isLastMatch = True\n else:\n isLastMatch = False\n\nreader(\"07-AdvFlowControl.py\", matcher(\"matcher\"))\n\n\"\"\"\nGenerators and coroutines are hard to wrap your head around.\nThis is just a taste so if you run into them you at least know \nwhat you are looking at.\n\"\"\"\n\n\n\"\"\"######\nPython 3.5 introduced actual coroutine syntax.\nThis is used for asynchronous programming and \"tasks\".\n\nhttps://docs.python.org/3.5/library/asyncio-task.html\n\"\"\"\n\nimport asyncio\n\nasync def compute(x, y):\n print(\"Compute %s + %s ...\" % (x, y))\n await asyncio.sleep(1.0)\n return x + y\n\nasync def print_sum(x, y):\n result = await compute(x, y)\n print(\"%s + %s = %s\" % (x, y, result))\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(print_sum(1, 2))\nloop.close()\n\n\"\"\"This is mostly just syntactically different.\n\nawait is the same as yield from. And there are libraries that do this\nkind of scheduling for generators.\n\nI think there are other differences, but honestly I didn't know about\nthis until yesterday.\n\n\"\"\"\n","sub_path":"Python/07-AdvFlowControl (1).py","file_name":"07-AdvFlowControl (1).py","file_ext":"py","file_size_in_byte":6536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"418965486","text":"import csv\r\nimport numpy as np\r\n\r\ndef getData(filename):\r\n with open(filename, \"rb\") as csvfile:\r\n datareader = csv.reader(csvfile)\r\n count = 0\r\n for row in datareader:\r\n \r\n \r\n if len(row) < 4096 :\r\n maxValue = max(row)\r\n minValue = min(row)\r\n row = np.asarray(row)\r\n interm = np.zeros(4096)\r\n interm[:row.size] = row\r\n row = interm\r\n if len(row) > 4096:\r\n maxValue = max(row[:4096])\r\n minValue = min(row[:4096])\r\n row = np.asarray(row)\r\n row =row[:4096]\r\n \r\n count = count + 1\r\n yield (row, maxValue, minValue)\r\n \r\n\r\nif __name__ == \"__main__\":\r\n data = []\r\n path = \"data/test.csv\"\r\n count =0\r\n min_num = 0\r\n max_num = 0\r\n\r\n for row, maxValue , minValue in getData(path):\r\n # print(row.max(axis=0))\r\n if (maxValue > max_num):\r\n max_num = maxValue\r\n if (minValue < min_num):\r\n min_num = minValue\r\n count = count +1\r\n print(min_num, max_num, count)\r\n # count = count +1\r\n # if count <10:\r\n # print(row)\r\n # data.append(row)\r\n # data = np.asarray(data)\r\n # print(b)\r\n \r\n","sub_path":"project_malware_detection/inputProcess.py","file_name":"inputProcess.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"420590511","text":"import torch\nfrom torch import nn\nfrom torchsummary import summary\n\ndef DoubleConV(in_channels, out_channels):\n mid_channels = out_channels\n return nn.Sequential(\n nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1), # padding = 1, giu nguyen size anh\n nn.BatchNorm2d(mid_channels),\n nn.LeakyReLU(0.2),\n nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.LeakyReLU(0.2)\n )\n# 0 0 0 0 0 0 0\n# 0 1 1 1 1 1 0\n# 0 1 1 1 1 1 0 \n# 0 1 1 1 1 1 0\n# 0 0 0 0 0 0 0\n\ndef Down(in_channels, out_channels):\n return nn.Sequential(\n nn.MaxPool2d(2),\n DoubleConV(in_channels, out_channels)\n )\n\ndef Up(in_channels, out_channels):\n return nn.Sequential(\n nn.ConvTranspose2d(in_channels, out_channels, kernel_size=2, stride=2)\n )\n\ndef OutConv(in_channels, out_channels):\n return nn.Conv2d(in_channels, out_channels, kernel_size=1)\n\nclass UNet(nn.Module):\n def __init__(self, n_channels, n_classes):\n super().__init__()\n self.n_channels = n_channels\n self.n_classes = n_classes\n self.inc = DoubleConV(n_channels, 64) #floor 1\n self.down1 = Down(64,128)\n self.down2 = Down(128,256)\n self.down3 = Down(256,512)\n self.center = Down(512,1024)\n self.up1 = Up(1024,512)\n self.tmp1 = DoubleConV(1024,512)\n self.up2 = Up(512,256)\n self.tmp2 = DoubleConV(512,256)\n self.up3 = Up(256,128)\n self.tmp3 = DoubleConV(256,128)\n self.up4 = Up(128,64)\n self.tmp4 = DoubleConV(128,64)\n self.output = nn.Sequential(\n OutConv(64, n_classes),\n # nn.Tanh()\n )\n def forward(self, x):\n f1L = self.inc(x) #64\n f2L = self.down1(f1L) #128\n f3L = self.down2(f2L) #256\n f4L = self.down3(f3L) #512\n cent = self.center(f4L) #1024\n\n f4R = self.up1(cent) #512\n f4RT = self.tmp1(torch.cat((f4L, f4R), dim=1)) #512->1024\n f3R = self.up2(f4RT) #256\n f3RT = self.tmp2(torch.cat((f3L, f3R), dim=1)) #256->512\n f2R = self.up3(f3RT) #128\n f2RT = self.tmp3(torch.cat((f2L, f2R), dim=1)) #128->256\n f1R = self.up4(f2RT) #64\n f1RT = self.tmp4(torch.cat((f1L, f1R), dim=1)) #512->1024\n logits = self.output(f1RT)\n return logits\n \nif __name__ == \"__main__\":\n model = UNet(3,1)\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model = model.to(device)\n summary(model, input_size=(3, 240, 320))\n ","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"299316179","text":"import streamlit as vAR_st\r\nimport statistics as sts\r\nimport source.title_1 as head\r\n\r\ndef to_clr():\r\n vAR_st.session_state['sdvr']=\"Standard Deviation\"\r\n vAR_st.session_state['sd_in']=\"\"\r\n\r\ndef sd(x):\r\n w1,col1,col2,w2=vAR_st.columns((1,2,2,1)) \r\n us1,bc1,bc2,us2=vAR_st.columns((4,3,3,6)) \r\n vAR_c=[]\r\n vAR_b=x.split(\",\")\r\n with bc1:\r\n vAR_st.write(\"\") \r\n if vAR_st.button(\"submit\"):\r\n try:\r\n if x==\"\":\r\n with col2:\r\n vAR_st.info(\"Enter the values separated by comma\")\r\n else:\r\n for i in vAR_b:\r\n vAR_c.append(float(i))\r\n standard_deviation = sts.stdev(vAR_c)\r\n with col1:\r\n standard_deviation=round(standard_deviation,4)\r\n vAR_st.write(\"\")\r\n vAR_st.markdown(\"### Result\")\r\n with col2:\r\n vAR_st.write(\"\")\r\n vAR_st.success(standard_deviation)\r\n except BaseException as er:\r\n with col2:\r\n vAR_st.info(\"Invalid input\")\r\n with bc2:\r\n vAR_st.write(\"\")\r\n vAR_st.button(\"Clear\", on_click=to_clr)\r\n \r\ndef var(x):\r\n w1,col1,col2,w2=vAR_st.columns((1,2,2,1)) \r\n us1,bc1,bc2,us2=vAR_st.columns((4,3,3,6)) \r\n vAR_c=[]\r\n \r\n \r\n vAR_b=x.split(\",\")\r\n with bc1:\r\n vAR_st.write(\"\") \r\n if vAR_st.button(\"submit\"):\r\n try:\r\n if x==\"\":\r\n with col2:\r\n vAR_st.info(\"Enter the values separated by comma\")\r\n else:\r\n for i in vAR_b:\r\n vAR_c.append(float(i))\r\n vari=sts.variance(vAR_c)\r\n with col1:\r\n vAR_st.write(\"\")\r\n vAR_st.markdown(\"### Varience\")\r\n with col2:\r\n vari=round(vari,4)\r\n vAR_st.write(\"\")\r\n vAR_st.success(vari)\r\n except BaseException as er:\r\n with col2:\r\n vAR_st.info(\"Invalid input\")\r\n with bc2:\r\n vAR_st.write(\"\")\r\n vAR_st.button(\"Clear\", on_click=to_clr)\r\n\r\ndef stats():\r\n head.title()\r\n vAR_st.markdown(\"Problem Statement: Application to find the Standard deviation and Varience
\", unsafe_allow_html=True)\r\n vAR_st.markdown(\"
\",unsafe_allow_html=True)\r\n w1,c1,c2,w2=vAR_st.columns((1,2,2,1))\r\n with c1:\r\n \r\n vAR_st.markdown(\"### \")\r\n vAR_st.markdown(\"### Enter the data\")\r\n \r\n vAR_st.markdown(\"## \")\r\n vAR_st.markdown(\"### Select\")\r\n with c2:\r\n vAR_a=vAR_st.text_input(\"\",key=\"sd_in\",placeholder=\"eg. 21,25,27,20,24,21,46\")\r\n vAR_r=vAR_st.selectbox(\"\",[\"Standard Deviation\",\"Varience\"],key=\"sdvr\")\r\n if vAR_r==\"Standard Deviation\":\r\n sd(vAR_a)\r\n if vAR_r==\"Varience\":\r\n var(vAR_a)\r\n#stats()","sub_path":"Streamlitapp/Grade-10/source/sd_var.py","file_name":"sd_var.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"618691669","text":"from flask import Flask,render_template,redirect, url_for, request\nimport os,json,math\n\napp = Flask(__name__)\n\ndef getLeaves():\n metadata=getMetadata(1)\n last=math.ceil(int(metadata['hashes'])/int(metadata['perfile']))\n lines=[]\n for x in range(1,last+1):\n file=\"lvl_1_\"+str(x)+\".txt\"\n path=os.path.join(os.getcwd(),\"data\",file)\n try:\n with open(path,'r') as f:\n lines=lines+f.read().splitlines()\n except:\n print(\"error\")\n return lines\n\ndef getMetadata(level):\n file=\"metadata_\"+str(level)+\".json\"\n path=os.path.join(os.getcwd(),\"data\",file)\n try:\n with open(path,'r') as f:\n json_data=f.read()\n except:\n print(\"metadata not found\")\n parsed_json = json.loads(json_data)\n metadata={}\n metadata['hashes']=parsed_json['hashes']\n metadata['perfile']=parsed_json['perfile']\n metadata['isLastLevel']=parsed_json['isLastLevel']\n return metadata\n\ndef updateMetadata(level):\n file=\"metadata_\"+str(level)+\".json\"\n path=os.path.join(os.getcwd(),\"data\",file)\n try:\n with open(path,'r') as f:\n json_data=f.read()\n except:\n print(\"metadata not found\")\n parsed_json = json.loads(json_data)\n parsed_json['hashes']=str(int(parsed_json['hashes'])+1)\n with open(path,'w') as f:\n f.write(json.dumps(parsed_json))\n\ndef insertLeaf(leafHash):\n metadata=getMetadata(1)\n if int(metadata['hashes'])==0:\n file=\"lvl_1_1.txt\"\n path=os.path.join(os.getcwd(),\"data\",file)\n try:\n with open(path, 'w') as f:\n f.write(str(leafHash)+\"\\n\")\n updateMetadata(1)\n except:\n print(\"error\")\n return \"error\"\n else:\n file=\"lvl_1_\"+str(int(int(metadata['hashes'])/int(metadata['perfile']))+1)+\".txt\"\n path=os.path.join(os.getcwd(),\"data\",file)\n try:\n with open(path, 'a') as f:\n f.write(str(leafHash)+\"\\n\")\n updateMetadata(1)\n except:\n print(error)\n return \"error\"\n return json.dumps(str(leafHash))\n\ndef getProof(leafHash):\n return \"proof\"\n\ndef checkDuplicate(leafHash):\n return \"no duplicate\"\n\n@app.route(\"/\")\ndef listApis():\n return \"list of all apis\"\n\n@app.route(\"/tree\", methods = ['GET'])\ndef hashes():\n if request.method == 'GET':\n return json.dumps(getLeaves())\n\n@app.route(\"/add\", methods = ['GET', 'POST'])\ndef insert():\n if request.method == 'POST':\n leafHash = request.form['leafHash']\n print(insertLeaf(leafHash))\n return redirect(url_for('success',leafHash = leafHash))\n else:\n return render_template('insertLeafHelper.html')\n\n@app.route(\"/proof\" , methods = ['GET', 'POST'])\ndef showProof():\n return \"return audit proof of a leaf\"\n\n@app.route('/success/')\ndef success(leafHash):\n return 'inserted %s' % leafHash\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"python/merkle_tree_python/merkle_leaves_working/merkle.py","file_name":"merkle.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"508086973","text":"######################################################################################################################\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. #\n# #\n# Licensed under the Apache License Version 2.0 (the \"License\"). You may not use this file except in compliance #\n# with the License. A copy of the License is located at #\n# #\n# http://www.apache.org/licenses/ #\n# #\n# or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES #\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions #\n# and limitations under the License. #\n######################################################################################################################\n\nimport os\nfrom boto3.dynamodb.conditions import Key\nfrom util.dynamodb_utils import DynamoDBUtils\n\nclass ScheduleState:\n\n def __init__(self, logger, service):\n self._logger = logger\n self.schedule_state_table_name = os.getenv(\"SCHEDULE_STATES_TABLE\", None)\n self.dynamodb_table = DynamoDBUtils.get_dynamodb_table_resource_ref(self.schedule_state_table_name)\n self.service = service\n\n def get_schedule_state(self, schedule_name):\n self._logger.debug(f\"Get scheduled state, for schedule name {schedule_name} for service {self.service}.\")\n if schedule_name is not None:\n resp = self.dynamodb_table.get_item(\n Key={\"name\": schedule_name, 'service': self.service}, ConsistentRead=True)\n return resp.get(\"Item\", {})\n else:\n self._logger.debug(f\"Schedule unavailable for schedule name {schedule_name} for service {self.service}.\")\n return {\"name\": schedule_name, 'service': self.service , \"state\": \"unknown\"}\n\n def save_schedule_state(self, schedule_name, state, localized_time, execution_id=None):\n self._logger.debug(f\"Update state {state}, for schedule name {schedule_name} for service {self.service} at time {localized_time} to save schedule state.\")\n get_schedule = self.get_schedule_state(schedule_name=schedule_name)\n if bool(get_schedule) is False:\n self._logger.debug(f\"Previous state {state}, for schedule name {schedule_name}, at time {localized_time} is unavailable creating a new entry\")\n try:\n resp = self.dynamodb_table.put_item(\n Item={\n 'name': schedule_name,\n 'state': state,\n 'ssm-execution-id': execution_id,\n 'service': self.service,\n 'time': localized_time\n }\n )\n return resp\n except Exception as error:\n self._logger.error(f\"Error saving state {state}, for schedule name {schedule_name}, service {self.service}, at time {localized_time}\")\n self._logger.error(error)\n else:\n try:\n return self.dynamodb_table.update_item(TableName=self.schedule_state_table_name, \n Key={\"name\": get_schedule[\"name\"], 'service': self.service},\n UpdateExpression=\"set #st =:s, #tm =:t, #ssmexecutionid =:e\",\n ExpressionAttributeNames={\n \"#ssmexecutionid\": 'ssm-execution-id',\n '#st': 'state',\n '#tm': 'time'\n },\n ExpressionAttributeValues={\n \":s\": str(state),\n \":t\": str(localized_time),\n \":e\": str(execution_id)\n },ReturnValues=\"UPDATED_NEW\")\n except Exception as error:\n self._logger.error(f\"Error updating state {state}, for schedule name {schedule_name} for service {self.service} at time {localized_time}\")\n self._logger.error(error)\n\n def get_all_schedules(self):\n self._logger.debug(\"Retrieve all the schedules with previous states\")\n schedules = []\n scan_kwargs = {\n 'FilterExpression': Key('service').eq(self.service),\n }\n resp = self.dynamodb_table.scan(**scan_kwargs)\n schedules.extend(resp.get(\"Items\"))\n while True:\n token = resp.get('LastEvaluatedKey', None)\n if token is not None:\n scan_kwargs = {\n 'ExclusiveStartKey': token,\n 'FilterExpression': Key('service').eq(self.service),\n }\n resp = self.dynamodb_table.scan(**scan_kwargs)\n schedules.extend(resp.get(\"Items\"))\n else:\n break\n return schedules\n\n def delete_schedule(self, schedule_name):\n self._logger.debug(f\"Remove the schedule {schedule_name} for service {self.service} and state.\")\n if schedule_name is not None:\n try:\n self.dynamodb_table.delete_item(Key={\"name\": schedule_name, \"service\": self.service})\n except Exception as error:\n self._logger.error(f\"Error removing schedule name {schedule_name} for service {self.service} and state.\")\n self._logger.error(error)\n","sub_path":"source/lambda/util/schedule_state.py","file_name":"schedule_state.py","file_ext":"py","file_size_in_byte":6325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"}
+{"seq_id":"527917830","text":"from django.test import TestCase\nfrom django.contrib.auth import get_user_model\nfrom .models import Doctor\nfrom .forms import DoctorForm\nimport json\n\n\nclass DoctorFormTestCase(TestCase):\n\n\t# def setup(self):\n\n\t# \tuser = get_user_model().object.create_user('Amy')\n\n\n\tdef test_valid_data(self):\n\n\t\tform = DoctorForm({\n\n\t\t\t'first_name': \"Amy\",\n\t\t\t'last_name': \"Anderson\",\n\t\t\t'email': \"Aanderson@gmail.com\",\n\t\t\t})\n\n\t\tself.assertTrue(form.is_valid())\n\t\tdoctor = form.save()\n\n\t\tself.assertEqual(doctor.first_name, \"Amy\")\n\t\tself.assertEqual(doctor.last_name, \"Anderson\")\n\t\tself.assertEqual(doctor.email, \"Aanderson@gmail.com\")\n\n\n\n\tdef test_get_doctors(self):\n\t\t\"\"\" Getting doctors from a populated database \"\"\"\n\n\t\tdoctorA = Doctor(first_name=\"Joe\", last_name= \"Alpha\", email= \"Janderson@gmail.com\")\n\n\t\tdoctorB = Doctor(first_name=\"Dan\", last_name= \"Beta\", email= \"Janderson@gmail.com\")\n\n\t\tdoctorA.save()\n\t\tdoctorB.save()\n\n\t\tresponse = self.client.get(\"/doctors/\")\n\n\t\tself.assertEqual(response.status_code, 200)\n\n\t\tdata = json.loads(response.content)\n\n\t\tprint(data)\n\n\t\tself.assertEqual(len(data), 2)\n\n\n\tdef test_get_doctor(self):\n\t\t\"\"\" Get 1 doctor from a database \"\"\"\n\n\t\tdoctorA = Doctor(first_name=\"Joe\", last_name= \"Alpha\", email= \"Janderson@gmail.com\")\n\n\t\tdoctorB = Doctor(first_name=\"Dan\", last_name= \"Beta\", email= \"Janderson@gmail.com\")\n\n\t\tdoctorA.save()\n\t\tdoctorB.save()\n\n\t\tresponse = self.client.get(\"/doctors/%s/\" % doctorA.id)\n\n\t\tself.assertEqual(response.status_code, 200)\n\n\t\tdata = json.loads(response.content.decode(\"utf-8\"))\n\n\t\tprint(data['first_name'])\n\n\t\tself.assertEqual(len(data), 3)\n\n\t\tself.assertEqual(data['first_name'], \"Joe\")\n\n\n\tdef test_doctor_does_not_exist(self):\n\t\t\"\"\" Return 404 iff no doctor \"\"\"\n\n\t\tdoctorA = Doctor(first_name=\"Joe\", last_name= \"Alpha\", email= \"Janderson@gmail.com\")\n\n\t\tdoctorB = Doctor(first_name=\"Dan\", last_name= \"Beta\", email= \"Janderson@gmail.com\")\n\n\t\tdoctorA.save()\n\t\tdoctorB.save()\n\n\t\tresponse = self.client.get(\"/doctors/4975948/\")\n\n\t\tself.assertEqual(response.status_code, 404)\n\n\n\n\n\n\t# def test_delete_doctor(self):\n\t# \t\"\"\" Delete doctor \"\"\"\n\n\t# \tdoctorA = Doctor(first_name=\"Joe\", last_name= \"Alpha\", email= \"Janderson@gmail.com\")\n\n\t# \tdoctorB = Doctor(first_name=\"Dan\", last_name= \"Beta\", email= \"Janderson@gmail.com\")\n\n\t# \tdoctorA.save()\n\t# \tdoctorB.save()\n\n\t# \tresponse = self.client.delete(\"/doctors/1/\")\n\n\t# \tself.assertEqual(response.status_code, 204)\n\n\t# \t# data = json.loads(response.content)\n\n\t# \t# print(data['first_name'])\n\n\t# \t# self.assertEqual(len(data), 3)\n\n\t# \t# self.assertEqual(data['first_name'], \"Joe\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\n\n","sub_path":"doctor/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"}
+{"seq_id":"626883613","text":"import requests\r\nimport boto3\r\n\r\n#Define ENV variables\r\ncompany_code = ''\r\nphone_number = ''\r\nsender_name = ''\r\nexchange_api_key = ''\r\n\r\n#Sanity Check\r\nif len(company_code) < 1 or len(phone_number) < 1 or len(sender_name) < 1 or len(exchange_api_key) < 1:\r\n print('Please set the parameters correctly')\r\n exit()\r\n\r\n#Get share price data and convert to JSON for dict operations\r\nsymbols = {'symbols': company_code}\r\nshare_data = requests.get('https://query1.finance.yahoo.com/v7/finance/quote?lang=en-US®ion=US&corsDomain=finance.yahoo.com&fields=regularMarketPrice', params=symbols)\r\npricedata = share_data.json()\r\n\r\n#Get exchange-rate list and convert to JSON for dict operations\r\napikey = {'app_id': exchange_api_key}\r\ncurr_exchange = requests.get('https://openexchangerates.org/api/latest.json', params=apikey)\r\nexdata = curr_exchange.json()\r\n\r\n#Extract the USD price and AUD exchange-rate from the JSONs and calculate the price in AUD\r\nusdprice = pricedata[\"quoteResponse\"]['result'][0]['regularMarketPrice']\r\nexrate = exdata['rates']['AUD']\r\nshareprice = str(round(usdprice * exrate, 2))\r\n\r\n#SMS the price\r\nclient = boto3.client('sns')\r\nclient.publish(PhoneNumber=phone_number, Message=shareprice, MessageAttributes={'AWS.SNS.SMS.SenderID': {'DataType': 'String', 'StringValue': sender_name}})","sub_path":"stock-price-sms.py","file_name":"stock-price-sms.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"}
+{"seq_id":"183317115","text":"#! /usr/bin/env python3\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.cmac import CMAC\nfrom cryptography.hazmat.primitives.ciphers import algorithms\n\n##################################################################\n### ###\n### NOTE: THIS FEATURE IS ONLY SUPPORTED ON IMX8 DXL B0 ###\n### ###\n##################################################################\n\n\n############### USE OF THIS SCRIPT ############################################\n#\n# 1. Fill in customer_otp variable below to correspond to OEM secret\n#\n# 2. Run this python script\n#\n# 3. Console will give SECO and V2X KEK to use for open and closed lifecycles\n#\n#################################################################################\n\n\n\n# Customer to fill in securely provisioned OEM closed otp secret with a valid AES 256 key\ncustomer_otp = \"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f\"\n\n# OEM open always uses facsimile otp secret - do not change this value\nfacsimile_otp = \"693f25bd6a299107cf7220b9ab504111fd3003bfe9aa38294262c3abab372790\"\n\n\ndef run_kdf(otp_val, label):\n\n# FIPS compliant key derivation (SP 800-108)\n# - CMAC based KDF in counter mode\n# - two loops of algorithm (256 bits generated)\n# - label set by caller as \"SECO HSM\" or \"V2X HSM\"\n# - context is \"NXP IMX8 DXL B0 OTP ROOT KEK\"\n\n label_hex = label.encode(\"utf_8\").hex()\n\n zero_byte = \"00\"\n\n context = \"NXP IMX8 DXL B0 OTP ROOT KEK\"\n context_hex = context.encode(\"utf_8\").hex()\n\n L = \"0100\" # 256 bits = 0x100\n\n fixed_info = label_hex + zero_byte + context_hex + L\n\n # First loop\n counter = \"00000001\"\n kdf_input = counter + fixed_info\n\n cmac = CMAC(algorithms.AES(bytes.fromhex(otp_val)), default_backend())\n cmac.update(bytes.fromhex(kdf_input))\n key_val = cmac.finalize()\n\n # Second loop\n counter = \"00000002\"\n kdf_input = counter + fixed_info\n\n cmac = CMAC(algorithms.AES(bytes.fromhex(otp_val)), default_backend())\n cmac.update(bytes.fromhex(kdf_input))\n key_val += cmac.finalize()\n\n print(key_val.hex())\n\ndef calc_seco_key(otp_val):\n run_kdf(otp_val, \"SECO HSM\")\n\ndef calc_v2x_key(otp_val):\n run_kdf(otp_val, \"V2X HSM\")\n\n\nif __name__ == \"__main__\":\n print(\"OEM closed SECO KEK:\")\n calc_seco_key(customer_otp)\n print(\"OEM closed V2X KEK:\")\n calc_v2x_key(customer_otp)\n print(\"OEM open SECO KEK:\")\n calc_seco_key(facsimile_otp)\n print(\"OEM open V2X KEK:\")\n calc_v2x_key(facsimile_otp)\n\n","sub_path":"tools/oem_kek_derivation.py","file_name":"oem_kek_derivation.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"}
+{"seq_id":"637047596","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/coils/core/vcard/render_team.py\n# Compiled at: 2012-10-12 07:02:39\nimport vobject\n\ndef render_team(team, ctx, **params):\n card = vobject.vCard()\n card.add('n')\n card.n.value = vobject.vcard.Name(family='OpenGroupware', given=team.name)\n card.add('fn').value = team.name\n card.add('uid').value = 'coils://Team/%d' % team.object_id\n return str(card.serialize())","sub_path":"pycfiles/OpenGroupware-0.1.48-py2.6/render_team.py","file_name":"render_team.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"557465097","text":"array = list(map(int,input().split()))\narray.sort()\n\nresult = 0\ncount = 0\nfor i in range(len(array)):\n count+=1\n if array[i]<=count:\n count=0\n result+=1\n\nprint(result)","sub_path":"ch_2/모험가길드.py","file_name":"모험가길드.py","file_ext":"py","file_size_in_byte":175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"354536837","text":"# ITP Week 3 Day 3 Solution\n\nimport requests\nimport json\nimport openpyxl\nfrom openpyxl.styles import Font\n\n# using the requests package, we can make API calls to retrieve JSON\n# and storing it into a variable here called \"response\"\nresponse = requests.get(\"https://rickandmortyapi.com/api/character\")\n\n# verify the response status as 200\n# print(response)\n\n# verify the raw string data of the response\n# print(response.text)\n\n# load as a python json object and store into a variable called \"clean_data\"\nclean_data = json.loads(response.text)\n\n# print(clean_data)\n\n# go through the results,\nresult = clean_data[\"results\"]\n\n# print(result[0])\n# print(result[0]['location']['name'])\n\nwb = openpyxl.load_workbook(\"./input.xlsx\")\nsheet = wb['Sheet1']\n\nsheet['A1'] = \"Name\"\n# sheet['A1'].font = Font(bold = True)\nsheet['B1'] = \"Species\"\n# sheet['B1'].font = Font(bold = True)\nsheet['C1'] = \"Gender\"\n# sheet['C1'].font = Font(bold = True)\nsheet['D1'] = \"Location\"\n# sheet['D1'].font = Font(bold = True)\n\nheader_list = [sheet['A1'], sheet['B1'], sheet['C1'], sheet['D1']]\n\nfor header in header_list:\n header.font = Font(bold = True)\n\ncounter = 2\n# for each row in an excel spreadsheet\nfor char in result:\n # print(\"Name: \" + char['name'])\n sheet['A' + str(counter)] = char['name']\n\n # print(\"Species: \" + char['species'])\n sheet['B' + str(counter)] = char['species']\n\n # print(\"Gender: \" + char[\"gender\"])\n sheet['C' + str(counter)] = char['gender']\n\n # print(\"Location: \" + char['location']['name'])\n sheet['D' + str(counter)] = char['location']['name']\n counter+=1\n# grab the name, species, gender, location name\n\n\nwb.save('./output.xlsx')","sub_path":"day_1/w3d3_solution.py","file_name":"w3d3_solution.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"418875569","text":"from selenium import webdriver\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\nimport xlwt # 电子表格操作模块\n\nbrowser = webdriver.Chrome(r'C:\\Users\\guo\\Desktop\\renshe\\chromedriver.exe')\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',\n}\n\nbrowser.get('https://网址/register/#/login?_k=ax56bx')\nbrowser.find_element_by_xpath(\n '/html/body/div/div/div/div[2]/div/div[2]/div[1]/div[2]/form/div[3]/span[2]/input').send_keys('用户名')\nbrowser.find_element_by_xpath(\n '/html/body/div/div/div/div[2]/div/div[2]/div[1]/div[2]/form/div[4]/span[2]/input').send_keys(',密码')\ntime.sleep(1)\nbrowser.find_element_by_xpath('/html/body/div/div/div/div[2]/div/div[2]/div[1]/div[2]/form/div[6]/button[1]').click()\ntime.sleep(1)\n\n\ndef getData(): # 获取数据函数\n datalist = [] # 总的数据列表\n for i in range(1, 65):\n url = 'https://网址/ApplyCollegeNew?page=' + str(i)\n page_text = requests.get(url=url, headers=headers, timeout=10).text\n # 实例化bs对象,加载页面源码\n soup = BeautifulSoup(page_text, 'lxml')\n # 数据解析,返回列表[]\n li_list = soup.select('#collegesLists > li')\n # 循环列表\n for li in li_list:\n data = [] # 定义列表,用于保存每一行的数据\n title = li.select('.collegeFeature >h3>a')[0].string\n data.append(title)\n detail = li.select('.collegeFeature')[0].text\n data.append(detail)\n datalist.append(data) # 将每行列表添加到总列表\n\n return datalist\n\n\ndef saveData(datalist, savepath):\n print('save....')\n book = xlwt.Workbook(encoding='utf-8')\n sheet = book.add_sheet('大学列表', cell_overwrite_ok=True)\n col = ('学校名称', '其他说明')\n # 表头字段名的写入\n for i in range(0, len(col)): # 元组是不可变的,len取长度\n sheet.write(0, i, col[i]) # 列名\n # 数据记录的写入\n for i in range(0, len(datalist)): # 使用len(列表)获得长度\n data = datalist[i]\n for j in range(0, len(data)):\n sheet.write(i + 1, j, data[j])\n book.save(savepath)\n print('save ok....')\n\n\nif __name__ == \"__main__\":\n savepath = '大学数据.xls'\n datalist = getData()\n saveData(datalist, savepath)\n\n","sub_path":"python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"416052592","text":"import requests\r\nfrom tkinter import *\r\n\r\ndef weather():\r\n city = city_listbox.get()\r\n url = 'https://openweathermap.org/data/2.5/weather?q={}&appid=---paste your appid here---'.format(city)\r\n res = requests.get(url)\r\n output = res.json()\r\n\r\n weather_status = output['weather'][0]['description']\r\n temperature = output['main']['temp']\r\n humidity = output['main']['humidity']\r\n wind_speed = output['wind']['speed']\r\n\r\n weather_status_label.configure(text=\"Weather status : \" + weather_status)\r\n temperature_label.configure(text=\"Temperature : \" + str(temperature))\r\n humidity_label.configure(text=\"Humidity : \" + str(humidity))\r\n wind_speed_label.configure(text=\"Wind speed : \" + str(wind_speed))\r\n\r\n\r\nwindow = Tk()\r\nwindow.geometry(\"400x350\")\r\n\r\ncity_name_list = [\"Lucknow\", \"Delhi\", \"Bangalore\", \"Pune\", \"Mumbai\", \"Akola\", 'Amravati']\r\n\r\ncity_listbox = StringVar(window)\r\ncity_listbox.set(\"Select the city\")\r\noption = OptionMenu(window, city_listbox, *city_name_list)\r\noption.grid(row=2, column=2, padx=150, pady=10)\r\n\r\nb1 = Button(window, text=\"GO\", width=15, command=weather)\r\nb1.grid(row=5, column=2, padx=150)\r\n\r\nweather_status_label = Label(window, font=(\"times\", 10, \"bold\"))\r\nweather_status_label.grid(row=10, column=2)\r\n\r\ntemperature_label = Label(window, font=(\"times\", 10, \"bold\"))\r\ntemperature_label.grid(row=12, column=2)\r\n\r\nhumidity_label = Label(window, font=(\"times\", 10, \"bold\"))\r\nhumidity_label.grid(row=14, column=2)\r\n\r\nwind_speed_label = Label(window, font=(\"times\", 10, \"bold\"))\r\nwind_speed_label.grid(row=16, column=2)\r\n\r\nwindow.mainloop()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"9.Current Weather.py","file_name":"9.Current Weather.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"31473550","text":"import pandas as pd\nfrom sklearn import svm, metrics\nfrom sklearn.model_selection import train_test_split\n\nbmi = pd.read_csv('bmi.csv', header=0)\n\nlabel = bmi['label']\n\nnormal_weight = bmi['weight'] / 180\nnormal_height = bmi['height'] / 80\n\nnormal_data = pd.concat([normal_weight,normal_height], axis=1)\n\ndata_train, data_test, label_train, label_test = train_test_split(normal_data, label)\n\nclf = svm.SVC(gamma='auto')\nclf.fit(data_train, label_train)\n\npredict = clf.predict(data_test)\n\nscore = metrics.accuracy_score(label_test, predict)\nreport = metrics.classification_report(label_test, predict)\n\nprint('정답률: %s%% '%round(score*100,2))\nprint(report)","sub_path":"03. AI/01. Machine Learning/머신러닝_학생평가/민현기_bmi_test.py","file_name":"민현기_bmi_test.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"631446489","text":"#!/usr/bin/env python \nimport roslib\nroslib.load_manifest('projection')\nimport rospy\nimport math\nimport tf\nimport geometry_msgs.msg\nimport tests_affichages\nfrom geometry_msgs.msg import WrenchStamped\n\n#def callback(data):\n #rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", data.data)\n #print(\"Valeur\")\n #print(data.force[0])\n\n\n\ndef listener():\n print(\"je me lance\")\n rospy.init_node('tf_listener')\n listener_tf = tf.TransformListener()\n rate = rospy.Rate(1.0)\n L = []\n #rospy.Subscriber(\"optoforce_1\", WrenchStamped, callback)\n print(\"J'ai souscrit\")\n #while not rospy.is_shutdown():\n #try:\n if listener_tf.frameExists('/base_link'):\n print(\"Existe\")\n (trans,rot) = listener_tf.lookupTransform('base_link', '/world', rospy.Time(0)) #le temps de ce noeud bug ac le ros bag...\n print(\"Force\")\n x =tests_affichages.fois_dix(trans[0])\n print(trans[0],x)\n else:\n print(\"NotExist\")\n#except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):\n #print(\"Exception\")\n #continue\n\n #rate.sleep()\n rospy.spin()\n \nif __name__ == '__main__':\n listener()\n","sub_path":"nodes/listerner2.py","file_name":"listerner2.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"55361543","text":"import math\nimport numpy as np\nimport pandas as pd\nimport random\nimport re\nfrom scipy.special import digamma, gammaln, psi # gamma function utils\nfrom scipy.special import polygamma\nfrom sklearn import svm\nimport time\n\n\ndef normalize(row):\n return row / (row.sum() + 0.0000001)\n\n\ndef normalize_rows(input_matrix):\n \"\"\"\n Normalizes the rows of a 2d input_matrix so they sum to 1\n \"\"\"\n row_sums = input_matrix.sum(axis=1) + 0.0000001\n new_matrix = input_matrix / row_sums[:, np.newaxis]\n return new_matrix\n\n\ndef normalize_columns(input_matrix):\n \"\"\"\n Normalizes the columns of a 2d input_matrix so they sum to 1\n \"\"\"\n col_sums = input_matrix.sum(axis=0) + 0.0000001\n new_matrix = input_matrix / col_sums[np.newaxis :]\n return new_matrix\n\n\ndef evaluate_embeddings(training_data, training_labels, testing_data, testing_labels):\n clf = svm.SVC()\n clf.fit(training_data, training_labels)\n predictions = clf.predict(testing_data)\n # print(predictions)\n # print(testing_labels)\n\n true_positives = 0\n false_positives = 0\n false_negatives = 0\n for i in range(len(predictions)):\n if predictions[i] == 1 and testing_labels[i] == 1:\n true_positives += 1\n elif predictions[i] == 1 and testing_labels[i] == 0:\n false_positives += 1\n elif predictions[i] == 0 and testing_labels[i] == 1:\n false_negatives += 1\n recall = true_positives/(true_positives+false_negatives)\n if true_positives+false_positives > 0:\n precision = true_positives/(true_positives+false_positives)\n print(\" F1 = {0:.3f}\".format(2*precision*recall/(precision+recall)))\n print(\" Precision = {0:.3f} ({1}/{2})\".format(precision, true_positives, true_positives+false_positives))\n print(\" Recall = {0:.3f} ({1}/{2})\".format(recall, true_positives, true_positives+false_negatives))\n\n\ndef load_csv(input_path, test_set_size, training_set_size, num_stop_words, min_word_freq, text_column, label_column, label_dict):\n labels = []\n documents = []\n df = pd.read_csv(input_path,\n converters={\n label_column: lambda x: (label_dict[x]),\n text_column: lambda line: (re.sub('[^0-9a-zA-Z]+', ' ', line).lower().split()),\n # replace non-alphanumeric characters with spaces\n },\n encoding='unicode_escape',\n nrows=test_set_size+training_set_size)\n testing_df = df[:test_set_size]\n training_df = df[test_set_size:]\n\n print('Training data size = {}'.format(training_df.shape[0]))\n print('Testing data size = {}'.format(testing_df.shape[0]))\n\n # Remove the stop words\n word_freq = {}\n for i, row in training_df.iterrows():\n for word in row[text_column]:\n if word in word_freq.keys():\n word_freq[word] += 1\n else:\n word_freq[word] = 1\n words_sorted_by_freq = sorted(word_freq.items(), key=lambda kv: kv[1])[:-num_stop_words]\n words_sorted_by_freq = list(filter(lambda kv: kv[1] >= min_word_freq, words_sorted_by_freq))\n\n vocabulary = sorted([kv[0] for kv in words_sorted_by_freq])\n words = set(vocabulary)\n vocabulary_size = len(vocabulary)\n idx = dict(zip(vocabulary, range(len(vocabulary))))\n print('Vocabulary size = {}'.format(len(words)))\n # print(idx)\n\n testing_term_doc_matrix = np.zeros([testing_df.shape[0], vocabulary_size], dtype=np.float)\n for i, row in testing_df.iterrows():\n for word in row[text_column]:\n if word in words:\n testing_term_doc_matrix[i][idx[word]] += 1\n\n training_term_doc_matrix = np.zeros([training_df.shape[0], vocabulary_size], dtype=np.float)\n for i, row in training_df.iterrows():\n for word in row[text_column]:\n if word in words:\n training_term_doc_matrix[i-test_set_size][idx[word]] += 1\n\n return (vocabulary_size,\n training_term_doc_matrix,\n training_df[label_column],\n testing_term_doc_matrix,\n testing_df[label_column],\n vocabulary,)\n\n# From gensim. \n# https://github.com/RaRe-Technologies/gensim/blob/6c80294ad8df16a878cb6df586c797184b39564a/gensim/models/ldamodel.py#L434\ndef dirichlet_expectation(alpha):\n \"\"\"\n For a vector `theta~Dir(alpha)`, compute `E[log(theta)]`.\n \"\"\"\n if (len(alpha.shape) == 1):\n result = psi(alpha) - psi(np.sum(alpha))\n else:\n result = psi(alpha) - psi(np.sum(alpha, 1))[:, np.newaxis]\n return result.astype(alpha.dtype) # keep the same precision as input\n\n\nclass LDA(object):\n def __init__(self, vocabulary_size):\n self.vocabulary_size = vocabulary_size\n self.num_topics = None\n self.alpha = None\n self.phi = None\n\n def get_variable_length_docs(self, term_doc_matrix):\n variable_length_docs = []\n for row in term_doc_matrix:\n variable_length_doc = []\n for word, count in enumerate(row.tolist()):\n for i in range(int(count)):\n variable_length_doc.append(word)\n variable_length_docs.append(variable_length_doc)\n return variable_length_docs\n\n\n def train(self, num_topics, term_doc_matrix, iterations, e_iterations, e_epsilon, alpha_learning_rate=0.2, alpha_learning_rate_decay=0.01, initial_training_set_size=None, initial_training_iterations=None):\n print('Training an LDA model with {} topics...'.format(num_topics))\n docs = self.get_variable_length_docs(term_doc_matrix)\n\n # Initialize the model\n self.num_topics = num_topics\n self.alpha = np.repeat(1.0 / num_topics, num_topics)\n self.phi = normalize_rows(np.random.random((self.num_topics, self.vocabulary_size)))\n # word distribution of each topic\n # dim = num_topics * vocabulary_size\n\n if initial_training_set_size is not None and initial_training_iterations is not None:\n print('Initialize the model using {} documents'.format(initial_training_set_size))\n\n initial_docs = docs[:initial_training_set_size]\n\n # Initialize the hidden variables\n pi = [normalize_rows(np.random.random((len(doc), self.num_topics))) for doc in initial_docs]\n # topic assignment of each word in each doc\n # dim = num_docs * |doc| * num_topics\n\n gamma = normalize_rows(np.random.random((len(initial_docs), self.num_topics)))\n # topic assignment of each doc\n # dim = num_docs * num_topics\n\n for iteration in range(initial_training_iterations):\n print(' E-M iteration {}'.format(iteration))\n # E-step\n (pi, gamma) = self.e_step(initial_docs, pi, gamma, e_iterations, e_epsilon)\n\n # M-step\n self.m_step(initial_docs, pi, gamma, alpha_learning_rate)\n print(self.alpha)\n alpha_learning_rate = alpha_learning_rate * (1-alpha_learning_rate_decay)\n\n print('Train the model using {} documents'.format(len(docs)))\n\n # Reset the hidden variables\n pi = [normalize_rows(np.random.random((len(doc), self.num_topics))) for doc in docs]\n # topic assignment of each word in each doc\n # dim = num_docs * |doc| * num_topics\n gamma = normalize_rows(np.random.random((len(docs), self.num_topics)))\n # topic assignment of each doc\n # dim = num_docs * num_topics\n (pi, gamma) = self.e_step(docs, pi, gamma, e_iterations, e_epsilon)\n\n for iteration in range(iterations):\n print(' E-M iteration {}'.format(iteration))\n # E-step\n (pi, gamma) = self.e_step(docs, pi, gamma, e_iterations, e_epsilon)\n\n # M-step\n self.m_step(docs, pi, gamma, alpha_learning_rate)\n print(self.alpha)\n alpha_learning_rate = alpha_learning_rate * (1-alpha_learning_rate_decay)\n\n\n def e_step(self, docs, pi, gamma, e_iterations, e_epsilon):\n for j, doc in enumerate(docs):\n for e_iteration in range(e_iterations):\n previous_gamma = gamma[j].copy()\n for t, word in enumerate(doc):\n x = digamma(gamma[j].sum())\n for i in range(self.num_topics):\n pi[j][t][i] = self.phi[i][word] * np.exp(digamma(gamma[j][i]) - x)\n pi[j] = normalize_rows(pi[j])\n\n for i in range(self.num_topics):\n gamma[j][i] = self.alpha[i] + pi[j][:,i].sum()\n\n gamma_diff = np.absolute(gamma[j] - previous_gamma).sum()\n if gamma_diff < e_epsilon:\n break\n\n return (pi, gamma)\n\n\n def m_step(self, docs, pi, gamma, alpha_learning_rate):\n for i in range(self.num_topics):\n for v in range(self.vocabulary_size):\n self.phi[i][v] = 0.0\n for j, doc in enumerate(docs):\n for t, word in enumerate(doc):\n if word == v:\n self.phi[i][v] += pi[j][t][i]\n self.phi = normalize_rows(self.phi)\n # print(self.phi)\n self.alpha = self.alpha * (1.0-alpha_learning_rate) + normalize(np.average(normalize_rows(gamma), axis=0)) * alpha_learning_rate\n\n\n def print_model(self, vocabulary, print_freq_threshold=0.02):\n for topic, words in enumerate(self.phi):\n print('Topic {0}: {1:.3f}'.format(topic, self.alpha[topic]))\n for w, p in enumerate(words / (np.sum(words) + 0.0000001)):\n if p > print_freq_threshold:\n print(' {0} : {1}'.format(vocabulary[w], p))\n\n\n def get_topic_distributions(self, term_doc_matrix, e_iterations, e_epsilon):\n print(\"Predict topic distributions for the new documents using the existing LDA model...\")\n\n docs = self.get_variable_length_docs(term_doc_matrix)\n num_docs = term_doc_matrix.shape[0]\n\n # Initialize the hidden variables\n pi = [normalize_rows(np.random.random((len(doc), self.num_topics))) for doc in docs]\n # topic assignment of each word in each doc\n # dim = num_docs * |doc| * num_topics\n\n gamma = normalize_rows(np.random.random((num_docs, self.num_topics)))\n # topic assignment of each doc\n # dim = num_docs * num_topics\n\n (pi, gamma) = self.e_step(docs, pi, gamma, e_iterations, e_epsilon)\n return normalize_rows(gamma)\n\n\ndef main():\n np.random.seed(0)\n\n '''\n (vocabulary_size,\n training_term_doc_matrix,\n training_labels,\n testing_term_doc_matrix,\n testing_labels,\n vocabulary) = load_csv(input_path = 'spam.csv',\n test_set_size=1000,\n training_set_size=2000,\n num_stop_words=20,\n min_word_freq=5,\n text_column='Message',\n label_column='Category',\n label_dict = {'spam': 1, 'ham': 0})\n '''\n (vocabulary_size,\n training_term_doc_matrix,\n training_labels,\n testing_term_doc_matrix,\n testing_labels,\n vocabulary) = load_csv(input_path = 'FA-KES-Dataset.csv',\n test_set_size=200,\n training_set_size=200,\n num_stop_words=100,\n min_word_freq=3,\n text_column='article_content',\n label_column='labels',\n label_dict = {'1': 1, '0': 0})\n\n print(\"== SVM with word frequencies ==\")\n evaluate_embeddings(normalize_rows(training_term_doc_matrix),\n training_labels,\n normalize_rows(testing_term_doc_matrix),\n testing_labels)\n\n print(\"== SVM with topic distributions from LDA ==\")\n lda = LDA(vocabulary_size)\n\n lda.train(num_topics=15, term_doc_matrix=training_term_doc_matrix, iterations=10, e_iterations=10, e_epsilon=0.001, initial_training_set_size=50, initial_training_iterations=50, alpha_learning_rate=0.4, alpha_learning_rate_decay=0.005)\n lda.print_model(vocabulary, print_freq_threshold=0.01)\n\n evaluate_embeddings(lda.get_topic_distributions(term_doc_matrix=training_term_doc_matrix, e_iterations=100, e_epsilon=0.001),\n training_labels,\n lda.get_topic_distributions(term_doc_matrix=testing_term_doc_matrix, e_iterations=100, e_epsilon=0.001),\n testing_labels)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"lda_var_inf_without_smoothing_v2.py","file_name":"lda_var_inf_without_smoothing_v2.py","file_ext":"py","file_size_in_byte":12775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"285828216","text":"#全排列\n\nclass Solution:\n def permute(self, nums) :\n #self.nums=nums\n res=[]\n lenth = len(nums)\n self.down(0,res,lenth,nums)\n return res\n\n\n def down(self,first,res,lenth,nums):\n if first==lenth:\n res.append(nums[:])\n\n for i in range(first,lenth):\n nums[first], nums[i] = nums[i], nums[first]\n self.down(first+1,res,lenth,nums)\n nums[first], nums[i] = nums[i], nums[first]","sub_path":"Week_03/permute.py","file_name":"permute.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"184921276","text":"\"\"\"\nModule for Proper Orthogonal Decomposition (POD).\nThree different methods can be employed: Truncated Singular Value Decomposition,\nTruncated Randomized Singular Value Decomposition, Truncated Singular Value \nDecomposition via correlation matrix.\n\"\"\"\nimport numpy as np\n\nfrom .reduction import Reduction\n\n\nclass POD(Reduction):\n def __init__(self, method='svd', **kwargs):\n \"\"\"\n \"\"\"\n available_methods = {\n 'svd': (self._svd, {\n 'rank': -1\n }),\n 'randomized_svd': (self._rsvd, {\n 'rank': -1\n }),\n 'correlation_matrix': (self._corrm, {\n 'rank': -1,\n 'save_memory': False\n }),\n }\n\n self._modes = None\n self._singular_values = None\n\n method = available_methods.get(method)\n if method is None:\n raise RuntimeError(\n \"Invalid method for POD. Please chose one among {}\".format(\n ', '.join(available_methods)))\n\n self.__method, args = method\n args.update(kwargs)\n\n for hyperparam, value in args.items():\n setattr(self, hyperparam, value)\n\n @property\n def modes(self):\n \"\"\"\n The POD modes.\n\n :type: numpy.ndarray\n \"\"\"\n return self._modes\n\n @property\n def singular_values(self):\n \"\"\"\n The singular values\n\n :type: numpy.ndarray\n \"\"\"\n return self._singular_values\n\n def fit(self, X):\n \"\"\"\n Create the reduced space for the given snapshots `X` using the\n specified method\n\n :param numpy.ndarray X: the input snapshots matrix (stored by column)\n \"\"\"\n self._modes, self._singular_values = self.__method(X)\n return self\n\n def reduce(self, X):\n \"\"\"\n Reduces the given snapshots.\n\n :param numpy.ndarray X: the input snapshots matrix (stored by column).\n \"\"\"\n return self.modes.T.conj().dot(X)\n\n def expand(self, X):\n \"\"\"\n Projects a reduced to full order solution.\n\n :type: numpy.ndarray\n \"\"\"\n return self.modes.dot(X).T\n\n def _truncation(self, X, s):\n \"\"\"\n Return the number of modes to select according to the `rank` parameter.\n See POD.__init__ for further info.\n\n :param numpy.ndarray X: the matrix to decompose.\n :param numpy.ndarray s: the singular values of X.\n\n :return: the number of modes\n :rtype: int\n \"\"\"\n if self.rank == 0:\n omega = lambda x: 0.56 * x**3 - 0.95 * x**2 + 1.82 * x + 1.43\n beta = np.divide(*sorted(X.shape))\n tau = np.median(s) * omega(beta)\n rank = np.sum(s > tau)\n elif self.rank > 0 and self.rank < 1:\n cumulative_energy = np.cumsum(s**2 / (s**2).sum())\n rank = np.searchsorted(cumulative_energy, self.rank) + 1\n elif self.rank >= 1 and isinstance(self.rank, int):\n rank = self.rank #min(self.rank, U.shape[1])\n else:\n rank = X.shape[1]\n\n return rank\n\n def _svd(self, X):\n \"\"\"\n Truncated Singular Value Decomposition.\n\n :param numpy.ndarray X: the matrix to decompose.\n :return: the truncated left-singular vectors matrix, the truncated\n singular values array, the truncated right-singular vectors matrix.\n :rtype: numpy.ndarray, numpy.ndarray, numpy.ndarray\n\n References:\n Gavish, Matan, and David L. Donoho, The optimal hard threshold for\n singular values is, IEEE Transactions on Information Theory 60.8\n (2014): 5040-5053.\n \"\"\"\n U, s = np.linalg.svd(X, full_matrices=False)[:2]\n\n rank = self._truncation(X, s)\n return U[:, :rank], s[:rank]\n\n def _rsvd(self, X):\n \"\"\"\n Truncated randomized Singular Value Decomposition.\n\n :param numpy.ndarray X: the matrix to decompose.\n :return: the truncated left-singular vectors matrix, the truncated\n singular values array, the truncated right-singular vectors matrix.\n :rtype: numpy.ndarray, numpy.ndarray, numpy.ndarray\n \"\"\"\n\n P = np.random.rand(X.shape[1], X.shape[0])\n Q = np.linalg.qr(X.dot(P))[0]\n\n Y = Q.T.conj().dot(X)\n\n Uy, s = np.linalg.svd(Y, full_matrices=False)[:2]\n U = Q.dot(Uy)\n\n rank = self._truncation(X, s)\n return U[:, :rank], s[:rank]\n\n def _corrm(self, X):\n \"\"\"\n Truncated Singular Value Decomposition. calculated with correlation matrix.\n\n :param numpy.ndarray X: the matrix to decompose.\n :return: the truncated left-singular vectors matrix, the truncated\n singular values array, the truncated right-singular vectors matrix.\n :rtype: numpy.ndarray, numpy.ndarray, numpy.ndarray\n \"\"\"\n\n if self.save_memory:\n corr = np.empty(shape=(X.shape[1], X.shape[1]))\n for i, i_snap in enumerate(X.T):\n for j, k_snap in enumerate(X.T):\n corr[i, j] = np.inner(i_snap, k_snap)\n\n else:\n corr = X.T.dot(X)\n\n s, U = np.linalg.eig(corr)\n U = X.dot(U) / np.sqrt(s)\n rank = self._truncation(X, s)\n\n return U[:, :rank], s[:rank]\n","sub_path":"ezyrb/pod.py","file_name":"pod.py","file_ext":"py","file_size_in_byte":5320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"211790187","text":"#!/usr/bin/env python\n#coding=utf8\n\"\"\"\n====================================\n :mod:`main` Main\n====================================\n.. moduleauthor:: Daewoo Kim\n.. note:: note...\n\n설명\n=====\n\nThis is for analyzing energy consumption of drone,\nand propose the neural network model for drone's energy consumption\n\n참고\n====\n * https://github.com/rhoowd/energy_drone\n\n관련 작업자\n===========\n\n본 모듈은 다음과 같은 사람들이 관여했습니다:\n * Daewoo Kim\n * Se-eun Yoon\n\n CUDA_VISIBLE_DEVICES=0\n\n\"\"\"\nimport config\nimport log_result as log\nimport models\nimport graph\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nimport pandas as pd\nimport numpy as np\nfrom keras import backend as K\n\nimport time\n\nimport input_preprocess as ip\n\nFLAGS = config.flags.FLAGS\n\n\nif __name__ == '__main__':\n\n\tdataframe = pd.read_csv(FLAGS.f_dir+FLAGS.f_n)\n\n\tHISTORY_NUM = 0\n\thistory_labels = ['vel_x', 'vel_y', 'vel_z', 'acc_x', 'acc_y', 'acc_z', 'roll', 'pitch', 'yaw', 'act_vx', 'act_vy']\n\t# x_labels: 'vel_x', 'vel_y', 'vel_z', 'acc_x', 'acc_y', 'acc_z', 'roll', 'pitch', 'yaw', 'act_vx', 'act_vy'\n\tx_labels = ['vel_x', 'vel_y', 'vel_z', 'acc_x', 'acc_y', 'acc_z', 'roll', 'pitch', 'yaw', 'act_vx', 'act_vy']\n\ty_label = ['power']\n\n\t# make history columns\n\tfor l in history_labels:\n\t\tfor n in range(HISTORY_NUM):\n\t\t\tx_labels.append(l+\"_\" + str(n+1))\t\n\n\t# input normalization\n\tsc = StandardScaler()\n\tx_data = sc.fit_transform(dataframe[x_labels])\n\t# x_data = dataframe[x_labels].values\n\n\ty_data = dataframe[y_label].values\n\n\n\tlog.logger.info(\"x_shape: \" + str(x_data.shape) + \", y_shape:\" + str(y_data.shape))\n\n\n\tx_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=FLAGS.test_size, random_state=FLAGS.seed)\n\n\t# Create model\n\tmodel = models.flexible_model_koo(input_dim=x_data.shape[1], output_dim=1)\n\n\t# Start training\n\tmodel.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=FLAGS.n_e,\n\t\t\t batch_size=FLAGS.b_s, verbose=FLAGS.verbose)\n\n\t# Evaluate the model\n\tscores = model.evaluate(x_test, y_test)\n\tlog.logger.info(\"ACC(test):\\t\" + str(scores[2] * 100) + \"%\\t\" + log.filename + \" s\" + str(FLAGS.seed) + \"\\t\")\n\tlog.logger.info(\"MSE(test):\\t\" + str(scores[1]) + \"\\t\" + log.filename + \" s\"+ str(FLAGS.seed) + \"\\t\")\n\tscores = model.evaluate(x_data, y_data)\n\tlog.logger.info(\"ACC(all):\\t\" + str(scores[2] * 100) + \"%\\t\" + log.filename + \" s\" + str(FLAGS.seed) + \"\\t\")\n\tlog.logger.info(\"MSE(all):\\t\" + str(scores[1]) + \"\\t\" + log.filename + \" s\" + str(FLAGS.seed) + \"\\t\")\n\n\n\t# save prediction result\n\tpredictions = model.predict(x_test)\n\ty_test_t = y_test.reshape((-1, 1))\n\tpredictions_train = model.predict(x_train)\n\ty_train_t = y_train.reshape((-1, 1))\n\tresult = np.concatenate((y_test_t,predictions),axis=1)\n\tresult_train = np.concatenate((y_train_t, predictions_train), axis=1)\n\tnow = time.localtime()\n\ts_time = \"%02d%02d-%02d%02d%02d\" % (now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)\n\tresult_file_name = \"pred_result/\"+str(FLAGS.depth)+ \"-\" + str(FLAGS.h_size)+\"-\"+s_time+\".csv\"\n\ttrain_result_file_name = \"pred_result/\"+str(FLAGS.depth)+ \"-\" + str(FLAGS.h_size)+\"-\"+s_time+\"-train.csv\"\n\tnp.savetxt(result_file_name, result, delimiter=\",\")\n\tnp.savetxt(train_result_file_name, result_train, delimiter=\",\")\n\n\n\t# Save model\n\tmodel_json = model.to_json()\n\twith open(\"result/model/\"+log.filename+\".json\", \"w\") as json_file:\n\t\tjson_file.write(model_json) # serialize model to JSON\n\tmodel.save_weights(\"result/model/\"+log.filename+\".h5\") # weight\n\tprint(\"Save model ... done\")\n\n\t# Make graph\n\tif FLAGS.graph == 1:\n\t\test = model.predict(x_data)\n\t\tgraph.draw_graph(x_data[:, -1], y_data, est)\n\t\tprint(\"Save graph ... done\")\n\n\tK.clear_session()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"154403648","text":"from django.test import TestCase, RequestFactory\nfrom django.urls import reverse\nfrom .models import List\nfrom .views import delete\n\n\nclass ListTests(TestCase):\n\n def setUp(self):\n self.item = List.objects.create(item='Testing')\n\n # def create_model(self, item='Testing'):\n # return List.objects.create(item=item)\n\n # def create_model2(self, item='Testing delete'):\n # return List.objects.create(item=item)\n\n # def create_model3(self, item='Testing cross'):\n # return List.objects.create(item=item)\n\n def test_content(self):\n # items = self.create_model()\n items = List.objects.get(pk=1)\n result_item = f'{items.item}'\n assert result_item == 'Testing'\n\n def test_correct_view_used(self):\n response = self.client.get(reverse('home'))\n assert response.status_code == 200\n\n def test_delete_views(self):\n self.factory = RequestFactory()\n request = self.factory.get('/delete/')\n request.item = self.item\n response = delete(request, list_id=1)\n assert response.status_code == 302\n","sub_path":"build/lib/models/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"126564456","text":"\"\"\"Handles most database transactions. It has knowledge of the primary classes\nand their relationships and saves them accordingly.\n\"\"\"\n\nimport sqlalchemy as sa\n\nfrom substrate import BioCategory, Curator, GeneList, GeneSignature, \\\n GeoDataset, Report, SoftFile, Tag\n\nfrom gen3va.database.utils import session_scope\n\n\ndef count(class_):\n \"\"\"Returns the number of rows in an class's associated table.\n \"\"\"\n with session_scope() as session:\n return session.query(class_).count()\n\n\ndef get(class_, value, key='id'):\n \"\"\"Gets entity by comparing column to value.\n \"\"\"\n with session_scope() as session:\n return session\\\n .query(class_)\\\n .filter(getattr(class_, key) == value)\\\n .first()\n\n\ndef get_many(klass, values, key='id'):\n \"\"\"Gets entities whose column values are in values.\n \"\"\"\n with session_scope() as session:\n return session\\\n .query(klass)\\\n .filter(getattr(klass, key).in_(values))\\\n .all()\n\n\ndef get_all(klass):\n \"\"\"Gets all entities of a specific class.\n \"\"\"\n with session_scope() as session:\n return session.query(klass).all()\n\n\ndef get_signatures_by_ids(extraction_ids):\n \"\"\"Returns all gene signatures with matching extraction IDs.\n \"\"\"\n with session_scope() as session:\n return session\\\n .query(GeneSignature)\\\n .filter(GeneSignature.extraction_id.in_(extraction_ids))\\\n .all()\n\n\ndef add_object(obj):\n \"\"\"Create new object.\n \"\"\"\n with session_scope() as session:\n session.add(obj)\n\n\ndef update_object(obj):\n \"\"\"Update object, i.e. saves any edits.\n \"\"\"\n with session_scope() as session:\n session.merge(obj)\n\n\ndef delete_object(obj):\n \"\"\"Deletes object provided.\n \"\"\"\n with session_scope() as session:\n session.delete(obj)\n\n\ndef get_tags_by_curator(curator):\n \"\"\"Returns all tags by a particular curator\n \"\"\"\n with session_scope() as session:\n return session\\\n .query(Tag)\\\n .filter(Tag.curator_fk == Curator.id)\\\n .filter(Curator.name == curator)\\\n .all()\n\n\ndef get_bio_categories():\n \"\"\"Returns all bio categories which have tags from particular curators.\n \"\"\"\n with session_scope() as session:\n return session\\\n .query(BioCategory)\\\n .order_by(BioCategory.order)\\\n .all()\n\n\ndef get_bio_categories_by_curator(curator):\n \"\"\"Returns all bio categories which have tags from particular curators.\n \"\"\"\n with session_scope() as session:\n return session\\\n .query(BioCategory)\\\n .filter(BioCategory.id == Tag.bio_category_fk)\\\n .filter(Curator.id == Tag.curator_fk)\\\n .filter(Curator.name == curator)\\\n .all()\n\n\ndef get_statistics():\n \"\"\"Returns object with DB statistics for about page.\n \"\"\"\n with session_scope() as session:\n meta_counts = session\\\n .execute(\"\"\"SELECT `name`, COUNT(DISTINCT `value`) AS `count`\n FROM `optional_metadata` \n WHERE `name` IN ('cell', 'dose', 'time') \n GROUP BY `name`\"\"\")\\\n .fetchall()\n meta_counts = dict(meta_counts) \n\n cell_counts = session\\\n .execute(\"\"\"SELECT `value`, COUNT(`value`) AS `count` \n FROM `optional_metadata` \n WHERE `name`='cell' \n GROUP BY `value`\n \"\"\")\\\n .fetchall()\n cell_counts = [{'cell': item[0], 'count': item[1]} for item in cell_counts]\n\n return {\n 'num_gene_signatures': count(GeneSignature),\n 'num_reports': count(Report),\n 'num_cells': meta_counts['cell'],\n 'num_doses': meta_counts['dose'],\n 'num_times': meta_counts['time'],\n 'cell_counts': cell_counts\n }\n\ndef get_all_drug_meta():\n \"\"\"Returns a dict {pert_id: pert_iname} for all the drugs.\n \"\"\"\n with session_scope() as session:\n d_pert_name = session\\\n .execute(\"\"\"SELECT `pert_id`, `pert_iname` \n FROM `drug`\n \"\"\")\\\n .fetchall()\n d_pert_name = dict(d_pert_name)\n\n return d_pert_name\n","sub_path":"gen3va/database/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"334592937","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/kieffer/workspace/fabio/build/lib.macosx-10.6-intel-3.5/fabio/test/codecs/test_bruker100image.py\n# Compiled at: 2020-04-03 09:02:03\n# Size of source mod 2**32: 3955 bytes\n\"\"\"\n#bruker100 Unit tests\n\n19/01/2015\n\"\"\"\nfrom __future__ import print_function, with_statement, division, absolute_import\nimport unittest, os, logging\nlogger = logging.getLogger(__name__)\nfrom fabio.bruker100image import Bruker100Image\nfrom fabio.openimage import openimage\nfrom ..utilstest import UtilsTest\nTESTIMAGES = 'NaCl_10_01_0009.sfrm 512 512 -30 5912 34.4626 26.189\\n NaCl_10_01_0009.sfrm.gz 512 512 -30 5912 34.4626 26.189\\n NaCl_10_01_0009.sfrm.bz2 512 512 -30 5912 34.4626 26.189'\nREFIMAGE = 'NaCl_10_01_0009.npy.bz2'\n\nclass TestBruker100(unittest.TestCase):\n __doc__ = ' check some read data from bruker version100 detector'\n\n def setUp(self):\n \"\"\"\n download images\n \"\"\"\n UtilsTest.getimage(REFIMAGE)\n self.im_dir = os.path.dirname(UtilsTest.getimage(TESTIMAGES.split()[0] + '.bz2'))\n\n def test_read(self):\n \"\"\" check we can read bruker100 images\"\"\"\n for line in TESTIMAGES.split('\\n'):\n vals = line.split()\n name = vals[0]\n dim1, dim2 = [int(x) for x in vals[1:3]]\n shape = (dim2, dim1)\n mini, maxi, mean, stddev = [float(x) for x in vals[3:]]\n obj = Bruker100Image()\n obj.read(os.path.join(self.im_dir, name))\n self.assertAlmostEqual(mini, obj.getmin(), 2, 'getmin')\n self.assertAlmostEqual(maxi, obj.getmax(), 2, 'getmax')\n self.assertAlmostEqual(mean, obj.getmean(), 2, 'getmean')\n self.assertAlmostEqual(stddev, obj.getstddev(), 2, 'getstddev')\n self.assertEqual(shape, obj.shape)\n\n def test_same(self):\n \"\"\" check we can read bruker100 images\"\"\"\n ref = openimage(os.path.join(self.im_dir, REFIMAGE))\n for line in TESTIMAGES.split('\\n'):\n obt = openimage(os.path.join(self.im_dir, line.split()[0]))\n self.assertTrue(abs(ref.data - obt.data).max() == 0, 'data are the same')\n\n def test_write(self):\n fname = TESTIMAGES.split()[0]\n obt = openimage(os.path.join(self.im_dir, fname))\n name = os.path.basename(fname)\n obj = Bruker100Image(data=obt.data, header=obt.header)\n obj.write(os.path.join(UtilsTest.tempdir, name))\n other = openimage(os.path.join(UtilsTest.tempdir, name))\n self.assertEqual(abs(obt.data - other.data).max(), 0, 'data are the same')\n for key in obt.header:\n self.assertTrue(key in other.header, 'Key %s is in header' % key)\n self.assertEqual(obt.header[key], other.header[key], 'value are the same for key %s' % key)\n\n os.unlink(os.path.join(UtilsTest.tempdir, name))\n\n\ndef suite():\n loadTests = unittest.defaultTestLoader.loadTestsFromTestCase\n testsuite = unittest.TestSuite()\n testsuite.addTest(loadTests(TestBruker100))\n return testsuite\n\n\nif __name__ == '__main__':\n runner = unittest.TextTestRunner()\n runner.run(suite())","sub_path":"pycfiles/fabio-0.10.0-cp35-cp35m-macosx_10_6_intel/test_bruker100image.cpython-35.py","file_name":"test_bruker100image.cpython-35.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"516532672","text":"#coding=utf-8\n\n\nclass Article:\n def __init__(self,\n volume,\n number,\n index,\n title,\n text,\n keywords,\n text_zh):\n self.volume = volume\n self.number = number\n self.index = index\n self.title = title\n self.text = text\n self.keywords = keywords\n self.text_zh = text_zh\n","sub_path":"article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"135024033","text":"import numpy as np\nimport pickle\nimport PIL.Image as Image\n\nimport pylot.utils\nfrom pylot.perception.segmentation.utils import transform_to_cityscapes_palette\n\nfrom erdos.op import Op\nfrom erdos.utils import setup_csv_logging, setup_logging\n\n\nclass CameraLoggerOp(Op):\n \"\"\" Logs frames for different types of cameras.\"\"\"\n\n def __init__(self, name, flags, log_file_name=None, csv_file_name=None):\n super(CameraLoggerOp, self).__init__(name)\n self._flags = flags\n self._logger = setup_logging(self.name, log_file_name)\n self._csv_logger = setup_csv_logging(self.name + '-csv', csv_file_name)\n self._bgr_frame_cnt = 0\n self._segmented_frame_cnt = 0\n self._top_down_segmented_frame_cnt = 0\n self._depth_frame_cnt = 0\n self._left_bgr_frame_cnt = 0\n self._right_bgr_frame_cnt = 0\n\n @staticmethod\n def setup_streams(input_streams):\n input_streams.filter(pylot.utils.is_center_camera_stream).add_callback(\n CameraLoggerOp.on_bgr_frame)\n input_streams.filter(pylot.utils.is_left_camera_stream).add_callback(\n CameraLoggerOp.on_bgr_frame_left)\n input_streams.filter(pylot.utils.is_right_camera_stream).add_callback(\n CameraLoggerOp.on_bgr_frame_right)\n input_streams.filter(\n pylot.utils.is_front_segmented_camera_stream).add_callback(\n CameraLoggerOp.on_front_segmented_frame)\n input_streams.filter(\n pylot.utils.is_top_down_segmented_camera_stream).add_callback(\n CameraLoggerOp.on_top_down_segmented_frame)\n input_streams.filter(\n pylot.utils.is_depth_camera_stream).add_callback(\n CameraLoggerOp.on_depth_frame)\n return []\n\n def on_bgr_frame(self, msg):\n self._bgr_frame_cnt += 1\n if self._bgr_frame_cnt % self._flags.log_every_nth_frame != 0:\n return\n # Write the image.\n assert msg.encoding == 'BGR', 'Expects BGR frames'\n rgb_array = pylot.utils.bgr_to_rgb(msg.frame)\n file_name = '{}carla-center-{}.png'.format(\n self._flags.data_path, msg.timestamp.coordinates[0])\n rgb_img = Image.fromarray(np.uint8(rgb_array))\n rgb_img.save(file_name)\n\n def on_bgr_frame_left(self, msg):\n self._left_bgr_frame_cnt += 1\n if self._left_bgr_frame_cnt % self._flags.log_every_nth_frame != 0:\n return\n # Write the image.\n assert msg.encoding == 'BGR', 'Expects BGR frames'\n rgb_array = pylot.utils.bgr_to_rgb(msg.frame)\n file_name = '{}carla-left-{}.png'.format(\n self._flags.data_path, msg.timestamp.coordinates[0])\n rgb_img = Image.fromarray(np.uint8(rgb_array))\n rgb_img.save(file_name)\n\n def on_bgr_frame_right(self, msg):\n self._right_bgr_frame_cnt += 1\n if self._right_bgr_frame_cnt % self._flags.log_every_nth_frame != 0:\n return\n # Write the image.\n assert msg.encoding == 'BGR', 'Expects BGR frames'\n rgb_array = pylot.utils.bgr_to_rgb(msg.frame)\n file_name = '{}carla-right-{}.png'.format(\n self._flags.data_path, msg.timestamp.coordinates[0])\n rgb_img = Image.fromarray(np.uint8(rgb_array))\n rgb_img.save(file_name)\n\n def on_front_segmented_frame(self, msg):\n self._segmented_frame_cnt += 1\n if self._segmented_frame_cnt % self._flags.log_every_nth_frame != 0:\n return\n frame = transform_to_cityscapes_palette(msg.frame)\n # Write the segmented image.\n img = Image.fromarray(np.uint8(frame))\n file_name = '{}carla-segmented-{}.png'.format(\n self._flags.data_path, msg.timestamp.coordinates[0])\n img.save(file_name)\n\n def on_top_down_segmented_frame(self, msg):\n self._top_down_segmented_frame_cnt += 1\n if self._top_down_segmented_frame_cnt % self._flags.log_every_nth_frame != 0:\n return\n frame = transform_to_cityscapes_palette(msg.frame)\n # Write the segmented image.\n img = Image.fromarray(np.uint8(frame))\n file_name = '{}carla-top-down-segmented-{}.png'.format(\n self._flags.data_path, msg.timestamp.coordinates[0])\n img.save(file_name)\n\n def on_depth_frame(self, msg):\n self._depth_frame_cnt += 1\n if self._depth_frame_cnt % self._flags.log_every_nth_frame != 0:\n return\n # Write the depth information.\n file_name = '{}carla-depth-{}.pkl'.format(\n self._flags.data_path, msg.timestamp.coordinates[0])\n pickle.dump(msg.frame,\n open(file_name, 'wb'),\n protocol=pickle.HIGHEST_PROTOCOL)\n","sub_path":"pylot/loggers/camera_logger_operator.py","file_name":"camera_logger_operator.py","file_ext":"py","file_size_in_byte":4712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"277175596","text":"#coding:utf-8\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport math\nimport cv2\n\ndef cal_conv_out_img_size(img_size, filter_size, padding=None, strides=1):\n if not padding:\n padding = [0]*4\n if not strides:\n strides = 1\n if len(filter_size) == 1:\n filter_size = [filter_size, filter_size]\n h = int(np.ceil((img_size[0] + padding[0] + padding[1] - filter_size[0])*1.0 / strides[0]) + 1)\n w = int(np.ceil((img_size[1] + padding[2] + padding[3] - filter_size[1])*1.0 / strides[1]) + 1)\n return [h, w]\n\ndef convolve(filter, mat, padding, strides, gray_flag=False):\n '''\n 图像二维卷积\n :param filter:卷积核,必须为二维(2 x 1也算二维) 否则返回None\n :param mat:图片 [h,w] || [h,w,3]\n :param padding:对齐 [4] : [0,0,5,5]\n :param strides: int\n :return:返回卷积后的图片。(灰度图,彩图都适用)\n '''\n shape = cal_conv_out_img_size(mat.shape, filter.shape, padding, strides)\n result = np.zeros(shape)\n filter_size = filter.shape\n mat_size = mat.shape\n assert len(filter_size) == 2\n # 灰度图像\n if len(mat_size) == 2:\n mat = mat.reshape([mat_size[0], mat_size[1], 1])\n result = result.reshape(shape[0], shape[1], 1)\n mat_size = mat.shape\n gray_flag = True\n # 先遍历图像的行\n for c in range(mat_size[-1]):\n # pad: [0,0,5,5] [h,w]=>[h, 5+w+5] :在图片的左右填充\n # pad: [5,5,0,0] [h,w]=>[5+h+5, w] :在图片的上下填充\n pad_mat = np.pad(mat[:, :, c], ((padding[0], padding[1]), (padding[2], padding[3])), 'constant')\n # 遍历图像的列\n for i in range(0, mat_size[0], strides[1]):\n # 以卷积核的左上角为原点,拿卷积核和图像的相应位置相乘然后相加,就是做卷积操作\n for j in range(0, mat_size[1], strides[0]):\n val = (filter*pad_mat[i:i+filter_size[0], j:j+filter_size[1]]).sum()\n result[i, j, c] = val\n return result.reshape([result.shape[0], result.shape[1]]) if gray_flag else result\n\n\ndef row_convolve(filter, mat, padding=None, strides=[1, 1]):\n '''\n 线性卷积就是先用一维的卷积横向卷积\n :param filter:线性卷积核 [1, n]\n :param mat:图片 [h,w] || [h,w,3]\n :param padding:对齐\n :param strides:移动步长\n :return:返回卷积后的图片。(灰度图,彩图都适用) 若不是线性卷积核,返回None\n '''\n filter_size = filter.shape\n assert len(filter_size) <= 2\n if len(filter_size) == 1:\n filter = filter.reshape([1, -1])\n filter_size = filter.shape\n if padding == None or len(padding) < 2:\n padding = [filter_size[1]//2, filter_size[1]//2]\n result = convolve(filter, mat, [0, 0, padding[0], padding[1]], strides)\n return result\n\n\ndef col_convolve(filter, mat, padding=None, strides=[1, 1]):\n '''\n 线性卷积就是先用一维的卷积横向卷积\n :param filter:线性卷积核 [n, 1]\n :param mat:图片 [h,w] || [h,w,3]\n :param padding:对齐\n :param strides:移动步长\n :return:返回卷积后的图片。(灰度图,彩图都适用) 若不是线性卷积核,返回None\n '''\n\n # 卷积核标准化为[n,1]\n filter_size = filter.shape\n assert len(filter_size) <= 2\n if len(filter_size) == 1:\n filter = filter.reshape([-1, 1])\n filter_size = filter.shape\n elif filter_size[0] == 1:\n filter = filter.reshape([-1, 1])\n filter_size = filter.shape\n if padding == None or len(padding) < 2:\n padding = [filter_size[0]//2, filter_size[0]//2]\n result = convolve(filter, mat, [padding[0], padding[1], 0, 0], strides)\n return result\n\n\ndef divided_convolve(filter, img):\n '''\n 将二维卷积分解为横向线性卷积和纵向线性卷积的叠加,先横向线性卷积,再进行纵向线性卷积\n :param filter: 线性卷积核 touple: ([n], [n]) n为卷积核的大小\n :param mat: 图片 [h, w, 3] || [h, w]\n :return: 卷积后的图片,(灰度图,彩图都适用)\n '''\n (row_filter, col_filter) = filter if len(filter) == 2 else (filter, filter)\n result = row_convolve(row_filter, img)\n result = col_convolve(col_filter, result)\n return result\n\n\ndef judgeConnect(m2, threshold):\n '''\n 极大值过于稀疏,将极大值点的八邻域的模糊点也设为255,设置为边界,这样边界会更加明显\n :param m2:[h,w] 图像\n :param threshold: 阈值是上下限\n :return: 图像[h,w]\n '''\n\n e = 0.01\n # 存所有极大值点的坐标,假设有n个极大值点,最后s为[n, 2]\n s = []\n # 存所有点的坐标,遍历完后cood为[h,w,2] 2表示[x, y]\n cood = []\n # 遍历h\n for i in range(m2.shape[0]):\n cood.append([])\n # 遍历w\n for j in range(m2.shape[1]):\n cood[-1].append([i, j])\n if abs(m2[i, j] - 255) < e:\n s.append([i, j])\n cood = np.array(cood)\n # 如果栈没有空,就一直查找\n while not len(s) == 0:\n # 从栈中弹出一个值来判断其八邻域内是否有极大值点\n index = s.pop()\n # 得到index点的八邻域的像素值窗口\n jud = m2[max(0, index[0] - 1):min(index[0] + 2, m2.shape[1]), max(0, index[1] - 1):min(index[1] + 2, m2.shape[0])]\n # 取得index坐标的八邻域坐标点\n jud_i = cood[max(0, index[0] - 1):min(index[0] + 2, cood.shape[1]), max(0, index[1] - 1):min(index[1] + 2, cood.shape[0])]\n # 取出在八邻域内像素值在模糊区间的点的掩码mask\n jud = (jud > threshold[0]) & (jud < threshold[1])\n # 将这些点的坐标取出来\n jud_i = jud_i[jud]\n # 将这些点的坐标入栈,并将这些点的八领域的模糊点的像素置255,然后等待下一步继续判断,也就是将所有极大值点的八邻域的模糊点也作为边界\n for i in range(jud_i.shape[0]):\n s.append(list(jud_i[i]))\n m2[jud_i[i][0], jud_i[i][1]] = 255\n return m2\n\n\ndef DecideAndConnectEdge(g_l, g_t, threshold=None):\n '''\n 非极大值抑制函数+连接函数\n :param g_l:图像每一点梯度的幅值 [h, w]\n :param g_t:图像每一点梯度的相角[h, w]\n :param threshold: 上下限\n :return:图片\n '''\n if threshold == None:\n lower_boundary = g_l.mean()*0.5\n threshold = [lower_boundary, lower_boundary*3]\n result = np.zeros(g_l.shape)\n for i in range(g_l.shape[0]):\n for j in range(g_l.shape[1]):\n isLocalExtreme = True\n # 得到一个像素点的八邻域,并限制不会超出图像的尺度\n eight_neiborhood = g_l[max(0, i-1): min(i+2, g_l.shape[0]), max(0, j-1): min(j+2, g_l.shape[1])]\n # 在图像内部可以双线性插值的点才进行非极大值抑制,图像边缘点直接设为极大值\n if eight_neiborhood.shape == (3, 3):\n # 梯度的正方向为dy向上,dx向左\n # 如果梯度的tanθ∈[0, 1], 角度在0到45度之间 abs(tanθ)=abs(dy/dx) = d/1 => d=abs(dy/dx)\n if 0 <= g_t[i, j] < 1:\n d = abs(g_t[i, j])\n first = eight_neiborhood[1, 2] + (eight_neiborhood[0, 2] - eight_neiborhood[1, 2]) * d\n second = eight_neiborhood[1, 0] + (eight_neiborhood[2, 0] - eight_neiborhood[1, 0]) * d\n if not (g_l[i, j] > first and g_l[i, j] > second):\n isLocalExtreme = False\n\n # 如果梯度的tanθ > 1 角度在45度到90度之间, abs(tanθ)=abs(dy/dx) = 1/d => d=abs(dx/dy)\n elif g_t[i, j] >= 1:\n d = abs(1 / g_t[i, j])\n first = eight_neiborhood[0, 1] + (eight_neiborhood[0, 2] - eight_neiborhood[0, 1]) * d\n second = eight_neiborhood[2, 1] + (eight_neiborhood[2, 0] - eight_neiborhood[2, 1]) * d\n if not (g_l[i, j] > first and g_l[i, j] > second):\n isLocalExtreme = False\n\n # 如果梯度的tanθ < -1 角度在90度到145度之间, abs(tanθ)=abs(dy/dx) = 1/d => d=abs(dx/dy)\n elif g_t[i, j] <= -1:\n d = abs(1 / g_t[i, j])\n first = eight_neiborhood[0, 1] + (eight_neiborhood[0, 0] - eight_neiborhood[0, 1]) * d\n second = eight_neiborhood[2, 1] + (eight_neiborhood[2, 2] - eight_neiborhood[2, 1]) * d\n if not (g_l[i, j] > first and g_l[i, j] > second):\n isLocalExtreme = False\n\n # 如果梯度的tanθ∈[-1, 0] 角度在145度到180度之间 abs(tanθ)=abs(dy/dx) = d/1 => d=abs(dy/dx)\n elif -1 < g_t[i, j] < 0:\n d = abs(g_t[i, j])\n first = eight_neiborhood[1, 0] + (eight_neiborhood[0, 0] - eight_neiborhood[1, 0]) * d\n second = eight_neiborhood[1, 2] + (eight_neiborhood[2, 2] - eight_neiborhood[1, 2]) * d\n if not (g_l[i, j] > first and g_l[i, j] > second):\n isLocalExtreme = False\n if isLocalExtreme:\n result[i, j] = g_l[i, j] #非极大值抑制\n # 将大于阈值的点设置为255,也就是梯度大于上阈值的点,直接就可以判定为边界,对处于阈值之间的模糊点进行保留,最后在连接函数来筛选这些模糊点\n result[result >= threshold[1]] = 255\n # 将小于最小阈值的点设置为0,也就是很小的极值当做是局部的最大,但是幅值太低了,直接设置为0,舍弃掉这些\n result[result <= threshold[0]] = 0\n\n # 进行非极大值抑制后连接所有可能连接的边\n result = judgeConnect(result, threshold)\n result[result != 255] = 0\n return result\n\n\ndef OneDimensionStandardNormalDistribution(x, sigma):\n '''\n 计算一维高斯核的工具函数\n :param x:坐标,也就是离中心的距离\n :param sigma: 模糊参数\n :return: 该点的高斯核的参数\n '''\n E = -0.5 / (sigma*sigma)\n return 1/ (math.sqrt(2*math.pi)*sigma)*math.exp(x*x*E)\n\n\nif __name__ == '__main__':\n\n # Gaussian_filter_3 = 1.0/16*np.array([(1,2,1),(2,4,2),(1,2,1)]) #Gaussian smoothing kernel when sigma = 0.8, size: 3x3\n # Gaussian_filter_5 = 1.0/159*np.array([\n # [2,4,5,4,2],\n # [4,9,12,9,4],\n # [5,12,15,12,5],\n # [4,9,12,9,4],\n # [2,4,5,4,2]\n # ]) #Gaussian smoothing kernel when sigma = 1.4, size: 5x5\n\n\n\n pic_path = 'img'\n pics = os.listdir(pic_path)\n\n # 读取图片\n for i in pics:\n # 因为png的像素值是0-1所以乘以255,标准化到0-255的范围,和jpg一致\n\n filename = os.path.join(pic_path, i)\n # [h, w, 3]\n img = plt.imread(filename)\n if i.split('.')[-1] == 'png':\n img = img * 255\n # 在rgb通道上取均值,灰度化\n img = img.mean(axis=-1)\n\n # 高斯核函数的参数\n sigma = 1.52\n # 卷积核的大小, 11\n dim = int(np.round(6*sigma+1))\n # 将卷积核限定为奇数\n dim = dim + 1 if dim % 2 == 0 else dim\n # 算出一维的高斯核的坐标取值,坐标表示离当前点的距离\n # [5,4,3,2,1,0,1,2,3,4,5]\n linear_Gaussian_filter = [np.abs(t - (dim//2)) for t in range(dim)]\n\n # 将坐标送入高斯核产生函数中产生高斯核数值\n # [11]\n linear_Gaussian_filter = np.array([OneDimensionStandardNormalDistribution(t, sigma) for t in linear_Gaussian_filter])\n # 高斯核归一化\n linear_Gaussian_filter = linear_Gaussian_filter / linear_Gaussian_filter.sum()\n\n # 拆分的线性卷积代替二维卷积,进行高斯滤波\n img2 = divided_convolve(linear_Gaussian_filter, img)\n # 也可以直接用二维卷积来做\n # img2 = convolve(Gaussian_filter_5, img, [2, 2, 2, 2], [1, 1])\n\n # 显示灰度化后的图片\n plt.imshow(img2.astype(np.uint8), cmap='gray')\n plt.axis('off')\n plt.show()\n\n # 两个sobel矩阵求梯度。sobel算子的正负隐含梯度的正方向为dy向上,dx向左,这里会影响后面的线性插值\n sobel_kernel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])\n sobel_kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])\n # 对灰度化后的图片求导,也就是用sobel核来卷积,x方向求导\n img_x_grad = convolve(sobel_kernel_x, img2, [1,1,1,1], [1,1])\n plt.imshow(img_x_grad.astype(np.uint8), cmap='gray')\n plt.axis('off')\n plt.show()\n # y方向求导\n img_y_grad = convolve(sobel_kernel_y, img2, [1,1,1,1], [1,1])\n plt.imshow(img_y_grad.astype(np.uint8), cmap='gray')\n plt.axis('off')\n plt.show()\n # 平方开根号得到梯度的幅值\n gradiant_length = (img_x_grad**2 + img_y_grad**2)**(1.0/2)\n\n # 展示梯度幅值的图像\n img_x_grad = img_x_grad.astype(np.float64)\n img_y_grad = img_y_grad.astype(np.float64)\n # 防止求比值的时候出现Nan\n img_x_grad[img_x_grad == 0] = 0.00000001\n # 梯度的角度\n gradiant_tangent = img_y_grad / img_x_grad\n\n plt.imshow(gradiant_length.astype(np.uint8), cmap='gray')\n plt.axis('off')\n plt.show()\n\n #lower_boundary = 50\n # 后处理,非极大值抑制和连接极大值的像素点,形成边界\n final_img = DecideAndConnectEdge(gradiant_length, gradiant_tangent)\n cv2.imshow('edge', final_img.astype(np.uint8))\n cv2.waitKey(0)","sub_path":"1、canny edge detection/CannyDetection.py","file_name":"CannyDetection.py","file_ext":"py","file_size_in_byte":13709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"338323980","text":"#problem21\r\nA=float(input())\r\nN=A\r\nprint(\"NOTAS:\")\r\nprint(\"%d nota(s) de R$ 100.00\"%(N/100))\r\nb=N%100\r\nprint(\"%d nota(s) de R$ 50.00\"%(b/50))\r\nd=b%50\r\nprint(\"%d nota(s) de R$ 20.00\"%(d/20))\r\nf=d%20\r\nprint(\"%d nota(s) de R$ 10.00\"%(f/10))\r\nh=f%10\r\nprint(\"%d nota(s) de R$ 5.00\"%(h/5))\r\nj=h%5\r\nprint(\"%d nota(s) de R$ 2.00\"%(j/2))\r\nl=j%2\r\nprint(\"MOEDAS:\")\r\nE=A*100\r\nB=(int(E))\r\nprint(\"%d moeda(s) de R$ 1.00\"%l)\r\nm=B%100\r\nprint(\"%d moeda(s) de R$ 0.50\"%(m/50))\r\no=m%50\r\nprint(\"%d moeda(s) de R$ 0.25\"%(o/25))\r\nq=o%25\r\nprint(\"%d moeda(s) de R$ 0.10\"%(q/10))\r\ns=q%10\r\nprint(\"%d moeda(s) de R$ 0.05\"%(s/5))\r\nu=s%5\r\nprint(\"%d moeda(s) de R$ 0.01\"%u)\r\n#problem22\r\nA,B,C,D=map(int,input().split())\r\nif B>C and D>A and (C+D)>(A+B) and C>=0 and D>=0 and A%2==0:\r\n print(\"Valores aceitos\")\r\nelse:\r\n print(\"Valores nao aceitos\")\r\n# problem23\r\nA,B,C =map(float,input().split())\r\nd = B * B - 4 * A * C\r\ne = pow(d,0.5)\r\nif (d < 0 or A == 0):\r\n print(\"Impossivel calcular\")\r\nelse:\r\n f = (-B + e) / (2 * A)\r\n g = (-B - e) / (2 * A)\r\n print(\"R1 = %.5f\"%f)\r\n print(\"R2 = %.5f\"%g)\r\n# problem24\r\nn=float(input())\r\nif n<0.00 or n>100.00:\r\n print(\"Fora de intervalo\")\r\nelif n>=0.00 and n<=25.00:\r\n print(\"Intervalo [0,25]\")\r\nelif n>25.00 and n<=50.00:\r\n print(\"Intervalo (25,50]\")\r\nelif n>50.00 and n<=75.00:\r\n print(\"Intervalo (50,75]\")\r\nelif n>75.00 and n<=100.00:\r\n print(\"Intervalo (75,100]\")\r\n#problem24\r\nsnack={\r\n 1:4.00,\r\n 2:4.50,\r\n 3:5.00,\r\n 4:2.00,\r\n 5:1.50\r\n}\r\nX,Y=map(int,input().split())\r\nTotal=snack[X]*Y\r\nprint(\"Total: R$ %.2f\"%Total)\r\n# problem25\r\nN1,N2,N3,N4=map(float,input().split())\r\nMedia=((N1*2)+(N2*3)+(N3*4)+(N4*1))/10\r\nprint(\"Media: %.1f\"%Media)\r\nif Media>=7.0:\r\n print(\"Aluno aprovado.\")\r\nelif Media<5.0:\r\n print(\"Aluno reprovado.\")\r\nelif Media >=5.0 and Media<=6.9:\r\n print(\"Aluno em exame.\")\r\n N5=float(input())\r\n print(\"Nota do exame:\",N5)\r\n Media2=(N5+Media)/2\r\n if Media2>=5.0:\r\n print(\"Aluno aprovado.\")\r\n print(\"Media final: %.1f\"%Media2)\r\n elif Media2<=4.9:\r\n print(\"Aluno reprovado.\")\r\n print(\"Media final: %.1f\" % Media2)\r\n# problem26\r\nX,Y=map(float,input().split())\r\nif(X==0 and Y==0):\r\n print(\"Origem\")\r\nelif(X==0):\r\n print(\"Eixo Y\")\r\nelif(Y==0):\r\n print(\"Eixo X\")\r\nelif(X>0 and Y>0):\r\n print(\"Q1\")\r\nelif(X<0 and Y>0):\r\n print(\"Q2\")\r\nelif(X<0 and Y<0):\r\n print(\"Q3\")\r\nelif(X>0 and Y<0):\r\n print(\"Q4\")\r\n# problem27\r\nA,B,C=map(int,input().split())\r\nlist=[A,B,C]\r\nlist.sort()\r\nfor x in list:\r\n print(x)\r\nprint()\r\nprint(A)\r\nprint(B)\r\nprint(C)\r\n#another\r\na,b,c=map(float,input().split())\r\nif(a < b):\r\n temp = a\r\n a = b\r\n b = temp\r\nif(b < c):\r\n temp = b\r\n b = c\r\n c = temp\r\nif(a < b):\r\n temp = a\r\n a = b\r\n b = temp\r\nprint(a)\r\nprint(b)\r\nprint(c)\r\n\r\n#problem28\r\nA,B,C=map(float,input().split())\r\nif (B+C)>A and (A+B)>C and (A+C)>B:\r\n Perimetro=A+B+C\r\n print(\"Perimetro = %.1f\"%Perimetro)\r\nelse:\r\n Area=((1/2)*(A+B))*C\r\n print(\"Area = %.1f\"%Area)\r\n#problem29\r\nA,B=map(int,input().split())\r\nif A%B==0 or B%A==0:\r\n print(\"Sao Multiplos\")\r\nelse:\r\n print(\"Nao Sao Multiplos\")\r\n#problem30\r\nA,B,C=map(float,input().split())\r\nlist=[A,B,C]\r\nlist.sort(reverse=True)\r\nprint(list)\r\nA=list[0]\r\nB=list[1]\r\nC=list[2]\r\nif (A >= B + C):\r\n print(\"NAO FORMA TRIANGULO\")\r\nelif ((A*A)==((B*B) + (C*C))):\r\n print(\"TRIANGULO RETANGULO\")\r\nelif ((A*A)>((B*B) + (C*C))):\r\n print(\"TRIANGULO OBTUSANGULO\")\r\nelif ((A*A)<((B*B) + (C*C))):\r\n print(\"TRIANGULO ACUTANGULO\")\r\nif (A==B==C):\r\n print(\"TRIANGULO EQUILATERO\")\r\nelif (A==B or A==C or B==C):\r\n print(\"TRIANGULO ISOSCELES\")","sub_path":"uri-problem21-30.py","file_name":"uri-problem21-30.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"16706015","text":"# -*- coding: future_annotations -*-\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom nbsafety.data_model.timestamp import Timestamp\nfrom nbsafety.singletons import nbs\n\nif TYPE_CHECKING:\n from typing import Iterable, Set\n\n # avoid circular imports\n from nbsafety.data_model.data_symbol import DataSymbol\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.ERROR)\n\n\nclass UpdateProtocol:\n def __init__(self, updated_sym: DataSymbol) -> None:\n self.updated_sym = updated_sym\n self.seen: Set[DataSymbol] = set()\n\n def __call__(self, new_deps: Set[DataSymbol], mutated: bool, propagate_to_namespace_descendents: bool) -> None:\n # in most cases, mutated implies that we should propagate to namespace descendents, since we\n # do not know how the mutation affects the namespace members. The exception is for specific\n # known events such as 'list.append()' or 'list.extend()' since we know these do not update\n # the namespace members.\n logger.warning(\n \"updated sym %s (containing scope %s) with children %s\",\n self.updated_sym,\n self.updated_sym.containing_scope,\n self.updated_sym.children_by_cell_position.values(),\n )\n directly_updated_symbols = nbs().aliases[self.updated_sym.obj_id] if mutated else {self.updated_sym}\n self._collect_updated_symbols_and_refresh_namespaces(\n directly_updated_symbols, propagate_to_namespace_descendents\n )\n logger.warning(\n 'for symbol %s: mutated=%s; updated_symbols=%s', self.updated_sym, mutated, directly_updated_symbols\n )\n updated_symbols_with_ancestors = set(self.seen)\n logger.warning('all updated symbols for symbol %s: %s', self.updated_sym, updated_symbols_with_ancestors)\n nbs().updated_symbols |= self.seen\n for updated_sym in directly_updated_symbols:\n if not updated_sym.is_stale and updated_sym is not self.updated_sym:\n updated_sym.refresh()\n self.seen |= new_deps # don't propagate to stuff on RHS\n for dsym in updated_symbols_with_ancestors:\n self._propagate_staleness_to_deps(dsym, skip_seen_check=True)\n\n def _collect_updated_symbols_and_refresh_namespaces(\n self, updated_symbols: Iterable[DataSymbol], refresh_descendent_namespaces: bool\n ) -> None:\n logger.warning('collecting updated symbols and namespaces for %s', updated_symbols)\n for dsym in updated_symbols:\n if dsym.is_import or dsym in self.seen:\n continue\n dsym.updated_timestamps.add(Timestamp.current())\n self.seen.add(dsym)\n containing_ns = dsym.containing_namespace\n if containing_ns is not None:\n logger.warning('containing scope for %s: %s; ids %s, %s', dsym, containing_ns, dsym.obj_id, containing_ns.obj_id)\n containing_ns.namespace_stale_symbols.discard(dsym)\n containing_ns.max_descendent_timestamp = Timestamp.current()\n self._collect_updated_symbols_and_refresh_namespaces(\n nbs().aliases[containing_ns.obj_id], refresh_descendent_namespaces\n )\n if refresh_descendent_namespaces:\n dsym_ns = dsym.namespace\n if dsym_ns is not None:\n self._collect_updated_symbols_and_refresh_namespaces(\n dsym_ns.all_data_symbols_this_indentation(), refresh_descendent_namespaces\n )\n\n def _propagate_staleness_to_namespace_parents(self, dsym: DataSymbol, skip_seen_check=False):\n if not skip_seen_check and dsym in self.seen:\n return\n self.seen.add(dsym)\n containing_ns = dsym.containing_namespace\n if containing_ns is None:\n return\n logger.warning(\"add %s to namespace stale symbols of %s\", dsym, containing_ns)\n containing_ns.namespace_stale_symbols.add(dsym)\n for containing_alias in nbs().aliases[containing_ns.obj_id]:\n self._propagate_staleness_to_namespace_parents(containing_alias)\n\n for containing_alias in nbs().aliases[containing_ns.obj_id]:\n # do this in 2 separate loops to make sure all containing_alias are added to 'seen'\n # works around the issue when one alias depends on another\n for child in self._non_class_to_instance_children(containing_alias):\n logger.warning('propagate from namespace parent of %s to child %s', dsym, child)\n self._propagate_staleness_to_deps(child)\n\n def _non_class_to_instance_children(self, dsym):\n if self.updated_sym is dsym:\n for dep_introduced_pos, dsym_children in dsym.children_by_cell_position.items():\n if not nbs().settings.backwards_cell_staleness_propagation and dep_introduced_pos <= nbs().active_cell_position_idx:\n continue\n yield from dsym_children\n return\n for dep_introduced_pos, dsym_children in dsym.children_by_cell_position.items():\n if not nbs().settings.backwards_cell_staleness_propagation and dep_introduced_pos <= nbs().active_cell_position_idx:\n continue\n for child in dsym_children:\n # Next, complicated check to avoid propagating along a class -> instance edge.\n # The only time this is OK is when we changed the class, which will not be the case here.\n child_namespace = child.namespace\n if child_namespace is not None and child_namespace.cloned_from is not None:\n if child_namespace.cloned_from.obj_id == dsym.obj_id:\n continue\n yield child\n\n def _propagate_staleness_to_namespace_children(self, dsym: DataSymbol, skip_seen_check=False):\n if not skip_seen_check and dsym in self.seen:\n return\n self.seen.add(dsym)\n self_ns = nbs().namespaces.get(dsym.obj_id, None)\n if self_ns is None:\n return\n for ns_child in self_ns.all_data_symbols_this_indentation(exclude_class=True):\n logger.warning('propagate from %s to namespace child %s', dsym, ns_child)\n self._propagate_staleness_to_deps(ns_child)\n\n def _propagate_staleness_to_deps(self, dsym: DataSymbol, skip_seen_check=False):\n if not skip_seen_check and dsym in self.seen:\n return\n self.seen.add(dsym)\n if dsym not in nbs().updated_symbols:\n if dsym.should_mark_stale(self.updated_sym):\n dsym.fresher_ancestors.add(self.updated_sym)\n dsym.required_timestamp = Timestamp.current()\n self._propagate_staleness_to_namespace_parents(dsym, skip_seen_check=True)\n self._propagate_staleness_to_namespace_children(dsym, skip_seen_check=True)\n for child in self._non_class_to_instance_children(dsym):\n logger.warning('propagate %s %s to %s', dsym, dsym.obj_id, child)\n self._propagate_staleness_to_deps(child)\n","sub_path":"nbsafety/data_model/update_protocol.py","file_name":"update_protocol.py","file_ext":"py","file_size_in_byte":7111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"389697842","text":"import time\nimport os, sys\nimport argparse\nfrom argparse import Namespace\nfrom multiprocessing import Process\nfrom typing import Dict, Any, Optional\nimport random\nimport logging\nimport json\n\nimport torch\nfrom torch import nn\nimport numpy as np\n\nimport dopt\nfrom dopt import NEIOptimizer, Trainer, Server\nfrom dopt.utils import get_output_shape\nfrom test_objective_function import run_train_net_kfold # The objective function\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# The configurations\nCONFIG = {}\nCONFIG[\"computer_list\"] = {\n \"acet_update\": ['tst008@acet116-lnx-11.bucknell.edu'], # To git pull\n \"acet\": [\n# 'tst008@acet116-lnx-11.bucknell.edu',\n 'tst008@acet116-lnx-12.bucknell.edu',\n# 'tst008@acet116-lnx-13.bucknell.edu',\n# 'tst008@acet116-lnx-14.bucknell.edu',\n# 'tst008@acet116-lnx-15.bucknell.edu',\n# 'tst008@acet116-lnx-16.bucknell.edu',\n# 'tst008@acet116-lnx-17.bucknell.edu',\n# 'tst008@acet116-lnx-18.bucknell.edu',\n# 'tst008@acet116-lnx-19.bucknell.edu',\n# 'tst008@acet116-lnx-1.bucknell.edu',\n# 'tst008@acet116-lnx-20.bucknell.edu',\n# 'tst008@acet116-lnx-21.bucknell.edu',\n ],\n# \"tung-torch\": ['tung@jvs008-r1.bucknell.edu']\n}\n# Commands to run on target machines here\nCONFIG[\"commands\"] = {\n \"acet_update\": \"cd PycharmProjects/distributed-optimizer/ && git pull\" + \\\n \" && module switch python/3.7-2020-05-28\" + \\\n \" && export LD_LIBRARY_PATH=/usr/remote/lib:/usr/remote/anaconda-3.7-2020-05-28/lib\" + \\\n \" && python3 ~/PycharmProjects/distributed-optimizer/distributed_optimizer_bird.py --run_as trainer\",\n \"acet\": \"sleep 10 && module switch python/3.7-2020-05-28\" + \\\n \" && export LD_LIBRARY_PATH=/usr/remote/lib:/usr/remote/anaconda-3.7-2020-05-28/lib\" + \\\n \" && python3 ~/PycharmProjects/distributed-optimizer/distributed_optimizer_bird-Copy1.py --run_as trainer\",\n \"tung-torch\": \"/opt/anaconda/envs/jupyter37/bin/python ~/pj/dopt_v2/distributed_optimizer_bird.py --run_as trainer --data_folder ~/pj/dopt_v2/data/CroppedYale/\"\n}\n#\n# CONFIG[\"commands\"] = {\n# \"acet\": \"sleep 20 && echo 'Hey'\",\n# \"tung-torch\": \"sleep 20 && echo 'Hey'\"\n# }\nCONFIG[\"server\"] = {\n \"host\": \"jvs008-r1.bucknell.edu\",\n \"port\": 15556,\n \"logging_level\": logging.WARNING\n}\nCONFIG[\"trainer\"] = {\n \"username\": \"tst008\",\n \"num_constraints\": 1\n}\nCONFIG[\"optimizer\"] = {\n \"bounds\": {\n \"x1\": [0, 10],\n \"x2\": [0, 10]\n },\n \"initial_candidates\": [\n {\"x1\": 3, \"x2\": 6},\n {\"x1\": 4, \"x2\": 7}\n ],\n \"device\": \"cpu\",\n \"seed\": 0,\n \"filename\": \"test2.dopt\"\n}\n\n\ndef get_feasibility(candidate) -> float:\n x1, x2, _ = candidate.values()\n return -(x1 - x2 + 1.5)\n \ndef objective_function_torch_input(X):\n BASE_VAR = 0.1\n \n X = -X.view(-1, 2)\n mask_constraint = X[...,0] - X[...,1] + 1.5 > 0\n cos_x = torch.cos(X[...,0])\n sin_y = torch.sin(X[...,1])\n first_term = sin_y * torch.exp((1-cos_x)**2)\n second_term = cos_x * torch.exp((1-sin_y)**2)\n third_term = (X[...,0] - X[...,1])**2\n result = -(first_term + second_term + third_term) \n Y = ((result + 120) / 230) #* mask_constraint \n # Add noise\n se = torch.norm(X, dim=-1, keepdim=True) * 0.02\n Yvar = BASE_VAR + se * torch.rand_like(se)\n true_var = BASE_VAR + se\n Y = Y.view(-1, 1, 1) + torch.rand_like(se) * Yvar\n return Y, Yvar.view_as(Y)**2, true_var.view_as(Y)**2\n \n# Plug in the objective function here\ndef objective_function(candidate, logger):\n time.sleep(random.randint(60, 90))\n logger.info(json.dumps(candidate))\n feasibility = get_feasibility(candidate)\n if feasibility > 0:\n logger.info(\"Infeasible!\")\n observation = {\n \"objective\": [0.001, 0.001],\n \"constraints\": [feasibility]\n }\n return observation\n logger.info(\"Returning the observation\")\n \n # Simulate input\n X = torch.tensor([candidate[\"x1\"], candidate[\"x2\"]], dtype=float)\n Y, Yvar, _ = objective_function_torch_input(X)\n mean, variance = Y.item(), Yvar.item()\n observation = {\n \"objective\": [mean, variance],\n \"constraints\": [feasibility]\n }\n return observation\n\n \n# Calls start_optimizer and start_trainers simultaneously\ndef start_server():\n optimizer = NEIOptimizer(\n CONFIG[\"optimizer\"][\"filename\"], \n CONFIG[\"optimizer\"][\"bounds\"], \n initial_candidates=CONFIG[\"optimizer\"][\"initial_candidates\"],\n device=CONFIG[\"optimizer\"][\"device\"],\n seed=CONFIG[\"optimizer\"][\"seed\"]\n )\n server = Server(optimizer, CONFIG, logging_level=CONFIG[\"server\"][\"logging_level\"])\n server.run()\n \ndef start_trainers():\n trainer = Trainer(\n objective_function, \n CONFIG[\"trainer\"][\"username\"],\n CONFIG[\"server\"][\"host\"],\n CONFIG[\"server\"][\"port\"],\n num_constraints=CONFIG[\"trainer\"][\"num_constraints\"]\n )\n trainer.run()\n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(prog='distributed_optimizer.py',\n description='''Optimize objective function of specified by a `Trainer`''')\n parser.add_argument('--run_as', action='store', dest='run_as',\n help='Specify the role of the machine (server or trainer). Defaults to server',\n type=str, required=False,\n default=\"server\")\n parser.add_argument('--data_folder', action='store', dest='data_folder',\n help='Specify the directory to the data folder (for clients only)',\n type=str, required=False,\n default=\"~/PycharmProjects/summer/data/CroppedYale/\")\n args = parser.parse_args()\n \n # Can modify these code to accomodate more options\n # E.g. Run different Trainers on same task\n if args.run_as == \"server\":\n start_server()\n elif args.run_as == \"trainer\":\n start_trainers()\n \n \n \n","sub_path":"distributed_optimizer_bird-Copy1.py","file_name":"distributed_optimizer_bird-Copy1.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"629606794","text":"from os.path import join\n\nimport numpy as np\nimport pandas as pd\n\n\ndef return_filtered_and_normed(signal, delta, type='min'):\n # TODO: comment\n l_smooth = signal.rolling(window=delta, center=True).mean().dropna()\n if type == 'min':\n l_norm = (l_smooth - l_smooth.min()) / (l_smooth.max() - l_smooth.min())\n else:\n l_norm = l_smooth / l_smooth.max()\n\n return l_norm\n\n\n# TODO: to be removed?\ndef retrieve_load_data_partitions(path_load_data, date_slice, alpha, delta, regions, norm_type):\n \"\"\"Allows to get load for a whole region or per subregion\"\"\"\n dict_regions = {'EU': ['AT', 'BE', 'CH', 'DE', 'DK', 'ES',\n 'FR', 'UK', 'IE', 'IT', 'LU',\n 'NL', 'PT', 'SE', 'CZ',\n 'BG', 'CH', 'EE',\n 'FI', 'EL', 'HR', 'HU', 'LT', 'LV', 'PL', 'RO', 'SI', 'SK'],\n 'CWE': ['FR', 'BE', 'LU', 'NL', 'DE'],\n 'BL': ['BE', 'LU', 'NL']} # TODO: BL is actually also the code of country\n\n load_data = pd.read_csv(join(path_load_data, 'load_opsd_2015_2018.csv'), index_col=0)\n # load_data.index = pd.date_range('2015-01-01T00:00', '2018-12-31T23:00', freq='H')\n load_data.index = pd.to_datetime(load_data.index)\n\n print(load_data)\n exit()\n\n load_data_sliced = load_data.loc[date_slice[0]:date_slice[1]]\n\n # Adding the stand-alone regions to load dict.\n standalone_regions = list(load_data.columns)\n for region in standalone_regions:\n dict_regions.update({str(region): str(region)})\n\n if alpha == 'load_central':\n\n # Extract lists of load subdivisions from load_dict.\n # e.g.: for regions ['BL', 'DE'] => ['BE', 'NL', 'LU', 'DE']\n regions_list = []\n for key in regions:\n if isinstance(dict_regions[key], str):\n regions_list.append(str(dict_regions[key]))\n elif isinstance(dict_regions[key], list):\n regions_list.extend(dict_regions[key])\n else:\n raise TypeError('Check again the type. Should be str or list.')\n\n load_vector = load_data_sliced[regions_list].sum(axis=1)\n\n elif alpha == 'load_partition':\n\n if regions in standalone_regions:\n load_vector = load_data_sliced[dict_regions[regions]]\n else:\n load_vector = load_data_sliced[dict_regions[regions]].sum(axis=1)\n\n load_vector_norm = return_filtered_and_normed(load_vector, delta, norm_type)\n\n return load_vector_norm\n\n\ndef resource_quality_mapping(cap_factor_df, delta, measure):\n # TODO: comment\n\n cap_factor_rolling = cap_factor_df.rolling(delta, center=True)\n\n if measure == 'mean':\n cap_factor_per_window_df = cap_factor_rolling.mean().dropna()\n elif measure == 'median':\n cap_factor_per_window_df = cap_factor_rolling.median().dropna()\n\n else:\n raise ValueError(' Measure {} is not available.'.format(str(measure)))\n\n return cap_factor_per_window_df\n\n\ndef critical_window_mapping(cap_factor_per_window_df, alpha, delta, regions, load_df, norm_type):\n # TODO: comment\n\n if alpha == 'load_central':\n\n load_df_sum = load_df.sum(axis=1)\n alpha_reference = return_filtered_and_normed(load_df_sum, delta, norm_type).to_frame()\n critical_windows = cap_factor_per_window_df.gt(alpha_reference.values).astype(int)\n\n return critical_windows\n\n elif alpha == 'load_partition':\n\n # TODO: update or remove\n for region, tech in key_list:\n l_norm = retrieve_load_data_partitions(path_load_data, date_slice, alpha, delta, region, norm_type)\n # Flip axes.\n alpha_reference = l_norm[:, np.newaxis]\n\n # Select region of interest within the dict value with 'tech' key.\n critical_windows = (input_dict[region][tech] > alpha_reference).astype(int)\n output_dict[region][tech] = critical_windows\n\n else:\n raise ValueError('No such alpha rule. Retry.')\n\n return output_dict\n","sub_path":"resite/models/complementarity/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"318156729","text":"import sys\nimport numpy as np\nfrom collections import Counter\nfrom statistics import stdev\nfrom scipy.spatial.distance import cityblock\n\ndef normalise(data, test_data):\n max = np.max(data[:,:-1])\n data[:,:-1] = data[:,:-1]/max\n max = np.max(test_data[:,:-1])\n test_data[:,:-1] = test_data[:,:-1]/max\n return data, test_data\n\ndef nearest_neighbor(train_data, test_data, k):\n object_id = 1\n accuracy = []\n for predict in test_data:\n distance = []\n for data in train_data:\n temp_dist =cityblock(np.array(data[:-1]) , np.array(predict[:-1]))\n distance.append((temp_dist,data[-1]))\n votes = [i[1] for i in sorted(distance)[:k]]\n predicted_class = Counter(votes).most_common(1)[0][0]\n votes = np.asarray(votes)\n print(object_id, votes)\n if len(np.unique(votes)) == k:\n if predict[-1] in votes:\n accuracy.append(1/k)\n else:\n accuracy.append(0)\n else:\n accuracy.append(1) if predicted_class == predict[-1] else accuracy.append(0)\n #print('ID=%5d, predicted=%3d, true=%3d, accuracy=%4.2f'% (object_id, predicted_class, predict[-1], accuracy[-1]));\n object_id += 1\n print('classification accuracy=%6.2f'%(sum(accuracy)/len(accuracy)*100))\n\nif __name__ == '__main__':\n train_data,test_data = normalise(np.loadtxt(sys.argv[1]),np.loadtxt(sys.argv[2]) )\n data = np.loadtxt(sys.argv[1])\n k = int(sys.argv[3])\n print(len(train_data[0])-1)\n print(train_data.shape)\n nearest_neighbor(train_data, test_data, k)\n","sub_path":"kNN/knn_classift_opt.py","file_name":"knn_classift_opt.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"109379075","text":"from pygameJoystick import pyGameJoystick\nfrom roboSocketCom import RoboSocketCom\nfrom jsonController import jsonController\nfrom webSocketsOpencvServer import WebSocketsOpencvServer\nimport json,pygame,time,asyncio,websockets,threading\n\n\ndef SocketsOpencv(ipAdress,port):\n WebSocketsOpencvServer(serverHost=ipAdress,serverPort=port)\n\nif __name__ == '__main__':\n try:\n socketsOpencv =threading.Thread(target=SocketsOpencv,args=(\"0.0.0.0\",5001,))\n socketsOpencv.run()\n except threading.ThreadError as exp:\n print(\"WebSocketsOpencvServer Thread ta bir sorun ile karşılaşıldı...\",exp)\n try:\n pygame.init()\n joystcik = pyGameJoystick(pyGame=pygame)\n except Exception as exp:\n print(\"joytcik veya pygame başlatılırken bir sorun çıktı sorun... : \", exp)\n try:\n roboSocketCom = RoboSocketCom(clientHost=\"172.19.96.227\", clientPort=5000)\n except Exception as exp:\n print(\"RoboSocketCom sunucuya bağlanma işlemi başlatılırken bir sorun çıktı sorun... hata kodu : \", exp)\n\n try:\n json_Controller = jsonController(joyStick=joystcik, roboSocketCom=roboSocketCom)\n except Exception as exp:\n print(\"jsonController başlatılırken bir sorun çıktı sorun... hata kodu : \", exp)\n\n","sub_path":"Rover - ver2.3/Controller-PC/loopPC.py","file_name":"loopPC.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"217511436","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport os\nimport sys\nfrom datetime import datetime\nimport requests\n\n\nlogging.basicConfig()\nlogger = logging.getLogger(\"task\")\nfile_handler = logging.FileHandler(\"log/task.log\")\nfile_handler.setFormatter(logging.Formatter(\"%(asctime)s %(levelname)s %(message)s\"))\nlogger.addHandler(file_handler)\nlogger.setLevel(logging.DEBUG)\n\n\ndef run_task(func, task_name='task', **kwargs):\n try:\n d1 = datetime.now()\n func(**kwargs)\n d2 = datetime.now()\n logger.debug('task[%s] cost %ss' % (task_name, (d2 - d1).__str__()))\n except Exception as ex:\n logger.debug('task[%s] error' % (task_name, ))\n logger.exception(ex)\n\n\nif __name__ == '__main__':\n\n logger.debug('start task %s %s' % (sys.argv[1:].__str__(), datetime.now().__str__()))\n if len(sys.argv) > 1:\n t = __import__('apps.%s.sub_task' % sys.argv[1], fromlist=[''])\n t.run(sys.argv[1:])","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"147440068","text":"import os\nimport shutil\nimport subprocess\nimport math\n\nfrom datetime import datetime\nfrom PIL import Image, ImageDraw\nfrom dataclasses import dataclass\nfrom typing import Tuple, List\nfrom random import randint, uniform, choice, random\n\nCOLORS = ['#F0CA4D',\n '#324d5c', \n '#f2a336',\n '#BD9E20',\n '#0A1C28',\n '#EEE9D1',\n '#333741',\n '#F1EAD1',\n '#424142',\n '#BFB7A8',\n '#111826',\n '#F0EBEF',\n '#1477B2',\n '#0C3F60',\n '#12537E' ]\n\nBLUES = [ '#060B23',\n '#162137',\n '#27374B',\n '#374D5F',\n '#486373',\n '#597987',\n '#698F9B',\n '#7AA5AF',\n '#8ABBC3',\n '#9BD1D7',\n '#ACE8EC',]\n\nRED_ORANGES = [\n '#E36D60',\n '#DB6860',\n '#D46461',\n '#CD6062',\n '#C65C63',\n '#BF5864',\n '#B85364',\n '#B14F65',\n '#AA4B66',\n '#A34767',\n '#9C4368',\n]\n\nEARTH_WORM = [\n'#CA6671',\n'#C46771',\n'#BF6972',\n'#B96B73',\n'#B46C74',\n'#AE6E75',\n'#A97076',\n'#A37177',\n'#9E7378',\n'#987579',\n'#93777A',\n'#7E4047', \n'#80454C', \n'#824B51', \n'#845056', \n'#86565B', \n'#885B60', \n'#8A6165', \n'#8C666A', \n'#8E6C6F', \n'#907174', \n'#93777A', \n'#7E4047',\n'#854950',\n'#8D535A',\n'#945D64',\n'#9C676D',\n'#A47177',\n'#AB7B81',\n'#B3858A',\n'#BA8F94',\n'#C2999E',\n'#CAA3A8',\n'#4B262A',\n'#573236',\n'#643F43',\n'#714B4F',\n'#7D585C',\n'#8A6469',\n'#977175',\n'#A37D82',\n'#B08A8E',\n'#BD969B',\n'#CAA3A8',\n]\n\nBLUE_WITH_A_TASTE_OF_YELLOW = BLUES + [ '#f48b00', '#c98a2d', 'black', 'white']\n\ndef random_color(): \n return (randint(0, 255), randint(0, 255), randint(0, 255))\n\ndef random_curve():\n return uniform(-20, 20)\n\ndef random_fill():\n return randint(0, len(COLORS)-1)\n\ndef random_grey():\n thing = randint(0, 255)\n return (thing, thing, thing)\n\ndef random_green():\n return (randint(0, 100), randint(150, 255), randint(0, 100))\n\ndef random_angle(): \n return randint(180, 360)\n\ndef whites(num):\n return [\"white\" for _ in range(num)]\n\ndef random_blue():\n return choice(BLUES + RED_ORANGES+COLORS+whites(10))\n\ndef yellowish():\n base = randint(0,168)\n return (base + 87, base + 56, base)\n\nSO_MANY_CHOICES = BLUES + RED_ORANGES + [random_grey() for _ in range(30)] + COLORS\nR_N_B = BLUES + whites(100)\n\n@dataclass\nclass Circle: \n radius: float\n location: Tuple[int, int]\n angle: int = 0\n fill = 0\n active: bool = True\n curve: int = 0\n oob_deactiavte = False\n history = []\n\n def __post_init__(self):\n self.angle = random_angle()\n self.curve = random_curve()\n self.fill = random_fill()\n self.history = []\n\n @property\n def x(self):\n return self.location[0]\n\n @property\n def y(self):\n return self.location[1]\n\n def draw(self): \n if not self.active:\n return\n #DRAW.ellipse((self.x - self.radius, \n #self.y - self.radius,\n #self.x + self.radius,\n #self.y + self.radius), fill=random_blue())\n self.history.append(((self.x - self.radius, self.y - self.radius, self.x + self.radius, self.y + self.radius), 'white'))#choice(R_N_B)))\n\n def really_draw(self): \n if self.oob_deactiavte:\n return\n out = yellowish()\n for thing in self.history:\n DRAW.ellipse(thing[0], fill=thing[1], outline=out)\n\n def maybe_deactivate(self):\n # If we are above 10% of the max we have a chance to deactivate\n if self.x > IMAGE_WIDTH*.97 or self.x < IMAGE_WIDTH * .03:\n if random() > .9:\n self.active = False\n self.oob_deactiavte = True\n if self.y > IMAGE_HEIGHT*.9 or self.y < IMAGE_HEIGHT * .1:\n if random() > .9:\n self.active = False\n self.oob_deactiavte = True\n\n\n def step(self):\n if not self.active:\n return\n step = self.radius/2\n rad_angle = math.radians(self.angle)\n self.location = (self.x + step*math.cos(rad_angle), \n self.y + step*math.sin(rad_angle))\n self.angle += self.curve\n\n # Maybe decrease radius\n if randint(0, 100) > 70:\n self.radius -= 1\n #if randint(0, 100) > 99:\n #self.radius += 5\n #Maybe change our rotation\n if randint(0, 100) > 79:\n self.curve = random_curve()\n\n self.maybe_deactivate()\n if self.x + self.radius >= IMAGE_WIDTH or self.x - self.radius <= 0:\n self.active = False\n self.oob_deactiavte = True\n if self.y + self.radius >= IMAGE_HEIGHT or self.y - self.radius <= 0:\n self.active = False\n self.oob_deactiavte = True\n if self.radius <= 0:\n self.active = False\n\n# Get the current time, use it as the directory we save everything in\nSAVE_DIR = datetime.now().strftime(\"%Y-%m-%d %H.%M.%S\")\nos.mkdir(SAVE_DIR)\nshutil.copy(__file__, SAVE_DIR) # Save a copy of this script so that we can recreate stuff\n\n# The size of the image\nIMAGE_WIDTH = 2000\nIMAGE_HEIGHT = 2000\n# Create a new image\nCURRENT_IMAGE = Image.new('RGB', (IMAGE_WIDTH, IMAGE_HEIGHT), color=random_grey())\nDRAW = ImageDraw.Draw(CURRENT_IMAGE)\n\n# Missing: initial setup\ncircles = []\nfor _ in range(100):\n rad = randint(10, 30)\n #x = randint(2*rad, IMAGE_WIDTH-2*rad)\n #y = randint(2*rad, IMAGE_HEIGHT-2*rad)\n x = IMAGE_WIDTH/2\n y = IMAGE_HEIGHT/2\n circles.append(Circle(rad, (x, y)))\n\nfor c in circles:\n while c.active:\n c.draw()\n c.step()\n c.really_draw()\n\nCURRENT_IMAGE.show()\nCURRENT_IMAGE.save(os.path.join(SAVE_DIR, \"{}.png\".format(\"final\")))","sub_path":"2018-05-14 23.45.01/circles.py","file_name":"circles.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"645497635","text":"# Copyright (C) 2010,2011 Linaro Limited\n#\n# Author: Zygmunt Krynicki \n#\n# This file is part of lava-dashboard-tool.\n#\n# lava-dashboard-tool is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License version 3\n# as published by the Free Software Foundation\n#\n# lava-dashboard-tool 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 Lesser General Public License\n# along with lava-dashboard-tool. If not, see .\n\n\"\"\"\nUnit tests for the launch_control.commands package\n\"\"\"\n\nfrom unittest import TestCase\n\nfrom lava_dashboard_tool.commands import XMLRPCCommand\n\n\nclass XMLRPCCommandTestCase(TestCase):\n\n def test_construct_xml_rpc_url_preserves_path(self):\n self.assertEqual(\n XMLRPCCommand._construct_xml_rpc_url(\"http://domain/path\"),\n \"http://domain/path/xml-rpc/\")\n self.assertEqual(\n XMLRPCCommand._construct_xml_rpc_url(\"http://domain/path/\"),\n \"http://domain/path/xml-rpc/\")\n\n def test_construct_xml_rpc_url_adds_proper_suffix(self):\n self.assertEqual(\n XMLRPCCommand._construct_xml_rpc_url(\"http://domain/\"),\n \"http://domain/xml-rpc/\")\n self.assertEqual(\n XMLRPCCommand._construct_xml_rpc_url(\"http://domain\"),\n \"http://domain/xml-rpc/\")\n","sub_path":"lava_dashboard_tool/tests/test_commands.py","file_name":"test_commands.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"318074611","text":"# coding=utf-8\nfrom __future__ import division, absolute_import, print_function, unicode_literals\nimport unittest\nfrom .core import get_app\n\nURLS = [\n '/',\n '/about',\n '/cfp',\n '/login',\n '/metrics'\n]\n\n\nclass BasicTestCase(unittest.TestCase):\n\n def setUp(self):\n self.client, self.app, self.db = get_app()\n\n def test_url(self):\n for url in URLS:\n rv = self.client.get(url)\n assert rv.status_code == 200, \"Fetching %s results in HTTP 200\" % url\n","sub_path":"tests/test_basic.py","file_name":"test_basic.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"328167833","text":"# IMPORTS ####################################################\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams.update({'figure.max_open_warning': 0})\n\nimport pandas as pd\nimport seaborn as sns\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom IPython import display\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.utils.class_weight import compute_class_weight\nfrom torch.utils.data import TensorDataset\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nfrom sklearn.cluster import KMeans\n\nfrom sklearn import metrics\nfrom sklearn.preprocessing import LabelBinarizer\nimport statistics\nfrom statistics import mean\nfrom scipy.stats import entropy\n\nimport pdb\n\nimport argparse\n\ntorch.manual_seed(1)\nnp.random.seed(7)\nsns.set(style=\"white\", palette=\"muted\", color_codes=True, context=\"talk\")\n\nimport warnings\nfrom sklearn.exceptions import DataConversionWarning\nwarnings.filterwarnings(action='ignore', category=DataConversionWarning)\nwarnings.filterwarnings(action='ignore', category=UserWarning)\n\n# hyperparameters and parser\nlambdas = 100\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--outputfile', required=True, type=int, help='number for c1 trial')\nparser.add_argument('--n', required=True, type=int, help='number of clusters')\n\nparams = parser.parse_args()\n\nmy_n = params['n']\nmy_trial = params['outputfile']\n\nprint(f\"my_trail #: {my_trial}\")\n\n# open output file\nfile1 = open(f\"output/clustering/clustering_{my_trial}/output_c1.txt\",\"w\")\n\n# LOAD DATA ####################################################\n\ndef load_ICU_data(path, n):\n column_names = ['age', 'workclass', 'fnlwgt', 'education', 'education_num',\n 'martial_status', 'occupation', 'relationship', 'race', 'sex',\n 'capital_gain', 'capital_loss', 'hours_per_week', 'country', 'target']\n input_data = (pd.read_csv(path, names=column_names,\n na_values=\"?\", sep=r'\\s*,\\s*', engine='python'))\n \n # targets: 1 when someone makes over 50k , otherwise 0\n y = (input_data['target'] == '>50K').astype(int)\n\n # x featues: including protected classes\n X = (input_data\n .drop(columns=['target', 'fnlwgt'])\n .fillna('Unknown')\n .pipe(pd.get_dummies))\n\n # z features:\n Z_race = X[['race_Amer-Indian-Eskimo',\n 'race_Asian-Pac-Islander',\n 'race_Black',\n 'race_Other',\n 'race_White']]\n Z_race = Z_race.rename(columns = {'race_Amer-Indian-Eskimo':0,\n 'race_Asian-Pac-Islander':1,\n 'race_Black':2,\n 'race_Other':3,\n 'race_White':4})\n\n Z_sex = X[['sex_Female','sex_Male']]\n Z_sex = Z_sex.rename(columns = {'sex_Female':0,'sex_Male':1})\n\n X = X.drop(columns = ['race_Amer-Indian-Eskimo','race_Asian-Pac-Islander','race_Black','race_Other','race_White', 'sex_Female','sex_Male'])\n\n n_clusters = n\n Kmean1 = KMeans(n_clusters=n_clusters)\n Kmean1.fit(X)\n b = np.zeros((X.shape[0],n_clusters))\n b[np.arange(X.shape[0]),Kmean1.labels_] = 1\n Z_c1 = pd.DataFrame(b)\n\n n_clusters = 4\n Kmean2 = KMeans(n_clusters=n_clusters)\n Kmean2.fit(X)\n c = np.zeros((X.shape[0],n_clusters))\n c[np.arange(X.shape[0]),Kmean2.labels_] = 1\n Z_c2 = pd.DataFrame(c)\n \n return X, y, Z_race, Z_sex, Z_c1, Z_c2\n\n# load ICU data set\nX, y, Z_race, Z_sex, Z_c1, Z_c2 = load_ICU_data('data/adult.data', my_n)\n\n# split into train/test set\n(X_train, X_test, y_train, y_test, _, Z_test_race, _, Z_test_sex, Z_train_c1, Z_test_c1, _, Z_test_c2) = train_test_split(X, y, Z_race, Z_sex, Z_c1, Z_c2, test_size=0.5, stratify=y, random_state=7)\n \nZ_sets = [Z_test_sex, Z_test_race, Z_test_c1, Z_test_c2]\nZ_sets_names = ['Z_test_sex', 'Z_test_race', 'Z_test_c1', 'Z_test_c2'] \n\nfile1.writelines([f\"features X: {X.shape[0]} samples, {X.shape[1]} attributes \\n\",\n f\"targets y: {y.shape} samples \\n\",\n f\"sensitives Z_train_c1: {Z_train_c1.shape[0]} samples, {Z_train_c1.shape[1]} attributes \\n\",\n f\"sensitives Z_test_race: {Z_test_race.shape[0]} samples, {Z_test_race.shape[1]} attributes \\n\",\n f\"sensitives Z_test_sex: {Z_test_sex.shape[0]} samples, {Z_test_sex.shape[1]} attributes \\n\",\n f\"sensitives Z_test_c1: {Z_test_c1.shape[0]} samples, {Z_test_c1.shape[1]} attributes \\n\",\n f\"sensitives Z_test_c2: {Z_test_c2.shape[0]} samples, {Z_test_c2.shape[1]} attributes \\n\"])\n\n# standardize the data\nscaler = StandardScaler().fit(X_train)\nscale_df = lambda df, scaler: pd.DataFrame(scaler.transform(df), \n columns=df.columns, index=df.index)\nX_train = X_train.pipe(scale_df, scaler) \nX_test = X_test.pipe(scale_df, scaler)\n\nclass PandasDataSet(TensorDataset):\n\n def __init__(self, *dataframes):\n tensors = (self._df_to_tensor(df) for df in dataframes)\n super(PandasDataSet, self).__init__(*tensors)\n\n def _df_to_tensor(self, df):\n if isinstance(df, pd.Series):\n df = df.to_frame('dummy')\n return torch.from_numpy(df.values).float()\n\ntrain_data = PandasDataSet(X_train, y_train, Z_train_c1)\ntest_data = PandasDataSet(X_test, y_test, Z_test_c1, Z_test_c2, Z_test_race, Z_test_sex)\n\ntrain_loader = DataLoader(train_data, batch_size=32, shuffle=True, drop_last=True)\n\nfile1.writelines([f\"# training samples: {len(train_data)} \\n\",f\"# batches: {len(train_loader)} \\n\"])\nfile1.writelines(\"\\n\")\n\n# HELPER FUNCTIONS ####################################################\ndef p_rule(y_pred, protected, Z_test, threshold = 0.5):\n p_rule_out = []\n for i in range(Z_test.shape[1]):\n with warnings.catch_warnings():\n warnings.simplefilter(action='ignore', category=FutureWarning)\n y_z_i = y_pred[np.array(protected) == i] > threshold if threshold else y_pred[np.array(protected) == i]\n y_z_all = y_pred[np.array(protected) != i] > threshold if threshold else y_pred[np.array(protected) != i]\n odds = y_z_i.mean() / y_z_all.mean()\n p_rule_out.append(min(odds, 1./odds) * 100)\n return p_rule_out\n\ndef plot_distributions(y_true, Z_true, y_pred, name, image_name, Z_pred = None, epoch=None):\n fig, axes = plt.subplots(figsize=(8, 5))\n \n protected = []\n for _, row in Z_true.iterrows():\n protected.append(row[row == 1].index[0])\n \n subplot_df = (\n Z_true\n .assign(protected=protected)\n .assign(y_pred=y_pred))\n _subplot(subplot_df, protected,\n name, ax = axes)\n _performance_text(fig, y_true, Z_true, y_pred, name, image_name, protected, Z_pred, epoch)\n fig.tight_layout()\n return fig\n\ndef _subplot(subplot_df, col, name, ax):\n for label, df in subplot_df.groupby(col):\n sns.kdeplot(df['y_pred'].fillna(0), ax=ax, label=df['protected'].iloc[0], shade=True)\n ax.set_title(f'Sensitive attribute: {name}')\n ax.set_xlim(0, 1)\n ax.set_ylim(0, 7)\n ax.set_yticks([])\n ax.set_ylabel('Prediction distribution')\n ax.set_xlabel(r'$P({{income>50K}}|z_{{{}}})$'.format(name))\n\ndef _performance_text(fig, y_test, Z_test, y_pred, name, image_name, protected, Z_pred=None, epoch=None):\n\n file1.writelines(f\"{image_name}_{name} \\n\")\n file1.writelines(\"\\n\")\n \n clf_roc_auc = metrics.roc_auc_score(y_test, y_pred)\n clf_accuracy = metrics.accuracy_score(y_test, y_pred > 0.5) * 100\n p_rule_out = p_rule(y_pred, protected, Z_test)\n for i in range(Z_test.shape[1]):\n file1.writelines(f\"Class {i}: {round(p_rule_out[i],2)} \\n\")\n \n file1.writelines([f\"overall_min: {round(np.array(p_rule_out).min(),2)} \\n\", f\"overall_mean: {round(np.array(p_rule_out).mean(),2)} \\n\"])\n\n file1.writelines(\"\\n\")\n file1.writelines([\"Classifier performance: \\n\",f\"- ROC AUC: {clf_roc_auc:.2f} \\n\", f\"- Accuracy: {clf_accuracy:.1f} \\n\"])\n file1.writelines(\"\\n\")\n \n if Z_pred is not None:\n adv_roc_auc = multiclass_roc_auc_score(Z_test, Z_pred)\n file1.writelines([\"Adversary performance: \\n\",f\"- ROC AUC: {adv_roc_auc:.2f} \\n\"])\n file1.writelines(\"\\n\")\n\ndef multiclass_roc_auc_score(y_test, y_pred, average=\"macro\"):\n lb = LabelBinarizer()\n lb.fit(y_test)\n y_test = lb.transform(y_test)\n y_pred = lb.transform(classify(y_pred))\n return metrics.roc_auc_score(y_test, y_pred, average=average)\n\ndef classify(y_pred):\n y_pred_out = y_pred\n r = 0\n for _, row in y_pred.iterrows():\n row_max = row.max()\n for c in range(len(row)):\n y_pred_out.at[r,c] = (int(0) if row[c] < row_max else int(1))\n r += 1\n return y_pred_out\n\ndef test(image_name):\n i = 0\n for Z_test, Z_test_name in zip(Z_sets, Z_sets_names):\n print(i)\n adv = Adversary(n_features = 1, n_sensitive = Z_test.shape[1])\n \n with torch.no_grad():\n pre_clf_test = clf(test_data.tensors[0])\n pre_adv_test = adv(pre_clf_test)\n\n y_pre_clf = pd.Series(pre_clf_test.data.numpy().ravel(),\n index=y_test.index)\n y_pre_adv = pd.DataFrame(pre_adv_test.numpy())\n \n fig = plot_distributions(y_test, Z_test, y_pre_clf, Z_test_name, image_name, y_pre_adv)\n fig.savefig('output/clustering/clustering_{}/{}_{}.png'.format(my_trial, image_name, Z_test_name))\n\ndef average(my_list):\n total = 0\n for i in my_list: total += i\n return float(total)/float(len(my_list))\n \n \n# PRETRAIN CLASSIFIER ####################################################\n\nclass Classifier(nn.Module):\n\n def __init__(self, n_features, n_hidden=32, p_dropout=0.2):\n super(Classifier, self).__init__()\n self.network = nn.Sequential(\n nn.Linear(n_features, n_hidden),\n nn.ReLU(),\n nn.Dropout(p_dropout),\n nn.Linear(n_hidden, n_hidden),\n nn.ReLU(),\n nn.Dropout(p_dropout),\n nn.Linear(n_hidden, n_hidden),\n nn.ReLU(),\n nn.Dropout(p_dropout),\n nn.Linear(n_hidden, 1),\n )\n\n def forward(self, x):\n return torch.sigmoid(self.network(x))\n\nclf = Classifier(n_features=X.shape[1])\nclf_criterion = nn.BCELoss()\nclf_optimizer = optim.Adam(clf.parameters())\n\ndef pretrain_classifier(clf, data_loader, optimizer, criterion):\n for x, y, _ in data_loader:\n clf.zero_grad()\n p_y = clf(x)\n loss = criterion(p_y, y)\n loss.backward()\n optimizer.step()\n return clf\n\nN_CLF_EPOCHS = 2\n\nfor epoch in range(N_CLF_EPOCHS):\n clf = pretrain_classifier(clf, train_loader, clf_optimizer, clf_criterion)\n\n# PRETRAIN ADVERSARY ####################################################\n\nclass Adversary(nn.Module):\n\n def __init__(self, n_features, n_sensitive, n_hidden=32):\n super(Adversary, self).__init__()\n self.network = nn.Sequential(\n nn.Linear(n_features, n_hidden),\n nn.ReLU(),\n nn.Linear(n_hidden, n_hidden),\n nn.ReLU(),\n nn.Linear(n_hidden, n_hidden),\n nn.ReLU(),\n nn.Linear(n_hidden, n_sensitive),\n )\n\n def forward(self, x):\n return torch.sigmoid(self.network(x)) \n\n\ndef pretrain_adversary1(adv, clf, data_loader, optimizer, criterion, lambdas):\n for x, _, z1 in data_loader:\n p_y = clf(x).detach()\n adv.zero_grad()\n p_z = adv(p_y) \n loss = (criterion(p_z, z1) * lambdas).mean() \n loss.backward()\n optimizer.step()\n return adv\n\nadv1 = Adversary(n_features = 1, n_sensitive = Z_train_c1.shape[1])\nadv_criterion = nn.BCELoss(reduce=False)\nadv1_optimizer = optim.Adam(adv1.parameters(), lr = 0.02, eps = 10e-9)\n\nN_ADV_EPOCHS = 5\n\nfor epoch in range(N_ADV_EPOCHS):\n adv1 = pretrain_adversary1(adv1, clf, train_loader, adv1_optimizer, adv_criterion, lambdas)\n\n# TRAIN AND TEST ####################################################\n\n# before training: baseline\ntest('baseline')\n\ndef train(clf, adv1, data_loader, clf_criterion, adv_criterion,\n clf_optimizer, adv1_optimizer, lambdas):\n \n # Train adversary\n adv_losses = []\n for x, y, z1 in data_loader:\n p_y = clf(x)\n adv1.zero_grad()\n p_z1 = adv1(p_y)\n loss_adv = (adv_criterion(p_z1, z1) * lambdas).mean()\n adv_losses.append(loss_adv)\n loss_adv.backward()\n adv1_optimizer.step()\n \n # Train classifier on a single batch\n clf_losses = []\n entropies = []\n for x, y, z1 in data_loader:\n pass\n p_y = clf(x)\n p_z1 = adv1(p_y)\n for p_z1_i in p_z1:\n entropies.append(entropy(p_z1_i.detach()))\n clf.zero_grad()\n loss_adv = (adv_criterion(p_z1, z1) * lambdas).mean()\n clf_loss = clf_criterion(p_y, y) - loss_adv # minimax loss\n clf_losses.append(clf_loss)\n clf_loss.backward()\n clf_optimizer.step()\n\n return clf, adv1, average(adv_losses), average(clf_losses), average(entropies)\n\nN_EPOCH_COMBINED = 165\n\nplt_adv_loss = []\nplt_clf_loss = []\nz_entropies = []\n\nfor epoch in range(1, N_EPOCH_COMBINED):\n \n clf, adv1, adv_loss, clf_loss, z_entropy = train(clf, adv1, train_loader, clf_criterion, adv_criterion,\n clf_optimizer, adv1_optimizer, lambdas)\n\n plt_adv_loss.append(adv_loss)\n plt_clf_loss.append(clf_loss)\n z_entropies.append(z_entropy)\n \n with torch.no_grad():\n clf_pred = clf(test_data.tensors[0])\n adv_pred1 = adv1(clf_pred)\n\n print(epoch)\n \nplt.figure()\nplt.savefig(f'output/clustering/clustering_{my_trial}/entropy_fig.png')\n\nplt.figure()\nplt.savefig(f'output/clustering/clustering_{my_trial}/clf_loss_fig.png')\n\nplt.figure()\nplt.savefig(f'output/clustering/clustering_{my_trial}/adv_loss_fig.png')\n\n# after training: results\ntest('output')\n\nfile1.close()\n","sub_path":"fairness-c1-v1.py","file_name":"fairness-c1-v1.py","file_ext":"py","file_size_in_byte":14538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"211371975","text":"from queue import Queue\nfrom GraphAL import GraphAL, DisjointSetForest\n\n\ndef topological(graph):\n all_in_degrees = []\n sorted_results = []\n q = Queue()\n for i in range(GraphAL.get_num_vertices(graph)):\n all_in_degrees.append(GraphAL.get_vertex_in_degree(graph, i))\n # print(\"in >>>>>>\", all_in_degrees)\n\n for i in range(len(all_in_degrees)):\n if all_in_degrees[i] == 0:\n q.put(i)\n\n while not q.empty():\n u = q.get()\n sorted_results.append(u)\n for i in range(len(graph.adj_list)):\n all_in_degrees[i] -= 1\n if all_in_degrees[i] == 0:\n q.put(i)\n if len(sorted_results) != graph.get_num_vertices():\n return None\n\n print(\" Topological: \", sorted_results)\n\n\ndef k(graph):\n dsf = DisjointSetForest\n\n if graph.adj_list is None:\n return None\n edges = []\n for i in range(len(graph.adj_list)):\n temp = graph.adj_list[i]\n while temp is not None:\n edges.append([i, temp.item, temp.weight])\n temp = temp.next\n edges.sort(key=lambda tup: tup[2])\n\n print(\" Kruskal: \", edges)\n\n\ndef main():\n graph = GraphAL(initial_num_vertices=6, is_directed=True)\n graph_2 = GraphAL(initial_num_vertices=4, is_directed=False)\n # graph 1\n graph.add_edge(0, 1, 1.0)\n graph.add_edge(0, 4, 1.0)\n graph.add_edge(1, 2, 1.0)\n graph.add_edge(2, 3, 1.0)\n graph.add_edge(4, 5, 1.0)\n graph.add_edge(5, 2, 1.0)\n graph.add_edge(5, 3, 1.0)\n\n # graph_2\n graph_2.add_edge(0, 1, 6.0)\n graph_2.add_edge(0, 2, 5.0)\n graph_2.add_edge(2, 3, 1.0)\n graph_2.add_edge(1, 3, 2.0)\n\n # Algorithms\n # print(graph_2)\n topological(graph)\n k(graph_2)\n\n\nmain()\n","sub_path":"Lab6.py","file_name":"Lab6.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"549488530","text":"from modules import php\nfrom utils import DictTree\nfrom utils import torch_utils\nfrom utils import torch_wrapper as torch\nfrom . import vi_agent\n\n\nclass PHPAgent(vi_agent.VIAgent):\n def __init__(self, env, config):\n super().__init__(env, config)\n self._make_phps(env)\n\n def _make_phps(self, env):\n php_configs = self._php_configs(env)\n ctx_size = self.posterior_rnn_config.features_out_size * (1 + self.posterior_rnn_config.bidirectional)\n self.phps = {}\n for name, config in php_configs.items():\n if self.config.teacher:\n php_maker = config.get('teacher', php.PHP)\n else:\n php_maker = php.catalog\n self.phps[name] = php_maker(config.model | DictTree(\n sub_names=config.sub_names,\n obs_size=env.obs_size,\n ctx_size=ctx_size,\n ))\n for name, p in self.phps.items():\n p.finalize(self.phps, env.actions)\n if not self.config.teacher:\n self.add_module(name, p)\n\n def reset(self, init_arg):\n return DictTree(stack=[DictTree(\n name=self.root_php_name,\n arg=init_arg,\n cnt=torch.zeros(1, device=self._get_value(init_arg).device)),\n ])\n\n async def forward(self, iput):\n stack = iput.mem_in.stack.copy()\n ret_name = iput.ret_name\n ret_val = iput.ret_val\n steps = []\n loss = []\n log_p = []\n log_q = []\n step_idx = 0\n while True:\n top = stack[-1]\n top_php = self.phps[top.name]\n step_iput = DictTree(\n is_root=(len(stack) == 1),\n arg=self._get_value(top.arg),\n cnt=top.cnt,\n ret_name=ret_name,\n ret_val=self._get_value(ret_val),\n obs=self._get_value(iput.obs),\n )\n if 'ctx' in iput:\n step_iput.ctx = iput.ctx\n if 'mem_out' in iput:\n step = iput.mem_out.steps[step_idx]\n step_iput.sub_name = step.sub_name\n step_iput.sub_arg = step.sub_arg\n step_idx += 1\n step_iput.act_name = iput.act_name\n step_iput.act_arg = iput.act_arg\n elif 'act_name' in iput:\n step_iput.act_name = iput.act_name\n step_iput.act_arg = iput.act_arg\n step_oput = await top_php(step_iput)\n steps.append(DictTree(\n name=top.name,\n arg=self._get_value(top.arg, teacher=False),\n cnt=top.cnt,\n ret_name=ret_name,\n ret_val=self._get_value(ret_val, teacher=False),\n sub_name=step_oput.sub_name,\n sub_arg=step_oput.sub_arg,\n ))\n if 'ctx' in iput:\n loss.extend(step_oput.loss)\n log_p.extend(step_oput.log_p)\n log_q.extend(step_oput.log_q)\n if step_oput.sub_name is None:\n # terminate php\n assert top.cnt > 0\n stack.pop()\n if stack:\n ret_name = top.name\n ret_val = step_oput.sub_arg\n else:\n # terminate agent\n act_name = None\n act_arg = step_oput.sub_arg\n break\n elif step_oput.sub_name in self.act_names:\n # take action\n stack[-1] = DictTree(top, cnt=top.cnt + 1)\n act_name = step_oput.sub_name\n act_arg = step_oput.sub_arg\n break\n else:\n # call php\n stack[-1] = DictTree(top, cnt=top.cnt + 1)\n ret_name = None\n ret_val = ret_val.new_empty(0)\n stack.append(DictTree(name=step_oput.sub_name, arg=step_oput.sub_arg, cnt=ret_val.new_zeros(1)))\n oput = DictTree(\n mem_out=DictTree(steps=steps, stack=stack),\n )\n if 'mem_out' in iput:\n assert torch_utils.eq(iput.mem_out, oput.mem_out)\n if 'ctx' in iput:\n oput.loss = loss\n oput.log_p = log_p\n oput.log_q = log_q\n elif 'act_name' in iput:\n oput.error = step_oput.error\n else:\n oput.act_name = act_name\n oput.act_arg = act_arg\n return oput\n","sub_path":"agents/php_agent.py","file_name":"php_agent.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"445737780","text":"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Implementations of different data feeders to provide data for TF trainer.\"\"\"\n\n# TODO(ipolosukhin): Replace this module with feed-dict queue runners & queues.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport itertools\nimport math\n\nimport numpy as np\nimport six\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.platform import tf_logging as logging\n\n# pylint: disable=g-multiple-import,g-bad-import-order\nfrom .pandas_io import HAS_PANDAS, extract_pandas_data, extract_pandas_matrix, extract_pandas_labels\nfrom .dask_io import HAS_DASK, extract_dask_data, extract_dask_labels\n\n# pylint: enable=g-multiple-import,g-bad-import-order\n\n\ndef _get_in_out_shape(x_shape, y_shape, n_classes, batch_size=None):\n \"\"\"Returns shape for input and output of the data feeder.\"\"\"\n x_is_dict, y_is_dict = isinstance(\n x_shape, dict), y_shape is not None and isinstance(y_shape, dict)\n if y_is_dict and n_classes is not None:\n assert isinstance(n_classes, dict)\n\n if batch_size is None:\n batch_size = list(x_shape.values())[0][0] if x_is_dict else x_shape[0]\n elif batch_size <= 0:\n raise ValueError('Invalid batch_size %d.' % batch_size)\n\n if x_is_dict:\n input_shape = {}\n for k, v in list(x_shape.items()):\n input_shape[k] = [batch_size] + (list(v[1:]) if len(v) > 1 else [1])\n else:\n x_shape = list(x_shape[1:]) if len(x_shape) > 1 else [1]\n input_shape = [batch_size] + x_shape\n\n if y_shape is None:\n return input_shape, None, batch_size\n\n def out_el_shape(out_shape, num_classes):\n out_shape = list(out_shape[1:]) if len(out_shape) > 1 else []\n # Skip first dimension if it is 1.\n if out_shape and out_shape[0] == 1:\n out_shape = out_shape[1:]\n if num_classes is not None and num_classes > 1:\n return [batch_size] + out_shape + [num_classes]\n else:\n return [batch_size] + out_shape\n\n if not y_is_dict:\n output_shape = out_el_shape(y_shape, n_classes)\n else:\n output_shape = dict([\n (k, out_el_shape(v, n_classes[k]\n if n_classes is not None and k in n_classes else None))\n for k, v in list(y_shape.items())\n ])\n\n return input_shape, output_shape, batch_size\n\n\ndef _data_type_filter(x, y):\n \"\"\"Filter data types into acceptable format.\"\"\"\n if HAS_DASK:\n x = extract_dask_data(x)\n if y is not None:\n y = extract_dask_labels(y)\n if HAS_PANDAS:\n x = extract_pandas_data(x)\n if y is not None:\n y = extract_pandas_labels(y)\n return x, y\n\n\ndef _is_iterable(x):\n return hasattr(x, 'next') or hasattr(x, '__next__')\n\n\ndef setup_train_data_feeder(x,\n y,\n n_classes,\n batch_size=None,\n shuffle=True,\n epochs=None):\n \"\"\"Create data feeder, to sample inputs from dataset.\n\n If `x` and `y` are iterators, use `StreamingDataFeeder`.\n\n Args:\n x: numpy, pandas or Dask matrix or dictionary of aforementioned. Also\n supports iterables.\n y: numpy, pandas or Dask array or dictionary of aforementioned. Also\n supports\n iterables.\n n_classes: number of classes. Must be None or same type as y. In case, `y`\n is `dict`\n (or iterable which returns dict) such that `n_classes[key] = n_classes for\n y[key]`\n batch_size: size to split data into parts. Must be >= 1.\n shuffle: Whether to shuffle the inputs.\n epochs: Number of epochs to run.\n\n Returns:\n DataFeeder object that returns training data.\n\n Raises:\n ValueError: if one of `x` and `y` is iterable and the other is not.\n \"\"\"\n x, y = _data_type_filter(x, y)\n if HAS_DASK:\n # pylint: disable=g-import-not-at-top\n import dask.dataframe as dd\n if (isinstance(x, (dd.Series, dd.DataFrame)) and\n (y is None or isinstance(y, (dd.Series, dd.DataFrame)))):\n data_feeder_cls = DaskDataFeeder\n else:\n data_feeder_cls = DataFeeder\n else:\n data_feeder_cls = DataFeeder\n\n if _is_iterable(x):\n if y is not None and not _is_iterable(y):\n raise ValueError('Both x and y should be iterators for '\n 'streaming learning to work.')\n return StreamingDataFeeder(x, y, n_classes, batch_size)\n return data_feeder_cls(\n x, y, n_classes, batch_size, shuffle=shuffle, epochs=epochs)\n\n\ndef _batch_data(x, batch_size=None):\n if (batch_size is not None) and (batch_size <= 0):\n raise ValueError('Invalid batch_size %d.' % batch_size)\n\n x_first_el = six.next(x)\n x = itertools.chain([x_first_el], x)\n\n chunk = dict([(k, []) for k in list(x_first_el.keys())]) if isinstance(\n x_first_el, dict) else []\n chunk_filled = False\n for data in x:\n if isinstance(data, dict):\n for k, v in list(data.items()):\n chunk[k].append(v)\n if (batch_size is not None) and (len(chunk[k]) >= batch_size):\n chunk[k] = np.matrix(chunk[k])\n chunk_filled = True\n if chunk_filled:\n yield chunk\n chunk = dict([(k, []) for k in list(x_first_el.keys())]) if isinstance(\n x_first_el, dict) else []\n chunk_filled = False\n else:\n chunk.append(data)\n if (batch_size is not None) and (len(chunk) >= batch_size):\n yield np.matrix(chunk)\n chunk = []\n\n if isinstance(x_first_el, dict):\n for k, v in list(data.items()):\n chunk[k] = np.matrix(chunk[k])\n yield chunk\n else:\n yield np.matrix(chunk)\n\n\ndef setup_predict_data_feeder(x, batch_size=None):\n \"\"\"Returns an iterable for feeding into predict step.\n\n Args:\n x: numpy, pandas, Dask array or dictionary of aforementioned. Also supports\n iterable.\n batch_size: Size of batches to split data into. If `None`, returns one\n batch of full size.\n\n Returns:\n List or iterator (or dictionary thereof) of parts of data to predict on.\n\n Raises:\n ValueError: if `batch_size` <= 0.\n \"\"\"\n if HAS_DASK:\n x = extract_dask_data(x)\n if HAS_PANDAS:\n x = extract_pandas_data(x)\n if _is_iterable(x):\n return _batch_data(x, batch_size)\n if len(x.shape) == 1:\n x = np.reshape(x, (-1, 1))\n if batch_size is not None:\n if batch_size <= 0:\n raise ValueError('Invalid batch_size %d.' % batch_size)\n n_batches = int(math.ceil(float(len(x)) / batch_size))\n return [x[i * batch_size:(i + 1) * batch_size] for i in xrange(n_batches)]\n return [x]\n\n\ndef setup_processor_data_feeder(x):\n \"\"\"Sets up processor iterable.\n\n Args:\n x: numpy, pandas or iterable.\n\n Returns:\n Iterable of data to process.\n \"\"\"\n if HAS_PANDAS:\n x = extract_pandas_matrix(x)\n return x\n\n\ndef check_array(array, dtype):\n \"\"\"Checks array on dtype and converts it if different.\n\n Args:\n array: Input array.\n dtype: Expected dtype.\n\n Returns:\n Original array or converted.\n \"\"\"\n # skip check if array is instance of other classes, e.g. h5py.Dataset\n # to avoid copying array and loading whole data into memory\n if isinstance(array, (np.ndarray, list)):\n array = np.array(array, dtype=dtype, order=None, copy=False)\n return array\n\n\ndef _access(data, iloc):\n \"\"\"Accesses an element from collection, using integer location based indexing.\n\n Args:\n data: array-like. The collection to access\n iloc: `int` or `list` of `int`s. Location(s) to access in `collection`\n\n Returns:\n The element of `a` found at location(s) `iloc`.\n \"\"\"\n if HAS_PANDAS:\n import pandas as pd # pylint: disable=g-import-not-at-top\n if isinstance(data, pd.Series) or isinstance(data, pd.DataFrame):\n return data.iloc[iloc]\n return data[iloc]\n\n\ndef _check_dtype(dtype):\n if dtypes.as_dtype(dtype) == dtypes.float64:\n logging.warn(\n 'float64 is not supported by many models, consider casting to float32.')\n return dtype\n\n\nclass DataFeeder(object):\n \"\"\"Data feeder is an example class to sample data for TF trainer.\"\"\"\n\n def __init__(self,\n x,\n y,\n n_classes,\n batch_size=None,\n shuffle=True,\n random_state=None,\n epochs=None):\n \"\"\"Initializes a DataFeeder instance.\n\n Args:\n x: One feature sample which can either Nd numpy matrix of shape\n `[n_samples, n_features, ...]` or dictionary of Nd numpy matrix.\n y: label vector, either floats for regression or class id for\n classification. If matrix, will consider as a sequence of labels.\n Can be `None` for unsupervised setting. Also supports dictionary of\n labels.\n n_classes: Number of classes, 0 and 1 are considered regression, `None`\n will pass through the input labels without one-hot conversion. Also, if\n `y` is `dict`, then `n_classes` must be `dict` such that\n `n_classes[key] = n_classes for label y[key]`, `None` otherwise.\n batch_size: Mini-batch size to accumulate samples in one mini batch.\n shuffle: Whether to shuffle `x`.\n random_state: Numpy `RandomState` object to reproduce sampling.\n epochs: Number of times to iterate over input data before raising\n `StopIteration` exception.\n\n Attributes:\n x: Input features (ndarray or dictionary of ndarrays).\n y: Input label (ndarray or dictionary of ndarrays).\n n_classes: Number of classes (if `None`, pass through indices without\n one-hot conversion).\n batch_size: Mini-batch size to accumulate.\n input_shape: Shape of the input (or dictionary of shapes).\n output_shape: Shape of the output (or dictionary of shapes).\n input_dtype: DType of input (or dictionary of shapes).\n output_dtype: DType of output (or dictionary of shapes.\n \"\"\"\n x_is_dict, y_is_dict = isinstance(x, dict), y is not None and isinstance(\n y, dict)\n if isinstance(y, list):\n y = np.array(y)\n\n self._x = dict([(k, check_array(v, v.dtype)) for k, v in list(x.items())\n ]) if x_is_dict else check_array(x, x.dtype)\n self._y = None if y is None else (\n dict([(k, check_array(v, v.dtype)) for k, v in list(y.items())])\n if y_is_dict else check_array(y, y.dtype))\n\n # self.n_classes is not None means we're converting raw target indices\n # to one-hot.\n if n_classes is not None:\n if not y_is_dict:\n y_dtype = (np.int64\n if n_classes is not None and n_classes > 1 else np.float32)\n self._y = (None if y is None else check_array(y, dtype=y_dtype))\n\n self.n_classes = n_classes\n self.max_epochs = epochs\n\n x_shape = dict([(k, v.shape) for k, v in list(self._x.items())\n ]) if x_is_dict else self._x.shape\n y_shape = dict([(k, v.shape) for k, v in list(self._y.items())\n ]) if y_is_dict else None if y is None else self._y.shape\n\n self.input_shape, self.output_shape, self._batch_size = _get_in_out_shape(\n x_shape, y_shape, n_classes, batch_size)\n\n # Input dtype matches dtype of x.\n self._input_dtype = (\n dict([(k, _check_dtype(v.dtype)) for k, v in list(self._x.items())])\n if x_is_dict else _check_dtype(self._x.dtype))\n\n # self._output_dtype == np.float32 when y is None\n self._output_dtype = (\n dict([(k, _check_dtype(v.dtype)) for k, v in list(self._y.items())])\n if y_is_dict else (\n _check_dtype(self._y.dtype) if y is not None else np.float32))\n\n # self.n_classes is None means we're passing in raw target indices\n if n_classes is not None and y_is_dict:\n for key in list(n_classes.keys()):\n if key in self._output_dtype:\n self._output_dtype[key] = np.float32\n\n self._shuffle = shuffle\n self.random_state = np.random.RandomState(\n 42) if random_state is None else random_state\n\n num_samples = list(self._x.values())[0].shape[\n 0] if x_is_dict else self._x.shape[0]\n if self._shuffle:\n self.indices = self.random_state.permutation(num_samples)\n else:\n self.indices = np.array(range(num_samples))\n self.offset = 0\n self.epoch = 0\n self._epoch_placeholder = None\n\n @property\n def x(self):\n return self._x\n\n @property\n def y(self):\n return self._y\n\n @property\n def shuffle(self):\n return self._shuffle\n\n @property\n def input_dtype(self):\n return self._input_dtype\n\n @property\n def output_dtype(self):\n return self._output_dtype\n\n @property\n def batch_size(self):\n return self._batch_size\n\n def make_epoch_variable(self):\n \"\"\"Adds a placeholder variable for the epoch to the graph.\n\n Returns:\n The epoch placeholder.\n \"\"\"\n self._epoch_placeholder = array_ops.placeholder(\n dtypes.int32, [1], name='epoch')\n return self._epoch_placeholder\n\n def input_builder(self):\n \"\"\"Builds inputs in the graph.\n\n Returns:\n Two placeholders for inputs and outputs.\n \"\"\"\n\n def get_placeholder(shape, dtype, name_prepend):\n if shape is None:\n return None\n if isinstance(shape, dict):\n placeholder = {}\n for key in list(shape.keys()):\n placeholder[key] = array_ops.placeholder(\n dtypes.as_dtype(dtype[key]), [None] + shape[key][1:],\n name=name_prepend + '_' + key)\n else:\n placeholder = array_ops.placeholder(\n dtypes.as_dtype(dtype), [None] + shape[1:], name=name_prepend)\n return placeholder\n\n self._input_placeholder = get_placeholder(self.input_shape,\n self._input_dtype, 'input')\n self._output_placeholder = get_placeholder(self.output_shape,\n self._output_dtype, 'output')\n return self._input_placeholder, self._output_placeholder\n\n def set_placeholders(self, input_placeholder, output_placeholder):\n \"\"\"Sets placeholders for this data feeder.\n\n Args:\n input_placeholder: Placeholder for `x` variable. Should match shape\n of the examples in the x dataset.\n output_placeholder: Placeholder for `y` variable. Should match\n shape of the examples in the y dataset. Can be `None`.\n \"\"\"\n self._input_placeholder = input_placeholder\n self._output_placeholder = output_placeholder\n\n def get_feed_params(self):\n \"\"\"Function returns a `dict` with data feed params while training.\n\n Returns:\n A `dict` with data feed params while training.\n \"\"\"\n return {\n 'epoch': self.epoch,\n 'offset': self.offset,\n 'batch_size': self._batch_size\n }\n\n def get_feed_dict_fn(self):\n \"\"\"Returns a function that samples data into given placeholders.\n\n Returns:\n A function that when called samples a random subset of batch size\n from `x` and `y`.\n \"\"\"\n x_is_dict, y_is_dict = isinstance(\n self._x, dict), self._y is not None and isinstance(self._y, dict)\n\n # Assign input features from random indices.\n def extract(data, indices):\n return (np.array(_access(data, indices)).reshape((indices.shape[0], 1)) if\n len(data.shape) == 1 else _access(data, indices))\n\n # assign labels from random indices\n def assign_label(data, shape, dtype, n_classes, indices):\n shape[0] = indices.shape[0]\n out = np.zeros(shape, dtype=dtype)\n for i in xrange(out.shape[0]):\n sample = indices[i]\n # self.n_classes is None means we're passing in raw target indices\n if n_classes is None:\n out[i] = _access(data, sample)\n else:\n if n_classes > 1:\n if len(shape) == 2:\n out.itemset((i, int(_access(data, sample))), 1.0)\n else:\n for idx, value in enumerate(_access(data, sample)):\n out.itemset(tuple([i, idx, value]), 1.0)\n else:\n out[i] = _access(data, sample)\n return out\n\n def _feed_dict_fn():\n \"\"\"Function that samples data into given placeholders.\"\"\"\n if self.max_epochs is not None and self.epoch + 1 > self.max_epochs:\n raise StopIteration\n assert self._input_placeholder is not None\n feed_dict = {}\n if self._epoch_placeholder is not None:\n feed_dict[self._epoch_placeholder.name] = [self.epoch]\n\n # Take next batch of indices.\n x_len = list(self._x.values())[0].shape[\n 0] if x_is_dict else self._x.shape[0]\n end = min(x_len, self.offset + self._batch_size)\n batch_indices = self.indices[self.offset:end]\n\n # adding input placeholder\n feed_dict.update(\n dict([(self._input_placeholder[k].name, extract(v, batch_indices))\n for k, v in list(self._x.items())]) if x_is_dict else\n {self._input_placeholder.name: extract(self._x, batch_indices)})\n\n # move offset and reset it if necessary\n self.offset += self._batch_size\n if self.offset >= x_len:\n self.indices = self.random_state.permutation(\n x_len) if self._shuffle else np.array(range(x_len))\n self.offset = 0\n self.epoch += 1\n\n # return early if there are no labels\n if self._output_placeholder is None:\n return feed_dict\n\n # adding output placeholders\n if y_is_dict:\n for k, v in list(self._y.items()):\n n_classes = (self.n_classes[k] if k in self.n_classes else\n None) if self.n_classes is not None else None\n shape, dtype = self.output_shape[k], self._output_dtype[k]\n feed_dict.update({\n self._output_placeholder[k].name:\n assign_label(v, shape, dtype, n_classes, batch_indices)\n })\n else:\n shape, dtype, n_classes = self.output_shape, self._output_dtype, self.n_classes\n feed_dict.update({\n self._output_placeholder.name:\n assign_label(self._y, shape, dtype, n_classes, batch_indices)\n })\n\n return feed_dict\n\n return _feed_dict_fn\n\n\nclass StreamingDataFeeder(DataFeeder):\n \"\"\"Data feeder for TF trainer that reads data from iterator.\n\n Streaming data feeder allows to read data as it comes it from disk or\n somewhere else. It's custom to have this iterators rotate infinetly over\n the dataset, to allow control of how much to learn on the trainer side.\n \"\"\"\n\n def __init__(self, x, y, n_classes, batch_size):\n \"\"\"Initializes a StreamingDataFeeder instance.\n\n Args:\n x: iterator each element of which returns one feature sample. Sample can\n be a Nd numpy matrix or dictionary of Nd numpy matrices.\n y: iterator each element of which returns one label sample. Sample can be\n a Nd numpy matrix or dictionary of Nd numpy matrices with 1 or many\n classes regression values.\n n_classes: indicator of how many classes the corresponding label sample\n has for the purposes of one-hot conversion of label. In case where `y`\n is a dictionary, `n_classes` must be dictionary (with same keys as `y`)\n of how many classes there are in each label in `y`. If key is\n present in `y` and missing in `n_classes`, the value is assumed `None`\n and no one-hot conversion will be applied to the label with that key.\n batch_size: Mini batch size to accumulate samples in one batch. If set\n `None`, then assumes that iterator to return already batched element.\n\n Attributes:\n x: input features (or dictionary of input features).\n y: input label (or dictionary of output features).\n n_classes: number of classes.\n batch_size: mini batch size to accumulate.\n input_shape: shape of the input (can be dictionary depending on `x`).\n output_shape: shape of the output (can be dictionary depending on `y`).\n input_dtype: dtype of input (can be dictionary depending on `x`).\n output_dtype: dtype of output (can be dictionary depending on `y`).\n \"\"\"\n # pylint: disable=invalid-name,super-init-not-called\n x_first_el = six.next(x)\n self._x = itertools.chain([x_first_el], x)\n if y is not None:\n y_first_el = six.next(y)\n self._y = itertools.chain([y_first_el], y)\n else:\n y_first_el = None\n self._y = None\n self.n_classes = n_classes\n\n x_is_dict = isinstance(x_first_el, dict)\n y_is_dict = y is not None and isinstance(y_first_el, dict)\n if y_is_dict and n_classes is not None:\n assert isinstance(n_classes, dict)\n\n # extract shapes for first_elements\n if x_is_dict:\n x_first_el_shape = dict(\n [(k, [1] + list(v.shape)) for k, v in list(x_first_el.items())])\n else:\n x_first_el_shape = [1] + list(x_first_el.shape)\n\n if y_is_dict:\n y_first_el_shape = dict(\n [(k, [1] + list(v.shape)) for k, v in list(y_first_el.items())])\n elif y is None:\n y_first_el_shape = None\n else:\n y_first_el_shape = ([1] + list(y_first_el[0].shape if isinstance(\n y_first_el, list) else y_first_el.shape))\n\n self.input_shape, self.output_shape, self._batch_size = _get_in_out_shape(\n x_first_el_shape, y_first_el_shape, n_classes, batch_size)\n\n # Input dtype of x_first_el.\n if x_is_dict:\n self._input_dtype = dict(\n [(k, _check_dtype(v.dtype)) for k, v in list(x_first_el.items())])\n else:\n self._input_dtype = _check_dtype(x_first_el.dtype)\n\n # Output dtype of y_first_el.\n def check_y_dtype(el):\n if isinstance(el, np.ndarray):\n return el.dtype\n elif isinstance(el, list):\n return check_y_dtype(el[0])\n else:\n return _check_dtype(np.dtype(type(el)))\n\n # Output types are floats, due to both softmaxes and regression req.\n if n_classes is not None and (y is None or not y_is_dict) and n_classes > 0:\n self._output_dtype = np.float32\n elif y_is_dict:\n self._output_dtype = dict(\n [(k, check_y_dtype(v)) for k, v in list(y_first_el.items())])\n elif y is None:\n self._output_dtype = None\n else:\n self._output_dtype = check_y_dtype(y_first_el)\n\n def get_feed_params(self):\n \"\"\"Function returns a `dict` with data feed params while training.\n\n Returns:\n A `dict` with data feed params while training.\n \"\"\"\n return {'batch_size': self._batch_size}\n\n def get_feed_dict_fn(self):\n \"\"\"Returns a function, that will sample data and provide it to placeholders.\n\n Returns:\n A function that when called samples a random subset of batch size\n from x and y.\n \"\"\"\n self.stopped = False\n\n def _feed_dict_fn():\n \"\"\"Samples data and provides it to placeholders.\n\n Returns:\n `dict` of input and output tensors.\n \"\"\"\n\n def init_array(shape, dtype):\n \"\"\"Initialize array of given shape or dict of shapes and dtype.\"\"\"\n if shape is None:\n return None\n elif isinstance(shape, dict):\n return dict([(k, np.zeros(shape[k], dtype[k]))\n for k in list(shape.keys())])\n else:\n return np.zeros(shape, dtype=dtype)\n\n def put_data_array(dest, index, source=None, n_classes=None):\n \"\"\"Puts data array into container.\"\"\"\n if source is None:\n dest = dest[:index]\n elif n_classes is not None and n_classes > 1:\n if len(self.output_shape) == 2:\n dest.itemset((index, source), 1.0)\n else:\n for idx, value in enumerate(source):\n dest.itemset(tuple([index, idx, value]), 1.0)\n else:\n if len(dest.shape) > 1:\n dest[index, :] = source\n else:\n dest[index] = source[0] if isinstance(source, list) else source\n return dest\n\n def put_data_array_or_dict(holder, index, data=None, n_classes=None):\n \"\"\"Puts data array or data dictionary into container.\"\"\"\n if holder is None:\n return None\n if isinstance(holder, dict):\n if data is None:\n data = {k: None for k in holder.keys()}\n assert isinstance(data, dict)\n for k in holder.keys():\n num_classes = n_classes[k] if (n_classes is not None and\n k in n_classes) else None\n holder[k] = put_data_array(holder[k], index, data[k], num_classes)\n else:\n holder = put_data_array(holder, index, data, n_classes)\n return holder\n\n if self.stopped:\n raise StopIteration\n\n inp = init_array(self.input_shape, self._input_dtype)\n out = init_array(self.output_shape, self._output_dtype)\n\n for i in xrange(self._batch_size):\n # Add handling when queue ends.\n try:\n next_inp = six.next(self._x)\n inp = put_data_array_or_dict(inp, i, next_inp, None)\n except StopIteration:\n self.stopped = True\n if i == 0:\n raise\n inp = put_data_array_or_dict(inp, i, None, None)\n out = put_data_array_or_dict(out, i, None, None)\n break\n\n if self._y is not None:\n next_out = six.next(self._y)\n out = put_data_array_or_dict(out, i, next_out, self.n_classes)\n\n # creating feed_dict\n if isinstance(inp, dict):\n feed_dict = dict([(self._input_placeholder[k].name, inp[k])\n for k in list(self._input_placeholder.keys())])\n else:\n feed_dict = {self._input_placeholder.name: inp}\n if self._y is not None:\n if isinstance(out, dict):\n feed_dict.update(\n dict([(self._output_placeholder[k].name, out[k])\n for k in list(self._output_placeholder.keys())]))\n else:\n feed_dict.update({self._output_placeholder.name: out})\n\n return feed_dict\n\n return _feed_dict_fn\n\n\nclass DaskDataFeeder(object):\n \"\"\"Data feeder for that reads data from dask.Series and dask.DataFrame.\n\n Numpy arrays can be serialized to disk and it's possible to do random seeks\n into them. DaskDataFeeder will remove requirement to have full dataset in the\n memory and still do random seeks for sampling of batches.\n \"\"\"\n\n def __init__(self,\n x,\n y,\n n_classes,\n batch_size,\n shuffle=True,\n random_state=None,\n epochs=None):\n \"\"\"Initializes a DaskDataFeeder instance.\n\n Args:\n x: iterator that returns for each element, returns features.\n y: iterator that returns for each element, returns 1 or many classes /\n regression values.\n n_classes: indicator of how many classes the label has.\n batch_size: Mini batch size to accumulate.\n shuffle: Whether to shuffle the inputs.\n random_state: random state for RNG. Note that it will mutate so use a\n int value for this if you want consistent sized batches.\n epochs: Number of epochs to run.\n\n Attributes:\n x: input features.\n y: input label.\n n_classes: number of classes.\n batch_size: mini batch size to accumulate.\n input_shape: shape of the input.\n output_shape: shape of the output.\n input_dtype: dtype of input.\n output_dtype: dtype of output.\n\n Raises:\n ValueError: if `x` or `y` are `dict`, as they are not supported currently.\n \"\"\"\n\n if isinstance(x, dict) or isinstance(y, dict):\n raise ValueError(\n 'DaskDataFeeder does not support dictionaries at the moment.')\n\n # pylint: disable=invalid-name,super-init-not-called\n import dask.dataframe as dd # pylint: disable=g-import-not-at-top\n # TODO(terrytangyuan): check x and y dtypes in dask_io like pandas\n self._x = x\n self._y = y\n # save column names\n self._x_columns = list(x.columns)\n if isinstance(y.columns[0], str):\n self._y_columns = list(y.columns)\n else:\n # deal with cases where two DFs have overlapped default numeric colnames\n self._y_columns = len(self._x_columns) + 1\n self._y = self._y.rename(columns={y.columns[0]: self._y_columns})\n\n # TODO(terrytangyuan): deal with unsupervised cases\n # combine into a data frame\n self.df = dd.multi.concat([self._x, self._y], axis=1)\n self.n_classes = n_classes\n\n x_count = x.count().compute()[0]\n x_shape = (x_count, len(self._x.columns))\n y_shape = (x_count, len(self._y.columns))\n # TODO(terrytangyuan): Add support for shuffle and epochs.\n self._shuffle = shuffle\n self.epochs = epochs\n self.input_shape, self.output_shape, self._batch_size = _get_in_out_shape(\n x_shape, y_shape, n_classes, batch_size)\n self.sample_fraction = self._batch_size / float(x_count)\n self._input_dtype = _check_dtype(self._x.dtypes[0])\n self._output_dtype = _check_dtype(self._y.dtypes[self._y_columns])\n if random_state is None:\n self.random_state = 66\n else:\n self.random_state = random_state\n\n def get_feed_params(self):\n \"\"\"Function returns a `dict` with data feed params while training.\n\n Returns:\n A `dict` with data feed params while training.\n \"\"\"\n return {'batch_size': self._batch_size}\n\n def get_feed_dict_fn(self, input_placeholder, output_placeholder):\n \"\"\"Returns a function, that will sample data and provide it to placeholders.\n\n Args:\n input_placeholder: tf.Placeholder for input features mini batch.\n output_placeholder: tf.Placeholder for output labels.\n\n Returns:\n A function that when called samples a random subset of batch size\n from x and y.\n \"\"\"\n\n def _feed_dict_fn():\n \"\"\"Samples data and provides it to placeholders.\"\"\"\n # TODO(ipolosukhin): option for with/without replacement (dev version of\n # dask)\n sample = self.df.random_split(\n [self.sample_fraction, 1 - self.sample_fraction],\n random_state=self.random_state)\n inp = extract_pandas_matrix(sample[0][self._x_columns].compute()).tolist()\n out = extract_pandas_matrix(sample[0][self._y_columns].compute())\n # convert to correct dtype\n inp = np.array(inp, dtype=self._input_dtype)\n # one-hot encode out for each class for cross entropy loss\n if HAS_PANDAS:\n import pandas as pd # pylint: disable=g-import-not-at-top\n if not isinstance(out, pd.Series):\n out = out.flatten()\n out_max = self._y.max().compute().values[0]\n encoded_out = np.zeros((out.size, out_max + 1), dtype=self._output_dtype)\n encoded_out[np.arange(out.size), out] = 1\n return {input_placeholder.name: inp, output_placeholder.name: encoded_out}\n\n return _feed_dict_fn\n","sub_path":"Tensorflow/source/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py","file_name":"data_feeder.py","file_ext":"py","file_size_in_byte":31142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"482884304","text":"\nimport os\nfrom flask import Flask\nfrom flask import render_template\napp = Flask(__name__, static_folder=\"static\")\n\n@app.route('/')\ndef index():\n images = [x for x in os.listdir(app.static_folder)]\n return render_template('index.html', images=images)\n #return \"Image hosting for I/O Bot. I'm currently seeing these images:
{0}\".format(\", \".join(images))\n #return page\n\nif __name__ == '__main__':\n app.run()","sub_path":"pics.py","file_name":"pics.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"30235196","text":"import numpy as np\nimport pandas as pd\n\n\nclass Model:\n\n\n def place_bets(self, opps, summary, inc):\n N = len(opps)\n min_bet = summary.iloc[0].to_dict()['Min_bet']\n bets = np.zeros((N,3))\n bets[np.arange(N), np.random.choice([0,1,2], N)] = min_bet \n return pd.DataFrame(data=bets, columns=['BetH', 'BetD', 'BetA'], index=opps.index)\n\n","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"439479228","text":"#!/usr/bin/env python\n# vim: set fileencoding=utf-8 :\n# Created by Andre Anjos \n# Sun 28 Feb 19:52:16 2010 \n\n\"\"\"A bunch of methods that will be added to the boostrap script. Please refer\nto the virtualenv homepage for the explanation on those.\n\"\"\"\n\nimport os, sys, subprocess\n\nSWURL = 'http://sw.andreanjos.org/git/simple/'\nPACKAGES = [\n 'django-rosetta',\n ]\n\ndef after_install(options, home_dir):\n \"\"\"After everything is installed, this function is called.\n \n At this point, we populate our environment with all our goods.\n \"\"\"\n if sys.platform == 'win32': bin = 'Scripts'\n else: bin = 'bin'\n\n # we first install pip, which is easier to use\n installer = [os.path.join(home_dir, bin, 'easy_install'), '--quiet']\n subprocess.call(installer + ['pip'])\n \n installer = [os.path.join(home_dir, bin, 'pip'), 'install']\n installer.append('--find-links=%s' % SWURL)\n\n # installs our current development package\n subprocess.call(installer + ['--editable=.'])\n\n # a sequence of installs\n if options.upgrade: installer.append('--upgrade')\n if PACKAGES: subprocess.call(installer + PACKAGES)\n\ndef extend_parser(parser):\n \"\"\"Adds an upgrade option.\"\"\"\n parser.add_option('-U', '--upgrade', action='store_true', dest='upgrade', \n help='Use this if you want to upgrade instead of installing (default)')\n","sub_path":"scripts/extra_text.py","file_name":"extra_text.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"390927324","text":"import os\nimport inspect\nimport numpy as np\nimport math\nfrom NNModels.data_source import DataSource\nfrom helpers.read import readDataAndLabelsFromDiskFQ, readSelectedDataAndLabelsFromDiskFQ\nfrom helpers.data import selectCases\n\n\nclass DataLoader(DataSource):\n TRAINING_DATA = 0\n VALIDATION_DATA = 1\n TESTING_DATA = 2\n ALL_DATA = 3\n DATA_SPLIT = [0.7, 0.9]\n DATA_LOADER_ROOT = os.path.dirname(os.path.abspath(inspect.stack()[0][1])) + \"/../data_loaders\"\n\n # Constructor\n\n def __init__(self, balanced=True):\n self._data_source = None\n self._year = None\n self._save_file_path = None\n self._numpy_data_path = None\n self._numpy_labels_path = None\n self._headers_path = None\n self._headers = []\n self._data_train = None\n self._labels_train = None\n self._data_val = None\n self._labels_val = None\n self._data_test = None\n self._labels_test = None\n self._data_loaded = False\n self._full_data_set = None\n self._full_data_set_loaded = False\n self._label_name = \"\"\n self._balanced = balanced\n\n if not os.path.exists(self.DATA_LOADER_ROOT):\n os.makedirs(self.DATA_LOADER_ROOT)\n\n # Private functions\n\n def _package_data(self, data_array, headers_list=None, labels_array=None, combine=False):\n # Check that if headers_list is specified, that its size matches the given data\n if headers_list is not None:\n assert len(headers_list) == data_array.shape[1], \"Length mismatch\"\n else:\n headers_list = self._headers\n\n ret_dict = dict()\n for header in headers_list:\n header_ind = headers_list.index(header)\n ret_dict[header] = data_array[:, header_ind]\n\n if combine:\n ret_dict[self._label_name] = labels_array\n return ret_dict\n else:\n return (ret_dict, labels_array)\n\n def _saved_file_exists(self):\n return os.path.isfile(self._save_file_path)\n\n def _save_selected_indices(self, indices):\n np.save(self._save_file_path, indices)\n\n def _load_selected_indices(self):\n return np.load(self._save_file_path)\n\n # Public functions\n\n def load_data(self, load_full=False):\n if not self._data_loaded:\n data_and_labels = None\n\n # There is no save file for this loader, we need to load the data from disk and shuffle it\n if not self._saved_file_exists():\n [data_all, labels_all] = readDataAndLabelsFromDiskFQ(self._numpy_data_path, self._numpy_labels_path)\n\n if self._balanced:\n [data, labels, selected_indices] = selectCases(data_all, labels_all, shuffle=True)\n else:\n data = data_all\n labels = labels_all\n selected_indices = np.arange(0, data_all.shape[0])\n\n # Save the selected indices so that this exact data split can be reproduced\n self._save_selected_indices(selected_indices)\n\n data_and_labels = np.hstack([data, labels.reshape(labels.shape[0], 1)])\n\n # There is a save file for this loader, so we need to load it to reproduce the data split\n else:\n selected_indices = self._load_selected_indices()\n data_and_labels = readSelectedDataAndLabelsFromDiskFQ(self._numpy_data_path, self._numpy_labels_path,\n selected_indices)\n\n # Split the data\n num_samples = data_and_labels.shape[0]\n\n # Training data split\n train_split = data_and_labels[0:int(np.round(self.DATA_SPLIT[0] * num_samples)), :]\n self._data_train = train_split[:, :-1]\n self._labels_train = train_split[:, -1]\n\n # Evaluation data split\n val_split = data_and_labels[int(np.round(self.DATA_SPLIT[0] * num_samples)):int(np.round(self.DATA_SPLIT[1]\n * num_samples)), :]\n self._data_val = val_split[:, :-1]\n self._labels_val = val_split[:, -1]\n\n # Test data split\n # Test data split\n test_split = data_and_labels[int(np.round(self.DATA_SPLIT[1] * num_samples)):, :]\n self._data_test = test_split[:, :-1]\n self._labels_test = test_split[:, -1]\n\n self._data_loaded = True\n\n # Also Load the full data set if requested\n if load_full:\n self._full_data_set = data_and_labels\n self._full_data_set_loaded = True\n\n def steps_per_epoch(self, data_type, batch_size):\n if data_type is self.TRAINING_DATA:\n return int(math.ceil(self._data_train.shape[0] / batch_size))\n elif data_type is self.VALIDATION_DATA:\n return int(math.ceil(self._data_val.shape[0] / batch_size))\n elif data_type is self.TESTING_DATA:\n return int(math.ceil(self._data_test.shape[0] / batch_size))\n elif data_type is self.ALL_DATA and self._full_data_set_loaded:\n return int(math.ceil(self._full_data_set.shape[0] / batch_size))\n else:\n raise KeyError(\"Invalid data type\" + str(data_type))\n\n def get_all_data(self):\n # Format the data as expected by the prebuilt estimators:\n # A dictionary of arrays by column name\n\n dict_train = self._package_data(data_array=self._data_train)\n dict_val = self._package_data(data_array=self._data_val)\n dict_test = self._package_data(data_array=self._data_test)\n\n return (dict_train, self._labels_train), (dict_val, self._labels_val), (dict_test, self._labels_test)\n\n def get_raw_data_by_type(self, data_type):\n if data_type is self.TRAINING_DATA:\n return self._data_train, self._labels_train\n elif data_type is self.VALIDATION_DATA:\n return self._data_val, self._labels_val\n elif data_type is self.TESTING_DATA:\n return self._data_test, self._labels_test\n elif data_type is self.ALL_DATA and self._full_data_set_loaded:\n return self._full_data_set, None\n else:\n raise KeyError(\"Invalid data type\" + str(data_type))\n\n def get_packaged_data_by_type(self, data_type, combine=False):\n if data_type is self.TRAINING_DATA:\n return self._package_data(data_array=self._data_train, labels_array=self._labels_train, combine=combine)\n elif data_type is self.VALIDATION_DATA:\n return self._package_data(data_array=self._data_val, labels_array=self._labels_val, combine=combine)\n elif data_type is self.TESTING_DATA:\n return self._package_data(data_array=self._data_test, labels_array=self._labels_test, combine=combine)\n else:\n raise KeyError(\"Invalid data type\" + str(data_type))\n\n def get_total_rows_for_data_type(self, data_type):\n if data_type is self.TRAINING_DATA:\n return self._data_train.shape[0]\n elif data_type is self.VALIDATION_DATA:\n return self._data_val.shape[0]\n elif data_type is self.TESTING_DATA:\n return self._data_test.shape[0]\n else:\n raise KeyError(\"Invalid data type\" + str(data_type))\n\n def get_data_for_header(self, header):\n if not self._full_data_set_loaded:\n raise AttributeError(\"Full data set must be loaded\")\n\n if header == self._label_name:\n return self._full_data_set[:, -1]\n else:\n header_ind = self._headers.index(header)\n return self._full_data_set[:, header_ind]\n\n def get_data_name(self):\n return self._data_source\n\n # TF Enumerator data functions\n def train_input_fn(self, features, labels, batch_size, epochs):\n raise NotImplementedError(\"Not Implemented\")\n\n def eval_input_fn(self, features, labels, batch_size):\n raise NotImplementedError(\"Not Implemented\")\n\n def get_feature_columns(self):\n raise NotImplementedError(\"Not Implemented\")\n\n def get_feature_columns_for_headers(self, header_list):\n raise NotImplementedError(\"Not Implemented\")\n\n def get_header_list(self):\n if self._full_data_set_loaded:\n return self._headers + [self._label_name]\n else:\n return self._headers\n\n def get_header_list_with_label(self):\n return self._headers + [self._label_name]\n\n def get_label_name(self):\n return self._label_name\n\n def get_diagnosis_headers(self):\n raise NotImplementedError(\"Not Implemented\")\n\n def get_procedure_headers(self):\n raise NotImplementedError(\"Not Implemented\")\n\n def get_rounding_exception_columns(self):\n raise NotImplementedError(\"Not Implemented\")\n\n def get_raw_data(self):\n raw_data, _ = self.get_raw_data_by_type(self.ALL_DATA)\n return raw_data\n\n def get_all_data_and_labels(self):\n raw_data, _ = self.get_raw_data_by_type(self.ALL_DATA)\n\n label_index = self._headers.index(self._label_name)\n labels = raw_data[:, label_index]\n\n return np.delete(raw_data, label_index, axis=1), labels\n\n def get_indices_for_headers(self, header_list):\n full_header_list = self.get_header_list()\n return list(map(full_header_list.index, header_list))\n\n def get_diagnosis_data(self, data_type, packaged=False, num_rows=None):\n diag_headers = self.get_diagnosis_headers()\n diag_header_indices = self.get_indices_for_headers(diag_headers)\n raw_data, _ = self.get_raw_data_by_type(data_type)\n raw_data = raw_data[0:num_rows, diag_header_indices]\n\n if packaged:\n packaged_data, _ = self._package_data(data_array=raw_data, headers_list=diag_headers)\n return packaged_data\n else:\n return raw_data\n\n def get_procedure_data(self, data_type, packaged=False, num_rows=None):\n proc_headers = self.get_procedure_headers()\n proc_header_indices = self.get_indices_for_headers(proc_headers)\n raw_data, _ = self.get_raw_data_by_type(data_type)\n raw_data = raw_data[0:num_rows, proc_header_indices]\n\n if packaged:\n packaged_data, _ = self._package_data(data_array=raw_data, headers_list=proc_headers)\n return packaged_data\n else:\n return raw_data\n","sub_path":"NNModels/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":10528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"313458971","text":"# coding=utf-8\nimport datetime\n\nimport geopandas as gp\nimport numpy as np\nfrom shapely.geometry import Point\n\nfrom src import constants as C\n\n\n# some helper function for Bower.pred()\ndef get_distance(row):\n a = np.array(row.geometry.coords[0])\n b = np.array(row.cen_coords)\n return np.linalg.norm(a - b)\n\n\ndef calc_risk(df, grid_size, now_date):\n distance = df.apply(get_distance, axis=1) // (grid_size / 2) + 1\n n_weeks = df[C.COL.datetime].apply(lambda x: (now_date - x).days // 7 + 1)\n return (1 / distance * 1 / n_weeks).sum()\n\n\nclass Bower:\n \"\"\"developed in:\n Bowers, K.J. et al. 2004. Prospective Hot-SpottingThe Future of Crime Mapping?\n The British journal of criminology. 44, 5 (Sep. 2004), 641–658.\n\n Attributes\n ----------\n last_date: the last date of the events, set after self.fit(), used in self.has_fit()\n events\n \"\"\"\n\n def __str__(self):\n return (\n 'Bower method: weighted by distance and time, '\n 'bandwidth={}, time window={}, verbose={}'\n ''.format(self.bw, self.tw, self.verbose))\n\n def __init__(self, grid_size, bw=400, tw=60, verbose=0):\n \"\"\"\n :param grid_size: bower normalize distance by 1/2 of grid_size\n :param bw: bandwidth, int, default = 400\n :param tw: time window, int, default = 60, number of days in the past to be considered\n :param verbose: level of verbosity\n \"\"\"\n self.bw = bw\n self.tw = tw\n self.verbose = verbose\n self.grid_size = grid_size\n # attributes set after self.fit\n self.last_date = None\n self.events = None\n\n def has_fit(self):\n return self.last_date is not None\n\n def fit(self, x_coords, y_coords=None, last_date=None):\n \"\"\"\n :param x_coords: pd.Series\n Indexed and sorted by Date, with values = coords\n\n For compatibility with inputs containing names of coords, such as those for RTM,\n coords can be dict. In this case, only len(coords)=1 (1 key) is allowed.\n\n :param y_coords: not used in bower, for compatibility purpose\n\n :param last_date: string (format='%Y-%m-%d') or DateTime, default None\n the last date of the time window. If None, the last date of coords is used\n \"\"\"\n\n # for compatibility\n if isinstance(x_coords, dict):\n if len(x_coords) != 1: raise ValueError('input coords is dict, but len!=1')\n if self.verbose > 0: print('coords is a dictionary, len==1, keep its value only')\n x_coords = list(x_coords.values())[0]\n\n if self.tw is not None:\n if last_date is None:\n last_date = x_coords.index.max().normalize() + datetime.timedelta(days=1, seconds=-1)\n elif isinstance(last_date, str):\n last_date = datetime.datetime.strptime(last_date, '%Y-%m-%d') + datetime.timedelta(seconds=-1)\n if self.verbose > 0:\n print('last_date = %s' % last_date)\n\n # pandas time index slice include both begin and last date,\n # to have a time window=tw, the difference should be tw-1\n # the above is wrong, since we're using datetime. down to the last sec\n begin_date = last_date - datetime.timedelta(days=self.tw)\n x_coords = x_coords.loc[begin_date:last_date]\n self.last_date = last_date\n\n events = gp.GeoDataFrame(x_coords.apply(lambda x: Point(*x))).rename(\n columns={C.COL.coords: 'geometry'}).reset_index()\n self.events = events\n\n def predict(self, spatial_units, now_date=None):\n \"\"\"\n\n :param spatial_units: assuming coords of the centers. pd.Series([coord], index=Date)\n :param now_date: Datetime-like object, default None\n now_date for the prediction. If None, now_date=self.last_date+1sec\n :return: pd.Series, index=data.index, value=risk score\n \"\"\"\n # TODO spatial_units can be shapes other than grids\n\n if now_date is None:\n now_date = self.last_date + datetime.timedelta(seconds=1)\n if self.verbose > 0:\n print('now_date is None, using self.last_date+1sec=%s as now_date' % now_date)\n\n # grids_center has same index as coords\n grids = gp.GeoDataFrame(spatial_units.values)\n grids.columns = ['cen_coords']\n grids['geometry'] = grids.cen_coords.apply(lambda x: Point(*x))\n grids['geometry'] = grids.buffer(self.bw)\n joined = gp.sjoin(self.events, grids)\n pred = joined.groupby('index_right') \\\n .apply(lambda df: calc_risk(df, self.grid_size, now_date)) \\\n .reindex(grids.index).fillna(0)\n return pred\n\n def tune(self, bw=None):\n \"\"\"\n Bowers' paper doesn't have bw tuning, this method is for consistency\n \"\"\"\n if bw is not None:\n self.bw = bw\n\n\ndef main():\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/model/bsln_bower.py","file_name":"bsln_bower.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"134459836","text":"#!/usr/bin/env python\n\"\"\"GUI for Experiments.\"\"\"\nfrom __future__ import division, print_function\n\nimport elaps.defines as defines\nimport elaps.io\nimport elaps.symbolic as symbolic\nimport elaps.signature as signature\n\nfrom elaps.qt import QCall, QJobProgress\n\nimport sys\nimport os\nimport string\nimport itertools\nfrom PyQt4 import QtGui, QtCore\nfrom PyQt4.QtCore import pyqtSlot\n\n\nclass PlayMat(QtGui.QMainWindow):\n\n \"\"\"GUI for Experiment.\"\"\"\n\n def __init__(self, app=None, load=None, reset=False):\n \"\"\"Initilialize the PlayMat.\"\"\"\n if app:\n self.Qapp = app\n else:\n self.Qapp = QtGui.QApplication(sys.argv)\n self.Qapp.viewer = None\n self.Qapp.playmat = self\n QtGui.QMainWindow.__init__(self)\n self.samplers = elaps.io.load_all_samplers()\n if not self.samplers:\n self.alert(\"ERROR: No Samplers found!\")\n sys.exit()\n self.docs = {}\n self.sigs = {}\n self.papi_names = elaps.io.load_papinames()\n self.last_filebase = None\n\n # set up UI\n self.UI_init()\n self.hideargs = set([signature.Ld, signature.Inc, signature.Work,\n signature.Lwork, signature.Info])\n if not reset:\n try:\n self.UI_settings_load()\n self.UI_jobprogress.hide()\n except:\n pass\n\n # set experiment\n self.experiment = None\n if load:\n try:\n self.experiment_load(load)\n except:\n self.alert(\"ERROR: Can't load %r\" % load)\n if not self.experiment and not reset:\n try:\n self.experiment_qt_load()\n except:\n pass\n if not self.experiment:\n self.experiment_reset()\n\n self.UI_setall()\n\n def UI_init(self):\n \"\"\"Initialize all GUI elements.\"\"\"\n self.UI_setting = 1\n\n # window\n self.pyqtConfigure(\n windowTitle=\"ELAPS:PlayMat\", unifiedTitleAndToolBarOnMac=True\n )\n self.setCorner(QtCore.Qt.TopRightCorner, QtCore.Qt.TopDockWidgetArea)\n self.statusBar()\n\n # DEBUG: print experiment\n QtGui.QShortcut(\n QtGui.QKeySequence.Print, self, lambda: print(self.experiment)\n )\n\n def create_menus():\n \"\"\"Create all menus.\"\"\"\n menu = self.menuBar()\n\n # file\n fileM = menu.addMenu(\"File\")\n\n # file > submit\n self.UI_submitA = QtGui.QAction(\n \"Run\", self, shortcut=QtGui.QKeySequence(\"Ctrl+R\"),\n triggered=self.on_submit\n )\n fileM.addAction(self.UI_submitA)\n\n # submit last shortcut\n QtGui.QShortcut(\n QtGui.QKeySequence(\"Ctrl+Shift+R\"), self, self.on_submit_last\n )\n\n # file\n fileM.addSeparator()\n\n # file > reset\n fileM.addAction(QtGui.QAction(\n \"Reset Experiment\", self, triggered=self.on_experiment_reset\n ))\n\n # file > load\n fileM.addAction(QtGui.QAction(\n \"Load Experiment ...\", self,\n shortcut=QtGui.QKeySequence.Open,\n triggered=self.on_experiment_load\n ))\n\n # load report shortcut\n QtGui.QShortcut(\n QtGui.QKeySequence(\"Ctrl+Shift+O\"), self,\n self.on_experiment_load_report\n )\n\n # fie > save\n fileM.addAction(QtGui.QAction(\n \"Save Experiment ...\", self,\n shortcut=QtGui.QKeySequence.Save,\n triggered=self.on_experiment_save\n ))\n\n # file\n fileM.addSeparator()\n\n fileM.addAction(QtGui.QAction(\n \"Start Viewer\", self, triggered=self.on_viewer_start\n ))\n\n # view\n self.UI_viewM = menu.addMenu(\"View\")\n\n # view > hideargs\n self.UI_hideargs = []\n for desc, classes in (\n (\"hide flags\", (signature.Flag,)),\n (\"hide scalars\", (signature.Scalar,)),\n (\"hide leading dimensions\", (signature.Ld, signature.Inc)),\n (\"hide work spaces\", (signature.Work, signature.Lwork)),\n (\"hide infos\", (signature.Info,))\n ):\n action = QtGui.QAction(\n desc, self, checkable=True, toggled=self.on_hideargs_toggle\n )\n action.classes = set(classes)\n self.UI_viewM.addAction(action)\n self.UI_hideargs.append((action, set(classes)))\n\n def create_toolbar():\n \"\"\"Create all toolbars.\"\"\"\n # sampler\n self.UI_sampler = QtGui.QComboBox()\n self.UI_sampler.addItems(sorted(self.samplers.keys()))\n self.UI_sampler.currentIndexChanged[str].connect(\n self.on_sampler_change\n )\n\n samplerT = self.addToolBar(\"Sampler\")\n samplerT.pyqtConfigure(movable=False, objectName=\"Sampler\")\n samplerT.addWidget(QtGui.QLabel(\"Sampler:\"))\n samplerT.addWidget(self.UI_sampler)\n\n # #threads\n self.UI_nthreads = QtGui.QComboBox()\n self.UI_nthreads.currentIndexChanged[str].connect(\n self.on_nthreads_change\n )\n\n nthreadsT = self.addToolBar(\"#threads\")\n nthreadsT.pyqtConfigure(movable=False, objectName=\"#threads\")\n nthreadsT.addWidget(QtGui.QLabel(\"#threads:\"))\n nthreadsT.addWidget(self.UI_nthreads)\n\n # submit\n samplerT = self.addToolBar(\"Submit\")\n samplerT.pyqtConfigure(movable=False, objectName=\"Submit\")\n\n # spacer\n spacer = QtGui.QWidget()\n spacer.setSizePolicy(QtGui.QSizePolicy.Expanding,\n QtGui.QSizePolicy.Expanding)\n samplerT.addWidget(spacer)\n\n # submit\n self.UI_submit = QtGui.QAction(self.style().standardIcon(\n QtGui.QStyle.SP_DialogOkButton\n ), \"Run\", self, triggered=self.on_submit)\n samplerT.addAction(self.UI_submit)\n\n def create_ranges():\n \"\"\"Create the ranges dock widget.\"\"\"\n # checkboxes\n self.UI_userange = QtGui.QCheckBox(\n \" \", toggled=self.on_userange_toggle\n )\n\n self.UI_usesumrange = QtGui.QCheckBox(\n \" \", toggled=self.on_usesumrange_toggle\n )\n\n self.UI_calls_parallel = QtGui.QCheckBox(\n \" \", toggled=self.on_calls_parallel_toggle\n )\n\n # range\n self.UI_rangevar = QtGui.QLineEdit(\n textEdited=self.on_rangevar_change,\n editingFinished=self.UI_range_set\n )\n self.UI_rangevar.setValidator(QtGui.QRegExpValidator(\n QtCore.QRegExp(\"[a-zA-Z]+\"), self.UI_rangevar\n ))\n self.UI_rangevar.setFixedWidth(32)\n self.UI_rangevals = QtGui.QLineEdit(\n minimumWidth=32,\n textEdited=self.on_rangevals_change,\n editingFinished=self.UI_range_set\n )\n\n rangeL = QtGui.QHBoxLayout(spacing=0)\n rangeL.setContentsMargins(0, 0, 0, 0)\n rangeL.addWidget(QtGui.QLabel(\"for \"))\n rangeL.addWidget(self.UI_rangevar)\n rangeL.addWidget(QtGui.QLabel(\" = \"))\n rangeL.addWidget(self.UI_rangevals)\n rangeL.addWidget(QtGui.QLabel(\":\"))\n rangeL.addStretch(1)\n self.UI_rangeW = QtGui.QWidget()\n self.UI_rangeW.setLayout(rangeL)\n\n # reps\n self.UI_nreps = QtGui.QLineEdit(\n textEdited=self.on_nreps_change,\n editingFinished=self.UI_nreps_set\n )\n # self.UI_nreps.setValidator(QtGui.QIntValidator(bottom=1))\n self.UI_nreps.setValidator(QtGui.QIntValidator(1, 1000000, self))\n self.UI_nreps.setFixedWidth(32)\n\n nrepsL = QtGui.QHBoxLayout(spacing=0)\n nrepsL.setContentsMargins(16, 4, 0, 0)\n nrepsL.addWidget(QtGui.QLabel(\"repeat \"))\n nrepsL.addWidget(self.UI_nreps)\n nrepsL.addWidget(QtGui.QLabel(\" times:\"))\n nrepsL.addStretch(1)\n self.UI_nrepsW = QtGui.QWidget()\n self.UI_nrepsW.setLayout(nrepsL)\n\n # sumrange\n self.UI_sumrange_parallel = QtGui.QComboBox()\n self.UI_sumrange_parallel.addItems([\"sum over\", \"#omp for\"])\n self.UI_sumrange_parallel.currentIndexChanged[int].connect(\n self.on_sumrange_parallel_change\n )\n self.UI_sumrangevar = QtGui.QLineEdit(\n textEdited=self.on_sumrangevar_change,\n editingFinished=self.UI_sumrange_set\n )\n self.UI_sumrangevar.setValidator(QtGui.QRegExpValidator(\n QtCore.QRegExp(\"[a-zA-Z]+\"), self.UI_sumrangevar\n ))\n self.UI_sumrangevar.setFixedWidth(32)\n self.UI_sumrangevals = QtGui.QLineEdit(\n minimumWidth=32,\n textEdited=self.on_sumrangevals_change,\n editingFinished=self.UI_sumrange_set\n )\n\n sumrangeL = QtGui.QHBoxLayout(spacing=0)\n sumrangeL.setContentsMargins(32, 0, 0, 0)\n sumrangeL.addWidget(self.UI_sumrange_parallel)\n sumrangeL.addWidget(QtGui.QLabel(\" \"))\n sumrangeL.addWidget(self.UI_sumrangevar)\n sumrangeL.addWidget(QtGui.QLabel(\" = \"))\n sumrangeL.addWidget(self.UI_sumrangevals)\n sumrangeL.addWidget(QtGui.QLabel(\":\"))\n sumrangeL.addStretch(1)\n self.UI_sumrangeW = QtGui.QWidget()\n self.UI_sumrangeW.setLayout(sumrangeL)\n\n # calls_parallel\n calls_parallelL = QtGui.QHBoxLayout()\n calls_parallelL.setContentsMargins(48, 0, 0, 0)\n calls_parallelL.addWidget(QtGui.QLabel(\"in parallel:\"))\n calls_parallelL.addStretch(1)\n self.UI_calls_parallelW = QtGui.QWidget()\n self.UI_calls_parallelW.setLayout(calls_parallelL)\n\n rangesL = QtGui.QGridLayout(spacing=0)\n rangesL.addWidget(self.UI_userange, 0, 0)\n rangesL.addWidget(self.UI_rangeW, 0, 1)\n rangesL.addWidget(self.UI_nrepsW, 1, 1)\n rangesL.addWidget(self.UI_usesumrange, 2, 0)\n rangesL.addWidget(self.UI_sumrangeW, 2, 1)\n rangesL.addWidget(self.UI_calls_parallel, 3, 0)\n rangesL.addWidget(self.UI_calls_parallelW, 3, 1)\n rangesL.setRowStretch(4, 1)\n\n rangesW = QtGui.QWidget()\n rangesW.setLayout(rangesL)\n\n rangesD = QtGui.QDockWidget(\n \"Ranges\", objectName=\"Ranges\",\n features=QtGui.QDockWidget.DockWidgetVerticalTitleBar,\n )\n rangesD.setWidget(rangesW)\n\n self.addDockWidget(QtCore.Qt.TopDockWidgetArea, rangesD)\n\n def create_note():\n \"\"\"Create the note input.\"\"\"\n self.UI_note = QtGui.QTextEdit(\n textChanged=self.on_note_change\n )\n\n noteD = QtGui.QDockWidget(\n \"Note\", objectName=\"Note\",\n features=(QtGui.QDockWidget.DockWidgetVerticalTitleBar |\n QtGui.QDockWidget.DockWidgetMovable)\n )\n noteD.setWidget(self.UI_note)\n\n self.addDockWidget(QtCore.Qt.TopDockWidgetArea, noteD)\n\n def create_calls():\n \"\"\"Create the calls list and add button (central widget).\"\"\"\n self.UI_calls = QtGui.QListWidget(\n verticalScrollMode=QtGui.QListWidget.ScrollPerPixel,\n selectionMode=QtGui.QListWidget.ExtendedSelection,\n dragDropMode=QtGui.QListWidget.InternalMove,\n contextMenuPolicy=QtCore.Qt.CustomContextMenu,\n customContextMenuRequested=self.on_calls_rightclick\n )\n self.UI_calls.model().layoutChanged.connect(self.on_calls_reorder)\n\n self.setCentralWidget(self.UI_calls)\n\n # shortcuts\n QtGui.QShortcut(\n QtGui.QKeySequence.New, self.UI_calls,\n activated=self.on_call_add\n )\n QtGui.QShortcut(\n QtGui.QKeySequence.Close, self.UI_calls,\n activated=self.on_call_remove\n )\n\n # context menus\n self.UI_call_contextmenu = QtGui.QMenu()\n self.UI_calls_contextmenu = QtGui.QMenu()\n\n # add\n add = QtGui.QAction(\n \"Add call\", self, shortcut=QtGui.QKeySequence.New,\n triggered=self.on_call_add\n\n )\n self.UI_call_contextmenu.addAction(add)\n self.UI_calls_contextmenu.addAction(add)\n\n # remove\n self.UI_call_contextmenu.addAction(QtGui.QAction(\n \"Remove call\", self,\n shortcut=QtGui.QKeySequence.Close,\n triggered=self.on_call_remove\n ))\n\n # clone\n self.UI_call_contextmenu.addAction(QtGui.QAction(\n \"Clone call\", self, triggered=self.on_call_clone\n ))\n\n self.UI_call_contextmenu.addSeparator()\n self.UI_calls_contextmenu.addSeparator()\n\n self.UI_call_contextmenu.addMenu(self.UI_viewM)\n self.UI_calls_contextmenu.addMenu(self.UI_viewM)\n\n def create_counters():\n \"\"\"Create the counters widget.\"\"\"\n countersW = QtGui.QWidget()\n countersW.setLayout(QtGui.QVBoxLayout())\n countersW.layout().insertStretch(100, 1)\n\n self.UI_countersD = QtGui.QDockWidget(\n \"PAPI counters\", objectName=\"PAPI counters\",\n features=(QtGui.QDockWidget.DockWidgetVerticalTitleBar |\n QtGui.QDockWidget.DockWidgetMovable)\n )\n self.UI_countersD.setWidget(countersW)\n\n self.addDockWidget(QtCore.Qt.TopDockWidgetArea, self.UI_countersD)\n self.UI_countersD.hide()\n\n self.UI_countersD.widgets = []\n\n def create_style():\n \"\"\"Set style options.\"\"\"\n # stylesheet\n self.setStyleSheet(\"\"\"\n QLineEdit[invalid=\"true\"],\n *[invalid=\"true\"] QLineEdit {\n background: #FFDDDD;\n }\n QLabel:disabled,\n QLineEdit:disabled {\n color: #888888;\n }\n \"\"\")\n\n palette = self.Qapp.palette()\n dark = palette.text().color()\n darka = palette.text().color()\n darka.setAlpha(63)\n # pens and brushes (for dataargs)\n self.pens = {\n None: QtGui.QColor(0, 0, 255, 0),\n \"maxfront\": darka,\n \"maxback\": QtGui.QPen(darka, 0, QtCore.Qt.DashLine),\n \"minfront\": dark,\n \"minback\": QtGui.QPen(dark, 0, QtCore.Qt.DashLine)\n }\n windowcolor = palette.window().color()\n windowcoloralpha = palette.window().color()\n windowcoloralpha.setAlpha(63)\n self.brushes = {\n \"max\": windowcoloralpha,\n \"min\": windowcolor\n }\n\n create_menus()\n create_toolbar()\n create_ranges()\n create_note()\n create_calls()\n create_counters()\n create_style()\n\n self.UI_jobprogress = QJobProgress(self)\n\n self.show()\n\n self.UI_setting -= 1\n\n def UI_settings_load(self):\n \"\"\"Load Qt settings.\"\"\"\n settings = QtCore.QSettings(\"HPAC\", \"ELAPS:PlayMat\")\n self.hideargs = eval(str(settings.value(\"hideargs\", type=str)),\n signature.__dict__)\n self.UI_setting += 1\n self.restoreGeometry(settings.value(\"geometry\",\n type=QtCore.QByteArray))\n self.restoreState(settings.value(\"windowState\",\n type=QtCore.QByteArray))\n self.UI_setting -= 1\n\n def start(self):\n \"\"\"Start the Mat (enter the main loop).\"\"\"\n import signal\n signal.signal(signal.SIGINT, self.on_console_quit)\n\n # make sure python handles signals every 500ms\n timer = QtCore.QTimer(timeout=lambda: None)\n timer.start(500)\n\n sys.exit(self.Qapp.exec_())\n\n # utility\n def log(self, *args):\n \"\"\"Log a message to stdout and statusbar.\"\"\"\n msg = \" \".join(map(str, args))\n self.statusBar().showMessage(msg, 2000)\n print(msg)\n\n def alert(self, *args):\n \"\"\"Log a message to stderr and statusbar.\"\"\"\n msg = \" \".join(map(str, args))\n self.statusBar().showMessage(msg)\n print(\"\\033[31m%s\\033[0m\" % msg, file=sys.stderr)\n\n def UI_set_invalid(self, widget, state=True):\n \"\"\"Set a widget's \"invalid\" property.\"\"\"\n widget.setProperty(\"invalid\", state)\n widget.style().unpolish(widget)\n widget.style().polish(widget)\n widget.update()\n\n # experiment routines\n def experiment_set(self, ex):\n \"\"\"Insert own/new objects into loaded experiment.\"\"\"\n # own Sampler\n if ex.sampler is None or ex.sampler[\"name\"] not in self.samplers:\n sampler = self.samplers[min(self.samplers)]\n else:\n sampler = self.samplers[ex.sampler[\"name\"]]\n ex.set_sampler(sampler, force=True)\n\n # own Signatures\n newcalls = []\n for call in ex.calls:\n sig = self.sig_get(call[0])\n if sig:\n newcalls.append(sig(*call[1:]))\n else:\n newcalls.append(call)\n ex.calls = newcalls\n\n self.experiment = ex\n\n def experiment_reset(self):\n \"\"\"Reset experiment to default.\"\"\"\n self.experiment_set(elaps.io.load_experiment_string(\n defines.default_experiment_str\n ))\n self.log(\"Loaded default Experiment\")\n\n def experiment_qt_load(self):\n \"\"\"Load Experiment from Qt setting.\"\"\"\n ex = elaps.io.load_experiment_string(str(\n QtCore.QSettings(\"HPAC\", \"ELAPS:PlayMat\").value(\"Experiment\",\n type=str)\n ))\n self.experiment_set(ex)\n self.log(\"Loaded last Experiment\")\n\n def experiment_load(self, filename):\n \"\"\"Load Experiment from a file.\"\"\"\n ex = elaps.io.load_experiment(filename)\n self.experiment_set(ex)\n self.log(\"Loaded Experiment from %r.\" % os.path.relpath(filename))\n\n def experiment_write(self, filename):\n \"\"\"Write Experiment to a file.\"\"\"\n elaps.io.wrte_experiment(self.experiment, filename)\n self.log(\"Written Experiment to %r.\" % os.path.relpath(filename))\n\n def experiment_infer_update_set(self, callid=None):\n \"\"\"Infer Ld and Lwork (if not showing).\"\"\"\n ex = self.experiment\n if signature.Ld in self.hideargs:\n ex.infer_lds(callid)\n if signature.Lwork in self.hideargs:\n ex.infer_lworks(callid)\n self.UI_submit_setenabled()\n self.UI_calls_set()\n\n def experiment_submit(self, filebase):\n \"\"\"Submit a job.\"\"\"\n ex = self.experiment\n backend = ex.sampler[\"backend\"]\n jobid = ex.submit(filebase)\n self.last_filebase = filebase\n self.UI_jobprogress.add_job(filebase, jobid, ex)\n self.log(\"Submitted job for %r to %r.\" % (filebase, backend.name))\n\n # loaders\n def sig_get(self, routine):\n \"\"\"(Try to) get the Signature for a routine.\"\"\"\n if routine not in self.sigs:\n try:\n sig = elaps.io.load_signature(routine)\n sig() # try the signature\n self.sigs[routine] = sig\n self.log(\"Loaded Signature for %r.\" % routine)\n except:\n self.sigs[routine] = None\n self.log(\"Can't load Signature for %r.\" % routine)\n return self.sigs[routine]\n\n def docs_get(self, routine):\n \"\"\"(Try to) get the documentation for a routine.\"\"\"\n if routine not in self.docs:\n try:\n self.docs[routine] = elaps.io.load_doc(routine)\n self.log(\"Loaded documentation for %r.\" % routine)\n except:\n self.docs[routine] = None\n self.log(\"Can't load documentation for %r.\" % routine)\n return self.docs[routine]\n\n # viewer\n def viewer_start(self, *args):\n \"\"\"Start the Viewer.\"\"\"\n from viewer import Viewer\n Viewer(*args, app=self.Qapp)\n\n # UI utility\n def UI_dialog(self, msgtype, title, text, callbacks=None):\n \"\"\"Show a simple user dialog with multiple options.\"\"\"\n if callbacks is None:\n callbacks = {\"Ok\": None}\n msgtypes = {\n \"information\": QtGui.QMessageBox.information,\n \"warning\": QtGui.QMessageBox.warning,\n \"question\": QtGui.QMessageBox.question,\n \"critical\": QtGui.QMessageBox.question\n }\n buttontypes = {\n \"Ok\": QtGui.QMessageBox.Ok,\n \"Cancel\": QtGui.QMessageBox.Cancel\n }\n\n callbackmap = {}\n buttons = 0\n for key, callback in callbacks.iteritems():\n callbackmap[buttontypes[key]] = callback\n buttons |= buttontypes[key]\n\n ret = msgtypes[msgtype](self, title, text, buttons)\n if callbackmap[ret] is not None:\n callbackmap[ret][0](*callbackmap[ret][1])\n\n def UI_alert(self, *args, **kwargs):\n \"\"\"Alert a messagebox.\"\"\"\n msg = \" \".join(map(str, args))\n title = kwargs.get(\"title\", \"\")\n self.UI_dialog(\"information\", title, msg)\n\n def UI_varyactions(self, name):\n \"\"\"Generate vary menu for Operand.\"\"\"\n ex = self.experiment\n data = ex.get_operand(name)\n vary = ex.vary[name]\n\n actions = []\n\n withrep = QtGui.QAction(\n \"Vary with repetitions\", self,\n checkable=True, checked=\"rep\" in vary[\"with\"],\n toggled=self.on_vary_with_toggle\n )\n withrep.name = name\n withrep.with_ = \"rep\"\n actions.append(withrep)\n\n if ex.sumrange:\n withsumrange = QtGui.QAction(\n \"Vary with %s\" % ex.sumrange_var, self,\n checkable=True, checked=ex.sumrange_var in vary[\"with\"],\n toggled=self.on_vary_with_toggle\n )\n\n withsumrange.name = name\n withsumrange.with_ = ex.sumrange_var\n actions.append(withsumrange)\n\n if not vary[\"with\"]:\n return actions\n\n if len(data[\"dims\"]) > 1:\n actions.append(None)\n alongG = QtGui.QActionGroup(self, exclusive=True)\n for along in range(len(data[\"dims\"])):\n if along < 3:\n text = \"Vary along %s (dim %d)\" % (\n u\"\\u2193\\u2192\\u2197\"[along],\n along + 1\n )\n else:\n text = \"Vary along dim %d\" % (along + 1)\n\n alongA = QtGui.QAction(\n text, self,\n checkable=True,\n checked=vary[\"along\"] == along,\n toggled=self.on_vary_along_toggle,\n )\n alongA.name = name\n alongA.along = along\n alongG.addAction(alongA)\n actions.append(alongA)\n\n actions.append(None)\n text = \"Change vary offset (%s)\" % vary[\"offset\"]\n offset = QtGui.QAction(\n text, self, triggered=self.on_vary_offset\n )\n offset.name = name\n actions.append(offset)\n\n actions.append(None)\n\n return actions\n\n # UI setters\n def UI_setall(self):\n \"\"\"Set all UI elements.\"\"\"\n # sampler\n self.UI_hideargs_set()\n self.UI_sampler_set()\n self.UI_nthreads_set()\n self.UI_range_set()\n self.UI_nreps_set()\n self.UI_sumrange_set()\n self.UI_calls_parallel_set()\n self.UI_submit_setenabled()\n self.UI_note_set()\n self.UI_counters_set()\n self.UI_calls_set()\n\n def UI_hideargs_set(self):\n \"\"\"Set UI element: hideargs options.\"\"\"\n self.UI_setting += 1\n for UI_showarg, classes in self.UI_hideargs:\n UI_showarg.setChecked(self.hideargs >= classes)\n self.UI_setting -= 1\n\n def UI_sampler_set(self):\n \"\"\"Set UI element: sampler.\"\"\"\n self.UI_setting += 1\n self.UI_sampler.setCurrentIndex(\n self.UI_sampler.findText(self.experiment.sampler[\"name\"])\n )\n self.UI_setting -= 1\n\n def UI_nthreads_set(self):\n \"\"\"Set UI element: #threads.\"\"\"\n self.UI_setting += 1\n self.UI_nthreads.clear()\n self.UI_nthreads.addItems(\n map(str, range(1, self.experiment.sampler[\"nt_max\"] + 1))\n )\n if self.experiment.range:\n self.UI_nthreads.addItem(str(self.experiment.range_var))\n self.UI_nthreads.setCurrentIndex(\n self.UI_nthreads.findText(str(self.experiment.nthreads))\n )\n self.UI_setting -= 1\n\n @pyqtSlot()\n def UI_range_set(self):\n \"\"\"Set UI element: range.\"\"\"\n self.UI_setting += 1\n ex = self.experiment\n userange = bool(ex.range)\n self.UI_userange.setChecked(userange)\n self.UI_rangeW.setEnabled(userange)\n if userange:\n self.UI_rangevar.setText(str(ex.range_var))\n self.UI_set_invalid(self.UI_rangevar, False)\n self.UI_rangevals.setText(str(ex.range_vals))\n self.UI_set_invalid(self.UI_rangevals, False)\n self.UI_setting -= 1\n\n @pyqtSlot()\n def UI_nreps_set(self):\n \"\"\"Set UI element: nreps.\"\"\"\n self.UI_setting += 1\n self.UI_nreps.setText(str(self.experiment.nreps))\n self.UI_set_invalid(self.UI_nreps, False)\n self.UI_setting -= 1\n\n @pyqtSlot()\n def UI_sumrange_set(self):\n \"\"\"Set UI element: sumrange.\"\"\"\n self.UI_setting += 1\n ex = self.experiment\n usesumrange = bool(ex.sumrange)\n self.UI_usesumrange.setChecked(usesumrange)\n self.UI_sumrangeW.setEnabled(usesumrange)\n if usesumrange:\n self.UI_sumrange_parallel.setEnabled(ex.sampler[\"omp_enabled\"])\n self.UI_sumrange_parallel.setCurrentIndex(int(ex.sumrange_parallel))\n self.UI_sumrangevar.setText(str(ex.sumrange_var))\n self.UI_set_invalid(self.UI_sumrangevar, False)\n self.UI_sumrangevals.setText(str(ex.sumrange_vals))\n self.UI_set_invalid(self.UI_sumrangevals, False)\n self.UI_setting -= 1\n\n def UI_calls_parallel_set(self):\n \"\"\"Set UI element: calls_parallel.\"\"\"\n self.UI_setting += 1\n ex = self.experiment\n calls_parallel = ex.calls_parallel\n self.UI_calls_parallel.setEnabled(ex.sampler[\"omp_enabled\"])\n self.UI_calls_parallel.setChecked(calls_parallel)\n self.UI_calls_parallelW.setEnabled(calls_parallel)\n self.UI_setting -= 1\n\n def UI_calls_set(self):\n \"\"\"Set UI element: calls.\"\"\"\n self.UI_setting += 1\n for callid, call in enumerate(self.experiment.calls):\n if callid >= self.UI_calls.count():\n UI_call = QCall(self, callid)\n self.UI_calls.addItem(UI_call)\n self.UI_calls.setItemWidget(UI_call, UI_call.widget)\n self.UI_calls.item(callid).setall()\n while self.UI_calls.count() > len(self.experiment.calls):\n self.UI_calls.takeItem(len(self.experiment.calls))\n self.UI_setting -= 1\n\n def UI_note_set(self):\n \"\"\"Set UI element: note.\"\"\"\n self.UI_setting += 1\n self.UI_note.setPlainText(self.experiment.note or \"\")\n self.UI_setting -= 1\n\n def UI_counters_set(self):\n \"\"\"Set UI element: counters.\"\"\"\n self.UI_setting += 1\n ex = self.experiment\n if not ex.sampler[\"papi_enabled\"]:\n self.UI_countersD.hide()\n self.UI_setting -= 1\n return\n\n # PAPI is available\n counterWs = self.UI_countersD.widgets\n for counterid in range(ex.sampler[\"papi_counters_max\"]):\n if counterid >= len(counterWs):\n # create widgets as needed\n counterW = QtGui.QComboBox(\n currentIndexChanged=self.on_counter_change\n )\n counterW.addItem(\"\", QtCore.QVariant(\"\"))\n for i, name in enumerate(ex.sampler[\"papi_counters_avail\"]):\n event = self.papi_names[name]\n counterW.addItem(event[\"short\"], QtCore.QVariant(name))\n counterW.setItemData(i + 1, name + \"\\n\" + event[\"long\"],\n QtCore.Qt.ToolTipRole)\n self.UI_countersD.widget().layout().insertWidget(counterid,\n counterW)\n counterWs.append(counterW)\n else:\n counterW = counterWs[counterid]\n # set values\n if counterid < len(ex.papi_counters):\n counterW.setCurrentIndex(counterW.findData(\n QtCore.QVariant(ex.papi_counters[counterid])\n ))\n else:\n counterW.setCurrentIndex(0)\n counterW.setVisible(counterid <= len(ex.papi_counters))\n # remove additional widgets\n while len(counterWs) > ex.sampler[\"papi_counters_max\"]:\n counterWs[-1].deleteLater()\n del counterWs[-1]\n self.UI_countersD.show()\n self.UI_setting -= 1\n\n def UI_submit_setenabled(self):\n \"\"\"En/Disable the submit Action.\"\"\"\n try:\n self.experiment.check_sanity(True)\n enabled = True\n tooltip = \"Run\"\n except Exception as e:\n enabled = False\n tooltip = str(e)\n self.UI_submitA.setEnabled(enabled)\n self.UI_submit.setEnabled(enabled)\n self.UI_submit.setToolTip(tooltip)\n\n # UI events\n def on_console_quit(self, *args):\n \"\"\"Event: Ctrl-C from the console.\"\"\"\n print(\"\\r\", end=\"\")\n self.close()\n if self.Qapp.viewer:\n self.Qapp.viewer.close()\n self.Qapp.quit()\n\n def closeEvent(self, event):\n \"\"\"Event: close main window.\"\"\"\n settings = QtCore.QSettings(\"HPAC\", \"ELAPS:PlayMat\")\n settings.setValue(\"geometry\", self.saveGeometry())\n settings.setValue(\"windowState\", self.saveState())\n settings.setValue(\"Experiment\", repr(self.experiment))\n settings.setValue(\"hideargs\", repr(self.hideargs))\n self.log(\"Experiment saved.\")\n\n @pyqtSlot()\n def on_submit(self):\n \"\"\"Event: submit.\"\"\"\n if self.Qapp.keyboardModifiers() & QtCore.Qt.ShiftModifier:\n if self.last_filebase:\n self.on_submit_last()\n return\n\n reportpath = elaps.io.reportpath\n if self.last_filebase:\n reportpath = \"%s.%s\" % (self.last_filebase,\n defines.report_extension)\n filename = QtGui.QFileDialog.getSaveFileName(\n self, \"Generate Report\", reportpath,\n \"*.\" + defines.report_extension\n )\n if not filename:\n return\n filebase = str(filename)\n if filebase[-4:] == \".\" + defines.report_extension:\n filebase = filebase[:-4]\n self.experiment_submit(filebase)\n\n @pyqtSlot()\n def on_submit_last(self):\n \"\"\"Event: resubmit last job.\"\"\"\n if not self.last_filebase:\n self.on_submit()\n return\n self.experiment_submit(self.last_filebase)\n\n @pyqtSlot()\n def on_experiment_reset(self):\n \"\"\"Event: reset experiment.\"\"\"\n self.experiment_reset()\n self.UI_setall()\n\n @pyqtSlot()\n def on_experiment_load(self, report=False):\n \"\"\"Event: load experiment.\"\"\"\n filename = QtGui.QFileDialog.getOpenFileName(\n self, \"Load Experiment\",\n elaps.io.reportpath if report else elaps.io.experimentpath,\n \" \".join(\"*.\" + ext for ext in defines.experiment_extensions)\n )\n if not filename:\n return\n self.experiment_load(str(filename))\n self.UI_setall()\n\n @pyqtSlot()\n def on_experiment_load_report(self):\n \"\"\"Event: load experiment from report.\"\"\"\n self.on_experiment_load(True)\n\n @pyqtSlot()\n def on_experiment_save(self):\n \"\"\"Event: save experiment.\"\"\"\n filename = QtGui.QFileDialog.getSaveFileName(\n self,\n \"Save Setup\",\n elaps.io.experimentpath,\n \"*.\" + defines.experiment_extension\n )\n if not filename:\n return\n filebase = str(filename)\n if filebase[-4:] == \".\" + defines.experiment_extension:\n filebase = filebase[:-4]\n filename = \"%s.%s\" % (filebase, defines.experiment_extension)\n elaps.io.write_experiment(self.experiment, filename)\n\n @pyqtSlot()\n def on_viewer_start(self):\n \"\"\"Event: start Viewer.\"\"\"\n if not self.Qapp.viewer:\n self.viewer_start()\n self.Qapp.viewer.show()\n\n # @pyqtSlot(bool) # sender() pyqt bug\n def on_hideargs_toggle(self, checked):\n \"\"\"Event: toggle showarg.\"\"\"\n if self.UI_setting:\n return\n classes = self.Qapp.sender().classes\n if checked:\n self.hideargs |= classes\n else:\n self.hideargs -= classes\n self.UI_hideargs_set()\n self.UI_calls_set()\n\n @pyqtSlot(str)\n def on_note_change(self):\n \"\"\"Event: changed note.\"\"\"\n if self.UI_setting:\n return\n self.experiment.note = self.UI_note.toPlainText()\n\n @pyqtSlot(str)\n def on_sampler_change(self, value, force=False):\n \"\"\"Event: change sampler.\"\"\"\n if self.UI_setting:\n return\n try:\n sampler = self.samplers[str(value)]\n self.experiment.set_sampler(sampler, force=force)\n self.UI_setall()\n except Exception as e:\n self.UI_dialog(\n \"question\", \"Incompatible sampler\",\n \"Sampler %s is not compatible with the current experiment\\n\"\n \"(%s)\\nAdjust the experiment?\" % (value, e),\n {\"Ok\": (self.on_sampler_change, (value, True)), \"Cancel\": None}\n )\n\n @pyqtSlot(str)\n def on_nthreads_change(self, value):\n \"\"\"Event: change #threads.\"\"\"\n if self.UI_setting:\n return\n self.experiment.set_nthreads(str(value), force=True)\n\n @pyqtSlot(bool)\n def on_userange_toggle(self, checked):\n \"\"\"Event: change if range is used.\"\"\"\n if self.UI_setting:\n return\n ex = self.experiment\n if checked:\n range_var = str(self.UI_rangevar.text())\n range_vals = str(self.UI_rangevals.text())\n ex.set_range((range_var, range_vals), force=True)\n else:\n ex.set_range(None)\n self.UI_sumrange_set()\n self.UI_nthreads_set()\n self.UI_range_set()\n self.UI_calls_set()\n self.UI_submit_setenabled()\n\n @pyqtSlot(str)\n def on_rangevar_change(self, value):\n \"\"\"Event: change range variable.\"\"\"\n try:\n self.experiment.set_range_var(str(value))\n self.UI_set_invalid(self.UI_rangevar, False)\n self.UI_nthreads_set()\n self.UI_sumrange_set()\n self.UI_calls_set()\n self.UI_submit_setenabled()\n except:\n self.UI_set_invalid(self.UI_rangevar)\n\n @pyqtSlot(str)\n def on_rangevals_change(self, value):\n \"\"\"Event: change range.\"\"\"\n try:\n self.experiment.set_range_vals(str(value))\n self.UI_set_invalid(self.UI_rangevals, False)\n self.experiment_infer_update_set()\n except:\n self.UI_set_invalid(self.UI_rangevals)\n\n @pyqtSlot(str)\n def on_nreps_change(self, value):\n \"\"\"Event: change #repetitions.\"\"\"\n try:\n self.experiment.set_nreps(str(value))\n self.UI_set_invalid(self.UI_nreps, False)\n self.experiment_infer_update_set()\n except:\n self.UI_set_invalid(self.UI_nreps)\n\n @pyqtSlot(bool)\n def on_usesumrange_toggle(self, checked):\n \"\"\"Event: change if sumrange is used.\"\"\"\n if self.UI_setting:\n return\n ex = self.experiment\n if checked:\n sumrange_var = str(self.UI_sumrangevar.text())\n sumrange_vals = str(self.UI_sumrangevals.text())\n sumrange_parallel = bool(int(\n self.UI_sumrange_parallel.currentIndex()\n ))\n ex.set_sumrange((sumrange_var, sumrange_vals), force=True)\n ex.set_sumrange_parallel(sumrange_parallel, force=True)\n else:\n ex.set_sumrange(None)\n self.UI_sumrange_set()\n self.UI_calls_set()\n self.UI_submit_setenabled()\n\n @pyqtSlot(int)\n def on_sumrange_parallel_change(self, value):\n \"\"\"Event: change if sumrange is in parallel.\"\"\"\n if self.UI_setting:\n return\n self.experiment.set_sumrange_parallel(bool(value))\n self.UI_sumrange_set()\n\n @pyqtSlot(str)\n def on_sumrangevar_change(self, value):\n \"\"\"Event: change sumrange variable.\"\"\"\n try:\n self.experiment.set_sumrange_var(str(value))\n self.UI_set_invalid(self.UI_sumrangevar, False)\n self.UI_calls_set()\n self.UI_submit_setenabled()\n except:\n self.UI_set_invalid(self.UI_sumrangevar)\n\n @pyqtSlot(str)\n def on_sumrangevals_change(self, value):\n \"\"\"Event: change sumrange.\"\"\"\n try:\n self.experiment.set_sumrange_vals(str(value))\n self.UI_set_invalid(self.UI_sumrangevals, False)\n self.experiment_infer_update_set()\n except:\n self.UI_set_invalid(self.UI_sumrangevals)\n\n @pyqtSlot(bool)\n def on_calls_parallel_toggle(self, value):\n \"\"\"Event: change if calls are in parallel.\"\"\"\n if self.UI_setting:\n return\n self.experiment.set_calls_parallel(bool(value))\n self.UI_calls_parallel_set()\n\n @pyqtSlot()\n def on_calls_reorder(self):\n \"\"\"Event: change call order.\"\"\"\n calls = self.experiment.calls\n self.experiment.calls = []\n for idx in range(self.UI_calls.count()):\n self.experiment.calls.append(\n calls[self.UI_calls.item(idx).fixcallid]\n )\n self.UI_calls_set()\n\n def on_routine_set(self, callid, value):\n \"\"\"Event: Set routine value.\"\"\"\n ex = self.experiment\n if value not in ex.sampler[\"kernels\"]:\n self.UI_set_invalid(self.UI_calls.item(callid).UI_args[0])\n return\n sig = self.sig_get(value)\n if not sig:\n try:\n # prepare call\n call = [value]\n\n # set call\n ex.set_call(callid, call)\n self.UI_set_invalid(self.UI_calls.item(callid).UI_args[0],\n False)\n self.experiment_infer_update_set()\n except:\n self.UI_set_invalid(self.UI_calls.item(callid).UI_args[0])\n else:\n try:\n # prepare call\n call = sig()\n operands = ex.operands\n varnames = [name for name in string.ascii_uppercase\n if name not in operands]\n for argid, arg in enumerate(sig):\n if isinstance(arg, (signature.Dim, signature.Ld)):\n call[argid] = defines.default_dim\n if isinstance(arg, signature.Data):\n call[argid] = varnames.pop(0)\n\n # set call\n ex.set_call(callid, call, force=True)\n ex.infer_lds(callid)\n ex.infer_lworks(callid)\n self.UI_set_invalid(self.UI_calls.item(callid).UI_args[0],\n False)\n self.experiment_infer_update_set()\n except Exception as e:\n import traceback\n traceback.print_exc()\n self.UI_set_invalid(self.UI_calls.item(callid).UI_args[0])\n\n def on_arg_set(self, callid, argid, value):\n \"\"\"Event: Set argument value.\"\"\"\n if self.UI_setting:\n return\n if argid == 0:\n self.on_routine_set(callid, value)\n return\n try:\n self.experiment.set_arg(callid, argid, value)\n self.UI_set_invalid(self.UI_calls.item(callid).UI_args[argid],\n False)\n self.experiment_infer_update_set()\n except Exception as e:\n if \"Incompatible operand sizes\" in str(e):\n ret = QtGui.QMessageBox.question(\n self, str(e), \"Adjust dimensions automatically?\",\n QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel\n )\n if ret == QtGui.QMessageBox.Ok:\n self.experiment.set_arg(callid, argid, value, force=True)\n self.UI_set_invalid(\n self.UI_calls.item(callid).UI_args[argid], False\n )\n self.experiment_infer_update_set()\n return\n self.UI_set_invalid(self.UI_calls.item(callid).UI_args[argid])\n if \"Incompatible operand types:\" in str(e):\n self.UI_alert(e)\n\n @pyqtSlot(QtCore.QPoint)\n def on_calls_rightclick(self, pos):\n \"\"\"Event: right click in calls.\"\"\"\n globalpos = self.UI_calls.viewport().mapToGlobal(pos)\n item = self.UI_calls.itemAt(pos)\n if item:\n self.UI_call_contextmenu.item = item\n self.UI_call_contextmenu.exec_(globalpos)\n else:\n self.UI_calls_contextmenu.exec_(globalpos)\n\n @pyqtSlot()\n def on_call_add(self):\n \"\"\"Event: add call.\"\"\"\n self.experiment.calls.append([\"\"])\n self.UI_submit_setenabled()\n self.UI_calls_set()\n callid = len(self.experiment.calls) - 1\n self.UI_calls.item(callid).UI_args[0].setFocus()\n selected_callid = self.UI_calls.currentRow()\n if selected_callid != -1:\n self.UI_calls.setItemSelected(self.UI_calls.item(selected_callid),\n False)\n self.UI_calls.setCurrentRow(callid)\n\n @pyqtSlot()\n def on_call_remove(self):\n \"\"\"Event: remove call.\"\"\"\n callid = self.UI_calls.currentRow()\n if callid == -1:\n return\n self.experiment.calls.pop(callid)\n self.UI_submit_setenabled()\n self.UI_calls_set()\n if callid:\n self.UI_calls.setCurrentRow(callid - 1)\n\n @pyqtSlot()\n def on_call_clone(self):\n \"\"\"Event: clone call.\"\"\"\n self.experiment.calls.append(\n self.experiment.calls[self.UI_call_contextmenu.item.callid].copy()\n )\n self.UI_submit_setenabled()\n self.UI_calls_set()\n\n def on_infer_ld(self, callid, argid):\n \"\"\"Event: infer ld.\"\"\"\n self.experiment.infer_ld(callid, argid)\n self.UI_submit_setenabled()\n self.UI_calls_set()\n\n @pyqtSlot()\n def on_infer_lwork(self, callid, argid):\n \"\"\"Event: infer lwork.\"\"\"\n self.experiment.infer_lwork(callid, argid)\n self.UI_submit_setenabled()\n self.UI_calls_set()\n\n # @pyqtSlot(bool) # sender() pyqt bug\n def on_vary_with_toggle(self, checked):\n \"\"\"Event: changed vary with.\"\"\"\n sender = self.Qapp.sender()\n ex = self.experiment\n name = sender.name\n with_ = sender.with_\n if checked:\n ex.add_vary_with(name, with_)\n else:\n ex.remove_vary_with(name, with_)\n self.experiment_infer_update_set()\n\n # @pyqtSlot(bool) # sender() pyqt bug\n def on_vary_along_toggle(self, checked):\n \"\"\"Event: changed vary along.\"\"\"\n sender = self.Qapp.sender()\n self.experiment.set_vary_along(sender.name, sender.along)\n self.experiment_infer_update_set()\n\n # @pyqtSlot() # sender() pyqt bug\n def on_vary_offset(self):\n \"\"\"Event: set vary offset.\"\"\"\n sender = self.Qapp.sender()\n ex = self.experiment\n name = sender.name\n offset = ex.vary[name][\"offset\"]\n value, ok = QtGui.QInputDialog.getText(\n self, \"Vary offset for %s\" % name,\n \"Vary offset for %s:\" % name, text=str(offset)\n )\n if not ok:\n return\n value = str(value) or \"0\"\n try:\n ex.set_vary_offset(name, value)\n self.experiment_infer_update_set()\n except:\n self.UI_alert(\"Invalid offset:\\n%s\" % value)\n\n @pyqtSlot()\n def on_counter_change(self):\n \"\"\"Event: changed PAPI counter.\"\"\"\n if self.UI_setting:\n return\n counternames = [\n str(widget.itemData(widget.currentIndex()).toString())\n for widget in self.UI_countersD.widgets\n ]\n self.experiment.papi_counters = [name for name in counternames if name]\n self.UI_counters_set()\n\n def on_open_viewer(self, filename):\n \"\"\"Event: open report in Viewer.\"\"\"\n if not self.Qapp.viewer:\n self.viewer_start(filename)\n return\n self.Qapp.viewer.report_load(filename, UI_alert=True)\n self.Qapp.viewer.UI_setall()\n self.Qapp.viewer.show()\n self.Qapp.viewer.raise_()\n","sub_path":"elaps/qt/playmat.py","file_name":"playmat.py","file_ext":"py","file_size_in_byte":46271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"617381781","text":"import logging\nfrom datetime import datetime, timedelta, date\nfrom model.option_data_details import OptionDataDetails\nfrom model.option_data import OptionData\nfrom service.nse_options_service import NseOptionsService\nfrom parsers.date_parser import DatesParser\n\nlog = logging.getLogger(__name__)\n\n\nclass NSEOptionsServiceAdapter:\n\n def __init__(self):\n self.nse_options_service = NseOptionsService()\n self.dates_parser = DatesParser()\n self.put_option_data = OptionDataDetails()\n self.call_option_data = OptionDataDetails()\n\n # this assumes only 1 expiry per week.\n def actual_next_weekly_expiry_date(self, option_chain, next_expiry_date):\n proposed_next_expiry = None\n expiry_on_thursday = False\n\n # expiry_dates = option_chain['records']['expiryDates']\n # expiry_dates[1] = '15-Sep-2021'\n for expiry_date in option_chain['records']['expiryDates']:\n if next_expiry_date == expiry_date:\n expiry_on_thursday = True # 90% of time it will be the case (expiry on Thursday)\n break\n\n # if expiry is not on Thursday, assuming it will be either on Monday, Tuesday, Wednesday or Friday\n if not expiry_on_thursday:\n proposed_next_expiry = self.dates_parser.date_parser_init.change_date_format_2(next_expiry_date)\n formatted_date = proposed_next_expiry.split('-')\n proposed_next_expiry = date(int(formatted_date[0]), int(formatted_date[1]), int(formatted_date[2]))\n\n for expiry_date in option_chain['records']['expiryDates']:\n expiry_date = self.dates_parser.date_parser_init.change_date_format_2(expiry_date)\n formatted_date = expiry_date.split('-')\n expiry_date = date(int(formatted_date[0]), int(formatted_date[1]), int(formatted_date[2]))\n if datetime.today().date() >= expiry_date:\n continue\n else:\n if proposed_next_expiry - timedelta(1) == expiry_date:\n proposed_next_expiry = expiry_date\n break\n if proposed_next_expiry - timedelta(2) == expiry_date:\n proposed_next_expiry = expiry_date\n break\n\n if proposed_next_expiry - timedelta(3) == expiry_date:\n proposed_next_expiry = expiry_date\n break\n if proposed_next_expiry + timedelta(1) == expiry_date:\n proposed_next_expiry = expiry_date\n break\n else:\n print(\"No expiry this week.\")\n print()\n exit(0)\n proposed_next_expiry = self.dates_parser.date_parser_init.change_date_format_1(proposed_next_expiry)\n\n if expiry_on_thursday:\n return next_expiry_date\n else:\n return proposed_next_expiry\n\n def get_reqd_fields(self, security):\n option_chain = self.nse_options_service.get_option_chain(security)\n\n # only for testing purposes, in real scenario API will be called as above\n # with open(f\"../test_data/option_chain_BANKNIFTY_2021_09_11 02_36_25_562800\", \"r\") as f:\n # option_chain = json.loads(f.read())\n\n next_expiry_date = self.dates_parser.proposed_next_weekly_expiry_date(datetime.today().date())\n actual_next_weekly_expiry = self.actual_next_weekly_expiry_date(option_chain, next_expiry_date)\n print(actual_next_weekly_expiry)\n print()\n\n put_option_data = dict()\n call_option_data = dict()\n start_time = datetime.now()\n for option_data in option_chain['records']['data']:\n if option_data['expiryDate'] == actual_next_weekly_expiry:\n self.put_option_data.strike_price = option_data['strikePrice']\n self.put_option_data.option_data = OptionData(option_data['PE'])\n put_option_data[self.put_option_data.strike_price] = self.put_option_data.option_data\n self.call_option_data.strike_price = option_data['strikePrice']\n self.call_option_data.option_data = OptionData(option_data['CE'])\n call_option_data[self.call_option_data.strike_price] = self.call_option_data.option_data\n\n end_time = datetime.now()\n total_time = end_time - start_time\n print(f\"Total time: {total_time}\")\n print()\n\n return put_option_data, call_option_data, actual_next_weekly_expiry\n\n\n# nse_option_adapter = NSEOptionsServiceAdapter()\n# print(nse_option_adapter.get_reqd_fields(\"BANKNIFTY\"))\n","sub_path":"adapter/nse_options_service_adapter.py","file_name":"nse_options_service_adapter.py","file_ext":"py","file_size_in_byte":4695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"211315638","text":"# Time Complexity : O(n)\n# Space Complexity : O(n)\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\n'''\n1. Maintain a stack containing active function call. Every time a new func call occurs update the prev log's execution time by subtracting prev end time and curr time\n2. When an end time of a func call is encountered, pop the lement from stack and update the prev logs execution time\nby subtracting prev end time and curr time + 1\n\n'''\n\nfrom collections import deque\nclass Solution:\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n \n if len(logs) < 2:\n return\n \n log_map = [0]*n\n \n stack = deque()\n prev_end = 0\n for i in range(len(logs)):\n \n log_id, SE, time = tuple(logs[i].split(\":\"))\n \n if SE == \"start\":\n if stack:\n peek_id = stack[-1]\n log_map[peek_id] += int(time) - prev_end\n \n stack.append(int(log_id))\n prev_end = int(time)\n else:\n log_map[stack.pop()] += int(time) - prev_end + 1\n prev_end = int(time) + 1\n \n \n return log_map\n \n \n \n ","sub_path":"execlusive_time_of_functions.py","file_name":"execlusive_time_of_functions.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"190724831","text":"'''\n@author:lvming\n@time:2021/6/28\n'''\nfrom time import sleep\n\n'''\n selenium grid模块的分布式部署\n Grid:\n Selenium Grid。是selenium家族存在时间特别有就,但是又鲜有人使用的组件。使用有难度限制\n 是一个分布式部署的组件。是分布式形态中最为典型的一种,叫做MS的形态。\n M表示主节点,不干活只下发任务\n S表示从节点,只干活\n 核心环境:\n 1.M环境\n 2.S环境\n 两者环境保持一致\n 1.JDK:百度安装指南\n 2.Selenium Stand alone.jar:在selenium官网下载。\n 3.webdriver.exe:浏览器驱动,版本对应即可\n 3.部署M节点\n 1.java -jar ./Selenium Stand alone.jar -role hub -port 4000\n 4.部署S节点\n 1.java -jar ./Selenium Stand alone.jar -role node -hub http://192.168.xx.xx:4000/grid/register -port 5000\n Remote创建grid的浏览器对象,webdriver创建selenium的浏览器对象\n 这个技术在面试的时候用来装逼,以及对于现有自动化测试框架体系技术做一个效率提升。和自动化测试精进很有帮助\n 课后练手:\n\t1.部署selenium grid\n\t2.结合多线程的用例并发,将原有的关键字驱动+Excel驱动实现一个excel一个线程的形态。\n\t3.尝试基于UnitTest来实现多线程用例并发处理。\n'''\n\n# 通过grid模块创建浏览器驱动对象\nfrom selenium.webdriver import Remote\nimport threading\n\n# 引入多线程实现自动化测试效果\ndef open(driver):\n driver.get('http://www.baidu.com')\n sleep(3)\n driver.quit()\n\n# 定义所有Node节点信息:M节点是不干活的,只需要写入所有的子节点信息即可\nhotsts = {'http://172.21.194.56:4000/wd/hub':'chrome',\n 'http://172.21.194.56:5000/wd/hub':'chrome',\n 'http://172.21.194.56:6000/wd/hub':'chrome'}\n\n# 定义线程组\nth = []\n# 基于节点创建浏览器对象\nfor host,browser in hotsts.items():\n\n driver = Remote(command_executor=host,\n desired_capabilities={\n \"platform\":\"Windows\",# mac的是OS\n \"browserName\":browser\n })\n # 将创建好的driver对象,创建对应的线程任务。\n th.append(threading.Thread(target=open,args=[driver]))\n\n# 启动所有的已存线程\nfor t in th:\n t.start()\n\n\n\n","sub_path":"class11/threading_demo/demo01.py","file_name":"demo01.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"286801","text":"import tessif.frused.namedtuples as nts\nimport numpy as np\nimport pandas as pd\n\n# gradient_costs_negative\n\n# one source, three sinks\n# due to flow costs starting flow: source to sink_1\n# due to change flow costs there will be a change in flow from source to sinks\n# difference between sink_2 and sink_3 are gradient costs\n# expected behaviour:source feed sink_1 until rise of flow costs, afterwards the sink with cheaper gradient costs will be fed\n\nmapping = {\n 'sources': {\n 'sourceA': {\n 'name': 'source1',\n 'outputs': ('electricity',),\n 'flow_rates': {'electricity': nts.MinMax(min=10, max=10)}, \t\t\t# force a flow rate of exactly 10\n },\n },\n 'transformers': {},\n 'sinks': {\n 'sinkA': {\n 'name': 'sink1',\n 'inputs': ('electricity',),\n 'flow_rates': {'electricity': nts.MinMax(min=0, max=10)}, \t\t\t\t# flow_rate between 0 and 10 (same as source)\n 'flow_costs': {'electricity': [0, 0, 0, 0, 0, 10, 10, 10, 10, 10]},\t\t# flow_costs force a change in terms fo the active sink\n 'gradient_costs': {\n 'electricity': nts.PositiveNegative(positive=0, negative=0), }, \t# zero gradient costs (default)\n },\n 'sinkB': {\n 'name': 'sink2',\n 'inputs': ('electricity',),\n 'flow_rates': {'electricity': nts.MinMax(min=0, max=10)}, \t\t\t\t# flow_rate between 0 and 10 (same as source)\n 'flow_costs': {'electricity': [10, 10, 10, 10, 10, 0, 0, 0, 0, 0]},\t\t# flow_costs force a change in terms fo the active sink\n 'gradient_costs': {\n 'electricity': nts.PositiveNegative(positive=2, negative=2)}, \t\t# high gradient costs\n },\n 'sinkC': {\n 'name': 'sink3',\n 'inputs': ('electricity',),\n 'flow_rates': {'electricity': nts.MinMax(min=0, max=10)}, \t\t\t\t# flow_rate between 0 and 10 (same as source)\n 'flow_costs': {'electricity': [10, 10, 10, 10, 10, 0, 0, 0, 0, 0]},\t\t# flow_costs force a change in terms fo the active sink\n 'gradient_costs': {\n 'electricity': nts.PositiveNegative(positive=1, negative=1)}, \t\t# low gradient costs\n },\n },\n 'storages': {},\n 'busses': {\n 'busA': {\n 'name': 'centralbus',\n 'inputs': ('source1.electricity',),\n 'outputs': ('sink1.electricity', 'sink2.electricity', 'sink3.electricity',),\n },\n },\n 'timeframe': {\n 'primary': pd.date_range('01/01/2022', periods=10, freq='H'),\n },\n 'global_constraints': {\n 'primary': {\n 'name': 'default',\n 'emissions': float('+inf'),\n 'material': float('+inf')},\n },\n} # minimum working example sink - linear - gradient_costs_negative\n","sub_path":"src/tessif/examples/application/verification_scenarios/sink/linear/gradient_costs_negative.py","file_name":"gradient_costs_negative.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"568974283","text":"load(\":cc_toolchain_util.bzl\", \"absolutize_path_in_str\")\nload(\":framework.bzl\", \"ForeignCcDeps\", \"get_foreign_cc_dep\")\n\ndef create_configure_script(\n workspace_name,\n target_os,\n tools,\n flags,\n root,\n user_options,\n user_vars,\n is_debug,\n configure_command,\n deps,\n inputs,\n configure_in_place):\n env_vars_string = get_env_vars(workspace_name, tools, flags, user_vars, deps, inputs)\n\n script = []\n for ext_dir in inputs.ext_build_dirs:\n script += [\"##increment_pkg_config_path## $$EXT_BUILD_ROOT$$/\" + ext_dir.path]\n\n script += [\"echo \\\"PKG_CONFIG_PATH=$$PKG_CONFIG_PATH$$\\\"\"]\n\n configure_path = \"$$EXT_BUILD_ROOT$$/{root}/{configure}\".format(\n root = root,\n configure = configure_command,\n )\n if (configure_in_place):\n script += [\"##symlink_contents_to_dir## $$EXT_BUILD_ROOT$$/{} $$BUILD_TMPDIR$$\".format(root)]\n configure_path = \"$$BUILD_TMPDIR$$/{}\".format(configure_command)\n\n script += [\"{env_vars} \\\"{configure}\\\" --prefix=$$BUILD_TMPDIR$$/$$INSTALL_PREFIX$$ {user_options}\".format(\n env_vars = env_vars_string,\n configure = configure_path,\n user_options = \" \".join(user_options),\n )]\n return \"\\n\".join(script)\n\ndef create_make_script(\n workspace_name,\n tools,\n flags,\n root,\n user_vars,\n deps,\n inputs,\n make_commands,\n prefix):\n env_vars_string = get_env_vars(workspace_name, tools, flags, user_vars, deps, inputs)\n script = []\n for ext_dir in inputs.ext_build_dirs:\n script += [\"##increment_pkg_config_path## $$EXT_BUILD_ROOT$$/\" + ext_dir.path]\n\n script += [\"echo \\\"PKG_CONFIG_PATH=$$PKG_CONFIG_PATH$$\\\"\"]\n\n script += [\"##symlink_contents_to_dir## $$EXT_BUILD_ROOT$$/{} $$BUILD_TMPDIR$$\".format(root)]\n script += [\"\" + \" && \".join(make_commands)]\n return \"\\n\".join(script)\n\ndef get_env_vars(\n workspace_name,\n tools,\n flags,\n user_vars,\n deps,\n inputs):\n vars = _get_configure_variables(tools, flags, user_vars)\n deps_flags = _define_deps_flags(deps, inputs)\n\n vars[\"LDFLAGS\"] = vars[\"LDFLAGS\"] + deps_flags.libs\n\n # -I flags should be put into preprocessor flags, CPPFLAGS\n # https://www.gnu.org/software/autoconf/manual/autoconf-2.63/html_node/Preset-Output-Variables.html\n vars[\"CPPFLAGS\"] = deps_flags.flags\n\n return \" \".join([\"{}=\\\"{}\\\"\"\n .format(key, _join_flags_list(workspace_name, vars[key])) for key in vars])\n\ndef _define_deps_flags(deps, inputs):\n # It is very important to keep the order for the linker => put them into list\n lib_dirs = []\n\n # Here go libraries built with Bazel\n gen_dirs_set = {}\n for lib in inputs.libs:\n dir_ = lib.dirname\n if not gen_dirs_set.get(dir_):\n gen_dirs_set[dir_] = 1\n lib_dirs += [\"-L$$EXT_BUILD_ROOT$$/\" + dir_]\n\n include_dirs_set = {}\n for include_dir in inputs.include_dirs:\n include_dirs_set[include_dir] = \"-I$$EXT_BUILD_ROOT$$/\" + include_dir\n for header in inputs.headers:\n include_dir = header.dirname\n if not include_dirs_set.get(include_dir):\n include_dirs_set[include_dir] = \"-I$$EXT_BUILD_ROOT$$/\" + include_dir\n include_dirs = include_dirs_set.values()\n\n # For the external libraries, we need to refer to the places where\n # we copied the dependencies ($EXT_BUILD_DEPS/), because\n # we also want configure to find that same files with pkg-config\n # -config or other mechanics.\n # Since we need the names of include and lib directories under\n # the $EXT_BUILD_DEPS/, we ask the provider.\n gen_dirs_set = {}\n for dep in deps:\n external_deps = get_foreign_cc_dep(dep)\n if external_deps:\n for artifact in external_deps.artifacts.to_list():\n if not gen_dirs_set.get(artifact.gen_dir):\n gen_dirs_set[artifact.gen_dir] = 1\n\n dir_name = artifact.gen_dir.basename\n include_dirs += [\"-I$$EXT_BUILD_DEPS$$/{}/{}\".format(dir_name, artifact.include_dir_name)]\n lib_dirs += [\"-L$$EXT_BUILD_DEPS$$/{}/{}\".format(dir_name, artifact.lib_dir_name)]\n\n return struct(\n libs = lib_dirs,\n flags = include_dirs,\n )\n\n# See https://www.gnu.org/software/make/manual/html_node/Implicit-Variables.html\n_CONFIGURE_FLAGS = {\n \"CFLAGS\": \"cc\",\n \"CXXFLAGS\": \"cxx\",\n \"ARFLAGS\": \"cxx_linker_static\",\n \"ASFLAGS\": \"assemble\",\n \"LDFLAGS\": \"cxx_linker_executable\",\n # missing: cxx_linker_shared\n}\n\n_CONFIGURE_TOOLS = {\n \"CC\": \"cc\",\n \"CXX\": \"cxx\",\n \"AR\": \"cxx_linker_static\",\n # missing: cxx_linker_executable\n}\n\ndef _get_configure_variables(tools, flags, user_env_vars):\n vars = {}\n\n for flag in _CONFIGURE_FLAGS:\n flag_value = getattr(flags, _CONFIGURE_FLAGS[flag])\n if flag_value:\n vars[flag] = flag_value\n\n # Merge flags lists\n for user_var in user_env_vars:\n toolchain_val = vars.get(user_var)\n if toolchain_val:\n vars[user_var] = toolchain_val + [user_env_vars[user_var]]\n\n tools_dict = {}\n for tool in _CONFIGURE_TOOLS:\n tool_value = getattr(tools, _CONFIGURE_TOOLS[tool])\n if tool_value:\n tools_dict[tool] = [tool_value]\n\n # Replace tools paths if user passed other values\n for user_var in user_env_vars:\n toolchain_val = tools_dict.get(user_var)\n if toolchain_val:\n tools_dict[user_var] = [user_env_vars[user_var]]\n\n vars.update(tools_dict)\n\n # Put all other environment variables, passed by the user\n for user_var in user_env_vars:\n if not vars.get(user_var):\n vars[user_var] = [user_env_vars[user_var]]\n\n return vars\n\ndef _absolutize(workspace_name, text):\n return absolutize_path_in_str(workspace_name, \"$$EXT_BUILD_ROOT$$/\", text)\n\ndef _join_flags_list(workspace_name, flags):\n return \" \".join([_absolutize(workspace_name, flag) for flag in flags])\n","sub_path":"tools/build_defs/configure_script.bzl","file_name":"configure_script.bzl","file_ext":"bzl","file_size_in_byte":6088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"513350482","text":"\r\nimport numpy as np\r\nimport os\r\nimport time\r\n#from resnet50 import ResNet50\r\nfrom keras.preprocessing import image\r\nfrom keras.layers import GlobalAveragePooling2D, Dense, Dropout,Activation,Flatten\r\nfrom tensorflow.keras.applications import EfficientNetB5\r\nfrom tensorflow.keras import layers\r\nimport tensorflow as tf\r\n#from imagenet_utils import preprocess_input\r\n\r\nfrom keras.layers import Input\r\nfrom keras.models import Model\r\nfrom keras.utils import np_utils\r\nfrom sklearn.utils import shuffle\r\nfrom sklearn.model_selection import train_test_split\r\nfrom keras.optimizers import Adam, SGD\r\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, TerminateOnNaN, CSVLogger, TensorBoard\r\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef lr_schedule(epoch,lr):\r\n if epoch < 25: \r\n return 0.01\r\n elif epoch < 75:\r\n return 0.00001\r\n #else:\r\n # return lr * tf.math.exp(-0.1)\r\n #if epoch < 80:\r\n # elif epoch < 100:\r\n # return 0.0001\r\n # else:\r\n # return 0.00001\r\n\r\n\r\n# Loading the training data\r\nPATH = os.getcwd()\r\n# Define data path\r\ndata_path = PATH + '/data'\r\ndata_dir_list = os.listdir(data_path)\r\n\r\nimg_data_list=[]\r\n\r\nfor dataset in data_dir_list:\r\n\timg_list=os.listdir(data_path+'/'+ dataset)\r\n\tprint ('Loaded the images of dataset-'+'{}\\n'.format(dataset))\r\n\tfor img in img_list:\r\n\t\timg_path = data_path + '/'+ dataset + '/'+ img \r\n\t\timg = image.load_img(img_path, target_size=(456, 456))\r\n\t\tx = image.img_to_array(img)\r\n\t\tx = np.expand_dims(x, axis=0)\r\n\t\tprint('Input image shape:', x.shape)\r\n\t\timg_data_list.append(x)\r\n\r\nimg_data = np.array(img_data_list)\r\n#img_data = img_data.astype('float32')\r\nprint (img_data.shape)\r\nimg_data=np.rollaxis(img_data,1,0)\r\nprint (img_data.shape)\r\nimg_data=img_data[0]\r\nprint (img_data.shape)\r\n\r\n\r\n# Define the number of classes\r\nnum_classes = 2\r\nnum_of_samples = img_data.shape[0]\r\nlabels = np.ones((num_of_samples,),dtype='int64')\r\n\r\nlabels[0:575]=0\r\nlabels[576:1151]=1\r\n#labels[404:606]=2\r\n#labels[606:]=3\r\n\r\nnames = ['defect','no defect']\r\n# convert class labels to on-hot encoding\r\nY = np_utils.to_categorical(labels, num_classes)\r\n\r\n#Shuffle the dataset\r\nx,y = shuffle(img_data,Y, random_state=2)\r\n# Split the dataset\r\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.1, random_state=2)\r\n\r\ntraining_datagen = ImageDataGenerator(rotation_range=10,brightness_range=(1.1, 0.9),shear_range=10.0,zoom_range=[0.8, 1.2],vertical_flip=True,fill_mode='wrap',\r\n width_shift_range=0.2,\r\n height_shift_range=0.2,\r\n horizontal_flip=True)\r\n\r\nvalid_datagen = ImageDataGenerator()\r\n\r\nt_gen = training_datagen.flow(X_train, y_train, batch_size=4)\r\nv_gen = valid_datagen.flow(X_test, y_test, batch_size=4)\r\n#t_gen = training_datagen.flow(X_train, y_train)\r\n#v_gen = valid_datagen.flow(X_test, y_test)\r\n\r\nimage_input = tf.keras.Input(shape=(456, 456, 3))\r\n#model = ResNet50(weights='imagenet')\r\nmodel = EfficientNetB5(input_tensor=image_input, include_top=False,weights=\"imagenet\")\r\nmodel.summary()\r\nmodel.trainable = False\r\nlast_layer = model.output\r\nlast_layer = tf.keras.layers.GlobalAveragePooling2D(name= 'avg_pool_last')(last_layer)\r\n#x= tf.keras.layers.Flatten(name='flatten')(last_layer)\r\nlast_layer = tf.keras.layers.BatchNormalization(name = 'batch_last')(last_layer)\r\ntop_dropout_rate = 0.2\r\nlast_layer = tf.keras.layers.Dropout(top_dropout_rate, name = 'top_dropout')(last_layer)\r\nout = tf.keras.layers.Dense(num_classes, activation='softmax', name='output_layer')(last_layer)\r\n#image_input = Input(shape=(500, 500, 3))\r\ncustom_resnet_model = tf.keras.Model(inputs=image_input,outputs= out)\r\ncustom_resnet_model.summary()\r\n\r\n#for layer in custom_resnet_model.layers[:-4]:\r\n#\tlayer.trainable = False\r\n\r\n\r\n\r\n\r\n\r\n#custom_resnet_model.layers[-6].trainable\r\n#custom_resnet_model.trainable=True\r\n\r\nadam = tf.keras.optimizers.Adam()\r\n\r\ncustom_resnet_model.compile(loss='categorical_crossentropy',optimizer=adam ,metrics=['accuracy'])\r\n\r\nt=time.time()\r\ncallback = tf.keras.callbacks.LearningRateScheduler(lr_schedule)\r\n#hist = custom_resnet_model.fit_generator(generator=t_gen, steps_per_epoch=1036//4, epochs=120, verbose = 1, validation_data= v_gen, validation_steps=116//4, shuffle = True, initial_epoch=0 )\r\nhist = custom_resnet_model.fit(t_gen,steps_per_epoch=1036//4, epochs=25, callbacks=[callback],verbose = 1, validation_data= v_gen, validation_steps=116//4, shuffle = True, initial_epoch=0 )\r\n\r\ntrain_loss=hist.history['loss']\r\nval_loss=hist.history['val_loss']\r\ntrain_acc=hist.history['accuracy']\r\nval_acc=hist.history['val_accuracy']\r\n\r\nfor layer in custom_resnet_model.layers:\r\n if not isinstance(layer, layers.BatchNormalization):\r\n layer.trainable = True\r\n\r\n\r\ncustom_resnet_model.compile(loss='categorical_crossentropy',optimizer=adam ,metrics=['accuracy'])\r\nhist = custom_resnet_model.fit(t_gen,steps_per_epoch=1036//4, epochs=75, callbacks=[callback],verbose = 1, validation_data= v_gen, validation_steps=116//4, shuffle = True, initial_epoch=25 )\r\n\r\ntrain_loss1=hist.history['loss']\r\nval_loss1=hist.history['val_loss']\r\ntrain_acc1=hist.history['accuracy']\r\nval_acc1=hist.history['val_accuracy']\r\n\r\ntrain_loss.append(train_loss1)\r\nval_loss.append(val_loss1)\r\ntrain_acc.append(train_acc1)\r\nval_acc.append(val_acc1)\r\n\r\nprint('Training time: %s' % (t - time.time()))\r\n(loss, accuracy) = custom_resnet_model.evaluate(X_test, y_test, batch_size=4, verbose=1)\r\n\r\nprint(\"[INFO] loss={:.4f}, accuracy: {:.4f}%\".format(loss,accuracy * 100))\r\n\r\n\r\ndata = train_loss + val_loss + train_acc + val_acc \r\n# opening the csv file in 'a+' mode \r\n#print(data.dtype)\r\nfile = open('data.csv', 'w+', newline ='') \r\n \r\n# writing the data into the file \r\nwith file: \r\n out = csv.writer(file)\r\n out.writerows(map(lambda x: [x], data))\r\n #write.writerows(data)\r\nfile.close()\r\n\r\nxc=range(0,75,1)\r\nprint(train_loss)\r\nplt.figure(1,figsize=(7,5))\r\nplt.plot(xc,train_loss)\r\nplt.plot(xc,val_loss)\r\nplt.xlabel('num of Epochs')\r\nplt.ylabel('loss')\r\nplt.title('train_loss vs test_loss')\r\nplt.grid(True)\r\nplt.legend(['train','test'])\r\n#print plt.style.available # use bmh, classic,ggplot for big pictures\r\nplt.style.use(['classic'])\r\nplt.savefig('loss_graph.png')\r\n\r\nplt.figure(2,figsize=(7,5))\r\nplt.plot(xc,train_acc)\r\nplt.plot(xc,val_acc)\r\nplt.xlabel('num of Epochs')\r\nplt.ylabel('accuracy')\r\nplt.title('train_acc vs test_acc')\r\nplt.grid(True)\r\nplt.legend(['train','test'],loc=4)\r\n#print plt.style.available # use bmh, classic,ggplot for big pictures\r\nplt.style.use(['classic'])\r\nplt.savefig('Accuracy_graph.png')","sub_path":"Encoder Models/EfficientNetB5_binary.py","file_name":"EfficientNetB5_binary.py","file_ext":"py","file_size_in_byte":6591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"116515166","text":"#!/usr/bin/python\n'''\nAuthor mark@espressive.com\nContributor: cesar@espressive.com\nTest the cards API\n'''\nimport json\nimport logging\nimport unittest\nimport xmlrunner\nfrom lib import APIUtils\nfrom lib import UIUtils as ui\n\nlogging.basicConfig(\n filename = 'csvAPITest.log',\n level = logging.INFO,\n format = '%(asctime)s %(message)s',\n filemode = 'w' # To overwrite the log\n)\n\nclass cardTest(unittest.TestCase):\n\n def setUp(self):\n self.headers1 = {\n 'Media-Type': 'multipart/form-data'\n }\n self.headers2 = {\n 'Content-Type': 'application/json'\n }\n self.version = 'v0.1'\n self.host = 'qa.dev.espressive.com'\n self.head = '/api/csv/'\n self.username = 'espressive@acme.com'\n self.protocol = 'https://'\n self.password = 'itautomation'\n self.url = self.protocol + self.host\n self.url = self.url + self.head \n self.url = self.url + self.version\n self.url = self.url + '/csvfile/'\n\n self.key = APIUtils.getAuthToken(\n username = self.username,\n password = self.password,\n host = self.host,\n )\n auth = \"Token \" + self.key\n self.headers1['Authorization'] = auth\n self.headers2['Authorization'] = auth\n\n def tearDown(self):\n APIUtils.killAuthToken(\n host = self.host, \n headers=self.headers1\n )\n\n def test_csv(self):\n\n #--------------------------------------------------\n #\n # Upload file and get the ID\n #\n #--------------------------------------------------\n file = ui.getCSV()\n url = self.url\n files = {'csv_file': (file)}\n data = {'business_object': '8'}\n response = APIUtils.APIPostCall(\n url = url,\n headers = self.headers1,\n files = files,\n data = data\n )\n logging.info(response.text)\n response = response.json()\n logging.info(response['id'])\n\n #--------------------------------------------------\n #\n # Update or create users\n #\n #--------------------------------------------------\n url = self.url + str(response['id']) \n url = url + '/parse_csv/'\n logging.info(url)\n response = APIUtils.APIPostCall(\n url = url,\n headers = self.headers2,\n data = None\n )\n logging.info(response.text)\n\n #--------------------------------------------------\n #\n # Verify HTTP Status\n #\n #--------------------------------------------------\n if( 200 != response.status_code ):\n status = str(response.status_code)\n self.fail( 'HTTP Status: ' + status )\n\nif __name__ == '__main__':\n unittest.main(testRunner=xmlrunner.XMLTestRunner(output='reports'))\n","sub_path":"tests/csvAPITest.py","file_name":"csvAPITest.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"560416999","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport utils\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport xarray as xr\n\n\nif __name__ == '__main__':\n # set dirs\n # -------------------------------------------------------------------------\n project_dir = os.path.dirname(os.path.realpath(__file__))\n data_dir = os.path.join(project_dir, 'data')\n out_dir = os.path.join(project_dir, 'results')\n\n # read input data\n # -------------------------------------------------------------------------\n fname = os.path.join(data_dir, 'ESA_CCI_SM_monthly_anomalies_0d25.nc')\n da_sm = utils.read_nc(fname, 'SM_anomaly')\n\n fname = os.path.join(data_dir, 'GRACE_CSR_monthly_0d25.nc')\n da_tws = utils.read_nc(fname, 'lwe_thickness')\n\n # SPI and SPEI\n # -------------------------------------------------------------------------\n aggs = [3, 12, 48]\n\n spis = []\n speis = []\n\n for agg in aggs:\n spi = utils.read_csv(\n infile=os.path.join(out_dir, 'taskB', 'methode_leander',\n 'SPI_time_scale_{}.csv'.format(agg)),\n parse_col='time').rename(\n columns={'Agg-{}'.format(agg): 'SPI-{}'.format(agg)})\n spis.append(spi)\n\n spei = utils.read_csv(\n infile=os.path.join(out_dir, 'taskB', 'methode_leander',\n 'SPEI_time_scale_{}.csv'.format(agg)),\n parse_col='time').rename(\n columns={'Agg-{}'.format(agg): 'SPEI-{}'.format(agg)})\n speis.append(spei)\n\n df_spis = pd.concat(spis, axis=1)\n df_speis = pd.concat(speis, axis=1)\n\n # discharge anomaly\n # -------------------------------------------------------------------------\n df_discharge = utils.read_grdc_discharge(data_dir)\n df_discharge.index.name = 'time'\n\n ds_discharge = df_discharge.to_xarray()\n climatology = ds_discharge.groupby('time.month').mean('time')\n\n anomalies = ds_discharge.groupby('time.month') - climatology\n print(anomalies)\n\n df_discharge_anoms = anomalies.to_dataframe()\n df_discharge_anoms = (df_discharge_anoms\n .drop('month', axis=1)\n .rename(columns={'harsova': 'Q_harsova',\n 'ceatal_izmail': 'Q_ceatal_izmail'}))\n\n # aggregate spatial data sets\n # -------------------------------------------------------------------------\n sm_basin = da_sm.groupby('time').mean().to_series()\n sm_basin.name = 'SM'\n tws_basin = da_tws.groupby('time').mean().to_series()\n tws_basin.name = 'TWS'\n\n # merge everything\n # -------------------------------------------------------------------------\n df_merged = pd.concat([sm_basin, tws_basin,\n df_spis, df_speis,\n df_discharge_anoms], axis=1)\n\n # calc correlations and plot\n # -------------------------------------------------------------------------\n corrs = df_merged.corr(method='pearson')\n corrs.to_csv(os.path.join(out_dir, 'taskC', 'correlation_matrix.csv'))\n\n # create triangular mask for heatmap\n mask = np.zeros_like(corrs)\n mask[np.triu_indices_from(mask)] = True\n\n # plot heatmap of pairwise correlations\n f, ax = plt.subplots(figsize=(8, 8))\n\n # define correct cbar height and pass to sns.heatmap function\n cbar_kws = {\"fraction\": 0.046, \"pad\": 0.04}\n sns.heatmap(corrs, mask=mask, cmap='coolwarm_r', square=True,\n vmin=-1, vmax=1, annot=True,\n cbar_kws=cbar_kws, ax=ax)\n # save\n plt.savefig(\n os.path.join(out_dir, 'taskC', 'correlation_matrix.png'),\n bbox_inches=\"tight\")\n plt.close()\n","sub_path":"taskC.py","file_name":"taskC.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"378385630","text":"import spacy\r\nimport torch\r\nimport socket\r\nimport os\r\nimport glob\r\n\r\nfrom algorithm import Coref\r\nfrom utils import (encode_distance, BATCH_SIZE_PATH, SIZE_FP,\r\n SIZE_FP_COMPRESSED, SIZE_FS, SIZE_FS_COMPRESSED,\r\n SIZE_GENRE, SIZE_PAIR_IN, SIZE_SINGLE_IN,SIZE_EMBEDDING)\r\nfrom dataset import (NCDataset, NCBatchSampler,\r\n load_embeddings_from_file, padder_collate,\r\n SIZE_PAIR_IN, SIZE_SINGLE_IN, SIZE_EMBEDDING)\r\nfrom model import Model\r\n\r\n# Load datasets and embeddings\r\nlist_of_files = glob.glob('checkpoints/*modelranking') # * means all if need specific format then *.csv\r\nlatest_file = max(list_of_files, key=os.path.getctime)\r\n#save_path = os.path.join('checkpoints', current_time + '_' + socket.gethostname() + '_')\r\n#save_name = \"ranking\"\r\n#best_model_path = save_path + \"best_model\" + save_name\r\nweights = 'weights/'\r\ncheckpoint_file = latest_file\r\nembed_path = weights\r\ntensor_embeddings, voc = load_embeddings_from_file(embed_path + \"tuned_word\")\r\n\r\n# Construct model\r\nprint(\"🏝 Build model\")\r\nh1 = 1000\r\nh2 = 500\r\nh3 = 500\r\nmodel = Model(len(voc), SIZE_EMBEDDING, h1,h2,h3, SIZE_PAIR_IN, SIZE_SINGLE_IN)\r\nmodel.load_embeddings(tensor_embeddings)\r\n\r\n#print(model.state_dict)\r\n#cklmvb = input(\"state dict printed\")\r\ncuda = torch.cuda.is_available()\r\n\r\nif cuda:\r\n\tmodel.cuda()\r\n#if weights is not None:\r\n#\tprint(\"🏝 Loading pre-trained weights\")\r\n#\tmodel.load_weights(weights)\r\nif checkpoint_file is not None:\r\n\tprint(\"⛄️ Loading model from\", checkpoint_file)\r\n\tmodel.load_state_dict(torch.load(checkpoint_file) if cuda else torch.load(checkpoint_file, map_location=lambda storage, loc: storage))\r\n\tmodel.eval()\r\n\r\nmy_utterances = ['My Sister has a dog.','She loves him.']\r\ncoref0 = Coref()\r\nprint(\"Single Pair Inp,\",SIZE_SINGLE_IN)\r\nprint(\"Pair Inp,\",SIZE_PAIR_IN)\r\n#lel = input()\r\ncoref_clusters = coref0.one_shot_coref(utterances=my_utterances)\r\nprint(\"Coref Clusters are\")\r\nprint(coref_clusters)","sub_path":"neuralcoref-memnet/test_coref_algo.py","file_name":"test_coref_algo.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"73149393","text":"import time\nimport sys\n\nimport json\nimport requests\n\nimport tornado.escape\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.locks\nimport tornado.options\nimport tornado.web\nimport tornado.gen\nimport logging\n\n\nfrom tornado.options import define, options\n\nimport tornado.queues\n\n\n\n\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\n\nq = tornado.queues.Queue(maxsize=4)\n\nclass NoResultError(Exception):\n pass\n\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/result/*(\\d+)*/*\", RESULT),\n (r\"/send\", SEND),\n ]\n\n super(Application, self).__init__(handlers)\n\n\nclass Quotes():\n def __init__(self):\n\n self.tasks = {}\n self.id_counter = 1\n self.worked_task = []\n self.need_work_task = []\n tornado.ioloop.IOLoop.current().spawn_callback(worker)\n\n\n\n\n async def new_task(self,URL):\n if URL not in list([url_[\"url\"] for url_ in self.tasks.values()]):\n self.tasks[str(self.id_counter)] = \\\n {\n \"url\":URL,\n \"Status\":\"New\",\n \"RESP C Len\": 0,\n \"RESP Status\": \"None\",\n \"RESP Body\" : \"None\"\n }\n\n logger.info(\"save new task {0}\".format(self.tasks[str(self.id_counter)]))\n\n await q.put(self.id_counter)\n # await q.join()\n self.need_work_task.append(self.id_counter)\n\n self.id_counter += 1\n\n return\n\n\n def info(self,num_q):\n logger.info(\"Info of task {0} {1}\".format(num_q,self.tasks[str(num_q)]))\n if str(num_q) in self.tasks.keys():\n return self.tasks[str(num_q)]\n else:\n logger.info(\"Info of task {0} id not founded\".format(num_q))\n return {\"info\":\"id not founded\"}\n\n async def get_url(self,count_id):\n\n try:\n logger.info(\"Get page ingormation\")\n self.tasks[str(count_id)][\"Status\"] = \"Pending\"\n logger.info(\"Task id: {0} status is Pending\".format(count_id))\n res = requests.get(self.tasks[str(count_id)][\"url\"])\n self.tasks[str(count_id)][\"RESP Status\"] = res.status_code\n self.tasks[str(count_id)][\"RESP Body\"] = res.text\n self.tasks[str(count_id)][\"RESP C Len\"] = len(res.text)\n\n self.tasks[str(count_id)][\"Status\"] = \"Completed\"\n logger.info(\"Task id: {0} status is Completed\".format(count_id))\n except:\n logger.info(\"Task id: {0} status is Error\".format(count_id))\n self.tasks[str(count_id)][\"Status\"] = \"Error\"\n\n\n\nasync def worker():\n\n async for count_id in q:\n if count_id is None:\n return\n\n try:\n await Q.get_url(count_id)\n except:\n logger.info(\"Worker error get_url\")\n finally:\n q.task_done()\n q.join()\n\n\nclass RESULT(tornado.web.RequestHandler):\n\n def get(self, *args, **kwargs):\n\n resp = {}\n if args[0] ==None:\n logger.info(\"Get info of latt 10 task\")\n resp[\"tasks\"] =list()\n for task_id in list(Q.tasks.keys())[-10:]:\n try:\n\n info_task = Q.tasks[task_id]\n info_task[\"id\"] = task_id\n resp[\"tasks\"].append(info_task)\n except:\n print(\"except\")\n\n resp[\"Error\"] = \"None\"\n\n\n else:\n logger.info(\"Get info of task id: {0}\".format(args[0]))\n\n\n resp[\"id\"] = args[0]\n\n if args[0] in list(Q.tasks.keys()):\n resp.update(Q.info(args[0]))\n resp[\"Error\"] = \"None\"\n else:\n resp[\"Error\"] = \"Task ID not defined\"\n return self.write(json.dumps(resp))\n\nclass SEND(tornado.web.RequestHandler):\n async def post(self, *args, **kwargs):\n\n\n data = json.loads(self.request.body.decode().rstrip())\n\n logger.info(\"post {0}\".format(data))\n await Q.new_task(data['url'])\n resp = data\n\n\n id_ = Q.id_counter-1\n if id_:\n\n logger.info(\"Creat new task id: {1} url: {0}\".format(data['url'],id_))\n\n resp[\"task id\"] = str(id_)\n resp[\"Error\"] = \"None\"\n\n else:\n logger.info(\"Url: {0} waiting of Quotes\".format(data['url']))\n resp[\"Error\"] = \"Url in Quotes\"\n\n try:\n self.write(json.dumps(resp))\n\n\n except Exception as e:\n resp[\"Error\"] = \"\"\n\n self.write(json.dumps(resp))\n logger.warning(e)\n\n finally:\n self.finish()\n\n\ndef setup_custom_logger(name):\n formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n handler = logging.FileHandler('log.txt', mode='a')\n handler.setFormatter(formatter)\n screen_handler = logging.StreamHandler(stream=sys.stdout)\n screen_handler.setFormatter(formatter)\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n logger.addHandler(handler)\n logger.addHandler(screen_handler)\n return logger\n\n\n\nasync def main():\n\n\n\n app = Application()\n app.listen(options.port)\n logger.info(\"Run server\")\n shutdown_event = tornado.locks.Event()\n await shutdown_event.wait()\n\n\nif __name__ == \"__main__\":\n\n Q = Quotes()\n logger = setup_custom_logger('Quotes')\n logger.info(\"Start app\")\n tornado.ioloop.IOLoop.current().run_sync(main)\n","sub_path":"async_tornado.py","file_name":"async_tornado.py","file_ext":"py","file_size_in_byte":5558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"222546325","text":"\"\"\"\n\n@author: ruben\n\n\"\"\"\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nfrom pastas.read.knmi import KnmiStation\n\n# How to use it?\n# data from a meteorological station\ndownload = False\n\nif not download:\n # use a file with locations:\n knmi = KnmiStation.fromfile('../data/KNMI_Bilt.txt')\n\n # without locations\n knmi = KnmiStation.fromfile('../data/KNMI_NoLocation.txt')\n\n # hourly data without locations\n knmi = KnmiStation.fromfile('../data/KNMI_Hourly.txt')\nelse:\n # or download it directly from\n # https://www.knmi.nl/nederland-nu/klimatologie/daggegevens\n knmi = KnmiStation(stns=260, start=datetime(1970, 1, 1),\n end=datetime(1971, 1, 1)) # de bilt\n knmi.download() # for now only works for meteorological stations\n # and daily data (so not hourly)\n\n# plot\nf1, axarr = plt.subplots(2, sharex=True)\nknmi.data['RH'].plot(ax=axarr[0])\naxarr[0].set_title(knmi.variables['RH'])\nif 'EV24' in knmi.data.keys():\n knmi.data['EV24'].plot(ax=axarr[1])\n axarr[1].set_title(knmi.variables['EV24'])\n\nif True:\n # use a file of a rainfall station:\n knmi = KnmiStation.fromfile('../data/KNMI_Akkrum.txt')\n # plot\n f2 = plt.figure()\n ax = f2.add_subplot(111)\n knmi.data['RD'].plot(ax=ax)\n ax.set_title(knmi.variables['RD'], fontsize=10)\n\nplt.show()\n\n","sub_path":"examples/reads/test_knmidata.py","file_name":"test_knmidata.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"554749847","text":"from __future__ import absolute_import\nfrom builtins import object\nfrom proteus import *\nfrom proteus.default_p import *\nfrom proteus.ctransportCoefficients import smoothedHeaviside\ntry:\n from .risingBubble import *\nexcept:\n from risingBubble import *\nfrom proteus.mprans import VOF3P\n\nLevelModelType = VOF3P.LevelModel\ncoefficients = VOF3P.Coefficients(LS_model=LS_model,\n V_model=V_model,\n RD_model=RD_model,\n ME_model=VOF_model,\n VOS_model=VOS_model,\n checkMass=True,\n useMetrics=useMetrics,\n epsFact=epsFact_vof,\n sc_uref=vof_sc_uref,\n sc_beta=vof_sc_beta,\n movingDomain=movingDomain,\n STABILIZATION_TYPE=1 if EXPLICIT_VOF is True else 0)\n #EXPLICIT_METHOD=EXPLICIT_VOF)\n\ndef getDBC_vof(x,flag):\n if flag == boundaryTags['top'] and openTop:\n return lambda x,t: 1.0\n\ndirichletConditions = {0:getDBC_vof}\n\ndef getAFBC_vof(x,flag):\n if flag != boundaryTags['top'] or not openTop:\n return lambda x,t: 0.0\n\nadvectiveFluxBoundaryConditions = {0:getAFBC_vof}\ndiffusiveFluxBoundaryConditions = {0:{}}\n\nclass VOF_IC(object):\n def uOfXT(self,x,t):\n return smoothedHeaviside(epsFact_consrv_heaviside*he,signedDistanceToBubble(x))\n\ninitialConditions = {0:VOF_IC()}\n","sub_path":"proteus/tests/surface_tension/rising_bubble_rans3p/vof_p.py","file_name":"vof_p.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"279086050","text":"from codigos.No import *\n\nclass Arvore:\n\n def __init__(self):\n self.raiz = No(None)\n self.raiz = None\n\n def InserirNo(self, chave):\n\n novo = No(chave)\n\n if self.raiz == None:\n self.raiz = novo\n else:\n atual = self.raiz\n while True:\n anterior = atual\n if chave <= atual.chave:\n atual = atual.esq\n if atual == None:\n anterior.esq = novo\n return\n\n else:\n atual = atual.dir\n if atual == None:\n anterior.dir = novo\n return\n\n\n\n def BuscarNo(self, chave):\n\n if self.raiz == None:\n return None\n\n noAtual = self.raiz\n\n while noAtual.chave != chave:\n\n if chave < noAtual.chave:\n noAtual = noAtual.esq\n\n else:\n noAtual = noAtual.dir\n\n if noAtual == None:\n return None\n\n # Retorna o no com a chave\n return noAtual\n\n def GetNoSucessor(self, apaga):\n paidosucessor = apaga\n sucessor = apaga\n noAtual = apaga.dir\n\n while noAtual != None:\n paidosucessor = sucessor\n sucessor = noAtual\n noAtual = noAtual.esq\n\n #Se o sucessor não for o filho a direita do nó que se quer apagar\n if sucessor != apaga.dir:\n #O pai do sucessor herda a subarvore a direita do sucessor\n paidosucessor.esq = sucessor.dir\n #A nova subarvore a direita do sucessor será a subarvore a direita do nó que se quer apagar\n sucessor.dir = apaga.dir\n\n return sucessor\n\n def ExcluirNo(self, chave):\n\n if self.raiz is None:\n return False\n\n noAtual = self.raiz\n pai = self.raiz\n filho_esq = True\n\n while noAtual.item != chave:\n pai = noAtual\n if chave < noAtual.chave:\n noAtual = noAtual.esq\n filho_esq = True\n else:\n noAtual = noAtual.dir\n filho_esq = False\n\n if noAtual == None:\n return False\n\n if noAtual.dir is None and noAtual.esq is None:\n if noAtual == self.raiz:\n self.raiz = None\n\n else:\n if filho_esq:\n pai.esq = None\n else:\n pai.dir = None\n\n elif noAtual.dir == None:\n if noAtual == self.raiz:\n self.raiz = noAtual.esq\n\n else:\n if filho_esq:\n pai.esq = noAtual.esq\n else:\n pai.dir = noAtual.esq\n\n elif noAtual.esq is None:\n if noAtual == self.raiz:\n self.raiz = noAtual.dir\n else:\n if filho_esq:\n pai.dir = noAtual.dir\n else:\n pai.esq = noAtual.dir\n\n else:\n sucessor = self.noSucessor(noAtual)\n\n if noAtual == self.raiz:\n self.raiz = sucessor\n else:\n if filho_esq:\n pai.esq = sucessor\n else:\n pai.dir = sucessor\n\n sucessor.esq = noAtual.esq\n\n return True\n\n def ImprimirEmOrdem(self, no):\n if no is not None:\n self.ImprimirEmOrdem(no.esq)\n print(no.chave, end=\" \")\n self.ImprimirEmOrdem(no.dir)\n\n def ImprimirPosOrdem(self, no):\n if no is not None:\n self.ImprimirPosOrdem(no.esq)\n self.ImprimirPosOrdem(no.dir)\n print(no.chave, end=\" \")\n\n def ImprimirPreOrdem(self, no):\n if no is not None:\n print(no.chave, end=\" \")\n self.ImprimirPreOrdem(no.esq)\n self.ImprimirPreOrdem(no.dir)\n\n def getRaiz(self):\n return self.raiz\n\n # def ImprimirEmOrdem2(self):\n #\n # self.ImprimirEmOrdem(no.esq)\n # print(no.item, end=\" \")\n # self.ImprimirEmOrdem(no.dir)\n","sub_path":"codigos/AVLTree_2.py","file_name":"AVLTree_2.py","file_ext":"py","file_size_in_byte":4171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"212193734","text":"import Nodes as nodes\nimport pygame\nimport math\n\nwidth = 700 # screen\nheight = 700 # screen\n\n#Display init\npygame.init()\ngameDisplay = pygame.display.set_mode((width, height))\npygame.display.set_caption('FTC')\nclock = pygame.time.Clock()\ntime = 0\ndone = False\n\n#Font/Image init\ncomic = pygame.font.SysFont('Comic Sans MS', 30)\ncomicS = pygame.font.SysFont('Comic Sans MS', 15)\nfield = pygame.image.load('field.png').convert()\nfield = pygame.transform.scale(field, (width, height))\n\n#Starting positions (inches)\nstartx = 12*11.25\nstarty = 12*9\nstarth = -90\n\n#Robot Dimensions\nrobotWidth = 18\nrobotHeight = 18\n\n#Simulation Update Speed (mills)\nspeedUp = 1 # keep < 5\n\n#Velocitys of Robot\nmaxForVel = 30 #inch/s\nmaxStaVel = 20 #inch/s\nmaxTurVel = 90 #deg/s\n\n#Robot Classes\nrc = nodes.RobotConstraints(startx,starty,starth,robotWidth,robotHeight,maxForVel,maxStaVel,maxTurVel)\nrp = nodes.RobotPos(rc)\npygame.mixer.music.load('zing.wav')\npath = nodes.Path(rc, 0.5, pygame)\n\n#Track\ntrack = []\n\n#Path Constraints\n\npath.addPose(-10,0,0)\npath.addPose(-22, -3, 45)\npath.addPose(-4, 4, 0)\n# path.addPose(20,20,45)\n# path.addPose(-10,60,90)\n# path.addPose(-4,0,0)x\n\n\n\n#Drawing Classes\ndef drawRobot():\n c = rp.getCorners()\n for i in range(3):\n pygame.draw.line(gameDisplay,(0,0,0),c[i],c[i+1],3)\n pygame.draw.line(gameDisplay, (0, 0, 0), c[3], c[0], 3)\n v = rp.getVect()\n pygame.draw.line(gameDisplay,(204,102,0),(v[0],v[1]),(v[2],v[3]),3)\n track.append((rp.inchToPix(rp.x),rp.inchToPix(rp.y)))\ndef drawTimer():\n ts = comic.render(str(getTime()), False, (0, 0, 0))\n pygame.draw.rect(gameDisplay,(204,204,255),(10,8,100,50))\n pygame.draw.rect(gameDisplay,(51,0,102),(10,8,100,50),5)\n gameDisplay.blit(ts, (15, 10))\ndef drawPathTimes():\n if len(path.times) != 0:\n pygame.draw.rect(gameDisplay, (255,255,200), (10, 70, 80, 25*len(path.times)+10))\n pygame.draw.rect(gameDisplay, (199, 184, 133), (10, 70, 80, 25*len(path.times)+10), 5)\n i = 0\n for t in path.times:\n i+=1\n pt = comicS.render(str(i)+': '+str(t), False, (255, 0, 0))\n gameDisplay.blit(pt, (15, 25*i+50))\ndef drawTrack():\n for (x,y) in track:\n pygame.draw.circle(gameDisplay, (0, 102, 0), (x, y), 1)\ndef drawPath():\n for (x,y,h) in path.getAllPoses():\n px = rp.inchToPix(x)\n py = rp.inchToPix(y)\n v = nodes.Vec2d(0,30)\n rv = v.getRotatedVec(-h)\n pygame.draw.line(gameDisplay,(255,255,200),(px,py),(px+rv.x,py-rv.y),3)\n pygame.draw.circle(gameDisplay, (100, 255, 0), (px, py), 3)\n\n#Time\ndef getTime():\n return (math.trunc(time/10)/100)*speedUp\n\n#Robot moving by path\ndef updateRobotPos():\n pows = path.update(rp.getPose(), getTime())\n rp.move(pows[0],pows[1],pows[2])\n\n#Updating the display\ndef updateDisplay():\n gameDisplay.blit(field, (0, 0))\n drawRobot()\n drawTrack()\n drawTimer()\n drawPath()\n drawPathTimes()\n if(getTime() > 1):\n updateRobotPos()\n\n#Main Display Loop\nwhile not done:\n updateDisplay()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n pygame.display.update()\n clock.tick(100*speedUp)\n time = pygame.time.get_ticks()\n","sub_path":"Display.py","file_name":"Display.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"332952867","text":"import os\r\nimport librosa\r\nimport librosa.display\r\nimport matplotlib.pyplot as plt\r\nimport pickle\r\nfrom tqdm.notebook import tqdm\r\nfrom sklearn.datasets import load_files \r\nfrom keras.utils import np_utils\r\nimport numpy as np\r\nfrom glob import glob\r\nimport torch\r\nimport numpy as np\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom torch import nn\r\nfrom torchvision import transforms\r\nimport torchvision\r\nfrom torch import optim\r\ninputPath = input()\r\n\r\nclass CNN(nn.Module):\r\n def __init__(self):\r\n super(CNN, self).__init__()\r\n \r\n self.Convolution1 = nn.Sequential(\r\n \r\n # convolutional layer\r\n nn.Conv2d(in_channels=1, out_channels=64, kernel_size=3, stride=1, padding=1),\r\n \r\n # Batch Normalization layer\r\n nn.BatchNorm2d(64),\r\n \r\n # Activation Function\r\n nn.ReLU(),\r\n \r\n nn.Dropout(p=0.2),\r\n \r\n # max pooling layer\r\n nn.MaxPool2d(kernel_size=2),\r\n \r\n nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1),\r\n \r\n nn.BatchNorm2d(128),\r\n \r\n nn.ReLU(),\r\n \r\n nn.Dropout(p=0.2),\r\n \r\n nn.MaxPool2d(kernel_size=2),\r\n \r\n \r\n nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1),\r\n \r\n nn.BatchNorm2d(256),\r\n \r\n nn.ReLU()\r\n \r\n \r\n )\r\n \r\n #Fully Connected 1\r\n \r\n self.fc = nn.Linear(10*35*256, 512)\r\n self.fc2 = nn.Linear(512, 64)\r\n self.fc3 = nn.Linear(64, 5)\r\n\r\n\r\n \r\n # forward function\r\n def forward(self, x):\r\n \r\n output = self.Convolution1(x)\r\n \r\n output = output.view(output.size(0), -1)\r\n \r\n output = self.fc(output)\r\n output = self.fc2(output)\r\n output = self.fc3(output)\r\n\r\n return output\r\n\r\n# We will train model on GPU. So we need to move the model first to the GPU.\r\nmodel = CNN()\r\nif torch.cuda.is_available():\r\n model.cuda()\r\nmodel.eval()\r\nmodel.load_state_dict(torch.load(r'C:\\Users\\Tarun\\Desktop\\MIDAS project\\MY_MODEL1.pt'))\r\n\r\npath = os.path.normpath(inputPath)\r\ncount = 0\r\nfor i in os.listdir(path):\r\n audio, sr = librosa.load(os.path.join(path,i))\r\n #fixing lenght and processing audio file\r\n y = librosa.util.fix_length(audio, 66150)\r\n S = np.abs(librosa.stft(y))\r\n D_short = librosa.feature.chroma_stft(S=S, n_chroma=40)\r\n\r\n #applying transformations on the data\r\n D_short = (D_short-D_short.min())/(D_short.max()-D_short.min())\r\n trans = transforms.ToPILImage()\r\n a = trans(D_short)\r\n trans = transforms.Resize((40,140))\r\n a = trans(a)\r\n trans = transforms.ToTensor()\r\n a = trans(a)\r\n a= a.unsqueeze(0)\r\n count+=1\r\n \r\n a = a.to('cuda')\r\n output = model(a)\r\n result = torch.argmax(output)\r\n if(result == 0):\r\n res = \"a\"\r\n elif(result == 1):\r\n res = \"b\"\r\n elif(result == 2):\r\n res = \"c\"\r\n elif(result == 3):\r\n res = \"d\"\r\n elif(result == 4):\r\n res = \"e\"\r\n with open('myfile.txt', 'a') as f_out:\r\n f_out.write(i)\r\n f_out.write(',')\r\n f_out.write(res)\r\n f_out.write('\\n')\r\nf_out.close()\r\n","sub_path":"SPEECH EMOTION PROBLEM/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"445193613","text":"# -*- coding: utf-8 -*-\n\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2012 - INECO PARTNERSHIP LIMITED ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import osv, fields\n\nclass account_journal(osv.osv):\n\n _inherit=\"account.journal\"\n\n def get_account_journal(self,cr,uid,model,type=False,subtype=False,context=None):\n\n if not context:\n context={}\n res =False\n\n company_obj=self.pool.get('res.company')\n company_id = context.get('company_id',False)\n if not company_id:\n company_id = self.pool.get('res.users')._get_company(cr, uid, context=context)\n #company_obj.get_company(cr,uid,context).id\n\n company=company_obj.browse(cr,uid,company_id)\n\n if model=='account.invoice':\n if type==\"in_invoice\":\n res=company.in_invoice_journal_id and company.in_invoice_journal_id.id or False\n if type==\"in_cash\":\n res=company.in_cash_journal_id and company.in_cash_journal_id.id or False\n if type==\"in_refund\":\n res=company.in_refund_journal_id and company.in_refund_journal_id.id or False\n if type==\"in_charge\":\n res=company.in_charge_journal_id and company.in_charge_journal_id.id or False\n if type==\"in_deposit\":\n res=company.in_deposit_journal_id and company.in_deposit_journal_id.id or False\n\n if type==\"out_invoice\":\n res=company.out_invoice_journal_id and company.out_invoice_journal_id.id or False\n if type==\"out_cash\":\n res=company.out_cash_journal_id and company.out_cash_journal_id.id or False\n if type==\"out_refund\":\n res=company.out_refund_journal_id and company.out_refund_journal_id.id or False\n if type==\"out_charge\":\n res=company.out_charge_journal_id and company.out_charge_journal_id.id or False\n if type==\"out_deposit\":\n res=company.out_deposit_journal_id and company.out_deposit_journal_id.id or False\n\n if model=='account.payment':\n if type==\"in\":\n res=company.in_payment_journal_id and company.in_payment_journal_id.id or False\n if type==\"out\":\n res=company.out_payment_journal_id and company.out_payment_journal_id.id or False\n\n if model=='account.advance' or model=='account.advance.clear':\n res=company.advance_journal_id and company.advance_journal_id.id or False\n\n if model=='account.petty.payment':\n res=company.out_petty_journal_id and company.out_petty_journal_id.id or False\n\n if model=='account.cash.move': # and type=\"in\":\n res=company.in_petty_journal_id and company.in_petty_journal_id.id or False\n\n if model=='account.bank.move' or model=='account.bank.transfer':\n res=company.bank_journal_id and company.bank_journal_id.id or False\n\n if model=='account.cheque.move' and type in ('RP','RR','RC','RS'):\n res=company.in_cheque_journal_id and company.in_cheque_journal_id.id or False\n\n if model=='account.cheque.move' and type in ('PP','PR','PC'):\n res=company.out_cheque_journal_id and company.out_cheque_journal_id.id or False\n\n return res\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4\n","sub_path":"ineco_thai_account/account_journal.py","file_name":"account_journal.py","file_ext":"py","file_size_in_byte":4215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"28247150","text":"\"\"\"Utilities for downloading from the web.\n\"\"\"\n\nimport chardet\nimport glob\nimport logging\nimport os\nimport shutil\nimport tarfile\nimport urllib\nimport zipfile\nimport warnings\n\nfrom tqdm import tqdm\nfrom smart_open import open, parse_uri\n\nfrom mirdata.validate import md5\n\nlogging.basicConfig(format=\"%(levelname)s: %(message)s\", level=logging.INFO)\n\n\nclass RemoteFileMetadata(object):\n \"\"\"The metadata for a remote file\n\n Attributes:\n filename (str): the remote file's basename\n url (str): the remote file's url\n checksum (str): the remote file's md5 checksum\n destination_dir (str or None): the relative path for where to save the file\n unpack_directories (list or None): list of relative directories. For each directory\n the contents will be moved to destination_dir (or data_home if not provieds)\n\n \"\"\"\n\n def __init__(\n self, filename, url, checksum, destination_dir=None, unpack_directories=None\n ):\n self.filename = filename\n self.url = url\n self.checksum = checksum\n self.destination_dir = destination_dir\n self.unpack_directories = unpack_directories\n\n\ndef downloader(\n save_dir,\n remotes=None,\n index=None,\n partial_download=None,\n info_message=None,\n force_overwrite=False,\n cleanup=False,\n allow_invalid_checksum=False,\n):\n \"\"\"Download data to `save_dir` and optionally log a message.\n\n Args:\n save_dir (str):\n The directory to download the data\n remotes (dict or None):\n A dictionary of RemoteFileMetadata tuples of data in zip format.\n If None, there is no data to download\n index (core.Index):\n A mirdata Index class, which may contain a remote index to be downloaded\n or a subset of remotes to download by default.\n partial_download (list or None):\n A list of keys to partially download the remote objects of the download dict.\n If None, all data specified by the index is downloaded\n info_message (str or None):\n A string of info to log when this function is called.\n If None, no string is logged.\n force_overwrite (bool):\n If True, existing files are overwritten by the downloaded files.\n cleanup (bool):\n Whether to delete the zip/tar file after extracting.\n allow_invalid_checksum (bool):\n Allow having an invalid checksum, and whenever this happens prompt a\n warning instead of deleting the files.\n\n \"\"\"\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n if not index:\n raise ValueError(\"Index must be specified.\")\n\n if allow_invalid_checksum:\n cleanup = True\n\n if cleanup:\n logging.warning(\n \"Zip and tar files will be deleted after they are uncompressed. \"\n + \"If you download this dataset again, it will overwrite existing files, even if force_overwrite=False\"\n )\n\n if index.remote:\n # add index to remotes\n if not remotes:\n remotes = {}\n remotes[\"index\"] = index.remote\n\n # if partial download is specified, use it. Otherwise, use the\n # partial download specified by the index.\n partial_download = partial_download if partial_download else index.partial_download\n\n if remotes:\n if partial_download:\n # check the keys in partial_download are in the download dict\n if not isinstance(partial_download, list) or any(\n [k not in remotes for k in partial_download]\n ):\n raise ValueError(\n \"partial_download must be a list which is a subset of {}, but got {}\".format(\n list(remotes.keys()), partial_download\n )\n )\n objs_to_download = partial_download\n else:\n objs_to_download = list(remotes.keys())\n\n logging.info(\"Downloading {} to {}\".format(objs_to_download, save_dir))\n\n for k in objs_to_download:\n logging.info(\"[{}] downloading {}\".format(k, remotes[k].filename))\n extension = os.path.splitext(remotes[k].filename)[-1]\n if \".zip\" in extension:\n download_zip_file(\n remotes[k],\n save_dir,\n force_overwrite,\n cleanup,\n allow_invalid_checksum,\n )\n elif \".gz\" in extension or \".tar\" in extension or \".bz2\" in extension:\n download_tar_file(\n remotes[k],\n save_dir,\n force_overwrite,\n cleanup,\n allow_invalid_checksum,\n )\n else:\n download_from_remote(\n remotes[k], save_dir, force_overwrite, allow_invalid_checksum\n )\n\n if remotes[k].unpack_directories:\n for src_dir in remotes[k].unpack_directories:\n # path to destination directory\n destination_dir = (\n os.path.join(save_dir, remotes[k].destination_dir)\n if remotes[k].destination_dir\n else save_dir\n )\n # path to directory to unpack\n source_dir = os.path.join(destination_dir, src_dir)\n\n if not os.path.exists(source_dir):\n logging.info(\n \"Data not downloaded, because it probably already exists on your computer. \"\n + \"Run .validate() to check, or rerun with force_overwrite=True to delete any \"\n + \"existing files and download from scratch\"\n )\n return\n\n move_directory_contents(source_dir, destination_dir)\n\n if info_message is not None:\n logging.info(info_message.format(save_dir))\n\n\nclass DownloadProgressBar(tqdm):\n \"\"\"\n Wrap `tqdm` to show download progress\n \"\"\"\n\n def update_to(self, b=1, bsize=1, tsize=None):\n if tsize is not None:\n self.total = tsize\n self.update(b * bsize - self.n)\n\n\ndef download_from_remote(remote, save_dir, force_overwrite, allow_invalid_checksum):\n \"\"\"Download a remote dataset into path\n Fetch a dataset pointed by remote's url, save into path using remote's\n filename and ensure its integrity based on the MD5 Checksum of the\n downloaded file.\n\n Adapted from scikit-learn's sklearn.datasets.base._fetch_remote.\n\n Args:\n remote (RemoteFileMetadata): Named tuple containing remote dataset\n meta information: url, filename and checksum\n save_dir (str): Directory to save the file to. Usually `data_home`\n force_overwrite (bool):\n If True, overwrite existing file with the downloaded file.\n If False, does not overwrite, but checks that checksum is consistent.\n\n Returns:\n str: Full path of the created file.\n\n \"\"\"\n file_uri = parse_uri(save_dir)\n if file_uri.scheme != \"file\":\n raise NotImplementedError(\n \"mirdata only supports downloading to a local filesystem. \"\n \"To use mirdata with a remote filesystem, download to a local filesytem, \"\n \"and transfer the data to your remote filesystem, setting data_home appropriately.\"\n )\n if remote.destination_dir is None:\n download_dir = save_dir\n else:\n download_dir = os.path.join(save_dir, remote.destination_dir)\n\n if not os.path.exists(download_dir):\n os.makedirs(download_dir)\n\n download_path = os.path.join(download_dir, remote.filename)\n\n if not os.path.exists(download_path) or force_overwrite:\n # if we got here, we want to overwrite any existing file\n if os.path.exists(download_path):\n os.remove(download_path)\n\n # If file doesn't exist or we want to overwrite, download it\n with DownloadProgressBar(\n unit=\"B\", unit_scale=True, unit_divisor=1024, miniters=1\n ) as t:\n try:\n urllib.request.urlretrieve(\n remote.url,\n filename=download_path,\n reporthook=t.update_to,\n data=None,\n )\n except Exception as exc:\n error_msg = \"\"\"\n mirdata failed to download the dataset from {}!\n Please try again in a few minutes.\n If this error persists, please raise an issue at\n https://github.com/mir-dataset-loaders/mirdata,\n and tag it with 'broken-link'.\n \"\"\".format(\n remote.url\n )\n logging.error(error_msg)\n raise exc\n else:\n logging.info(\n \"{} already exists and will not be downloaded. \".format(download_path)\n + \"Rerun with force_overwrite=True to delete this file and force the download.\"\n )\n\n checksum = md5(download_path)\n if remote.checksum != checksum:\n if allow_invalid_checksum:\n warnings.warn(\n \"{} has an MD5 checksum ({}) \"\n \"differing from expected ({}), \"\n \"file may be corrupted.\".format(\n download_path, checksum, remote.checksum\n ),\n UserWarning,\n )\n else:\n raise IOError(\n \"{} has an MD5 checksum ({}) \"\n \"differing from expected ({}), \"\n \"file may be corrupted.\".format(\n download_path, checksum, remote.checksum\n )\n )\n return download_path\n\n\ndef download_zip_file(\n zip_remote, save_dir, force_overwrite, cleanup, allow_invalid_checksum\n):\n \"\"\"Download and unzip a zip file.\n\n Args:\n zip_remote (RemoteFileMetadata):\n Object containing download information\n save_dir (str):\n Path to save downloaded file\n force_overwrite (bool):\n If True, overwrites existing files\n cleanup (bool):\n If True, remove zipfile after unziping\n\n \"\"\"\n zip_download_path = download_from_remote(\n zip_remote, save_dir, force_overwrite, allow_invalid_checksum\n )\n unzip(zip_download_path, cleanup=cleanup)\n\n\ndef extractall_unicode(zfile, out_dir):\n \"\"\"Extract all files inside a zip archive to a output directory.\n\n In comparison to the zipfile, it checks for correct file name encoding\n\n Args:\n zfile (obj): Zip file object created with zipfile.ZipFile\n out_dir (str): Output folder\n\n \"\"\"\n ZIP_FILENAME_UTF8_FLAG = 0x800\n\n for m in zfile.infolist():\n data = zfile.read(m) # extract zipped data into memory\n\n filename = m.filename\n\n # if block to deal with irmas and good-sounds archives\n # check if the zip archive does not have the encoding info set\n # encode-decode filename only if it's different than the original name\n if (m.flag_bits & ZIP_FILENAME_UTF8_FLAG == 0) and filename.encode(\n \"cp437\"\n ).decode(errors=\"ignore\") != filename:\n filename_bytes = filename.encode(\"cp437\")\n if filename_bytes.decode(\"utf-8\", \"replace\") != filename_bytes.decode(\n errors=\"ignore\"\n ):\n guessed_encoding = chardet.detect(filename_bytes)[\"encoding\"] or \"utf8\"\n filename = filename_bytes.decode(guessed_encoding, \"replace\")\n else:\n filename = filename_bytes.decode(\"utf-8\", \"replace\")\n\n disk_file_name = os.path.join(out_dir, filename)\n\n dir_name = os.path.dirname(disk_file_name)\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n\n if not os.path.isdir(disk_file_name):\n with open(disk_file_name, \"wb\") as fd:\n fd.write(data)\n\n\ndef unzip(zip_path, cleanup):\n \"\"\"Unzip a zip file inside it's current directory.\n\n Args:\n zip_path (str): Path to zip file\n cleanup (bool): If True, remove zipfile after unzipping\n\n \"\"\"\n zfile = zipfile.ZipFile(zip_path, \"r\")\n extractall_unicode(zfile, os.path.dirname(zip_path))\n zfile.close()\n if cleanup:\n os.remove(zip_path)\n\n\ndef download_tar_file(\n tar_remote, save_dir, force_overwrite, cleanup, allow_invalid_checksum\n):\n \"\"\"Download and untar a tar file.\n\n Args:\n tar_remote (RemoteFileMetadata): Object containing download information\n save_dir (str): Path to save downloaded file\n force_overwrite (bool): If True, overwrites existing files\n cleanup (bool): If True, remove tarfile after untarring\n\n \"\"\"\n tar_download_path = download_from_remote(\n tar_remote, save_dir, force_overwrite, allow_invalid_checksum\n )\n untar(tar_download_path, cleanup=cleanup)\n\n\ndef untar(tar_path, cleanup):\n \"\"\"Untar a tar file inside it's current directory.\n\n Args:\n tar_path (str): Path to tar file\n cleanup (bool): If True, remove tarfile after untarring\n\n \"\"\"\n tfile = tarfile.open(tar_path, \"r\")\n tfile.extractall(os.path.dirname(tar_path))\n tfile.close()\n if cleanup:\n os.remove(tar_path)\n\n\ndef move_directory_contents(source_dir, target_dir):\n \"\"\"Move the contents of source_dir into target_dir, and delete source_dir\n\n Args:\n source_dir (str): path to source directory\n target_dir (str): path to target directory\n\n \"\"\"\n directory_contents = glob.glob(os.path.join(source_dir, \"*\"))\n for fpath in directory_contents:\n target_path = os.path.join(target_dir, os.path.basename(fpath))\n if os.path.exists(target_path):\n logging.info(\n \"{} already exists. Run with force_overwrite=True to download from scratch\".format(\n target_path\n )\n )\n continue\n shutil.move(fpath, target_dir)\n\n shutil.rmtree(source_dir)\n","sub_path":"mirdata/download_utils.py","file_name":"download_utils.py","file_ext":"py","file_size_in_byte":14213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"109202165","text":"import os, sys\n\nfrom django.db import models\n\nclass BackupTask(models.Model):\n backup_directory = models.ForeignKey(\"chiropractor.BackupDirectory\")\n backup_destination_directory = models.CharField(max_length=500) \n created_date = models.DateTimeField(auto_now=True, auto_now_add=True)\n \n class Meta:\n ordering = ['-created_date']\n \n def __unicode__(self, *args, **kwargs):\n return \"{id}{bd}{cd}\".format(\n id=self.id, \n bd=self.backup_directory,\n cd=self.created_date)\n\nclass BackupDirectory(models.Model):\n backup_directory = models.CharField(blank=False, null=True, max_length=500)\n excluded_files = models.CharField(max_length=100, blank=True, null=True)\n \n class Meta:\n ordering = ['backup_directory']\n \n def __unicode__(self, *args, **kwargs):\n return \"{bd}\".format(bd=self.backup_directory)\n \n @property\n def backup_directory_contents(self):\n \"\"\"\n return contents of the BackupDirectory object attribute backup_directory.\n \"\"\"\n contents_l = []\n \n # walk contents of root direcotry\n for root, sub_directories, files in os.walk(self.backup_directory):\n tmp_d = {'root': root, \n 'sub_directories': sub_directories, \n 'files': files}\n contents_l.append(tmp_d)\n return contents_l \n \n @staticmethod\n def directory_contents(directory=None):\n \"\"\"\n return contents of a passed in directory.\n \"\"\"\n contents_l = []\n if not directory:\n return contents_l\n \n # need to add beginning slash, it is not present. \n directory = \"/{}\".format(directory)\n \n # walk contents of root direcotry\n for root, sub_directories, files in os.walk(directory):\n tmp_d = {'root': root, \n 'sub_directories': sub_directories, \n 'files': files}\n contents_l.append(tmp_d)\n return contents_l\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"325373517","text":"import importlib\nimport pkgutil\n\n_builders = {}\n_tools = {}\n_loaded_tools = False\n\ndef _load_tools():\n global _loaded_tools\n if not _loaded_tools:\n # Lazily load the tools so we don't get cyclic imports.\n # XXX: There's probably a better way to do this.\n for _, name, _ in pkgutil.walk_packages(__path__, '.'):\n importlib.import_module(name, __package__)\n _loaded_tools = True\n\ndef builder(*args):\n if len(args) == 0:\n raise TypeError('must provide at least one language')\n multi = len(args) > 1\n\n def wrapper(fn):\n for i in args:\n _builders[i] = (fn, multi)\n return fn\n return wrapper\n\ndef get_builder(lang, env):\n _load_tools()\n try:\n fn, multi = _builders[lang]\n return fn(env, lang) if multi else fn(env)\n except KeyError:\n raise ValueError('unknown language \"{}\"'.format(lang))\n\ndef tool(name):\n def wrapper(fn):\n _tools[name] = fn\n return fn\n return wrapper\n\ndef get_tool(name, env):\n _load_tools()\n try:\n return _tools[name](env)\n except KeyError:\n raise ValueError('unknown tool \"{}\"'.format(name))\n","sub_path":"bfg9000/tools/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"627041941","text":"import sys\r\nimport socket\r\n\r\n# Create a TCP/IP socket\r\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n# Connect the socket to the port where the server is listening\r\nserver_address = ('localhost', 31001)\r\nprint(f\"connecting to {server_address}\")\r\nsock.connect(server_address)\r\n\r\ntry:\r\n # Send data\r\n name=\"test.jpg\"\r\n file = open(name,'rb')\r\n content =file.read()\r\n print ('sending data...')\r\n sock.sendall(content)\r\nfinally:\r\n print(\"closing\")\r\n sock.close()","sub_path":"tugas1/Tugas1 B/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"461856394","text":"from django.shortcuts import redirect\nfrom django.urls import re_path\nfrom django.utils.translation import gettext_lazy as _\n\nfrom workbench import generic\nfrom workbench.logbook.forms import (\n BreakForm,\n BreakSearchForm,\n LoggedCostForm,\n LoggedCostMoveForm,\n LoggedCostSearchForm,\n LoggedHoursForm,\n LoggedHoursMoveForm,\n LoggedHoursSearchForm,\n)\nfrom workbench.logbook.models import Break, LoggedCost, LoggedHours\nfrom workbench.logbook.views import create\n\n\nurlpatterns = [\n re_path(\n r\"^$\", lambda request: redirect(\"logbook_loggedhours_list\"), name=\"logbook\"\n ),\n re_path(\n r\"^hours/create/$\",\n create,\n {\"viewname\": \"createhours\"},\n name=\"logbook_loggedhours_create\",\n ),\n re_path(\n r\"^hours/$\",\n generic.ListView.as_view(\n model=LoggedHours,\n search_form_class=LoggedHoursSearchForm,\n show_create_button=False,\n ),\n name=\"logbook_loggedhours_list\",\n ),\n re_path(\n r\"^hours/(?P\\d+)/$\",\n generic.DetailView.as_view(model=LoggedHours),\n name=\"logbook_loggedhours_detail\",\n ),\n re_path(\n r\"^hours/(?P\\d+)/update/$\",\n generic.UpdateView.as_view(model=LoggedHours, form_class=LoggedHoursForm),\n name=\"logbook_loggedhours_update\",\n ),\n re_path(\n r\"^hours/(?P\\d+)/move/$\",\n generic.UpdateView.as_view(\n model=LoggedHours,\n form_class=LoggedHoursMoveForm,\n template_name=\"modalform.html\",\n title=_(\"Move %(object)s\"),\n ),\n name=\"logbook_loggedhours_move\",\n ),\n re_path(\n r\"^hours/(?P\\d+)/delete/$\",\n generic.DeleteView.as_view(\n model=LoggedHours, template_name=\"modal_confirm_delete.html\"\n ),\n name=\"logbook_loggedhours_delete\",\n ),\n re_path(\n r\"^costs/create/$\",\n create,\n {\"viewname\": \"createcost\"},\n name=\"logbook_loggedcost_create\",\n ),\n re_path(\n r\"^costs/$\",\n generic.ListView.as_view(\n model=LoggedCost,\n search_form_class=LoggedCostSearchForm,\n show_create_button=False,\n ),\n name=\"logbook_loggedcost_list\",\n ),\n re_path(\n r\"^costs/(?P\\d+)/$\",\n generic.DetailView.as_view(model=LoggedCost),\n name=\"logbook_loggedcost_detail\",\n ),\n re_path(\n r\"^costs/(?P\\d+)/update/$\",\n generic.UpdateView.as_view(model=LoggedCost, form_class=LoggedCostForm),\n name=\"logbook_loggedcost_update\",\n ),\n re_path(\n r\"^hours/(?P\\d+)/move/$\",\n generic.UpdateView.as_view(\n model=LoggedCost,\n form_class=LoggedCostMoveForm,\n template_name=\"modalform.html\",\n title=_(\"Move %(object)s\"),\n ),\n name=\"logbook_loggedcost_move\",\n ),\n re_path(\n r\"^costs/(?P\\d+)/delete/$\",\n generic.DeleteView.as_view(\n model=LoggedCost, template_name=\"modal_confirm_delete.html\"\n ),\n name=\"logbook_loggedcost_delete\",\n ),\n re_path(\n r\"^breaks/$\",\n generic.ListView.as_view(\n model=Break,\n search_form_class=BreakSearchForm,\n # show_create_button=False,\n ),\n name=\"logbook_break_list\",\n ),\n re_path(\n r\"^breaks/(?P\\d+)/$\",\n generic.DetailView.as_view(model=Break),\n name=\"logbook_break_detail\",\n ),\n re_path(\n r\"^breaks/create/$\",\n generic.CreateView.as_view(\n model=Break, form_class=BreakForm, template_name=\"modalform.html\"\n ),\n name=\"logbook_break_create\",\n ),\n re_path(\n r\"^breaks/(?P\\d+)/update/$\",\n generic.UpdateView.as_view(\n model=Break, form_class=BreakForm, template_name=\"modalform.html\"\n ),\n name=\"logbook_break_update\",\n ),\n re_path(\n r\"^breaks/(?P\\d+)/delete/$\",\n generic.DeleteView.as_view(\n model=Break, template_name=\"modal_confirm_delete.html\"\n ),\n name=\"logbook_break_delete\",\n ),\n]\n","sub_path":"workbench/logbook/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"576023903","text":"# %% [markdown]\n# # Imports\nimport json\nimport os\nimport pickle\nimport random\nimport warnings\nfrom operator import itemgetter\nfrom pathlib import Path\nfrom timeit import default_timer as timer\n\nimport colorcet as cc\nimport matplotlib.colors as mplc\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom joblib import Parallel, delayed\nfrom matplotlib.cm import ScalarMappable\nfrom matplotlib.colors import LogNorm\nfrom sklearn.metrics import adjusted_rand_score\nfrom sklearn.model_selection import ParameterGrid\nfrom sklearn.neighbors import NearestNeighbors\n\nfrom graspy.cluster import AutoGMMCluster, GaussianCluster\nfrom graspy.embed import AdjacencySpectralEmbed, LaplacianSpectralEmbed\nfrom graspy.plot import gridplot, heatmap, pairplot\nfrom graspy.utils import symmetrize\nfrom src.cluster import DivisiveCluster\nfrom src.data import load_everything, load_metagraph\nfrom src.embed import ase, lse, preprocess_graph\nfrom src.graph import MetaGraph\nfrom src.hierarchy import signal_flow\nfrom src.io import savefig, saveobj, saveskels\nfrom src.utils import get_blockmodel_df, get_sbm_prob, invert_permutation\nfrom src.visualization import (\n bartreeplot,\n get_color_dict,\n get_colors,\n remove_spines,\n sankey,\n screeplot,\n)\n\nFNAME = os.path.basename(__file__)[:-3]\nprint(FNAME)\n\nSAVESKELS = True\nSAVEFIGS = True\nBRAIN_VERSION = \"2020-01-16\"\n\nsns.set_context(\"talk\")\n\nbase_path = Path(\"maggot_models/data/raw/Maggot-Brain-Connectome/\")\n\n\ndef stashfig(name, **kws):\n savefig(name, foldername=FNAME, save_on=SAVEFIGS, **kws)\n\n\ndef stashskel(name, ids, labels, colors=None, palette=None, **kws):\n saveskels(\n name,\n ids,\n labels,\n colors=colors,\n palette=None,\n foldername=FNAME,\n save_on=SAVESKELS,\n **kws,\n )\n\n\ndef r():\n return random.randint(0, 255)\n\n\ndef extract_ids(lod):\n out_list = []\n for d in lod:\n skel_id = d[\"skeleton_id\"]\n out_list.append(skel_id)\n return out_list\n\n\ndef get_edges(adj):\n adj = adj.copy()\n all_edges = []\n for i in range(adj.shape[0]):\n row = adj[i, :]\n col = adj[:, i]\n col = np.delete(col, i)\n edges = np.concatenate((row, col))\n all_edges.append(edges)\n return all_edges\n\n\n# %% [markdown]\n# # Play with getting edge df representatino\ngraph_type = \"Gadn\"\nmg = load_metagraph(graph_type, version=BRAIN_VERSION)\n\ng = mg.g\nmeta = mg.meta\nedgelist_df = mg.to_edgelist()\n\nmax_pair_edge_df = edgelist_df.groupby(\"edge pair ID\").max()\nedge_max_weight_map = dict(\n zip(max_pair_edge_df.index.values, max_pair_edge_df[\"weight\"])\n)\nedgelist_df[\"max_weight\"] = itemgetter(*edgelist_df[\"edge pair ID\"])(\n edge_max_weight_map\n)\n\n# %% [markdown]\n# # Try thresholding in this new format\nprops = []\nprop_edges = []\nprop_syns = []\nthreshs = np.linspace(0, 0.3, 20)\nfor threshold in threshs:\n thresh_df = max_pair_edge_df[max_pair_edge_df[\"weight\"] > threshold]\n prop = len(thresh_df[thresh_df[\"edge pair counts\"] == 2]) / len(thresh_df)\n props.append(prop)\n prop_edges_left = (\n thresh_df[\"edge pair counts\"].sum() / max_pair_edge_df[\"edge pair counts\"].sum()\n )\n prop_edges.append(prop_edges_left)\n temp_df = edgelist_df[edgelist_df[\"max_weight\"] > threshold]\n p_syns = temp_df[\"weight\"].sum() / edgelist_df[\"weight\"].sum()\n prop_syns.append(p_syns)\n# %% [markdown]\n# #\n\nplot_df = pd.DataFrame()\nplot_df[\"Threshold\"] = threshs\nplot_df[\"P(mirror edge present)\"] = props\nplot_df[\"Proportion of edges left\"] = prop_edges\nplot_df[\"Proportion of synapses left\"] = prop_syns\n\nfig, ax = plt.subplots(1, 1, figsize=(10, 5))\n\nsns.lineplot(data=plot_df, x=\"Threshold\", y=\"P(mirror edge present)\", ax=ax)\nax_right = ax.twinx()\nsns.lineplot(\n data=plot_df,\n x=\"Threshold\",\n y=\"Proportion of synapses left\",\n ax=ax_right,\n color=\"orange\",\n)\nremove_spines(ax_right)\nremove_spines(ax)\nax.set_ylim((0, 1))\nax_right.set_ylim((0, 1))\nax.set_title(f\"{graph_type}\")\nstashfig(f\"thresh-sweep-{graph_type}-brain-syns\")\n\n# %% [markdown]\n# # Plot these against each other\nfig, ax = plt.subplots(1, 1, figsize=(10, 10))\nsns.scatterplot(data=plot_df, x=\"P(mirror edge present)\", y=\"Proportion of edges left\")\nax.set_xlim((0, 1.1))\nax.set_ylim((0, 1.1))\nremove_spines(ax)\nstashfig(f\"thresh-sweep-paired-{graph_type}-brain\")\n# %% [markdown]\n# # Look at IOU\nthreshold = 0.05\nthresh_df = max_pair_edge_df[max_pair_edge_df[\"weight\"] > threshold]\n\nsource_pair_ids = np.unique(max_pair_edge_df[\"source Pair ID\"])\ntarget_pair_ids = np.unique(max_pair_edge_df[\"target Pair ID\"])\npair_ids = np.union1d(source_pair_ids, target_pair_ids)\n\nious = []\nkept_pairs = []\nremoved_pairs = []\nedge_dfs = []\nkeep_cols = [\n \"source\",\n \"target\",\n \"weight\",\n \"source Pair ID\",\n \"target Pair ID\",\n \"edge pair counts\",\n]\n\nfor pid in pair_ids:\n temp_df = thresh_df[\n (thresh_df[\"source Pair ID\"] == pid) | (thresh_df[\"target Pair ID\"] == pid)\n ]\n\n if len(temp_df) > 0:\n iou = len(temp_df[temp_df[\"edge pair counts\"] == 2]) / len(temp_df)\n ious.append(iou)\n kept_pairs.append(pid)\n edge_dfs.append(temp_df[keep_cols])\n else:\n removed_pairs.append(pid)\n\n# inds = np.argsort(ious)\n\n# edge_dfs[inds]\n\n# %% [markdown]\n# #\nplot_df = pd.DataFrame()\n\nfig, ax = plt.subplots(1, 1, figsize=(10, 5))\nsns.distplot(ious, norm_hist=False, kde=False)\nremove_spines(ax)\nax.set_xlabel(\"IOU Score\")\nax.set_xlim((0, 1))\nax.set_title(f\"{graph_type}, threshold = {threshold:0.2f}\")\nax.set_ylabel(\"Pair count\")\n\n# %% [markdown]\n# #\niou_df = pd.DataFrame()\niou_df[\"IOU Score\"] = ious\niou_df[\"Pair ID\"] = kept_pairs\niou_df[\"Left ID\"] = -1\niou_df[\"Right ID\"] = -1\nfor i, pid in enumerate(kept_pairs):\n temp_df = meta[meta[\"Pair ID\"] == pid]\n iou_df.loc[i, \"Left ID\"] = temp_df[temp_df[\"Hemisphere\"] == \"L\"].index[0]\n iou_df.loc[i, \"Right ID\"] = temp_df[temp_df[\"Hemisphere\"] == \"R\"].index[0]\n\n# %% [markdown]\n# #\niou_df.sort_values(\"IOU Score\", ascending=True, inplace=True)\niou_df.index = range(len(iou_df))\n\ncolors = []\nids = []\nfor i in range(100):\n left_id = iou_df.loc[i, \"Left ID\"]\n right_id = iou_df.loc[i, \"Right ID\"]\n iou = iou_df.loc[i, \"IOU Score\"]\n c = int(iou * 255.0)\n print(c)\n print(iou)\n hex_color = \"#%02X%02X%02X\" % (c, c, c)\n colors.append(hex_color)\n colors.append(hex_color)\n ids.append(left_id)\n ids.append(right_id)\n\nstashskel(\"low-iou-sorted-pairs\", ids, colors, colors=colors, palette=None)\n\n#%%\nleft_id = 12121795\npair_id = meta.loc[left_id, \"Pair ID\"]\nind = np.where(kept_pairs == pair_id)[0][0]\nedge_dfs[ind]\n# %% [markdown]\n# #\n\niou_df.sort_values(\"IOU Score\", ascending=False, inplace=True)\niou_df.index = range(len(iou_df))\n\ncolors = []\nids = []\nfor i in range(100):\n left_id = iou_df.loc[i, \"Left ID\"]\n right_id = iou_df.loc[i, \"Right ID\"]\n iou = iou_df.loc[i, \"IOU Score\"]\n c = int(iou * 255.0)\n print(c)\n print(iou)\n hex_color = \"#%02X%02X%02X\" % (c, c, c)\n colors.append(hex_color)\n colors.append(hex_color)\n ids.append(left_id)\n ids.append(right_id)\n\nstashskel(\"high-iou-sorted-pairs\", ids, colors, colors=colors, palette=None)\n\n# %% [markdown]\n# #\n\n# Get rid of unpaired cells for now\n\nmg.meta[\"is_paired\"] = False\npairs = mg[\"Pair\"]\nis_paired = pairs != -1\nmg.reindex(is_paired)\nmg.sort_values([\"Hemisphere\", \"Pair ID\"])\n\nplot_adj = False\nif plot_adj:\n heatmap(\n mg.adj,\n sort_nodes=False,\n inner_hier_labels=mg[\"Class 1\"],\n outer_hier_labels=mg[\"Hemisphere\"],\n transform=\"binarize\",\n cbar=False,\n figsize=(30, 30),\n hier_label_fontsize=10,\n )\n heatmap(\n mg.adj, sort_nodes=False, transform=\"binarize\", cbar=False, figsize=(30, 30)\n )\n\nn_pairs = mg.adj.shape[0] // 2\n\nmg.verify()\n\n\n# %% [markdown]\n# # Extract subgraphs\n\n\nextract_fb = True\nif extract_fb:\n from_classes = [\"MBON\", \"FAN\", \"FBN\", \"FB2N\"]\n to_classes = [\"MBIN\"]\n sub_mg = MetaGraph(mg.adj, mg.meta)\n from_class_inds = sub_mg.meta[\"Class 1\"].isin(from_classes)\n to_class_inds = sub_mg.meta[\"Class 1\"].isin(to_classes)\n any_inds = np.logical_or(from_class_inds, to_class_inds)\n sub_mg.reindex(any_inds)\n sub_mg.sort_values([\"Hemisphere\", \"Class 1\", \"Pair ID\"])\n # meta = sub_mg.meta\n # meta[\"Original index\"] = range(meta.shape[0])\n # meta.sort_values(\n # [\"Hemisphere\", \"Class 1\", \"Pair ID\"],\n # inplace=True,\n # kind=\"mergesort\",\n # ascending=False,\n # )\n # temp_inds = meta[\"Original index\"]\n # sub_mg = sub_mg.reindex(temp_inds)\n # sub_mg = MetaGraph(sub_mg.adj, meta)\n\n adj = sub_mg.adj.copy()\n from_class_inds = np.where(sub_mg.meta[\"Class 1\"].isin(from_classes).values)[0]\n left_inds = np.where(sub_mg.meta[\"Hemisphere\"] == \"L\")[0]\n right_inds = np.where(sub_mg.meta[\"Hemisphere\"] == \"R\")[0]\n to_class_inds = np.where(sub_mg.meta[\"Class 1\"].isin(to_classes).values)[0]\n from_left = np.intersect1d(left_inds, from_class_inds)\n from_right = np.intersect1d(right_inds, from_class_inds)\n to_left = np.intersect1d(left_inds, to_class_inds)\n to_right = np.intersect1d(right_inds, to_class_inds)\n\n left_left_adj = adj[np.ix_(from_left, to_left)]\n left_right_adj = adj[np.ix_(from_left, to_right)]\n right_right_adj = adj[np.ix_(from_right, to_right)]\n right_left_adj = adj[np.ix_(from_right, to_left)]\nelse:\n adj = mg.adj.copy()\n left_left_adj = adj[:n_pairs, :n_pairs]\n left_right_adj = adj[:n_pairs, n_pairs : 2 * n_pairs]\n right_right_adj = adj[n_pairs : 2 * n_pairs, n_pairs : 2 * n_pairs]\n right_left_adj = adj[n_pairs : 2 * n_pairs, :n_pairs]\n\nif plot_adj:\n heatmap(\n mg.adj,\n inner_hier_labels=mg[\"Class 1\"],\n outer_hier_labels=mg[\"Hemisphere\"],\n transform=\"binarize\",\n figsize=(10, 10),\n )\n\n# %% [markdown]\n# # Plot all edges, weights\n\nll_edges = left_left_adj.ravel()\nlr_edges = left_right_adj.ravel()\nrr_edges = right_right_adj.ravel()\nrl_edges = right_left_adj.ravel()\n\n\nleft_edges = np.concatenate((ll_edges, lr_edges))\nright_edges = np.concatenate((rr_edges, rl_edges))\n\n\nprops = []\nthreshs = np.linspace(0, 0.3, 200)\nfor threshold in threshs:\n keep_mask = np.logical_or(left_edges >= threshold, right_edges >= threshold)\n thresh_left_edges = left_edges.copy()[keep_mask]\n thresh_right_edges = right_edges.copy()[keep_mask]\n n_consistent = np.logical_and(thresh_left_edges != 0, thresh_right_edges != 0).sum()\n prop_consistent = n_consistent / len(thresh_left_edges)\n props.append(prop_consistent)\n\nif extract_fb:\n first_ind = np.where(np.array(props) > 0.95)[0][0]\n\nplot_df = pd.DataFrame()\nplot_df[\"Threshold\"] = threshs\nplot_df[\"P(mirror edge present)\"] = props\n\nfig, ax = plt.subplots(1, 1, figsize=(10, 5))\n\n# if extract_fb:\n# ax.axvline(threshs[first_ind], c=\"r\")\n\nsns.lineplot(data=plot_df, x=\"Threshold\", y=\"P(mirror edge present)\", ax=ax)\nremove_spines(ax)\n\nif extract_fb:\n ax.set_title(f\"{graph_type}, 0.95 at thresh = {threshs[first_ind]:0.2f}\")\n stashfig(f\"thresh-sweep-{graph_type}-fbpaper\")\nelse:\n ax.set_title(f\"{graph_type}\")\n stashfig(f\"thresh-sweep-{graph_type}-brain\")\n\n# %% [markdown]\n# #\n# left_edges = ll_edges + lr_edges\n# right_edges = rr_edges + rl_edges\n\nnonzero_inds = np.where(np.logical_or(left_edges > 0, right_edges > 0))[0]\nleft_edges = left_edges[nonzero_inds]\nright_edges = right_edges[nonzero_inds]\n\nsns.set_context(\"talk\", font_scale=1.25)\nplot_log = False\nif plot_log:\n left_edges = np.log10(left_edges + 0.01)\n right_edges = np.log10(right_edges + 0.01)\n xlabel = \"Log10(Left edge weight)\"\n ylabel = \"Log10(Right edge weight)\"\nelse:\n xlabel = \"Left edge weight\"\n ylabel = \"Right edge weight\"\n\npad = 1\nxmin = left_edges.min() - pad\nymin = right_edges.min() - pad\nxmax = left_edges.max() + pad\nymax = right_edges.max() + pad\n\nedge_plot_df = pd.DataFrame()\nscale = 0.15\nedge_plot_df[\"y\"] = left_edges + np.random.normal(scale=scale, size=left_edges.size)\nedge_plot_df[\"x\"] = right_edges + np.random.normal(scale=scale, size=right_edges.size)\nfig, axs = plt.subplots(1, 2, figsize=(16, 8), sharex=True, sharey=True)\nsns.scatterplot(\n data=edge_plot_df, x=\"x\", y=\"y\", ax=axs[0], s=1, alpha=0.2, linewidth=False\n)\nmax_val = max(xmax, ymax)\naxs[0].plot((0, max_val), (0, max_val), color=\"red\", linewidth=1, linestyle=\"--\")\naxs[0].set_xlabel(xlabel)\naxs[0].set_ylabel(ylabel)\naxs[0].axis(\"square\")\n\naxs[1].hexbin(\n left_edges,\n right_edges,\n bins=\"log\",\n gridsize=(int(left_edges.max()), int(right_edges.max())),\n cmap=\"Blues\",\n)\naxs[1].axis(\"square\")\naxs[1].set_xlabel(xlabel)\nfor ax in axs:\n remove_spines(ax, keep_corner=False)\n ax.set_xticks([])\n ax.set_yticks([])\n ax.yaxis.set_major_locator(plt.MaxNLocator(3))\n ax.xaxis.set_major_locator(plt.MaxNLocator(3))\n\naxs[1].set_ylim((ymin, ymax))\naxs[1].set_xlim((xmin, xmax))\n\nplt.tight_layout()\n\ncorr = np.corrcoef(left_edges, right_edges)[0, 1]\nplt.suptitle(f\"{graph_type}, all paired edges, correlation = {corr:0.2f}\", y=0.99)\nstashfig(f\"all-paired-edge-corr-{graph_type}\")\naxs[1].set_ylim((ymin, 30))\naxs[1].set_xlim((xmin, 30))\nstashfig(f\"all-paired-edge-corr-zoom-{graph_type}\")\n\n# %% [markdown]\n# # Get pairs into proper format\nll_edges = get_edges(left_left_adj)\nlr_edges = get_edges(left_right_adj)\nrr_edges = get_edges(right_right_adj)\nrl_edges = get_edges(right_left_adj)\n\nleft_edge_vecs = []\nright_edge_vecs = []\nfor i in range(n_pairs):\n left_edge_vecs.append(np.concatenate((ll_edges[i], lr_edges[i])))\n right_edge_vecs.append(np.concatenate((rr_edges[i], rl_edges[i])))\n\n# %% [markdown]\n# # Now add back in the super nodes - Janky but ok for now\n\ngraph_type = \"G\"\nmg_for_unpaired = load_metagraph(graph_type, version=BRAIN_VERSION)\nmg_for_unpaired.meta.head()\n\nkeep_classes = [\"KC\", \"sens\"]\n\n\nclass_label = mg_for_unpaired[\"Class 1\"]\nis_keep_class = [c in keep_classes for c in class_label]\n\nis_keep = np.logical_or(is_paired, is_keep_class)\n\nmg_for_unpaired.reindex(is_keep)\n# print(np.unique(mg[\"Pair\"]))\nmeta = mg_for_unpaired.meta\nmeta[\"Original index\"] = range(meta.shape[0])\nmeta.sort_values(\n [\"Hemisphere\", \"Pair ID\", \"Merge Class\"],\n inplace=True,\n kind=\"mergesort\",\n ascending=False,\n)\ntemp_inds = meta[\"Original index\"]\nmg_for_unpaired = mg_for_unpaired.reindex(temp_inds)\nmg_for_unpaired = MetaGraph(mg_for_unpaired.adj, meta)\n\nadj = mg_for_unpaired.adj\nfor c in keep_classes:\n for side in [\"L\", \"R\"]: # this is the side of the paired neurons\n for direction in [\"ipsi\", \"contra\"]:\n if direction == \"ipsi\":\n class_inds = np.where(\n np.logical_and(\n mg_for_unpaired[\"Hemisphere\"] == side,\n mg_for_unpaired[\"Class 1\"] == c,\n )\n )[0]\n unpaired_inds = np.where(\n np.logical_and(\n mg_for_unpaired[\"Hemisphere\"] == side,\n mg_for_unpaired[\"Pair ID\"] == -1,\n )\n )[0]\n elif direction == \"contra\":\n class_inds = np.where(\n np.logical_and(\n mg_for_unpaired[\"Hemisphere\"] != side,\n mg_for_unpaired[\"Class 1\"] == c,\n )\n )[0]\n unpaired_inds = np.where(\n np.logical_and(\n mg_for_unpaired[\"Hemisphere\"] != side,\n mg_for_unpaired[\"Pair ID\"] == -1,\n )\n )[0]\n unpaired_inds = np.intersect1d(class_inds, unpaired_inds)\n paired_inds = np.where(\n np.logical_and(\n mg_for_unpaired[\"Hemisphere\"] == side,\n mg_for_unpaired[\"Pair ID\"] != -1,\n )\n )[0]\n\n # from\n from_edges = adj[np.ix_(unpaired_inds, paired_inds)]\n pair_super_edges = from_edges.sum(axis=0)\n\n # to\n to_edges = adj[np.ix_(paired_inds, unpaired_inds)]\n pair_super_edges = to_edges.sum(axis=1)\n\n\n# %% [markdown]\n# # Plot, by pair, the IOU score\n\nthreshold = 8\n\niou_scores = []\nrand_iou_scores = []\nfor i in range(n_pairs):\n left_edge_vec = left_edge_vecs[i].copy()\n left_edge_vec[left_edge_vec <= threshold] = 0\n right_edge_vec = right_edge_vecs[i].copy()\n right_edge_vec[right_edge_vec <= threshold] = 0\n ind = np.random.choice(len(right_edge_vecs))\n rand_vec = right_edge_vecs[ind].copy()\n rand_vec[rand_vec <= threshold] = 0\n\n left_mask = left_edge_vec > 0\n right_mask = right_edge_vec > 0\n or_mask = np.logical_or(left_mask, right_mask) # anything that is an edge in either\n and_mask = np.logical_and(left_mask, right_mask) # edge in both\n iou_score = and_mask.sum() / or_mask.sum()\n if not np.isnan(iou_score):\n iou_scores.append(iou_score)\n else:\n left_id = mg.meta.index[i]\n right_id = mg.meta.index[i + n_pairs]\n print(f\"Nan IOU score for pair {left_id}, {right_id}\")\n rand_mask = rand_vec > 0\n or_mask = np.logical_or(left_mask, rand_mask) # anything that is an edge in either\n and_mask = np.logical_and(left_mask, rand_mask) # edge in both\n iou_score = and_mask.sum() / or_mask.sum()\n if not np.isnan(iou_score):\n rand_iou_scores.append(iou_score)\n\nfig, ax = plt.subplots(1, 1, figsize=(10, 5))\nsns.distplot(iou_scores, ax=ax, norm_hist=True, label=\"True pair\")\nsns.distplot(rand_iou_scores, ax=ax, norm_hist=True, label=\"Random pair\")\nax.set_xlabel(\"IOU score (binary edges)\")\nax.set_title(f\"Pair edge agreement, {graph_type}, theshold = {threshold}\")\nax.yaxis.set_major_locator(plt.NullLocator())\nremove_spines(ax)\nax.set_xlim((0, 1))\nstashfig(f\"pair-IOU-random-{graph_type}-t{threshold}\")\n\nfig, ax = plt.subplots(1, 1, figsize=(10, 5))\nsns.distplot(iou_scores, ax=ax, norm_hist=True)\nax.set_xlabel(\"IOU score (binary edges)\")\nax.set_title(f\"Pair edge agreement, {graph_type}, theshold = {threshold}\")\nax.yaxis.set_major_locator(plt.NullLocator())\nremove_spines(ax)\nax.set_xlim((0, 1))\nstashfig(f\"pair-IOU-{graph_type}-t{threshold}\")\n\n# %% [markdown]\n# # Plot, for a subset of random pairs, the edge weights\nn_plots = 5\nfor i in range(n_plots):\n fig, axs = plt.subplots(4, 6, figsize=(30, 20))\n axs = axs.ravel()\n rand = np.random.randint(1e8)\n np.random.seed(rand)\n for ax in axs:\n ind = np.random.choice(len(right_edge_vecs))\n left_edge_vec = left_edge_vecs[ind].copy()\n right_edge_vec = right_edge_vecs[ind].copy()\n left_mask = left_edge_vec > 0\n right_mask = right_edge_vec > 0\n or_mask = np.logical_or(left_mask, right_mask)\n remove_spines(ax)\n if or_mask.sum() > 0:\n left_id = mg.meta.index[ind]\n right_id = mg.meta.index[ind + n_pairs]\n left_edge_vec = left_edge_vec[or_mask]\n right_edge_vec = right_edge_vec[or_mask]\n corr = np.corrcoef(left_edge_vec, right_edge_vec)[0, 1]\n sns.scatterplot(left_edge_vec, right_edge_vec, ax=ax)\n ax.axis(\"equal\")\n ax.set_title(f\"Corr = {corr:0.2f}\")\n max_val = max(left_edge_vec.max(), right_edge_vec.max())\n ax.plot(\n (0, max_val), (0, max_val), color=\"red\", linewidth=1, linestyle=\"--\"\n )\n ax.text(max_val, max_val, max_val)\n # ax.xaxis.set_major_locator(plt.MaxNLocator(1))\n # xticks = ax.get_xticks()\n # print(xticks)\n # ax.set_yticks(xticks)\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n ax.set_xlabel(left_id)\n ax.set_ylabel(right_id)\n\n plt.suptitle(f\"{graph_type}, edge weights by pair\", y=1.02)\n plt.tight_layout()\n stashfig(f\"edge-weights-by-pair-{graph_type}-r{rand}\")\n# %% [markdown]\n# # For some random cells plot the pair correlations\n\n# %% [markdown]\n# # Look into a few of the low x or y edges\n\n# %% [markdown]\n# #\n# Extract edges\nll_edges = get_edges(left_left_adj)\nlr_edges = get_edges(left_right_adj)\nrr_edges = get_edges(right_right_adj)\nrl_edges = get_edges(right_left_adj)\n\npair_corrs = []\nfor i in range(n_pairs):\n left_edge_vec = np.concatenate((ll_edges[i], lr_edges[i]))\n right_edge_vec = np.concatenate((rr_edges[i], rl_edges[i]))\n both_edges = np.stack((left_edge_vec, right_edge_vec), axis=-1)\n avg_edges = np.mean(both_edges, axis=-1)\n # inds = np.where(avg_edges > threshold)[0]\n\n # check that left and right edge both have\n inds = np.where(\n np.logical_and(left_edge_vec > threshold, right_edge_vec > threshold)\n )[0]\n if len(inds) > 0:\n left_edge_vec = left_edge_vec[inds]\n # left_edge_vec[left_edge_vec > 0] = 1\n right_edge_vec = right_edge_vec[inds]\n # print(left_edge_vec)\n # print(right_edge_vec)\n # right_edge_vec[right_edge_vec > 0] = 1\n R = np.corrcoef(left_edge_vec, right_edge_vec)\n corr = R[0, 1]\n # print(corr)\n # print()\n if i < 40:\n plt.figure()\n plt.scatter(left_edge_vec, right_edge_vec)\n plt.title(corr)\n plt.axis(\"square\")\n # corr = np.count_nonzero(left_edge_vec - right_edge_vec) / len(left_edge_vec)\n else:\n corr = 0\n if np.isnan(corr):\n corr = 0\n pair_corrs.append(corr)\npair_corrs = np.array(pair_corrs)\n\n\nground_truth_file = (\n base_path / \"neuron-groups/GroundTruth_NeuronPairs_Brain-2019-07-29.csv\"\n)\n\nground_truth_df = pd.read_csv(ground_truth_file)\nground_truth_df.set_index(\"ID\", inplace=True)\nground_truth_df.head()\nground_truth_ids = ground_truth_df.index.values\nground_truth_sides = ground_truth_df[\"Hemisphere\"].values\n\nknown_inds = []\nfor cell_id, side in zip(ground_truth_ids, ground_truth_sides):\n if side == \" left\":\n ind = np.where(mg.meta.index.values == cell_id)[0]\n if len(ind) > 0:\n known_inds.append(ind[0])\n\nnot_known_inds = np.setdiff1d(range(n_pairs), known_inds)\nnew_pair_corrs = pair_corrs[not_known_inds]\ntruth_pair_corrs = pair_corrs[known_inds]\n\nsns.set_context(\"talk\")\nplt.figure(figsize=(10, 5))\nsns.distplot(new_pair_corrs, label=\"New pairs\")\nsns.distplot(truth_pair_corrs, label=\"Ground truth\")\nplt.legend()\nplt.title(threshold)\nstashfig(f\"both-t{threshold}-corr-nodewise\")\n\nout_pair_df = pd.DataFrame()\nout_pair_df\n\n# %% Look at correlation vs degree\ndeg_df = mg.calculate_degrees()\nplot_df = pd.DataFrame()\ntotal_degree = deg_df[\"Total degree\"].values\nplot_df[\"Mean total degree\"] = (\n total_degree[:n_pairs] + total_degree[n_pairs : 2 * n_pairs]\n) / 2\nplot_df[\"Correlation\"] = pair_corrs\nplt.figure(figsize=(10, 5))\nsns.scatterplot(data=plot_df, x=\"Mean total degree\", y=\"Correlation\")\nstashfig(\"corr-vs-degree\")\n\nsns.jointplot(\n data=plot_df, x=\"Mean total degree\", y=\"Correlation\", kind=\"hex\", height=10\n)\nstashfig(\"corr-vs-degree-hex\")\n\n# %% [markdown]\n# # Find the cells where correlation is < 0\nskeleton_labels = mg.meta.index.values[: 2 * n_pairs]\nside_labels = mg[\"Hemisphere\"][: 2 * n_pairs]\nleft_right_pairs = zip(\n skeleton_labels[:n_pairs], skeleton_labels[n_pairs : 2 * n_pairs]\n)\n\ncolors = []\nids = []\n\nfor i, (left, right) in enumerate(left_right_pairs):\n if pair_corrs[i] < 0:\n hex_color = \"#%02X%02X%02X\" % (r(), r(), r())\n colors.append(hex_color)\n colors.append(hex_color)\n ids.append(left)\n ids.append(right)\n\nstashskel(\"pairs-low-corr\", ids, colors, colors=colors, palette=None)\n\n# %% [markdown]\n# # Look at number of disagreements vs degree\nprop_disagreements = []\nfor i in range(n_pairs):\n left_edge_vec = np.concatenate((ll_edges[i], lr_edges[i]))\n right_edge_vec = np.concatenate((rr_edges[i], rl_edges[i]))\n left_edge_vec[left_edge_vec > 0] = 1\n right_edge_vec[right_edge_vec > 0] = 1\n n_disagreement = np.count_nonzero(left_edge_vec - right_edge_vec)\n prop_disagreement = n_disagreement / len(left_edge_vec)\n prop_disagreements.append(prop_disagreement)\nprop_disagreements = np.array(prop_disagreements)\nplot_df[\"Prop. disagreements\"] = prop_disagreements\n\nsns.jointplot(\n data=plot_df, x=\"Mean total degree\", y=\"Prop. disagreements\", kind=\"hex\", height=10\n)\n#%%\npair_corrs = []\nfor i in range(n_pairs):\n left_edge_vec = np.concatenate((ll_edges[i], lr_edges[i]))\n right_edge_vec = np.concatenate((rr_edges[i], rl_edges[i]))\n both_edges = np.stack((left_edge_vec, right_edge_vec), axis=-1)\n avg_edges = np.mean(both_edges, axis=-1)\n\n#%%\nleft_edges = np.concatenate((left_left_adj.ravel(), left_right_adj.ravel()))\nright_edges = np.concatenate((right_right_adj.ravel(), right_left_adj.ravel()))\nall_edges = np.stack((left_edges, right_edges), axis=1)\nall_edges_sum = np.sum(all_edges, axis=1)\nedge_mask = all_edges_sum > 0\nall_edges = all_edges[edge_mask]\nleft_edges = left_edges[edge_mask]\nright_edges = right_edges[edge_mask]\nmean_edges = np.mean(all_edges, axis=-1)\ndiff_edges = np.abs(left_edges - right_edges)\nplot_df = pd.DataFrame()\nplot_df[\"Mean (L/R) edge\"] = mean_edges\nplot_df[\"Diff (L/R) edge\"] = diff_edges\nplt.figure(figsize=(10, 10))\nsns.scatterplot(mean_edges, diff_edges)\nsns.jointplot(data=plot_df, x=\"Mean (L/R) edge\", y=\"Diff (L/R) edge\", kind=\"hex\")\nplt.figure(figsize=(10, 5))\nbins = np.linspace(-1, 40, 41)\nsns.distplot(diff_edges, kde=False, norm_hist=False, bins=bins)\nsns.jointplot(\n data=plot_df,\n x=\"Mean (L/R) edge\",\n y=\"Diff (L/R) edge\",\n kind=\"hex\",\n xlim=(0, 5),\n ylim=(0, 5),\n)\n\n# %% [markdown]\n# # this works, would be to plot a heatmap\n\nfig, ax = plt.subplots(1, 1, figsize=(10, 10))\nedge_plot_df = pd.DataFrame()\nedge_plot_df[\"y\"] = left_edges\nedge_plot_df[\"x\"] = right_edges\ncount_df = edge_plot_df.groupby([\"x\", \"y\"]).size().unstack(fill_value=0)\ncount_df = count_df.combine_first(count_df.T).fillna(0.0)\nsns.heatmap(\n count_df + 1,\n cmap=\"Blues\",\n cbar=True,\n ax=ax,\n square=True,\n norm=LogNorm(vmin=count_df.values.min(), vmax=count_df.values.max()),\n)\nylims = ax.get_ylim()\nax.set_ylim((ylims[1], ylims[0]))\nax.yaxis.set_major_locator(plt.MaxNLocator(3))\nax.xaxis.set_major_locator(plt.MaxNLocator(3))\n","sub_path":"notebooks/58.4-BDP-analyze-pairs.py","file_name":"58.4-BDP-analyze-pairs.py","file_ext":"py","file_size_in_byte":26324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"413477723","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nfrom os.path import join, dirname, abspath, isfile, isdir\nimport argparse\n\nfrom dotenv import load_dotenv\n\ndir_scr = os.path.abspath(os.path.dirname(__file__))\nsys.path.append(join(dir_scr, \"..\"))\nimport helper as fn\n\nos.chdir(dir_scr)\nfile_env = os.path.join(dir_scr, \".env\")\n\ndef main(_args):\n \"\"\"\n initialize container\n \"\"\"\n\n envs = fn.getenv(file_env)\n node = envs['NODE']\n if not _args.node is None:\n node = _args.node\n if node == \"\":\n print(f\"[error] node type not set.\")\n sys.exit()\n\n target = \"\"\n if node != \"all\":\n target = f\"rds-{node}\"\n\n # サービス削除\n cmd_down = \"docker-compose down\"\n for line in fn.cmdlines(_cmd=cmd_down):\n sys.stdout.write(line)\n\n fn.rmdir(join(dir_scr, \"vol\", node))\n\n # サービス作成\n for line in fn.cmdlines(_cmd=f\"docker-compose up -d {target}\"):\n sys.stdout.write(line)\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description='set env params')\n parser.add_argument('--node', '-n', help=\"(option) set generate node type. 'master' or 'slave' or 'all'\")\n args = parser.parse_args()\n\n _input = input(\"initialize container. ok? (y/*) :\").lower()\n if not _input in [\"y\", \"yes\"]:\n print(\"[info] initialize canceled.\")\n sys.exit()\n\n print(\"[info] initialize start.\")\n main(args)\n print(\"[info] initialize end.\")\n","sub_path":"init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"316666253","text":"def ui_config():\n dataset = [\n 'Stackexchange',\n 'Ionesoft'\n ]\n algorithm = [\n 'Plain',\n 'Stemming',\n 'Lemmatization',\n 'Stopwords',\n 'Stopwords & stemming',\n 'Stopwords & lemmatization'\n ]\n domain_limit = [\n 'max_df 100%',\n 'max_df 75%',\n 'max_df 50%'\n ]\n return dataset, algorithm, domain_limit\n","sub_path":"backend/lib/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"452606384","text":"maior = soma = 0\r\nmenor = 9999999999\r\nproduto = 1\r\nqtde = int(input(\"Quantos números você deseja informar: \"))\r\nwhile qtde > 0:\r\n numero = int(input(\"Digite um número: \"))\r\n if numero > maior:\r\n maior = numero\r\n if numero < menor:\r\n menor = numero\r\n soma = soma + numero\r\n produto = produto * numero\r\n qtde = qtde - 1\r\nprint('-='*30)\r\nprint(f'O menor valor digitado foi {menor}.')\r\nprint(f'O maior valor digitado foi {maior}.')\r\nprint(f'A soma entre os valores digitados é {soma}.')\r\nprint(f'O produto entre os valores digitados é {produto}.')\r\nprint('-='*30)\r\n\r\n","sub_path":"Exercícios 01/Quest 20.py","file_name":"Quest 20.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"324095585","text":"def mul(a,c):\n\treturn a*c\ndef tables (a,b):\n\tc = 0\n\twhile c!=b+1: \n\t\tprint (mul(a,c))\n\t\tc+=1\n\nif __name__ == '__main__':\n\ta = float(input(\"Enter the value of the number: \"))\n\tb = int(input(\"Enter the maximum number of table lines you need: \"))\n\tprint ('The tables of ',a,'to the number',b,)\n\ttables(a,b)","sub_path":"tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"379375575","text":"from coffea import processor\nfrom coffea.nanoevents import NanoAODSchema\nimport uproot3\nimport numpy as np\nimport sys\nimport os\nimport time\nimport argparse\nfrom collections import OrderedDict\n\nsys.path.append(\"../utilities/\")\nimport uproot3Utilities as uproot3utl\nimport processorPreSelection\n\n\ndef print_cutflow(cutflow):\n \"\"\"Print cut efficiencies for cuts needed for defining some of the variables.\n\n For instance, to compute deltaR between leading 2 jets, events needs\n to have at least 2 jets.\n\n Args:\n cutflow (dict[coffea.processor.defaultdict_accumulator]):\n Keys are cut names\n Values are numbers of processed events (sum of gen weights)\n \n Returns:\n dict[float]\n Keys are cut names\n Values are absolute efficiencies\n \"\"\"\n\n len_column1 = max([ len(k) for k in cutflow.keys() ])\n efficiencies = {}\n\n print(\"\\nCutflow:\")\n print(\"\\tCut\" + (len_column1-3)*\" \" + \" Abs. eff. [%] Rel. eff. [%]\")\n n_all = cutflow[\"all\"]\n for cut, n in cutflow.items():\n if cut != \"all\":\n absolute_efficiency = 100*n/n_all\n if n_previous_cut > 0.:\n relative_efficiency = 100*n/n_previous_cut\n else:\n relative_efficiency = np.nan\n spaces = (len_column1-len(cut)+(absolute_efficiency<10))*\" \"\n print(\"\\t%s%s %.2f %.2f\" %(cut, spaces, absolute_efficiency, relative_efficiency))\n efficiencies[cut] = absolute_efficiency/100\n n_previous_cut = n\n \n efficiencies[\"totalEfficiency\"] = absolute_efficiency\n \n return efficiencies\n\n\ndef write_root_file(output_file, events, efficiencies, debug):\n \"\"\"Write ROOT file with Events and Efficiencies TTrees.\n\n Args:\n output_file (str)\n events (coffea.processor.accumulator.dict_accumulator)\n Keys are Events branch names\n Values are branches (coffea.processor.accumulator.column_accumulator)\n efficiencies (dict[float])\n Keys are Efficicies branch names\n Values are efficiencies (float)\n debug (bool)\n\n Returns:\n None\n \"\"\"\n\n # Making branches to write to Events tree\n branches_events, branches_init_events = uproot3utl.make_branches(events, debug)\n branches_efficiencies, branches_init_efficiencies = uproot3utl.make_branches(efficiencies, debug)\n\n if debug:\n print(\"\\nEvents branches keys:\")\n print(branches_events.keys())\n print(\"\\nEvents branchesInit keys:\")\n print(branches_init_events.keys())\n\n\n with uproot3.recreate(output_file) as root_file:\n # Save events to output ROOT file\n uproot3utl.write_tree_to_root_file(root_file, \"Events\", branches_events, branches_init_events)\n print(\"\\nTTree Events saved to output file %s\" %output_file)\n\n # Save cut efficiencies to output ROOT file\n uproot3utl.write_tree_to_root_file(root_file, \"Efficiencies\", branches_efficiencies, branches_init_efficiencies)\n print(\"TTree Efficiencies saved to output file %s\" %output_file)\n\n return\n\n\ndef main(input_files, output_file, file_type, processor_name, chunksize, maxchunks, nworkers, debug):\n \"\"\"Produce ROOT file with pre-selected events.\n \n Args:\n input_files (list[str])\n output_file (str)\n file_type (str)\n processor_name (str)\n chunksize (int)\n maxchunks (int or None)\n nworkers (int)\n debug (bool)\n\n Returns:\n None\n \"\"\"\n\n print(\"Input files:\")\n print(input_files)\n\n ## Fileset\n fileset = { \"fileset\": input_files }\n\n ## Make pre-selections\n accumulator = processor.run_uproot_job(\n fileset,\n treename = \"Events\",\n processor_instance = getattr(processorPreSelection, processor_name)(file_type),\n executor = processor.iterative_executor,\n executor_args = {\"schema\": NanoAODSchema, \"workers\": nworkers},\n chunksize = chunksize,\n maxchunks = maxchunks\n )\n\n ## Print out cutflow\n cutflow = accumulator.pop(\"cutflow\")\n efficiencies = print_cutflow(cutflow)\n\n ## Making output ROOT file\n if efficiencies[\"totalEfficiency\"] == 0.:\n print(\"\\nWARNING: 0 event passed pre-selections. Will not write an empty ROOT file.\")\n else:\n write_root_file(output_file, accumulator, efficiencies, debug)\n\n return\n\n\nif __name__ == \"__main__\":\n\n tstart = time.time()\n\n ## Parse arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-i\", \"--inputFiles\",\n help=\"Input ROOT files to skim. Format: Comma separated list of files \"\\\n +\"or txt file with list of file (1 file name per line)\",\n # Example for the format:\n # Ex1: file1.root,file2.root\n # Ex2: $ cat input.txt\n # file1.root\n # file2.root\n required=True\n )\n parser.add_argument(\n \"-o\", \"--output\",\n help=\"Output ROOT file\",\n required=True\n )\n parser.add_argument(\n \"-t\", \"--fileType\",\n help=\"Input file type, mandatory argument\",\n choices=[\"PFNanoAOD_102X\", \"PFNanoAOD_106X_v01\", \"PFNanoAOD_106X_v02\"],\n required=True\n )\n parser.add_argument(\n \"-p\", \"--processor\",\n help=\"Coffea processor to be used, as defined in processorPreSelection.py\",\n required=True\n )\n parser.add_argument(\n \"-c\", \"--chunksize\",\n help=\"Size of the data chunks (default=100000)\",\n default=100000, type=int\n )\n parser.add_argument(\n \"-m\", \"--maxchunks\",\n help=\"Maximum number of chunks to process, no flag means no maximum\",\n type=int\n )\n parser.add_argument(\n \"-n\", \"--nworkers\",\n help=\"Number of worker nodes (default=4)\",\n default=4, type=int\n )\n parser.add_argument(\n \"-debug\", \"--debug\",\n help=\"Debug mode\",\n action=\"store_true\",\n )\n \n \n args = parser.parse_args()\n\n ## Create output directory if it does not exist\n split = args.output.split(\"/\")\n if len(split) > 1:\n if len(split) == 2:\n outputDirectory = (args.output[0]==\"/\")*\"/\" + split[0]\n elif len(split) > 1:\n outputDirectory = (args.output[0]==\"/\")*\"/\" + os.path.join(*args.output.split(\"/\")[:-1])\n if not os.path.exists(outputDirectory):\n os.makedirs(outputDirectory)\n\n ## Get list of input ROOT files\n # If coma separated list of ROOT files (which ends with the .root of the last ROOT file)\n if args.inputFiles.endswith(\".root\"):\n inputFiles = args.inputFiles.split(\",\")\n # Else list of ROOT files in txt file\n else:\n with open (args.inputFiles, \"r\") as txtfile:\n inputFiles = txtfile.readlines()\n inputFiles = [ x.replace(\"\\n\", \"\") for x in inputFiles ]\n inputFiles = [ x for x in inputFiles if x.endswith(\".root\") ]\n\n ## Make pre-selection\n main(inputFiles, args.output, args.fileType, args.processor, args.chunksize, args.maxchunks, args.nworkers, args.debug)\n\n\n elapsed = time.time() - tstart\n print(\"\\nTotal elapsed time: %d s\" %elapsed)\n\n\n","sub_path":"preSelection/makePreSelection.py","file_name":"makePreSelection.py","file_ext":"py","file_size_in_byte":7196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"344699077","text":"import os\nimport json\n\n# Gestion des logs\nclass TrainLogging(object):\n\n def __init__(self, current_results_path, train_id):\n # set paths\n self._current_results_path = current_results_path\n self._train_id = train_id\n self._settings_file_name = 'settings.csv'\n self._epochs_file_name = 'epochs.csv'\n self._results_file_name = 'results.csv'\n # init setting file\n log_path = self.get_settings_path()\n if not os.path.exists(log_path):\n file_handler = open(log_path, \"w\")\n header = TrainLogging._get_settings_header()\n file_handler.write(header+\"\\n\")\n file_handler.close()\n # init log file\n log_path = self.get_epochs_path()\n if not os.path.exists(log_path):\n file_handler = open(log_path, \"w\")\n header = TrainLogging._get_epochs_header()\n file_handler.write(header+\"\\n\")\n file_handler.close()\n # init results file\n log_path = self.get_results_path()\n if not os.path.exists(log_path):\n file_handler = open(log_path, \"w\")\n header = TrainLogging._get_results_header()\n file_handler.write(header+\"\\n\")\n file_handler.close()\n \n @staticmethod\n def _get_settings_header():\n return \"train_id;classes_count;classes;validation_size;img_size;num_channels;learning_rate;num_iteration;batch_size;input_layer_dropout;flatten_layer_dropout;conv_layers_count;conv_layers_params;fc_layers_count;fc_layers_params;transformations_count;transformations;training_data;validation_data\"\n \n @staticmethod\n def _get_epochs_header():\n return \"training_epoch;training_accuracy;validation_accuracy;validation_loss\"\n \n @staticmethod\n def _get_results_header():\n return \"train_id;class_count;data_count;correct_predictions\"\n\n def get_epochs_path(self):\n return os.path.join(self._current_results_path, self._train_id, self._epochs_file_name)\n\n def get_settings_path(self):\n return os.path.join(self._current_results_path, self._settings_file_name)\n\n def get_results_path(self):\n return os.path.join(self._current_results_path, self._results_file_name)\n \n def log_settings(self, classes, settings, conv_layers_params, fc_layers_params, transformations, data):\n log_path = self.get_settings_path()\n file_handler = open(log_path, \"a\")\n line = \"{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{}\".format(\n self._train_id,\n len(classes),\n json.dumps(classes),\n settings['validation_size'],\n settings['img_size'],\n settings['num_channels'],\n settings['learning_rate'],\n settings['num_iteration'],\n settings['batch_size'],\n settings['input_layer_dropout'],\n settings['flatten_layer_dropout'],\n len(conv_layers_params),\n json.dumps(conv_layers_params),\n len(fc_layers_params),\n json.dumps(fc_layers_params),\n len(transformations),\n json.dumps(transformations),\n len(data.train.labels),\n len(data.valid.labels)\n )\n file_handler.write(line+\"\\n\")\n file_handler.close()\n \n def log_epoch(self, epoch, acc, val_acc, val_loss):\n log_path = self.get_epochs_path()\n file_handler = open(log_path, \"a\")\n line = \"{};{};{};{}\".format(\n epoch+1,\n acc,\n val_acc,\n val_loss,\n )\n file_handler.write(line+\"\\n\")\n file_handler.close()\n\n def log_results(self,classes, data_counts, results):\n log_path = self.get_results_path()\n \n file_handler = open(log_path, \"a\")\n \n for index, class_name in enumerate(classes) :\n line = \"{};{};{};{}\".format(\n self._train_id,\n class_name,\n data_counts[index],\n results[index]\n )\n file_handler.write(line+\"\\n\")\n \n file_handler.close()","sub_path":"train_logging.py","file_name":"train_logging.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"216592035","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('server', '0002_move_user'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='game',\n name='players',\n field=models.ManyToManyField(to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='move',\n name='date',\n field=models.DateTimeField(auto_now_add=True, null=True),\n ),\n ]\n","sub_path":"anranserver/server/migrations/0003_auto_20150808_2136.py","file_name":"0003_auto_20150808_2136.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"499929949","text":"from collections import Counter\nstr1= \"pale\"\nstr2 = \"pile\"\n\ndef compare(str1,str2):\n a = len(str1)\n b = len(str2)\n va1 = 0\n if a == b:\n for i in range(a):\n if str1[i]==str2[i]:\n continue\n if str1[i]!=str2[i]:\n val += 1\n if val == 1:\n return True\n if a > b:\n if a == b+1:\n print(\"yes\")\n return 0\n\n\nanswer = compare(list(str1),list(str2))","sub_path":"string/string_compare.py","file_name":"string_compare.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"225913564","text":"print('=-='*10)\nprint(' TRANSAÇÕES EFETUADAS')\nprint('=-='*10)\n\ntotal = 0\nqnt = int(input(\"Informe a quantidade de transações efetuadas hoje: \"))\n\nfor n in range (qnt):\n valor = float(input(\"Informe o valor da transação: \"))\n total = total + valor\n\nmedia = total / qnt\n\nprint(f\"O valor total gasto foi de R$ {round(total,2)} e a média de gasto foi de R$ {round(media,2)}.\")\n\n\n\n\n\n\n\n\n","sub_path":"FIAP/Fase2_cap3/RM86567_Ex02.py","file_name":"RM86567_Ex02.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"103384520","text":"import torch\nimport pytorch_lightning as pl\nimport pandas as pd\nimport numpy as np\nimport cv2\n\n# from scipy import ndimage\n# from albumentations import CLAHE\n\nfrom .augmentation import get_augmentation_v2\n\n\ndef yolo2voc(image_height, image_width, bboxes):\n \"\"\"\n yolo => [xmid, ymid, w, h] (normalized)\n voc => [x1, y1, x2, y1]\n\n \"\"\"\n bboxes = bboxes.copy().astype(\n float\n ) # otherwise all value will be 0 as voc_pascal dtype is np.int\n\n bboxes[..., [0, 2]] = bboxes[..., [0, 2]] * image_width\n bboxes[..., [1, 3]] = bboxes[..., [1, 3]] * image_height\n\n bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]] / 2\n bboxes[..., [2, 3]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]\n\n return bboxes\n\n\nclass CXRDataset(torch.utils.data.Dataset):\n def __init__(\n self, data_dir, df, size=1024, mode=\"train\", transform=None, smooth=None\n ):\n self.data_dir = data_dir\n self.df = df\n self.size = size\n self.mode = mode\n self.training = self.mode == \"train\"\n self.transform = transform\n self.smooth = smooth\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, index):\n img_id = self.df.loc[index, \"id\"].split(\"_image\")[0]\n img_path = f\"{self.data_dir}/train/{img_id}_image.png\"\n\n label = np.array(\n list(\n self.df.loc[\n index,\n [\n \"Negative for Pneumonia\",\n \"Typical Appearance\",\n \"Indeterminate Appearance\",\n \"Atypical Appearance\",\n ],\n ]\n )\n )\n if self.smooth:\n label = np.clip(label, self.smooth, 1 - self.smooth)\n\n label = label.astype(\"float32\")\n img = cv2.imread(img_path, -1).astype(\"float32\")\n img = np.concatenate((img[:, :, np.newaxis],) * 3, axis=-1)\n\n mask_txt = img_path.replace(\".png\", \".txt\")\n mask = np.zeros(img.shape[:2])\n h, w = img.shape[:2]\n\n try:\n with open(mask_txt, \"r\") as f:\n data = (\n np.array(f.read().replace(\"\\n\", \" \").strip().split(\" \"))\n .astype(np.float32)\n .reshape(-1, 5)\n )\n bdata = data[:, 1:]\n bboxes = yolo2voc(h, w, bdata)\n for bbox in bboxes:\n x1, y1, x2, y2 = [int(bi) for bi in bbox]\n mask[y1:y2, x1:x2] = 1.0 # TODO: Check dimension\n except ValueError: # No opacity - empty\n pass\n\n aug = self.transform(image=img, mask=mask)\n img = aug[\"image\"]\n mask = aug[\"mask\"]\n\n return img, label, mask, img_path\n\n\nclass CXRDataModule(pl.LightningDataModule):\n def __init__(self, cfg):\n super().__init__()\n self.cfg = cfg\n self.batch_size = self.cfg.batch_size # For auto_scale_batch_size\n self.setup()\n\n def setup(self, stage=None):\n\n train_study_level = pd.read_csv(self.cfg.data_dir + \"/train_study_level.csv\")\n train_image_level = pd.read_csv(self.cfg.data_dir + \"/train_image_level.csv\")\n\n more_than_2_ids = []\n for i in range(len(train_image_level)):\n row = train_image_level.iloc[i]\n sid = row[\"StudyInstanceUID\"]\n sid_df = train_image_level[train_image_level[\"StudyInstanceUID\"] == sid]\n if len(sid_df) >= 2:\n more_than_2_ids.append(sid)\n\n # Cleansing\n train_image_level = train_image_level[\n ~train_image_level[\"StudyInstanceUID\"].isin(more_than_2_ids)\n ]\n train_image_level.reset_index(inplace=True)\n\n train_study_level[\"StudyInstanceUID\"] = train_study_level[\"id\"].apply(\n lambda x: x.replace(\"_study\", \"\")\n )\n del train_study_level[\"id\"]\n df = train_image_level.merge(train_study_level, on=\"StudyInstanceUID\")\n\n # Apply fold\n df = df.sample(frac=1).reset_index(drop=True)\n\n df[\"fold\"] = df.index % 5\n\n df_train = df[(df[\"fold\"] != self.cfg.fold_index)].reset_index(drop=True)\n df_valid = df[(df[\"fold\"] == self.cfg.fold_index)].reset_index(drop=True)\n # df_test = df[(df[\"fold\"] == self.cfg.fold_index)].reset_index(drop=True)\n\n if self.cfg.augment_class:\n negative = df_train[df_train[\"Negative for Pneumonia\"] == 1]\n typical = df_train[df_train[\"Typical Appearance\"] == 1]\n indeterminate = df_train[df_train[\"Indeterminate Appearance\"] == 1]\n atypical = df_train[df_train[\"Atypical Appearance\"] == 1]\n\n df_aug_train = pd.concat(\n (\n negative,\n negative,\n typical,\n indeterminate,\n indeterminate,\n indeterminate,\n atypical,\n atypical,\n atypical,\n atypical,\n atypical,\n atypical,\n ),\n axis=0,\n ).reset_index(drop=True)\n df_train = df_aug_train\n\n print(\"Training :: \", len(df_train))\n print(\"Validation :: \", len(df_valid))\n\n train_aug, val_aug = get_augmentation_v2(self.cfg.image_size)\n\n self.train_dataset = CXRDataset(\n data_dir=self.cfg.data_dir,\n df=df_train,\n size=self.cfg.image_size,\n mode=\"train\",\n transform=train_aug,\n smooth=self.cfg.label_smoothing,\n )\n\n self.val_dataset = CXRDataset(\n data_dir=self.cfg.data_dir,\n df=df_valid,\n size=self.cfg.image_size,\n mode=\"val\",\n transform=val_aug,\n )\n\n # self.test_dataset = CXRDataset(\n # data_dir=self.cfg.data_dir,\n # df=df_test,\n # size=self.cfg.image_size,\n # mode=\"test\",\n # transform=va,\n # )\n\n def train_dataloader(self):\n train_dataloader = torch.utils.data.DataLoader(\n self.train_dataset,\n batch_size=self.batch_size,\n shuffle=False,\n num_workers=self.cfg.num_workers,\n pin_memory=True,\n )\n\n return train_dataloader\n\n # FIXME: shuffle=True: for various viz, doesn't matter at performance right?\n def val_dataloader(self):\n val_dataloader = torch.utils.data.DataLoader(\n self.val_dataset,\n batch_size=self.batch_size * 2,\n shuffle=True,\n num_workers=self.cfg.num_workers,\n pin_memory=True,\n )\n\n return val_dataloader\n\n def test_dataloader(self):\n test_dataloader = torch.utils.data.DataLoader(\n self.test_dataset,\n batch_size=self.batch_size,\n shuffle=False,\n num_workers=self.cfg.num_workers,\n pin_memory=False,\n )\n\n return test_dataloader\n","sub_path":"lightning/inputs/cxr_dm_aux.py","file_name":"cxr_dm_aux.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"641160697","text":"import unittest\nimport copy\nfrom unittest.mock import Mock\n\nfrom shisell import AnalyticsDispatcher, AnalyticsContext\nfrom shisell.extenders import create_scoped, with_context, with_extra, with_extras, with_filter, with_identity, with_identities, with_meta\n\nRETURN_VALUE = 'some_return_value'\nEVENT_NAME = 'some_event_name'\n\n\nclass ExtendersTestSuite(unittest.TestCase):\n def setUp(self):\n dispatch_mock = Mock(name='dispatch')\n dispatch_mock.return_value = RETURN_VALUE\n self.dispatch_mock = dispatch_mock\n\n self.dispatcher = AnalyticsDispatcher(dispatch_mock)\n self.original_context = copy.deepcopy(self.dispatcher.Context)\n\n def test_with_context(self):\n \"\"\"\n should call dispatch with passed context\n \"\"\"\n\n context = AnalyticsContext()\n context.ExtraData = {'extra_key': 'some other data'}\n context.MetaData = {'meta_key': 'some other data'}\n context.Scopes = ['other', 'scope']\n\n self.dispatcher.extend(with_context(context)).dispatch(EVENT_NAME)\n\n self.dispatch_mock.assert_called_once_with(EVENT_NAME, context)\n self.assertEqual(self.dispatcher.Context, self.original_context)\n\n def test_create_scoped(self):\n \"\"\"\n should call dispatch with passed scope\n \"\"\"\n\n scope = \"some_scope\"\n context = AnalyticsContext()\n context.Scopes.append(scope)\n\n self.dispatcher.extend(create_scoped(scope)).dispatch(EVENT_NAME)\n\n self.dispatch_mock.assert_called_once_with(EVENT_NAME, context)\n self.assertEqual(self.dispatcher.Context, self.original_context)\n\n def test_with_extra(self):\n \"\"\"\n should call dispatch with passed extra data\n \"\"\"\n\n key = 'some_key'\n value = 'some_value'\n context = AnalyticsContext()\n context.ExtraData[key] = value\n\n self.dispatcher.extend(with_extra(key, value)).dispatch(EVENT_NAME)\n\n self.dispatch_mock.assert_called_once_with(EVENT_NAME, context)\n self.assertEqual(self.dispatcher.Context, self.original_context)\n\n def test_with_extras(self):\n \"\"\"\n should call dispatch with all extras\n \"\"\"\n\n extras = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}\n context = AnalyticsContext()\n context.ExtraData = extras\n\n self.dispatcher.extend(with_extras(extras)).dispatch(EVENT_NAME)\n\n self.dispatch_mock.assert_called_once_with(EVENT_NAME, context)\n self.assertEqual(self.dispatcher.Context, self.original_context)\n\n def test_with_extras_doesnt_throw(self):\n \"\"\"\n should return same dispatcher if invalid input\n \"\"\"\n\n dispatcher = self.dispatcher.extend(with_extras(None))\n\n self.assertIs(dispatcher, self.dispatcher)\n\n def test_with_filter(self):\n \"\"\"\n should call dispatch with passed filter\n \"\"\"\n\n filter = 'some_filter'\n context = AnalyticsContext()\n context.Filters.append(filter)\n\n self.dispatcher.extend(with_filter(filter)).dispatch(EVENT_NAME)\n\n self.dispatch_mock.assert_called_once_with(EVENT_NAME, context)\n self.assertEqual(self.dispatcher.Context, self.original_context)\n\n def test_with_filters(self):\n \"\"\"\n should call dispatch with all filters\n \"\"\"\n\n filters = ['filter1', 'filter2']\n context = AnalyticsContext()\n context.Filters = filters\n\n self.dispatcher.extend(with_filter(*filters)).dispatch(EVENT_NAME)\n\n self.dispatch_mock.assert_called_once_with(EVENT_NAME, context)\n self.assertEqual(self.dispatcher.Context, self.original_context)\n\n def test_with_metadata(self):\n \"\"\"\n should call dispatch with passed meta data\n \"\"\"\n\n key = 'some_key'\n value = 'some_value'\n context = AnalyticsContext()\n context.MetaData[key] = value\n\n self.dispatcher.extend(with_meta(key, value)).dispatch(EVENT_NAME)\n\n self.dispatch_mock.assert_called_once_with(EVENT_NAME, context)\n self.assertEqual(self.dispatcher.Context, self.original_context)\n\n def test_with_identity(self):\n \"\"\"\n should call dispatch with passed identity\n \"\"\"\n\n key = 'some_key'\n value = 'some_value'\n context = AnalyticsContext()\n context.Identities[key] = value\n\n self.dispatcher.extend(with_identity(key, value)).dispatch(EVENT_NAME)\n\n self.dispatch_mock.assert_called_once_with(EVENT_NAME, context)\n self.assertEqual(self.dispatcher.Context, self.original_context)\n\n def test_with_identities(self):\n \"\"\"\n should call dispatch with all passed identities\n \"\"\"\n\n identities = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}\n context = AnalyticsContext()\n context.Identities = identities\n\n self.dispatcher.extend(with_identities(identities)).dispatch(EVENT_NAME)\n\n self.dispatch_mock.assert_called_once_with(EVENT_NAME, context)\n self.assertEqual(self.dispatcher.Context, self.original_context)\n\n def test_with_identities_doesnt_throw(self):\n \"\"\"\n should return same dispatcher if invalid input\n \"\"\"\n\n dispatcher = self.dispatcher.extend(with_identities(None))\n\n self.assertIs(dispatcher, self.dispatcher)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_extenders.py","file_name":"test_extenders.py","file_ext":"py","file_size_in_byte":5394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"196574049","text":"x=input()\nm=int(input())\nd=ans=0\nr=int(1e20)\nfor i in x:\n\td=max(d,ord(i)-ord('0'))\nl=d+1\nwhile l<=r:\n\tmid=(l+r)//2\n\tcurr=0\n\tfor i in x:\n\t\tcurr*=mid\n\t\tcurr+=ord(i)-ord('0')\n\tif curr<=m:\n\t\tans=max(ans,mid)\n\t\tl=mid+1\n\telse:\n\t\tr=mid-1\nprint(ans-d)","sub_path":"atcoder/abc192/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"33805996","text":"# import required libraries\nimport os\nimport telebot\nimport datetime\nimport requests\nimport urllib.request\nimport subprocess\nimport config\n\n# setup bot with Telegram token from config\nbot = telebot.TeleBot(config.TELEGRAM_TOKEN)\n\nbot_text = '''\nBip-bop human,\nI classify images using neural networks 🚀\nSend me pictures, and I will classify them for you 🤟\n'''\n\n# store files in /tmp so storage does not get complete \nresult_storage_path = 'tmp'\n\n# Handles all text messages that contains the command '/start' \n@bot.message_handler(commands=['start'])\ndef send_welcome(message):\n bot.send_message(message.chat.id, bot_text)\n\n# Handles all photo messages\n@bot.message_handler(content_types=['photo'])\ndef handle(message):\n log_request(message)\n image_name = save_image_from_message(message)\n \n # object recognition\n object_recognition_image(image_name)\n bot.send_photo(message.chat.id, open('data/darknet/predictions.jpg','rb'), 'Identified objects, if any! 👻')\n \n # image classification\n classification_list_result = classify_image(image_name)\n \n # send classification results\n output = 'The image classifies as:\\n'\n for result in classification_list_result:\n output += result\n output += '\\n🚀 Gimme more pics! 🚀'\n \n bot.reply_to(message, output)\n cleanup_remove_image(image_name); \n \n# ----------- Helper functions ---------------\ndef log_request(message):\n file = open('data/logs.txt', 'a') #append to file\n file.write(\"{0} - {1} {2} [{3}]\\n\".format(datetime.datetime.now(), message.from_user.first_name, message.from_user.last_name, message.from_user.id)) \n print(\"{0} - {1} {2} [{3}]\".format(datetime.datetime.now(), message.from_user.first_name, message.from_user.last_name, message.from_user.id))\n file.close() \n \ndef get_image_id_from_message(message):\n # there are multiple array of images, check the biggest\n return message.photo[len(message.photo)-1].file_id\n\ndef save_image_from_message(message):\n cid = message.chat.id \n image_id = get_image_id_from_message(message)\n bot.send_message(cid, '🔥 Analyzing image, be patient ! 🔥')\n \n # prepare image for downlading\n file_path = bot.get_file(image_id).file_path\n\n # generate image download url\n image_url = \"https://api.telegram.org/file/bot{0}/{1}\".format(config.TELEGRAM_TOKEN, file_path)\n print(image_url)\n \n # create folder to store pic temporary, if it doesnt exist\n if not os.path.exists(result_storage_path):\n os.makedirs(result_storage_path)\n \n # retrieve and save image\n image_name = \"{0}.jpg\".format(image_id)\n urllib.request.urlretrieve(image_url, \"{0}/{1}\".format(result_storage_path,image_name))\n \n return image_name;\n\ndef classify_image(image_name):\n # classify image -> https://pjreddie.com/darknet/imagenet/\n os.system('cd data/darknet && ./darknet classifier predict cfg/imagenet1k.data cfg/darknet19.cfg darknet19.weights ../../{0}/{1} > ../../{0}/results.txt'.format(result_storage_path, image_name)) \n \n # retrieve classification results\n results_file = open(\"{0}/results.txt\".format(result_storage_path),\"r\") \n results = results_file.readlines()\n results_file.close() \n return results\n \ndef object_recognition_image(image_name):\n # object recognition -> https://pjreddie.com/darknet/yolo/\n os.system('cd data/darknet && ./darknet detect cfg/yolov3-tiny.cfg yolov3-tiny.weights ../../{0}/{1}'.format(result_storage_path, image_name)) \n \ndef cleanup_remove_image(image_name):\n os.remove('{0}/{1}'.format(result_storage_path, image_name))\n\nif __name__ == '__main__':\n # run bot in loop\n bot.polling(none_stop=True)\n","sub_path":"imageClassificationBot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"8958764","text":"import gmpy2\nfrom Crypto.Cipher import AES\nfrom Crypto.Util.number import long_to_bytes\n\nc = list(map(int, open('enc.txt').read().split()))\n\nq = int(gmpy2.gcd(c[0]-c[1] + 1, c[1] - c[2] + 1))\nfor i in range(1,len(c) - 1):\n q = int(gmpy2.gcd(q,c[i] - c[i+1] + 1))\n\nassert gmpy2.is_prime(q)\nprint(\"p: found!\")\n\nrand = c[0] % q - 1\nprint(\"rand: found!\")\n\np = (q - 1) // 2\np2 = int(gmpy2.iroot(p, 2)[0])\np1 = p // p2\n\nwhile p2 - p1 < 10 ** 9:\n if p == p1 * p2 and gmpy2.is_prime(p1) and gmpy2.is_prime(p2):\n break\n p2 += 1\n p1 = p // p2\n\nassert p == p1 * p2 and gmpy2.is_prime(p1) and gmpy2.is_prime(p2)\nprint(\"p1, p2: found!\")\n\nd = []\n\nfor i, c_i in enumerate(c):\n d.append((c_i - rand - i - 1) // (rand + i) // q)\n\nres = \"\"\nfor i in d:\n if pow(i, 2 * p2, q) == 1 :\n res += '0'\n elif pow(i, 2 * p1, q) == 1:\n res += '1'\n else:\n print('err')\n break\n\nres = int(res,2)\n\nprint('flag_enc: found!')\n\nc = long_to_bytes(res)\nkey = long_to_bytes(rand)\naes = AES.new(key[:16], AES.MODE_CBC, key[16:32])\nprint(aes.decrypt(c).decode('utf-8'))\n","sub_path":"sharif-ctf-2016/crypto/unterscheide-200/my_solve.py","file_name":"my_solve.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"}
+{"seq_id":"43097633","text":"# Copyright (c) 2021, IAC Electricals and contributors\n# For license information, please see license.txt\n\nimport frappe\nfrom frappe import _\nfrom frappe.model.document import Document\nfrom frappe.model.mapper import get_mapped_doc\n\nclass PriceSchedule(Document):\n\tdef validate(self):\n\t\tfor i in self.items:\n\t\t\tif i.freight_charges_type == \"Percent\" or i.freight_charges_type == \"Amount\":\n\t\t\t\tif i.freight_charges == 0 or i.freight_charges == None:\n\t\t\t\t\tfrappe.throw(\"Please Enter First Freight Charges for row \"+ str(i.idx)+\" in Item Table\")\n\n\t\t\t# if i.freight_charges != 0 or i.freight_charges != None:\n\t\t\t# \tprint(\"########################\")\n\t\t\t# \tif not i.freight_charges_type:\n\t\t\t# \t\tfrappe.throw(\"Please Enter First Freight Charges type.........................for row \"+ str(i.idx))\t\n\n\t\t\tif i.freight_charges_type_ == \"Percent\" or i.freight_charges_type_ == \"Amount\":\n\t\t\t\tif i.freight_charges_ == 0 or i.freight_charges_ == None:\n\t\t\t\t\tfrappe.throw(\"Please Enter Secound Freight Charges for row \"+ str(i.idx)+\" in Item Table\")\n\n\t\t\t# if i.freight_charges_ != 0 or i.freight_charges_ != None:\n\t\t\t# \tif not i.freight_charges_type_:\n\t\t\t# \t\tfrappe.throw(\"Please Enter Secound Freight Charges type.........................for row \"+ str(i.idx))\t\t\t\n\n\n@frappe.whitelist()\ndef address_query(name):\n\tif name:\n\t\taddress_lists = frappe.db.get_all(\"Address\",{'name':name},[\"name\",\"address_line1\",\"address_line2\",\"city\",\"state\",\"country\",\"pincode\"])\n\t\tif address_lists:\n\t\t\treturn address_lists\n\n@frappe.whitelist()\ndef contact_query(name):\n\tif name:\n\t\tcontact_info = {\n\t\t\t'mobile_no' :'',\n\t\t\t'email' :'',\n\t\t\t'first_name':'',\n\t\t\t'middle_name':'',\n\t\t\t'last_name':'' \n\t\t}\n\t\tcontact_doc = frappe.get_doc(\"Contact\",name)\n\t\tif contact_doc:\t\t\n\t\t\tcontact_info['first_name'] = contact_doc.get('first_name')\n\t\t\tcontact_info['middle_name'] = contact_doc.get('middle_name')\n\t\t\tcontact_info['last_name'] = contact_doc.get('last_name')\n\t\t\tfor phone in contact_doc.phone_nos:\n\t\t\t\tif phone.get('is_primary_mobile_no'):\n\t\t\t\t\tcontact_info['mobile_no'] = phone.get('phone')\n\t\t\tfor email in contact_doc.email_ids:\n\t\t\t\tif email.get('is_primary'):\n\t\t\t\t\tcontact_info['email'] = email.get('email_id')\t\t\n\t\t\treturn contact_info\t\t\n\n\n@frappe.whitelist()\ndef fetch_address_contact_name(name):\n\tif name:\n\t\taddress_contact_name = {\n\t\t\t'address_name' :'',\n\t\t\t'contact_name' :'' \n\t\t}\n\t\tadd_name = frappe.get_all('Dynamic Link', filters={'link_doctype': 'Customer', 'link_name': name, 'parenttype': 'Address'}, fields=['parent'])\n\t\tcon_name = frappe.get_all('Dynamic Link', filters={'link_doctype': 'Customer', 'link_name': name, 'parenttype': 'Contact'}, fields=['parent'])\n\t\tif add_name:\n\t\t\taddress_contact_name['address_name'] = add_name[0].get('parent')\n\t\tif con_name:\n\t\t\taddress_contact_name['contact_name'] = con_name[0].get('parent')\n\t\treturn address_contact_name\n\n\n@frappe.whitelist()\ndef number_to_word(amount):\n\tdef get_word(n):\n\t\twords={ 0:\"\", 1:\"One\", 2:\"Two\", 3:\"Three\", 4:\"Four\", 5:\"Five\", 6:\"Six\", 7:\"Seven\", 8:\"Eight\", 9:\"Nine\", 10:\"Ten\", 11:\"Eleven\", 12:\"Twelve\", 13:\"Thirteen\", 14:\"Fourteen\", 15:\"Fifteen\", 16:\"Sixteen\", 17:\"Seventeen\", 18:\"Eighteen\", 19:\"Nineteen\", 20:\"Twenty\", 30:\"Thirty\", 40:\"Forty\", 50:\"Fifty\", 60:\"Sixty\", 70:\"Seventy\", 80:\"Eighty\", 90:\"Ninty\" }\n\t\tif n<=20:\n\t\t\treturn words[n]\n\t\telse:\n\t\t\tones=n%10\n\t\t\ttens=n-ones\n\t\t\treturn words[tens]+\" \"+words[ones]\n\n\tdef get_all_word(n):\n\t\td=[100,10,100,100]\n\t\tv=[\"\",\"Hundred And\",\"Thousand\",\"lakh\"]\n\t\tw=[]\n\t\tfor i,x in zip(d,v):\n\t\t\tt=get_word(n%i)\n\t\t\tif t!=\"\":\n\t\t\t\tt+=\" \"+x\n\t\t\tw.append(t.rstrip(\" \"))\n\t\t\tn=n//i\n\t\tw.reverse()\n\t\tw=' '.join(w).strip()\n\t\tif w.endswith(\"And\"):\n\t\t\tw=w[:-3]\n\t\treturn w\n\n\tarr=str(amount).split(\".\")\n\tamount=int(arr[0])\n\tcrore=amount//10000000\n\tamount=amount%10000000\n\tword=\"\"\n\tif crore>0:\n\t\tword+=get_all_word(crore)\n\t\tword+=\" crore \"\n\tword+=get_all_word(amount).strip()+\" only.\"\n\tif len(arr)>1:\n\t\tif len(arr[1])==1:\n\t\t\tarr[1]+=\"0\"\n\t\tword+=\" and \"+get_all_word(int(arr[1]))+\" paisa\"\n\t\n\treturn word\n\n\n@frappe.whitelist()\ndef calculate_taxes(tax_temlet_name,total_amount,unit_price_1_total_amount):\n\ttry:\n\t\ttax_items = []\n\t\ttx_calculation = 0.0\n\t\ttotal_tax_amount =0.0\n\t\ttax_details = frappe.get_doc(\"Sales Taxes and Charges Template\", tax_temlet_name).taxes\n\t\tfor taxes in tax_details:\n\t\t\ttx_calculation = float(total_amount)/100*taxes.rate\n\t\t\tif taxes.idx == 1:\n\t\t\t\ttotal_tax_amount =float(total_amount) + tx_calculation\n\t\t\telse:\n\t\t\t\ttotal_tax_amount = total_tax_amount + tx_calculation\n\n\n\t\t\tunit_price_1_tx_calculation = float(unit_price_1_total_amount)/100*taxes.rate\n\t\t\tif taxes.idx == 1:\n\t\t\t\tunit_price_1_total_tax_amount =float(unit_price_1_total_amount) + unit_price_1_tx_calculation\n\t\t\telse:\n\t\t\t\tunit_price_1_total_tax_amount = unit_price_1_total_tax_amount + unit_price_1_tx_calculation\t\n\n\t\t\ttemp = {\n\t\t\t\t'charge_type' : taxes.charge_type,\n\t\t\t\t'account_head' : taxes.account_head,\n\t\t\t\t'description' : taxes.description,\n\t\t\t\t'rate' : taxes.rate,\n\t\t\t\t'unit_price_2_tax_amount' : tx_calculation,\n\t\t\t\t'unit_price_2_total':total_tax_amount,\n\t\t\t\t'unit_price_1_tax_amount' : unit_price_1_tx_calculation,\n\t\t\t\t'unit_price_1_total':unit_price_1_total_tax_amount\n\t\t\t}\n\t\t\ttax_items.append(temp)\n\t\treturn tax_items\n\texcept Exception as e:\n\t\traise e\n\n\n@frappe.whitelist()\ndef make_blanket_order(source_name, target_doc=None, ignore_permissions=False):\n\tfrappe.log_error(frappe.get_traceback(), _(\"Blanket order Button clicked....(Error_log)\"))\n\tdoclist = get_mapped_doc(\"Price Schedule\", source_name, {\n\t\t\"Price Schedule\": {\n\t\t\t\"doctype\": \"Blanket Order\",\n\t\t\t\"field_map\": {\n\t\t\t\t\t\"name\": \"Price Schedule\",\n\t\t\t\t\t\"name\":\"price_schedule_no\",\n\t\t\t\t\t\"terms\":\"tc_name\",\n\t\t\t\t\t\"term_details\":\"terms\"\n\t\t\t\t},\n\t\t\t\"validation\": {\n\t\t\t\t\t\"docstatus\": [\"=\", 1]\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"Price Schedule Items\": {\n\t\t\t\t\"doctype\": \"Blanket Order Item\",\n\t\t\t\t\"field_map\": {\n\t\t\t\t\t\"total_quantity\": \"qty\"\n\t\t\t\t},\n\t\t\t},\n\t\t}, target_doc)\n\n\treturn doclist\n\n\n@frappe.whitelist()\ndef make_sales_order(source_name, target_doc=None, ignore_permissions=False):\n\tdef set_missing_values(source, target):\n\t\ttarget.against_price_schedule = 1\n\tdef update_item(source_doc, target_doc, source_parent):\n\t\ttarget_doc.against_price_schedule = 1\n\t\ttarget_doc.price_schedule = source_name\n\n\tdoclist = get_mapped_doc(\"Price Schedule\", source_name, {\n\t\t\"Price Schedule\": {\n\t\t\t\"doctype\": \"Sales Order\",\n\t\t\t\"field_map\": {\n\t\t\t\t\t\"name\":\"price_schedule_no\",\n\t\t\t\t\t\"sales_taxes_and_charges_template\":\"taxes_and_charges\",\n\t\t\t\t\t\"contact_person_mobile_no\":\"contact_mobile\",\n\t\t\t\t\t\"terms\":\"tc_name\",\n\t\t\t\t\t\"term_details\":\"terms\"\n\t\t\t\t},\n\t\t\t\"validation\": {\n\t\t\t\t\t\"docstatus\": [\"=\", 1]\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"Price Schedule Items\": {\n\t\t\t\t\"doctype\": \"Sales Order Item\",\n\t\t\t\t\"field_map\": {\n\t\t\t\t\t\"total_quantity\": \"qty\"\n\t\t\t\t},\n\t\t\t\t\"postprocess\": update_item\n\t\t\t},\n\t\t\t\"Sales Taxes and Charges Table\": {\n\t\t\t\t\"doctype\": \"Sales Taxes and Charges\"\n\t\t\t},\n\t\t}, target_doc, set_missing_values)\n\n\treturn doclist\t\n\n\n","sub_path":"iac_electricals/iac_electricals/doctype/price_schedule/price_schedule.py","file_name":"price_schedule.py","file_ext":"py","file_size_in_byte":6875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"}
+{"seq_id":"287122655","text":"import sys\nimport tensorflow as tf\nimport coloredlogs, logging\nimport os, ipdb\nimport glob\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport re\n\n\ncoloredlogs.install()\nanomaly_classification_feature_selection_folder='/home/user/baxter_ws/src/SPAI/smach_based_introspection_framework/introspection_data_folder.AC_offline_test/anomaly_classification_feature_selection_folder'\n\n\ndef get_anomalous_samples():\n logger = logging.getLogger()\n logger.info(\"load_csv_data_from_filtered_scheme\")\n \n folders = glob.glob(os.path.join(\n anomaly_classification_feature_selection_folder,\n 'No.* filtering scheme',\n 'anomalies_grouped_by_type',\n 'anomaly_type_(*)',\n )) \n\n data_by_type = []\n types = []\n for folder in folders: # for each anomaly_type\n samples = []\n logger.info(folder)\n path_postfix = os.path.relpath(folder, anomaly_classification_feature_selection_folder).replace(\"anomalies_grouped_by_type\"+os.sep, \"\")\n\n prog = re.compile(r'anomaly_type_\\(?([^\\(\\)]+)\\)?')\n anomaly_type = prog.search(path_postfix).group(1)\n csvs = glob.glob(os.path.join(folder, '*', '*.csv'))\n for j in csvs:\n df = pd.read_csv(j, sep = ',')\n # delete the 1st column with is time index\n df = df.drop(['Unnamed: 0'], axis = 1)\n samples.append(df.values.T)\n data = np.stack(samples)\n logger.info('Successfully! load the data of %s'%anomaly_type)\n # np.save(\"./anomalies/\"+anomaly_type+\".npy\", data)\n \n data_by_type.append(data)\n types.append(anomaly_type)\n return data_by_type, types\n\ndef feed_dict(batch_size, samples_type=None):\n if samples_type == 'train':\n indeces = np.random.randint(num_train_samples, size=batch_size)\n samples = train_samples\n \n elif samples_type == 'valid':\n indeces = np.random.randint(num_valid_samples, size=batch_size)\n samples = valid_samples\n \n elif samples_type == 'test':\n indeces = np.random.randint(num_test_samples, size=batch_size)\n samples = test_samples\n \n return np.take(samples, indeces, axis=0)\n\n\nif __name__ == '__main__':\n\n x_in_dim = 6\n beta_1 = 0.05 # adam parameters\n beta_2 = 0.001 # adam parameters\n num_epochs = 3 # i.e. iterations 40000\n batch_size = 1\n num_hidden_units = 500\n learning_rate_1 = 2e-5\n learning_rate_2 = 1e-5\n num_epochs_to_diff_learn_rate = int(num_epochs/2) # change the learning rate after half of the epochs\n num_epochs_to_save_model = 1000 # save model after each 1000 iterations\n #decay_rate = .7\n\n z_dim = 20\n \n data_by_type, types = get_anomalous_samples()\n\n for i, samples in enumerate(data_by_type):\n anomaly_type = types[i]\n time_steps = samples.shape[1]\n train_samples = samples\n valid_samples = samples\n test_samples = samples\n num_train_samples = train_samples.shape[0] \n num_valid_samples = valid_samples.shape[0] \n num_test_samples = test_samples.shape[0] \n\n network_params = ''.join([\n 'time_steps={}-'.format(time_steps), \n 'latent_dim={}-'.format(z_dim), \n 'dataset={}'.format(anomaly_type)])\n\n # Dir structure : /base_dir/network_params/run_xx/train_or_test/\n log_root = './anomalies_%s'%anomaly_type\n log_base_dir = os.path.join(log_root, network_params)\n \n # Check for previous runs\n if not os.path.isdir(log_base_dir):\n os.makedirs(log_base_dir)\n\n previous_runs = os.listdir(log_base_dir)\n\n if len(previous_runs) == 0:\n run_number = 1\n else:\n run_number = max([int(str.split(s,'run_')[1]) for s in previous_runs if 'run' in s]) + 1\n\n log_dir = os.path.join(log_base_dir,'run_{0:02d}'.format(run_number))\n\n train_summary_writer = tf.summary.FileWriter(log_dir + '/train')\n valid_summary_writer = tf.summary.FileWriter(log_dir + '/valid')\n test_summary_writer = tf.summary.FileWriter(log_dir + '/test')\n model_save_path = log_dir + '/models'\n figure_save_path = log_dir + '/figures'\n\n #############################\n # Setup graph\n #############################\n tf.reset_default_graph()\n X = tf.placeholder(tf.float32, shape=(batch_size, x_in_dim, time_steps))\n\n # time_slices containts input x at time t across batches.\n x_in = time_steps * [None]\n x_out = time_steps * [None]\n h_enc = time_steps * [None]\n h_dec = (time_steps + 1) * [None]\n\n for t in range(time_steps):\n x_in[t] = tf.squeeze(tf.slice(X,begin=[0,0,t],size=[-1,-1,1]),axis=2)\n\n\n ###### Encoder network ###########\n with tf.variable_scope('encoder_rnn'):\n cell_enc = tf.nn.rnn_cell.BasicRNNCell(num_hidden_units,activation=tf.nn.tanh)\n h_enc[0] = tf.zeros([batch_size,num_hidden_units], dtype=tf.float32) # Initial state is 0\n\n # h_t+1 = tanh(Wenc*h_t + Win*x_t+1 + b )\n #Most basic RNN: output = new_state = act(W * input + U * state + B).\n #https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/python/ops/rnn_cell_impl.py\n for t in range(time_steps-1):\n _ , h_enc[t+1] = cell_enc(inputs=x_in[t+1], state=h_enc[t])\n\n\n mu_enc = tf.layers.dense(h_enc[-1], z_dim, activation=None, name='mu_enc')\n log_sigma_enc = tf.layers.dense(h_enc[-1], z_dim, activation=None, name='log_sigma_enc')\n\n ###### Reparametrize ##############\n eps = tf.random_normal(tf.shape(log_sigma_enc))\n z = mu_enc + tf.exp(log_sigma_enc) * eps\n\n ##### Decoder network ############\n with tf.variable_scope('decoder_rnn'):\n W_out = tf.get_variable('W_out',shape=[num_hidden_units, x_in_dim])\n b_out = tf.get_variable('b_out',shape=[x_in_dim])\n\n cell_dec = tf.nn.rnn_cell.BasicRNNCell(num_hidden_units,activation=tf.nn.tanh)\n h_dec[0] = tf.layers.dense(z, num_hidden_units, activation=tf.nn.tanh)\n\n for t in range(time_steps):\n x_out[t] = tf.nn.sigmoid(tf.matmul(h_dec[t], W_out) + b_out)\n if t < time_steps - 1:\n _, h_dec[t+1] = cell_dec(inputs=x_out[t], state=h_dec[t])\n\n ##### Loss #####################\n with tf.variable_scope('loss'):\n # Latent loss: -KL[q(z|x)|p(z)]\n with tf.variable_scope('latent_loss'):\n sigma_sq_enc = tf.square(tf.exp(log_sigma_enc))\n latent_loss = -.5 * tf.reduce_mean(tf.reduce_sum((1 + tf.log(1e-10 + sigma_sq_enc)) - tf.square(mu_enc) - sigma_sq_enc, axis=1),axis=0)\n latent_loss_summ = tf.summary.scalar('latent_loss',latent_loss)\n\n # Reconstruction Loss: log(p(x|z)) \n with tf.variable_scope('recon_loss'): \n for i in range(time_steps):\n if i == 0:\n recon_loss_ = x_in[i] * tf.log(1e-10 + x_out[i]) + (1 - x_in[i]) * tf.log(1e-10+1-x_out[i])\n else:\n recon_loss_ += x_in[i] * tf.log(1e-10 + x_out[i]) + (1 - x_in[i]) * tf.log(1e-10+1-x_out[i])\n\n #collapse the loss, mean across a sample across all x_dim and time points, mean over batches\n recon_loss = -tf.reduce_mean(tf.reduce_mean(recon_loss_/(time_steps),axis=1),axis=0)\n\n\n recon_loss_summ = tf.summary.scalar('recon_loss', recon_loss)\n\n with tf.variable_scope('total_loss'):\n total_loss = latent_loss + recon_loss\n\n total_loss_summ = tf.summary.scalar('total_loss', total_loss)\n\n global_step = tf.Variable(0,name='global_step') \n\n #learning_rate = tf.train.exponential_decay(initial_learning_rate, epoch_num, num_epochs, decay_rate, staircase=False)\n learning_rate = tf.Variable(learning_rate_1,name='learning_rate')\n train_step = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta_1, beta2=beta_2).minimize(total_loss,global_step=global_step) \n scalar_summaries = tf.summary.merge([latent_loss_summ, recon_loss_summ, total_loss_summ])\n #image_summaries = tf.summary.merge()\n\n train_summary_writer.add_graph(tf.get_default_graph())\n\n\n #############################\n # Training/Logging\n #############################\n num_batches = int(num_train_samples/batch_size)\n global_step_op = tf.train.get_global_step()\n saver = tf.train.Saver()\n\n avg_loss_epoch = []\n avg_latent_loss_epoch = []\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for epoch in range(num_epochs):\n epoch_loss = 0.\n epoch_latent_loss = 0.\n for batch in range(num_batches):\n batch_num = sess.run(global_step_op)\n\n if epoch < num_epochs_to_diff_learn_rate:\n curr_learning_rate = learning_rate_1\n else:\n curr_learning_rate = learning_rate_2\n\n #_ , loss, scalar_train_summaries, x_out_, x_in_,learning_rate_,latent_loss_ = \\\n #sess.run([train_step, total_loss, scalar_summaries, x_out, x_in,learning_rate, latent_loss],feed_dict={X: feed_dict(batch_size,'train'), learning_rate: curr_learning_rate})\n\n _ , loss, scalar_train_summaries, learning_rate_, latent_loss_ = \\\n sess.run([train_step, total_loss, scalar_summaries, learning_rate, latent_loss],feed_dict={X: feed_dict(batch_size,'train'), learning_rate: curr_learning_rate})\n\n # Check for NaN\n if np.isnan(loss):\n sys.exit(\"Loss during training at epoch: {}\".format(epoch))\n\n epoch_loss += loss\n epoch_latent_loss += latent_loss_\n\n print('Average loss epoch {0}: {1}'.format(epoch, epoch_loss/num_batches)) \n print('Average latent loss epoch {0}: {1}'.format(epoch, epoch_latent_loss/num_batches)) \n print('Learning Rate {}'.format(learning_rate_))\n print('')\n avg_loss_epoch.append(epoch_loss/num_batches)\n avg_latent_loss_epoch.append(epoch_latent_loss/num_batches)\n\n # Write train summaries once a epoch\n scalar_train_summaries = sess.run(scalar_summaries,feed_dict={X: feed_dict(batch_size,'train')})\n train_summary_writer.add_summary(scalar_train_summaries, global_step=batch_num)\n\n # Write validation summaries\n scalar_valid_summaries = sess.run(scalar_summaries,feed_dict={X: feed_dict(batch_size,'valid')})\n valid_summary_writer.add_summary(scalar_valid_summaries, global_step=batch_num)\n\n # Write test summaries\n scalar_test_summaries = sess.run(scalar_summaries,feed_dict={X: feed_dict(batch_size,'test')})\n test_summary_writer.add_summary(scalar_test_summaries, global_step=batch_num)\n\n # Save the models\n if epoch % num_epochs_to_save_model == 0:\n save_path = saver.save(sess, model_save_path + '/epoch_{}.ckpt'.format(epoch))\n\n # plotting\n fig, ax = plt.subplots()\n ax.plot(avg_loss_epoch, label='avg_loss_epoch')\n ax.plot(avg_latent_loss_epoch, label='avg_latent_loss_epoch')\n plt.legend()\n\n if not os.path.isdir(figure_save_path):\n os.makedirs(figure_save_path)\n plt.savefig(figure_save_path +'/loss.eps', format='eps', dpi=300)\n plt.show()\n","sub_path":"processing_anomalies_with_vrae.py","file_name":"processing_anomalies_with_vrae.py","file_ext":"py","file_size_in_byte":11855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"}
+{"seq_id":"416598516","text":"\n\nfrom xai.brain.wordbase.nouns._beagle import _BEAGLE\n\n#calss header\nclass _BEAGLES(_BEAGLE, ):\n\tdef __init__(self,): \n\t\t_BEAGLE.__init__(self)\n\t\tself.name = \"BEAGLES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"beagle\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_beagles.py","file_name":"_beagles.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"}
+{"seq_id":"564673352","text":"#!/usr/bin/python\n\nimport argparse\nimport time\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"targetTerm\", help=\"The number of terms to print\", type=int)\nparser.add_argument(\"-a\", \"--printAll\", help=\"Print all of the terms\", type=bool)\nargs = parser.parse_args()\n\ncurrentTerm = 0\na = 0\nb = 1\n\nstrings = []\nstart = time.time()\nwhile(currentTerm < args.targetTerm):\n strings.append(\"Term %s = %s\" % (currentTerm + 1, a))\n new = a + b\n a = b\n b = new\n \n currentTerm = currentTerm + 1\n \nif(args.printAll):\n print(\"\\n\".join(strings), \"\\nCalculated in : \", time.time() - start)\n print(\"Printed in : \", time.time() - start)\nelse:\n print(\"Term \", args.targetTerm, \" = \", b - a, \"\\nCalculated in : \", time.time() - start)\n","sub_path":"printterms.py","file_name":"printterms.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"}
+{"seq_id":"94063071","text":"from typing import Optional, Union, Sequence, Any\n\nimport torch\nfrom torch.nn import Module\n\nfrom tqdm import tqdm\n\nfrom torch_kalman.design import Design\nfrom torch_kalman.process import Process\nfrom torch_kalman.state_belief import Gaussian, StateBelief\nfrom torch_kalman.state_belief.over_time import StateBeliefOverTime\nfrom torch_kalman.internals.utils import identity\n\n\nclass KalmanFilter(Module):\n \"\"\"\n TODO\n \"\"\"\n family = Gaussian\n design_cls = Design\n\n def __init__(self, measures: Sequence[str], processes: Sequence[Process], **kwargs):\n\n super().__init__()\n self.design = self.design_cls(measures=measures, processes=processes, **kwargs)\n\n # parameters from design:\n self.design_parameters = self.design.param_dict()\n\n def predict_initial_state(self, design_for_batch: Design) -> 'Gaussian':\n return self.family(\n means=design_for_batch.initial_mean,\n covs=design_for_batch.initial_covariance,\n # we consider this a one-step-ahead prediction, so last measured one step ago:\n last_measured=torch.ones(design_for_batch.num_groups, dtype=torch.int)\n )\n\n def forward(self,\n input: Any,\n initial_prediction: Optional[StateBelief] = None,\n forecast_horizon: int = 0,\n progress: Union[tqdm, bool] = False,\n **kwargs) -> StateBeliefOverTime:\n \"\"\"\n :param input: The multivariate time-series to be fit by the kalman-filter. The exact structure depends on the\n kalman-filter `family`; for most, it is a tensor where the first dimension represents the groups, the second\n dimension represents the time-points, and the third dimension represents the measures.\n :param initial_prediction: If a StateBelief, this is used as the prediction for time=0; if None then each\n process generates initial values.\n :param forecast_horizon: Number of timesteps past the end of the input to continue making predictions\n :param progress: Should progress-bar be generated?\n :param kwargs: Other kwargs that will be passed to the `design_for_batch` method.\n :return: A StateBeliefOverTime consisting of one-step-ahead predictions.\n \"\"\"\n\n num_groups, num_timesteps, num_measures, *_ = self.family.get_input_dim(input)\n if num_measures != len(self.design.measures):\n raise ValueError(\n f\"This KalmanFilter has {len(self.design.measures)} measures; but the input shape is \"\n f\"{(num_groups, num_timesteps, num_measures)} (3rd dim should == measure-size).\"\n )\n\n assert forecast_horizon >= 0\n num_timesteps += forecast_horizon\n\n design_for_batch = self.design.for_batch(num_groups=num_groups, num_timesteps=num_timesteps, **kwargs)\n\n # initial state of the system:\n if initial_prediction is None:\n state_prediction = self.predict_initial_state(design_for_batch)\n else:\n state_prediction = initial_prediction.copy()\n\n progress = progress or identity\n if progress is True:\n progress = tqdm\n times = progress(range(num_timesteps))\n\n # generate one-step-ahead predictions:\n state_predictions = []\n for t in times:\n if t > 0:\n # take state-pred of previous t (now t-1), correct it according to what was actually measured at t-1\n state_belief = state_prediction.update_from_input(input, time=t - 1)\n\n # predict the state for t, from information from t-1\n # F at t-1 is transition *from* t-1 *to* t\n F = design_for_batch.F(t - 1)\n Q = design_for_batch.Q(t - 1)\n state_prediction = state_belief.predict(F=F, Q=Q)\n\n # compute how state-prediction at t translates into measurement-prediction at t\n H = design_for_batch.H(t)\n R = design_for_batch.R(t)\n state_prediction.compute_measurement(H=H, R=R)\n\n # append to output:\n state_predictions.append(state_prediction)\n\n return self.family.concatenate_over_time(state_beliefs=state_predictions, design=self.design)\n\n def smooth(self, states: StateBeliefOverTime):\n raise NotImplementedError\n","sub_path":"torch_kalman/kalman_filter.py","file_name":"kalman_filter.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"601513820","text":"#!/usr/bin/env python\n'''\n########################################################################\nwrap up widget construction in fuctions for easier use, base open some\nassuptions (e.g., expansion); use **extras fkw args for width, font/color,\ne.t.c., and repark result manually later to override defaults if needed;\n#########################################################################\n'''\nfrom tkinter import *\n\ndef frame(root,side=TOP, **extras):\n widget = Frame(root)\n widget.pack(side=side, expand=NO, fill=X)\n if extras: widget.config(**extras)\n return widget\n\ndef label(root,side,text,**extras):\n widget = Label(root,text=text,relief=RIDGE)\n widget.pack(side=side,expand=YES,fill=BOTH)\n if extras: widget.config(**extras)\n return widget\n\ndef button(root,text,command,side=TOP,**extras):\n widget = Button(root,text=text,command=command)\n widget.pack(side=side,expand=YES,fill=BOTH)\n if extras: widget.config(**extras)\n return widget\n \ndef entry(root,side,linkvar,**extras):\n widget = Entry(root,relief=SUNKEN,textvariable=linkvar)\n widget.pack(side=side,expand=YES,fill=BOTH)\n if extras: widget.config(**extras)\n return widget\n\nif __name__ == '__main__':\n app = Tk()\n frm = frame(app)\n label(frm,LEFT,'SPAM')\n button(frm,BOTTOM,'Press', lambda : print('pushed'))\n mainloop()\n ","sub_path":"widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"91364155","text":"\n\n# for doing system calls to the command line\nfrom subprocess import call\nimport os\n# import the Methods file so I can call the functinons from there\nimport Methods as Methods\nimport sys\n\n\n# Create a Liat (Array)\nnames=[\"Troy\",\"Liz\",\"Sam\"]\n\n\n# Step through the array using (foreach)\nfor i in names:\n if i==\"Liz\":\n print(\"We found Liz\")\n else:\n print(\"There was another user\")\n\n\n\n1\n# call something from the command line\ncall('dir /w /a', shell=True)\n\n# define a function\n# must be defined before it is called\ndef doForLoop():\n for x in range(0, 3):\n print(\"We're on iteration %d\" % (x+1))\n\n\n# Call a local method, previously defined\ndoForLoop()\n\n# Call a remote method\nMethods.doForLoopAgain()","sub_path":"TroyHello/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"356752082","text":"from Neuron import Neuron\n\n\nclass Layer:\n\n # Constructor\n def __init__(self, inputs, amountNeurons, _random):\n self._neurons = []\n self._random = _random\n self._output = []\n\n for i in range(amountNeurons):\n self._neurons.append(Neuron(inputs, self._random))\n\n # Behavior\n def outputs(self, inputs):\n f = [None] * len(self._neurons)\n\n for i in range(len(self._neurons)):\n f[i] = self._neurons[i].output(inputs)\n \n self._output = f\n\n # Getters & Setters\n def getOutput(self):\n return self._output","sub_path":"Perceptron/Layer.py","file_name":"Layer.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"586882356","text":"# A regular polygon has n number of sides. Each side has length s.\r\n\r\nimport math\r\n\r\ndef polysum(n, s):\r\n\tarea = (0.25 * n * (s**2)) / (math.tan(math.pi / n))\r\n\tperimeter = s * n\r\n\r\n\tresult = area + perimeter**2\r\n\treturn round(result, 4)\r\n\r\n# test case\r\nprint(polysum(24, 19))","sub_path":"MIT6001x/Week2/polysum.py","file_name":"polysum.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"135697812","text":"from discord.ext import commands, tasks\nimport os\nimport crawler\n\nbot = commands.Bot(\"!\")\nTOKEN = os.getenv(\"DISCORD_TOKEN\")\n\n\n@bot.event\nasync def on_ready():\n send_so.start()\n print(f\"Logged in as {bot.user.name}({bot.user.id})\")\n\n\n@tasks.loop(seconds=300)\nasync def send_so():\n ch_id = 781729030491209762\n url = 'https://www.coupang.com/vp/products/2378328151'\n if not crawler.isSoldOut(url):\n channel = bot.get_channel(ch_id)\n await channel.send('품절 풀림!')\n\n\n@bot.command(pass_context=True)\nasync def hi(ctx):\n await ctx.send('Hi, ' + ctx.author.mention)\n\nif __name__ == \"__main__\":\n bot.run(TOKEN)\n","sub_path":"bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"134066326","text":"import os\nimport allel\nimport numpy as np\nimport json\nimport multiprocessing\nimport pickle\nimport re\nimport zipfile\nfrom wsgiref.util import FileWrapper\nfrom functools import partial\nimport time\nimport sys\nimport gzip\nimport copy\nif sys.platform.startswith('linux'):\n import fcntl\nelse:\n from lockfile import LockFile\n\n\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,\n np.int16, np.int32, np.int64, np.uint8,\n np.uint16, np.uint32, np.uint64)):\n return int(obj)\n elif isinstance(obj, (np.float_, np.float16, np.float32,\n np.float64)):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return list(obj)\n elif isinstance(obj, np.bool_):\n return bool(obj)\n else:\n return json.JSONEncoder.default(self, obj)\n\n\ndef RenameJsonKey(strJson):\n if isinstance(strJson,dict):\n strJson = json.dumps(strJson)\n #先默认json的key中没有特殊符号\n pattern = re.compile(r\"\\\"([\\w.$:]+)\\\":\")\n strJson = pattern.sub(lambda m: m.group(0).replace('.', \"_\").replace('$', \"^\"), strJson)\n return strJson\n\n\nclass TransformV2J(object):\n def addhead(self, header, filepath_json):\n record_head = []\n for line in header:\n line = line.strip('\\n')\n record_head.append(line)\n record = {\n \"Header\": record_head\n }\n with open(filepath_json, 'a') as fp:\n recordstring = json.dumps(record, cls=MyEncoder)\n recordstring = recordstring[:-1] + ',' + '\\n'\n fp.write(recordstring)\n fp.write('\"Data\":[')\n return\n\n #delete the last comma, and add the bracket\n def addEnd(self, filepath_json):\n # in win platform is \\r\\n; in linux is \\n; in os is \\r\n if sys.platform.startswith('win'):\n offsize = -3\n else:\n offsize = -2\n with open(filepath_json, 'rb+') as filehandle:\n #delete \\n and ,\n filehandle.seek(offsize, os.SEEK_END)\n filehandle.truncate()\n with open(filepath_json, 'a') as fp:\n fp.write(']}')\n\n def chunker2string(self, chunker, fields, samples, mode='MergeSamples'):\n li = []\n # 把NaN转换成-1\n for i in range(chunker[1]):\n for field in fields:\n if isinstance(chunker[0][field][i], np.ndarray) and not isinstance(chunker[0][field][i][0], np.str):\n nanpos = np.isnan(chunker[0][field][i])\n chunker[0][field][i][nanpos] = -1.0\n\n if mode == 'MergeAll':\n for i in range(chunker[1]):\n #basic\n recorddict1 = {\n \"CHROM\": chunker[0]['variants/CHROM'][i],\n \"POS\" : chunker[0]['variants/POS'][i],\n \"ID\": chunker[0]['variants/ID'][i],\n \"REF\": chunker[0]['variants/REF'][i],\n \"ALT\": chunker[0]['variants/ALT'][i],\n \"QUAL\": chunker[0]['variants/QUAL'][i],\n }\n #filter\n recorddict2 = {\n \"FILTER\": {\n k_filter[9:] : chunker[0][k_filter][i] for k_filter in fields if 'variants/FILTER' in k_filter\n }\n }\n #Info\n recorddict3 = {\n \"Info\": {\n k_Info[9:] : chunker[0][k_Info][i] for k_Info in fields if k_Info not in ['variants/CHROM', 'variants/POS', 'variants/ID', 'variants/REF', 'variants/ALT', 'variants/QUAL', 'variants/numalt', 'variants/svlen', 'variants/is_snp']\n and 'variants/FILTER' not in k_Info and 'calldata/' not in k_Info\n }\n }\n #Samples\n recordsamples = []\n for k_sample, j in zip(samples, range(samples.size)):\n recordsample1 = {\n \"SampleNo\": k_sample\n }\n recordsample2 = {\n k_field[9:]: [chunker[0][k_field][i][j][n] for n in\n range(chunker[0][k_field][i][j].size)] if isinstance(\n chunker[0][k_field][i][j], np.ndarray) else chunker[0][k_field][i][j] for k_field in\n fields if \"calldata/\" in k_field\n }\n recordsample = dict(recordsample1, **recordsample2)\n recordsamples.append(recordsample)\n recorddict4 = {\n \"Samples\": recordsamples\n }\n recorddictMerge = dict(recorddict1, **recorddict2, **recorddict3, **recorddict4)\n li.append(recorddictMerge)\n\n elif mode == 'MergeSamples':\n for i in range(chunker[1]):\n recorddict1 = {\n k_field[9:]: [chunker[0][k_field][i][m] for m in range(chunker[0][k_field][i].size)] if isinstance(\n chunker[0][k_field][i], np.ndarray) else chunker[0][k_field][i] for k_field in fields if\n 'variants/' in k_field and k_field not in ['variants/numalt', 'variants/svlen', 'variants/is_snp']\n }\n recordsamples = []\n for k_sample, j in zip(samples, range(samples.size)):\n recordsample1 = {\n \"SampleNo\": k_sample\n }\n recordsample2 = {\n k_field[9:]: [chunker[0][k_field][i][j][n] for n in\n range(chunker[0][k_field][i][j].size)] if isinstance(\n chunker[0][k_field][i][j], np.ndarray) else chunker[0][k_field][i][j] for k_field in\n fields if \"calldata/\" in k_field\n }\n recordsample = dict(recordsample1, **recordsample2)\n recordsamples.append(recordsample)\n recorddict2 = {\n \"Samples\": recordsamples\n }\n\n recorddict = dict(recorddict1, **recorddict2)\n li.append(recorddict)\n\n recordstring = json.dumps(li, cls=MyEncoder)\n recordstring = recordstring[1:-1] #delete first and last brackets. \"[...]\" ----> \"...\"\n recordstring = recordstring + ','+ '\\n'\n return recordstring\n\n\n def IoOperat_multi(self, tmpfile, mode, chunker):\n # tmpfile = \"value_\" + md5 + \".dat\"\n with open(tmpfile, \"rb\") as f:\n fields = pickle.load(f)\n samples = pickle.load(f)\n headers = pickle.load(f)\n filepath_json = pickle.load(f)\n recordstring = self.chunker2string(chunker, fields, samples, mode)\n if sys.platform.startswith('linux'):\n with open(filepath_json, \"a\") as fp:\n fcntl.flock(fp.fileno(), fcntl.LOCK_EX)\n fp.write(recordstring)\n else:\n lock = LockFile(filepath_json)\n lock.acquire()\n with open(filepath_json, \"a\") as fp:\n fp.write(recordstring)\n lock.release()\n return\n\n #useless function. just for test\n def vcf2json_Single(self, filepath_vcf, filepath_json, mode):\n fields, samples, headers, chunks = allel.iter_vcf_chunks(filepath_vcf, fields=['*'], chunk_length=50)\n\n if os.path.exists(filepath_json):\n os.remove(filepath_json)\n self.addhead(headers[0], filepath_json)\n\n for chunker in chunks:\n with open(filepath_json, 'a') as fp:\n recordstring = self.chunker2string(chunker, fields, samples, mode)\n fp.write(recordstring)\n\n return\n\n def vcf2json_multi2(self, filepath_vcf, filepath_json, md5, mode):\n fields, samples, headers, chunks = allel.iter_vcf_chunks(filepath_vcf, fields=['variants/*', 'calldata/*'],chunk_length=500)\n\n if os.path.exists(filepath_json):\n os.remove(filepath_json)\n #增加原vcf文件的头部信息, 用于逆向转换\n self.addhead(headers[0], filepath_json)\n\n tmpfile = \"value_\" + md5 + \".dat\"\n with open(tmpfile, \"wb\") as f:\n pickle.dump(fields, f)\n pickle.dump(samples, f)\n pickle.dump(headers, f)\n pickle.dump(filepath_json, f)\n\n cores = multiprocessing.cpu_count()\n #processnum = int(cores / 2)\n processnum = max(int(cores / 2), 2)\n\n # 自己调度迭代器 防止内存溢出\n pool = multiprocessing.Pool(processes=processnum)\n index = 0\n tmpchunks = []\n first = True\n realchunks = []\n for chunker in chunks:\n index += 1\n tmpchunks.append(chunker)\n if index % (processnum * 10) == 0:\n if not first:\n AppResult.get()\n realchunks.clear()\n realchunks = copy.deepcopy(tmpchunks)\n tmpchunks.clear()\n first = False\n AppResult = pool.map_async(partial(self.IoOperat_multi, tmpfile, mode), realchunks)\n\n if \"AppResult\" in locals().keys():\n AppResult.get()\n\n pool.map(partial(self.IoOperat_multi, tmpfile, mode), tmpchunks)\n tmpchunks.clear()\n if realchunks:\n realchunks.clear()\n pool.close()\n pool.join() # 主进程阻塞等待子进程的退出\n #delete two last character '\\n' and ',' and add '}'\n self.addEnd(filepath_json)\n os.remove(tmpfile) # 删除临时文件,节约空间\n\n\n def dotranform(self, filepath_vcf, mode):\n file_json = os.path.splitext(filepath_vcf)[0] + \".json\"\n self.vcf2json_multi2(filepath_vcf, file_json, \"tmpdat\", mode)\n\n\n #with output path\n def dotransformWithOutPath(self, filepath_vcf, filepath_json, mode):\n self.vcf2json_multi2(filepath_vcf, filepath_json, \"tmpdat\", mode)\n\n\n def preview(self, filepath_vcf, mode):\n fields, samples, headers, chunks = allel.iter_vcf_chunks(filepath_vcf, fields=['*'], chunk_length=2)\n #get first 2 lines for example\n #get json\n for chunker in chunks:\n recordstring = self.chunker2string(chunker, fields, samples, mode)\n recordstring = RenameJsonKey(recordstring)\n break\n\n #get vcf\n if filepath_vcf.endswith('gz'): #.vcf.gz\n linenum = 0\n vcfline = str()\n with gzip.open(filepath_vcf, 'rb') as file:\n for line in file:\n if not line:\n break\n else:\n strline = bytes.decode(line)\n if strline[1] != '#':\n vcfline += strline\n linenum += 1\n if linenum == 3:\n break\n result = {\"vcf\": vcfline, \"json\": recordstring}\n else: #.vcf\n linenum = 0\n vcfline = str()\n with open(filepath_vcf, 'rb') as file:\n while True:\n line = file.readline()\n if not line:\n break\n else:\n if line[1] != '#':\n vcfline += line\n linenum += 1\n if linenum == 3:\n break\n\n result = {\"vcf\": vcfline, \"json\": recordstring}\n return result\n","sub_path":"transform_core.py","file_name":"transform_core.py","file_ext":"py","file_size_in_byte":11704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"545309268","text":"from datetime import datetime\nimport numpy as np\nimport networkx as nx\nimport torch\nimport random\n\ndef print_with_datetime(*args):\n now = datetime.now().strftime(\"[%H:%M:%S]\")\n print(now, *args)\n\ndef compute_eff_res(graph):\n num_nodes = graph.number_of_nodes()\n adj = np.array(nx.to_numpy_matrix(graph))\n laplacian_matrix = np.diag(np.array(adj.sum(1)).squeeze()) - adj\n pinv_laplacian_matrix = np.linalg.pinv(laplacian_matrix)\n Lp_dot_1 = np.matmul(\n np.matrix(pinv_laplacian_matrix.diagonal()).T,\n np.ones((1, num_nodes))\n )\n eff_res = torch.from_numpy(\n Lp_dot_1+Lp_dot_1.T-pinv_laplacian_matrix-pinv_laplacian_matrix.T\n )\n\n return eff_res\n\ndef set_random_seed(seed):\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.manual_seed(seed)\n random.seed(seed)\n np.random.seed(seed)\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"582386362","text":"import sys\nsys.path.append('..')\n\nimport unittest\nfrom model import Field, Model, field_assembler\n\nclass TestModel( unittest.TestCase ):\n def test_field( self ):\n fname = 'login'\n ftype = 'String(100)'\n field = Field( fname, ftype )\n self.assertEqual( \" login = db.Column( db.String(100), nullable=True )\", field.definition() )\n\n funique = True\n fnull = False\n field = Field( fname, ftype, unique=funique, nullable=fnull )\n self.assertEqual( \" login = db.Column( db.String(100), unique=True, nullable=False )\", field.definition() )\n\n fpk = True\n field = Field( fname, ftype, pkey=fpk )\n res1 = field.definition()\n self.assertEqual( \" login = db.Column( db.String(100), primary_key=True, autoincrement=True )\", res1 )\n field = Field( fname, ftype, unique=funique, nullable=fnull, pkey=fpk )\n res2 = field.definition()\n self.assertEqual( res1, res2 )\n\n fautoinc = False\n field = Field( fname, ftype, pkey=fpk, autoinc=fautoinc )\n self.assertEqual( \" login = db.Column( db.String(100), primary_key=True, autoincrement=False )\", field.definition() )\n\n f = field_assembler( ('login', 'String(100)') )\n self.assertEqual( \" login = db.Column( db.String(100), nullable=True )\", f.definition() )\n\n f = field_assembler( ('login', 'String(100)', ['unique']) )\n self.assertEqual( \" login = db.Column( db.String(100), unique=True, nullable=True )\", f.definition() )\n\n f = field_assembler( ('login', 'String(100)', ['unique','notnull']) )\n self.assertEqual( \" login = db.Column( db.String(100), unique=True, nullable=False )\", f.definition() )\n\n f = field_assembler( ('login', 'String(100)', ['pkey','autoinc']) )\n self.assertEqual( \" login = db.Column( db.String(100), primary_key=True, autoincrement=True )\", f.definition() )\n\n f = field_assembler( ('login', 'String(100)', ['pkey']) )\n self.assertEqual( \" login = db.Column( db.String(100), primary_key=True, autoincrement=False )\", f.definition() )\n\n def test_model( self ):\n name = 'company'\n fields = [ \n ('id', 'Integer', ['pkey', 'autoinc']),\n ('name', 'String(200)', ['notnull']),\n ('email', 'String(200)', ['unique', 'notnull']),\n ('active', 'Boolean'),\n ]\n model = Model( name, fields )\n value = model.value()\n self.assertIn( 'class Company( db.Model ):', value )\n self.assertIn( ' id = db.Column( db.Integer, primary_key=True, autoincrement=True )', value )\n self.assertIn( ' name = db.Column( db.String(200), nullable=False )', value )\n self.assertIn( ' email = db.Column( db.String(200), unique=True, nullable=False )', value )\n self.assertIn( ' active = db.Column( db.Boolean, nullable=True )', value )\n\n name = 'user'\n fields = [\n ('id', 'Integer', ['pkey', 'autoinc']),\n ('username', 'String(80)', ['unique', 'notnull']),\n ('email', 'String(100)', ['notnull']),\n ('company_id', 'Integer', ['fkey'], 'company.id')\n ]\n model = Model( name, fields )\n value = model.value()\n self.assertIn( \" company_id = db.Column( db.Integer, db.ForeignKey( 'company.id' ) )\", value )\n self.assertIn( \" company = db.relationship( 'Company' ) )\", value )\n\n uniques = [\n ['username', 'company_id'], \n ['email']\n ]\n model = Model( name, fields, uniques=uniques )\n value = model.value()\n self.assertIn( \" db.UniqueConstraint( 'username', 'company_id', name='ukey_1' )\", value )\n self.assertIn( \" db.UniqueConstraint( 'email', name='ukey_2' )\", value )\n self.assertIn( \"def __init__( self, id, username, email, company_id )\", value )\n self.assertIn( \"self.username = username\", value )\n self.assertIn( \"self.company_id = company_id\", value )\n self.assertNotIn( \"self.company = company\", value )\n \n model.remove_field( 'email' )\n self.assertNotIn( \"'name': 'email'\", model.show_fields() )\n model.add_field( ('email', 'String(200)', ['unique', 'notnull']) )\n\n value = model.value()\n self.assertIn( ' email = db.Column( db.String(200), unique=True, nullable=False )', value )\n \n model.clear_fields()\n self.assertEqual( 0, len (model.fields ) )\n model.add_fields( fields )\n self.assertEqual( len( fields ), len (model.fields ) )\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"flute/tests/model_test.py","file_name":"model_test.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"307370965","text":"# Auction scraper - looking for info from an auctions site to identify more into on govt sell offs of property to plug budget\n# This is a template for a Python scraper on morph.io (https://morph.io)\n# including some code snippets below that you should find helpful\nimport scraperwiki\nimport lxml.html\n#\n# # Read in a page\nhtml=scraperwiki.scrape(\"https://www.sdlauctions.co.uk/property-list/\")\n# Print the variable html containing the webpage\n##commented out the print link so running the page doesn't take ages!\n#print(html)\n# # Find something on the page using css selectors\nroot=lxml.html.fromstring(html)\n# inspecting the all the info in the and tags (P and LI are parents of A)\nroot.cssselect(\"li p a\")\n# then store the matched links in 'matchedlinks'\nmatchedlinks=root.cssselect(\"li p a\")\n##commented out the print link so running the page doesn't take ages!\n# print(matchedlinks)\n# create a dictionary called record\nrecord = {}\n# Set a counter\ncounter = 0\n# It's time to loop through the confusing codes from the page calling each one li\n# We're calling it li because it relates to the tag we've grabbed it from\nfor li in matchedlinks:\n #increase counter by 1\n counter= counter+1\n #store the text elements of li in a new variable called 'listtext'\n listtext=li.text_content()\n # print that\n print(listtext).encode('utf-8')\n # store it in the 'record' dictionary under the key 'address'\n record[\"address\"] = listtext\n #store the link in the data, the html reference or href\n record['link'] = li.attrib['href']\n # save the text that's been stored in the dictionary 'record' and save it to a table\n scraperwiki.sqlite.save(['address'],record)\n# # Write out to the sqlite database using scraperwiki library\n# scraperwiki.sqlite.save(unique_keys=['name'], data={\"name\": \"susan\", \"occupation\": \"software developer\"})\n#\n# # An arbitrary query against the database\n# scraperwiki.sql.select(\"* from data where 'name'='peter'\")\n\n# You don't have to do things with the ScraperWiki and lxml libraries.\n# You can use whatever libraries you want: https://morph.io/documentation/python\n# All that matters is that your final data is written to an SQLite database\n# called \"data.sqlite\" in the current working directory which has at least a table\n# called \"data\".\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"474760248","text":"\"\"\"NPUPA_workbench URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.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.urls import path, include\nfrom . import views\n\napp_name = 'downloader'\nurlpatterns = [\n path('', views.home, name='home'),\n path('base/', views.base, name='base'),\n path('upload/', views.upload, name='upload'),\n path('downloads/', views.downloads, name='downloads'),\n path('contents/', views.download_file, name='contents'),\n\n # url(r'^download/',views.download,name=\"download\"),\n]\n","sub_path":"downloader/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"627448523","text":"\nimport sys\nimport os\nimport time\nimport re\nimport math\n\n\n\n#Parses a file with the regex pattern \\w+\\t\\w+\\t\\d\ndef parse_emote_file_readin(some_file_path):\n myfile = open(some_file_path)\n liststr = myfile.read().lower()\n myfile.close()\n return re.findall(r\"\\w+\\t\\w+\\t\\d\", liststr)\n\n#Parses a file with the regex pattern [a-zA-Z]{3,}\ndef parse_file_readin(some_file_path):\n myfile = open(some_file_path)\n liststr = myfile.read().lower()\n myfile.close()\n return re.findall(r\"[a-zA-Z]{3,}\", liststr)\n\ndef print_ranked( emote_path, doc_path ):\n emotereg = []\n emotelist = []\n docreg = []\n emoteDict = {}\n docDict = {}\n\n## anger = 0\n## anticipation = 0\n## disgust = 0\n## fear = 0\n## joy\t= 0\n## negative = 0\n## positive = 0\n## sadness = 0\n## surprise = 0\n## trust = 0\n emote_vec = [0,0,0,0,0,0,0,0,0,0]\n emote_word =['anger', 'anticipation', 'disgust', 'fear',\n 'joy','negative','positive', 'sadness', 'surprise', 'trust']\n emotereg = parse_emote_file_readin(emote_path)\n\n for elem in emotereg:\n emotelist = elem.split('\\t')\n if not emoteDict.has_key(emotelist[0]) :\n emoteDict[emotelist[0]] = []\n emoteDict[emotelist[0]].append(int(emotelist[2]))\n else:\n emoteDict[emotelist[0]].append(int(emotelist[2]))\n\n docreg = parse_file_readin(doc_path)\n not_in_emote = 0\n for elem in docreg:\n if emoteDict.has_key(elem) :\n emote_vec[0] += emoteDict[elem][0]\n emote_vec[1] += emoteDict[elem][1]\n emote_vec[2] += emoteDict[elem][2]\n emote_vec[3] += emoteDict[elem][3]\n emote_vec[4] += emoteDict[elem][4]\n emote_vec[5] += emoteDict[elem][5]\n emote_vec[6] += emoteDict[elem][6]\n emote_vec[7] += emoteDict[elem][7]\n emote_vec[8] += emoteDict[elem][8]\n emote_vec[9] += emoteDict[elem][9]\n else:\n not_in_emote += 1\n \n return emote_vec\n\n\ndef main():\n\n#https://en.wikipedia.org/wiki/Contrasting_and_categorization_of_emotions\n\n e_path = \"NRC_wordlevel_alphabetized_v0.92.txt\"\n d_path = \"hfy_4c3y0v.txt\"\n\n cos_vec = []\n \n cos_vec.append(print_ranked(e_path, d_path))\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"Multiversee/word_emotion_lexicon/word_emote_test.py","file_name":"word_emote_test.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"69930122","text":"import os\nimport base64\n\nfrom flask import Flask, render_template, request, redirect, url_for, session\n\nfrom model import Donation, Donor, DoesNotExist\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n return redirect(url_for('all'))\n\n@app.route('/donations/')\ndef all():\n donations = Donation.select()\n return render_template('donations.jinja2', donations=donations)\n\n@app.route('/add_donation/', methods=['GET','POST'])\ndef add_donation():\n if request.method == 'POST':\n donor = request.form['donor']\n if donor == '':\n return render_template(\"add_donation.jinja2\", error=\"The Donor Name cannot be blank\")\n try:\n add_donation = float(request.form['donation'])\n except:\n return render_template(\"add_donation.jinja2\", error=\"Please enter a valid amount\")\n if add_donation <= 0:\n return render_template(\"add_donation.jinja2\", error=\"Please enter a valid amount\")\n try:\n donor_id = Donor.get(Donor.name == donor).id\n except DoesNotExist:\n donor_id = Donor.create(name=donor).id\n finally:\n Donation.create(value=add_donation, donor=donor_id)\n return redirect(url_for('all'))\n\n else:\n return render_template(\"add_donation.jinja2\")\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 6738))\n app.run(host='0.0.0.0', port=port)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"405423693","text":"import torch\nimport torch.utils.data\nfrom torchvision import datasets, transforms\nimport torchvision.datasets as dataset\nfrom random import randint\nimport numpy\nimport matplotlib\n# @yuchen\nmatplotlib.use(\"AGG\")\nimport matplotlib.pyplot as plt\nimport pickle\nfrom torch.autograd import grad, Variable\nfrom os import path, makedirs\nimport torch.nn.functional as F\nfrom tqdm import tqdm\n\ndef resize_image(mnist_images):\n # We wish to resize the mnist images from 28x28 to 32x32\n n, w, h = mnist_images.size()\n data = torch.zeros(n, 32, 32)\n data[:,2:30,2:30] = mnist_images\n return data\n\ndef get_data_synthetic():\n '''\n \n Generates random, uniform 2D Gaussians centered at:\n \n +-----+-----+-----+\n | | | |\n | 1 | 2 | 3 |\n | | | |\n +-----+-----+-----+\n | | | |\n | 4 | 5 | 6 |\n | | | |\n +-----+-----+-----+\n | | | |\n | 7 | 8 | 9 |\n | | | |\n +-----+-----+-----+\n \n Each image is (32, 32), with means of Gaussians at \n 5, 15 and 25 of the intersections of both axis.\n \n '''\n TOTAL = 20000\n DENSITY = 2000 # number of points to sample\n \n NUM_CLASSES = 9\n CHANNELS = 1\n \n means = [(j, i) for i in range(5, 26, 10) for j in range(5, 26, 10)]\n covar = [[2, 0], [0, 2]] # 1 -> radius of 3, 2 -> radius of 5\n \n train_data = [None]*TOTAL\n train_labels = [None]*TOTAL\n \n outdir = \"synthetic\"\n if not path.isdir(outdir):\n makedirs(outdir)\n \n # Note: pointer assignments are faster in Python than Numpy/Pytorch through Python.\n for i in tqdm(range(TOTAL), desc=\"Generating Gaussians\", ncols=80):\n label = randint(0, NUM_CLASSES-1)\n train_labels[i] = label\n mean = means[label]\n data = numpy.zeros((32, 32))\n x, y = numpy.random.multivariate_normal(mean, covar, DENSITY).T\n keep = (x >= 0) & (x <= 31) & (y >= 0) & (y <= 31)\n x = numpy.rint(x)[keep].astype(numpy.int32)\n y = numpy.rint(y)[keep].astype(numpy.int32)\n data[x, y] = 1.0\n train_data[i] = torch.from_numpy(data).float()\n \n #save_image(data, \"{:0>6}\".format(i), outdir, CHANNELS)\n \n train_data = torch.cat(train_data).view(TOTAL, CHANNELS, 32, 32)\n train_labels = onehot(torch.LongTensor(train_labels), NUM_CLASSES).view(TOTAL, 1, 1, NUM_CLASSES)\n \n test_data = torch.FloatTensor([])\n test_labels = torch.FloatTensor([])\n \n return train_data, train_labels\n\ndef onehot(indices, d):\n base = torch.zeros((indices.size(0), d))\n return base.scatter_(1, indices.view(-1, 1), 1)\n\ndef get_data():\n CIFAR10_train = dataset.CIFAR10(root=\"./data\", train=True, transform=transforms.Compose(\n [transforms.ToTensor(),transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))]), download=True)\n CIFAR10_train_data = [data[0].numpy() for data in CIFAR10_train]\n \n CIFAR10_train_data = torch.FloatTensor(CIFAR10_train_data)\n CIFAR10_train_labels = torch.LongTensor(CIFAR10_train.train_labels)\n return CIFAR10_train_data, CIFAR10_train_labels\n\ndef create_dataset(mnist_train_data, mnist_train_labels, batch_size):\n n = len(mnist_train_labels)\n # one hot encoding\n labels = torch.zeros(n, 10).scatter_(1, mnist_train_labels.view(n, 1), 1)\n dataset = torch.utils.data.TensorDataset(mnist_train_data, labels)\n return torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True, drop_last=True, pin_memory = True)\n\ndef create_dataset_yuchen(data, labels, batch_size):\n dataset = torch.utils.data.TensorDataset(data, labels)\n return torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True, drop_last=True, pin_memory=True)\n\ndef combine_to_tensor(gen_list):\n return torch.cat(gen_list, dim=0)\n\ndef exp_decay_loss(scores, constant, batchSize, windowSize, gpu_mode):\n n, d = scores.size()\n assert d == 1\n assert n % batchSize == 0\n numEditors = n // batchSize\n chunks = scores.view(numEditors, batchSize)\n factor = -constant/float(windowSize)\n decay = torch.exp(torch.arange(numEditors)*factor)\n \n if gpu_mode:\n decay = decay.cuda()\n \n means = chunks.mean(dim=1)\n assert means.size() == decay.size()\n \n return (means*decay).sum()\n\n#def grad_penalty(real_data, fake_data, penalty, discriminator, labels = None):\n# alpha = torch.cuda.FloatTensor(fake_data.shape[0], 1, 1, 1).uniform_(0, 1).expand(fake_data.shape)\n# interpolates = alpha * fake_data + (1 - alpha) * real_data\n# #interpolates = Variable(interpolates, requires_grad=True)\n# disc_interpolates = discriminator(interpolates, labels)\n\n# grad_out = torch.ones(disc_interpolates.size()).cuda()\n# \n# gradients = grad(\n# outputs=disc_interpolates,\n# inputs=interpolates,\n# grad_outputs = grad_out\n# )[0]\n# #create_graph=True, retain_graph=True, only_inputs=True)[0]\n# gradients = gradients.view(gradients.size(0), -1)\n# gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean()\n# return penalty * gradient_penalty\n\n# @yuchen unoptimized code below\n\ndef grad_penalty(real_data, fake_data, penalty, discriminator, update_index):\n alpha = torch.cuda.FloatTensor(fake_data.shape[0], 1, 1, 1).uniform_(0, 1).expand(fake_data.shape)\n interpolates = alpha * fake_data + (1 - alpha) * real_data\n interpolates = Variable(interpolates, requires_grad=True)\n disc_interpolates = discriminator(interpolates, update_index)\n\n grad_out = torch.ones(disc_interpolates.size()).cuda()\n gradients = grad(outputs=disc_interpolates, inputs=interpolates,\n grad_outputs = grad_out,\n create_graph=True, retain_graph=True, only_inputs=True)[0]\n gradients = gradients.view(gradients.size(0), -1)\n gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean()\n return penalty * gradient_penalty\n\n\ndef create_noisy_dataset(mnist_train_data, mnist_train_labels):\n noisy_to_real = {}\n def add_noise_to_image(image, prob):\n output = numpy.zeros(image.shape)\n thres = 1 - prob \n for i in range(image.shape[0]):\n for j in range(image.shape[1]):\n rdn = numpy.random.uniform(0,1)\n output[i][j] = rdn\n if rdn > prob:\n output[i][j] = image[i][j]\n return output\n\n noisy_dataset = []\n for i, image in enumerate(mnist_train_data):\n noisy_image = add_noise_to_image(image, 0.5)\n combined = combine_image_and_onehot_label(noisy_image, mnist_train_labels[i])\n noisy_dataset.append(combined)\n noisy_to_real[noisy_image.tostring()] = image\n print(i)\n\n noisy_dataset = torch.tensor(numpy.array(noisy_dataset))\n my_dataset = torch.utils.data.DataLoader(noisy_dataset, batch_size=100, shuffle=True, drop_last=True)\n pickle.dump(my_dataset, open(\"noisy_data\", \"wb\"))\n pickle.dump(noisy_to_real, open(\"noisy_to_real\", \"wb\"))\n return noisy_dataset\n\ndef show_image(data, label):\n # Plot\n data = data.permute(1,2,0)\n print(data.shape)\n plt.title(\"Label is \" + str(label)) \n plt.imshow(data)\n plt.show()\n\ndef save_image(data, label, directory):\n # Plot\n data = data.transpose((1,2,0))\n filename = directory + \"/\" + label + \".png\"\n matplotlib.image.imsave(filename, data) \n\ndef combine_image_and_onehot_label(data, label):\n id_matrix = numpy.identity(10)\n result = numpy.zeros((33, 32))\n label_result = numpy.zeros(32)\n \n label_onehot = id_matrix[label]\n label_result[0:10] = label_onehot\n \n result[:-1,:] = data\n result[-1,:] = label_result\n \n return result\n \ndef extract_label_and_image(combined):\n images = numpy.zeros((len(combined), 32, 32))\n labels = numpy.zeros((len(combined), 10))\n \n for i, element in enumerate(combined):\n image = element[:-1,:]\n images[i] = image\n \n onehot = element[-1,:10]\n labels[i] = onehot\n \n return torch.from_numpy(images).float(), torch.from_numpy(labels).float() \n\ndef normal_init(m, mean, std):\n if isinstance(m, torch.nn.ConvTranspose2d) or isinstance(m, torch.nn.Conv2d):\n m.weight.data.normal_(mean, std)\n m.bias.data.zero_()\n\ndef print_network(net):\n num_params = 0\n for param in net.parameters():\n num_params += param.numel()\n print(net)\n print('Total number of parameters: %d' % num_params)\n\ndef histo(network, name, epoch, directory):\n params = torch.FloatTensor([]).cuda()\n for p in network.parameters():\n p1 = p.view(-1)\n params = torch.cat((params, p1), 0)\n params = params.detach().cpu().numpy()\n plt.hist(params, bins = 1000)\n plt.title('Histogram of ' + name + ' network, ep: ' + str(epoch))\n label = name + '_hist_ep_' + str(epoch)\n plt.savefig(directory + \"/\" + label + \".png\")\n\ndef plot_editor_scores(generator, discriminator, gpu_mode, num_edits, folder, epoch, wlabels=False):\n batch = 64\n z = torch.randn((batch, 128))\n if gpu_mode:\n z = z.cuda().float()\n if wlabels:\n labels = numpy.random.choice(10,100)\n onehot_labels = numpy.eye(10)[labels]\n onehot_labels = torch.from_numpy(onehot_labels)\n onehot_labels = onehot_labels.view(-1,1,1,10).float()\n onehot_labels = onehot_labels.cuda() \n \n if wlabels:\n gen_images = generator(z, onehot_labels)\n else:\n gen_images = generator.forwardGenerateDetached(z, 1+num_edits)\n \n G_tensor = gen_images\n editor_scores = [discriminator(G_tensor).mean().item()]\n for i in range(num_edits):\n editor_scores.append(discriminator(generator.forwardGenerateDetached(z, 1+i)).mean().item())\n edit_id = numpy.arange(0, len(editor_scores), 1)\n \n fig, ax = plt.subplots()\n ax.plot(edit_id, editor_scores)\n ax.set(xlabel='Editor #', ylabel='D scores',\n title='Wish to see concave upward')\n ax.grid()\n plt.savefig(folder + \"/\" + \"Epoch\" + str(epoch) + \".png\")\n fig.clear()\n \n print(\"Edit losses:\" + str(editor_scores))\n\ndef compute_wass_distance(images, discriminator, generator, folder, epoch, num_editors):\n num_samples = 100\n z = torch.randn((num_samples, 128)).cuda()\n real = torch.mean(discriminator(images))\n \n generated = generator.forwardGenerate(z, num_editors+1)\n wass_distance = []\n for edit_images in generated:\n edit_images = edit_images.detach()\n edit_mean = torch.mean(discriminator(edit_images))\n wass_distance.append(real - edit_mean)\n\n edit_id = numpy.arange(0, len(wass_distance), 1)\n fig, ax = plt.subplots()\n ax.plot(edit_id, wass_distance)\n ax.set(xlabel='Editor #', ylabel='Wass distance',\n title='Wish to see convex downward')\n ax.grid()\n plt.savefig(folder + \"/\" + \"Epoch\" + str(epoch) + \".png\")\n fig.clear()\n\ndef wrong_label_gen(label, wrong_num):\n if label.is_cuda:\n ones = torch.ones(label.size()).cuda()\n generated_sample = torch.zeros(label.size()).cuda()\n generated_sample = torch.FloatTensor([]).cuda()\n else:\n ones = torch.ones(label.size())\n generated_sample = torch.zeros(label.size())\n generated_sample = torch.FloatTensor([])\n \n dim = label.shape[3]\n wrong_labels = ones - label\n \n for j in range(wrong_labels.shape[0]):\n wrongs = []\n for i in range(wrong_labels.shape[3]):\n if wrong_labels[j, 0, 0, i].item() != 0:\n wrongs.append(i)\n shuffle(wrongs)\n t = 0\n while t < wrong_num:\n onehot_labels = numpy.eye(dim)[wrongs[t]]\n onehot_labels = torch.from_numpy(onehot_labels)\n onehot_labels = onehot_labels.view(-1,1,1,dim).float()\n if label.is_cuda:\n onehot_labels = onehot_labels.cuda()\n generated_sample = torch.cat((generated_sample, onehot_labels), 0)\n t += 1\n \n return generated_sample\n\ndef get_var_of_data(data):\n std = torch.std(data, dim=0)\n return std \n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"249422333","text":"#!/usr/bin/env python3\n\n# pylint: disable=invalid-name\n\n# based on https://github.com/bamos/zsh-history-analysis\nimport argparse\nimport os\nimport sys\nimport time\nfrom itertools import groupby\nfrom collections import Counter, defaultdict\nfrom typing import Dict, Tuple, List\n# import statistics\n\ndef group_by_key(input_value):\n \"\"\"\n group dictionary by key\n \"\"\"\n grouped_m = defaultdict(list)\n for k, value in input_value:\n grouped_m[k].append(value)\n return grouped_m\n\nclass Command:\n \"\"\"\n class Command\n \"\"\"\n def __init__(self, raw):\n tup = raw.split(\";\")\n # TODO: Should this be hard-coded?\n self.timestamp_epoch = int(tup[0][2:-2].split(':')[0])\n self.timestamp_struct = time.gmtime(self.timestamp_epoch)\n self.full_command = tup[1].strip()\n self.base_command = tup[1].split()[0]\n\nclass HistoryData:\n \"\"\"\n class HistoryData\n \"\"\"\n def __init__(self, filenames):\n if isinstance(filenames, str):\n filenames = [filenames]\n commands = []\n for filename in filenames:\n with open(filename, 'rb') as f:\n it = iter(f)\n for line in it:\n try:\n full_line = line.decode()\n while full_line.strip()[-1] == '\\\\':\n full_line += next(it).decode()\n commands.append(Command(full_line))\n except Exception as ex:\n # print(\"Warning: Exception parsing.\")i\n # print(ex)\n pass\n\n self.commands = commands\n\n def get_commands(self) -> List[Command]:\n return self.commands\n\n def get_full_commands(self) -> List[str]:\n \"\"\"\n gets all the base commands\n \"\"\"\n return [cmd.full_command for cmd in self.commands]\n\n def get_base_commands(self) -> List[str]:\n \"\"\"\n gets all the base commands\n \"\"\"\n return [cmd.base_command for cmd in self.commands]\n\n def get_top_commands(self, amount=10, full=False) -> List[Tuple[str, int]]:\n \"\"\"\n get all the top commands\n \"\"\"\n if full:\n cmds = self.get_base_commands()\n else:\n cmds = self.get_full_commands()\n return Counter(cmds).most_common(amount, )\n\n\n\n\nhistory_file = \"/home/mandy/.zhistory\"\n\nhistory_data = HistoryData(history_file)\n\ncmd = history_data.get_commands()[0]\n\n\nfor (command, amount) in history_data.get_top_commands():\n print(\"command %s amount %s\" % (command, amount))\n\nprint(history_data.get_top_commands())\n\nprint(history_data.get_top_commands(full=True))\n","sub_path":"bin/zsh_history.py","file_name":"zsh_history.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"277089548","text":"from mint import RegridEdges\nimport numpy\nimport sys\nfrom pathlib import Path\n\n\ndef test_compute_weights():\n\n data_dir = Path(__file__).absolute().parent / '../../data'\n\n # create a regridder\n rg = RegridEdges()\n\n # src is lon-lat grid so set the flags to 0, 0. This will \n # not apply any transformations to the grid\n rg.setSrcGridFlags(0, 0)\n\n # src grid file\n src_file = str(data_dir / Path('latlon4x2.nc'))\n # load the src grid, latlon is the name of the mesh stored in the netcdf file\n rg.loadSrcGrid(f'{src_file}:latlon')\n\n # dst is cubed-sphere. Cells at the poles need to be fixed to\n # make them as compact as possible. Use flags 1, 1\n rg.setDstGridFlags(1, 1)\n\n # dst grid file\n dst_file = str(data_dir / Path('cs_4.nc'))\n # load the dst grid, physics is the name of the mesh stored in the netcdf file\n rg.loadDstGrid(f'{dst_file}:physics')\n\n # compute the regridding weights. numCellsPerBucket is used to accelerate the cell\n # search. The smaller numCellPerBucket the faster the search. However, numCellPerBucket\n # there are edge cases where the search fails when numCellsPerBucket is too small.\n # periodX is the periodicity length to add/subtract to make the cells well behaved. \n # (periodX can be 0 if a regional model)\n rg.build(numCellsPerBucket=128, periodX=360., debug=2)\n\n # save the weights in a netCDF file\n rg.dumpWeights('test_regrid_edges_py.nc')\n\n\ndef test_apply_weights():\n\n data_dir = Path(__file__).absolute().parent / '../../data'\n \n # create a regridder\n rg = RegridEdges()\n\n # src is lon-lat grid\n rg.setSrcGridFlags(0, 0)\n rg.loadSrcGrid(f'{data_dir}/latlon4x2.nc:latlon')\n\n # dst is cubed-sphere\n rg.setDstGridFlags(1, 1)\n rg.loadDstGrid(f'{data_dir}/cs_4.nc:physics')\n\n # load the weights \n rg.loadWeights('test_regrid_edges_py.nc')\n\n num_src_edges = rg.getNumSrcEdges()\n num_dst_edges = rg.getNumDstEdges()\n print(f'number of edges (src/dst): {num_src_edges}/{num_dst_edges}')\n\n # create some mock field\n src_data = numpy.array(range(0, num_src_edges), numpy.float64)\n\n # allocate some space to receive the data\n dst_data = numpy.empty((num_dst_edges,), numpy.float64)\n\n # apply the weights to the src field, will fill in dst_data\n rg.apply(src_data, dst_data)\n\n print(f'dst_data = {dst_data}')\n\n\nif __name__ == '__main__':\n\n test_compute_weights()\n test_apply_weights()\n\n\n","sub_path":"mint/tests/test_regrid_edges.py","file_name":"test_regrid_edges.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"160037311","text":"import torch\nfrom typing import Tuple, Optional\nimport warnings\nimport nvtx\nfrom sptrans.sddmm import bsddmm\nfrom sptrans.spmm import bspmm\nfrom sptrans.softmax import bcsr_softmax\n\n\ndef sp_multi_head_attention_forward(\n query: torch.Tensor, # query (seq_len, bs, embed_dim)\n key: torch.Tensor, # key (seq_len, bs, embed_dim)\n value: torch.Tensor, # value (seq_len, bs, embed_dim)\n embed_dim_to_check: int, # This equals to embed_dim\n num_heads: int, # number of attention heads\n in_proj_weight: torch.Tensor, # Project the input q, k, v, (3 * embed_dim, embed_dim)\n in_proj_bias: torch.Tensor, # Bias for the above projection. (3 * embed_dim)\n bias_k: Optional[torch.Tensor], # bias for key, (1, 1, embed_dim)\n bias_v: Optional[torch.Tensor], # bias for value, (1, 1, embed_dim)\n add_zero_attn: bool, # TODO\n dropout_p: float, # probability of an element to be zeros\n out_proj_weight: torch.Tensor, # output projection weight (embed_dim, embed_dim)\n out_proj_bias: torch.Tensor, # output projection bias (embed_dim)\n training: bool = True, # training or inference\n key_padding_mask: Optional[torch.Tensor] = None, # TODO:\n need_weights: bool = True, # If True, returns the attention weight\n row_indices: Optional[torch.Tensor] = None, # indices to the csr mask rows\n row_offsets: Optional[torch.Tensor] = None, # the row indices of the csr mask\n column_indices: Optional[torch.Tensor] = None, # the column indices of the csr mask\n vec_length: Optional[int] = 2, # the vector length of column vector sparsity\n use_separate_proj_weight: bool = False, # if True, the q/k/v_proj_weight will be used rather than in_proj_weight\n q_proj_weight: Optional[torch.Tensor] = None,\n k_proj_weight: Optional[torch.Tensor] = None,\n v_proj_weight: Optional[torch.Tensor] = None,\n static_k: Optional[torch.Tensor] = None, # TODO\n static_v: Optional[torch.Tensor] = None, # TODO\n) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:\n\n # Get problem size\n tgt_len, bsz, embed_dim = query.size()\n assert embed_dim == embed_dim_to_check\n # allow MHA to have different sizes for the feature dimension\n assert key.size(0) == value.size(0) and key.size(1) == value.size(1)\n\n # Get feature dimension of each head\n head_dim = embed_dim // num_heads\n assert head_dim * num_heads == embed_dim, \"embed_dim must be divisible by num_heads\"\n\n # This computes the 1/sqrt{d} in the attention score before softmax\n scaling = float(head_dim) ** -0.5\n\n with nvtx.annotate(\"sp Input Linear Projection\"):\n # If using the in_proj_weight for projection\n if not use_separate_proj_weight:\n # For self-attention whose query, key, and value are the same\n if (query is key or torch.equal(query, key)) and (key is value or torch.equal(key, value)):\n q, k, v = torch.nn.functional.linear(query, in_proj_weight, in_proj_bias).chunk(3, dim=-1)\n\n elif key is value or torch.equal(key, value):\n # encoder-decoder attention\n # This is inline in_proj function with in_proj_weight and in_proj_bias\n _b = in_proj_bias\n _start = 0\n _end = embed_dim\n _w = in_proj_weight[_start:_end, :]\n if _b is not None:\n _b = _b[_start:_end]\n q = torch.nn.functional.linear(query, _w, _b)\n\n if key is None:\n assert value is None\n k = None\n v = None\n else:\n\n # This is inline in_proj function with in_proj_weight and in_proj_bias\n _b = in_proj_bias\n _start = embed_dim\n _end = None\n _w = in_proj_weight[_start:, :]\n if _b is not None:\n _b = _b[_start:]\n k, v = torch.nn.functional.linear(key, _w, _b).chunk(2, dim=-1)\n\n else:\n # This is inline in_proj function with in_proj_weight and in_proj_bias\n _b = in_proj_bias\n _start = 0\n _end = embed_dim\n _w = in_proj_weight[_start:_end, :]\n if _b is not None:\n _b = _b[_start:_end]\n q = torch.nn.funtional.linear(query, _w, _b)\n\n # This is inline in_proj function with in_proj_weight and in_proj_bias\n _b = in_proj_bias\n _start = embed_dim\n _end = embed_dim * 2\n _w = in_proj_weight[_start:_end, :]\n if _b is not None:\n _b = _b[_start:_end]\n k = torch.nn.functional.linear(key, _w, _b)\n\n # This is inline in_proj function with in_proj_weight and in_proj_bias\n _b = in_proj_bias\n _start = embed_dim * 2\n _end = None\n _w = in_proj_weight[_start:, :]\n if _b is not None:\n _b = _b[_start:]\n v = torch.nn.functional.linear(value, _w, _b)\n else:\n q_proj_weight_non_opt = torch.jit._unwrap_optional(q_proj_weight)\n len1, len2 = q_proj_weight_non_opt.size()\n assert len1 == embed_dim and len2 == query.size(-1)\n\n k_proj_weight_non_opt = torch.jit._unwrap_optional(k_proj_weight)\n len1, len2 = k_proj_weight_non_opt.size()\n assert len1 == embed_dim and len2 == key.size(-1)\n\n v_proj_weight_non_opt = torch.jit._unwrap_optional(v_proj_weight)\n len1, len2 = v_proj_weight_non_opt.size()\n assert len1 == embed_dim and len2 == value.size(-1)\n\n if in_proj_bias is not None:\n q = torch.nn.functional.linear(query, q_proj_weight_non_opt, in_proj_bias[0:embed_dim])\n k = torch.nn.functional.linear(key, k_proj_weight_non_opt, in_proj_bias[embed_dim : (embed_dim * 2)])\n v = torch.nn.functional.linear(value, v_proj_weight_non_opt, in_proj_bias[(embed_dim * 2) :])\n else:\n q = torch.nn.functional.linear(query, q_proj_weight_non_opt, in_proj_bias)\n k = torch.nn.functional.linear(key, k_proj_weight_non_opt, in_proj_bias)\n v = torch.nn.functional.linear(value, v_proj_weight_non_opt, in_proj_bias)\n\n batch_size = bsz * num_heads\n with nvtx.annotate(\"sp Input transpose\"):\n # Transpose the batch*head and sequence length dimensions\n q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)\n if k is not None:\n k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1)\n if v is not None:\n v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1)\n\n if static_k is not None:\n assert static_k.size(0) == bsz * num_heads\n assert static_k.size(2) == head_dim\n k = static_k\n\n if static_v is not None:\n assert static_v.size(0) == bsz * num_heads\n assert static_v.size(2) == head_dim\n v = static_v\n\n src_len = k.size(1)\n\n if key_padding_mask is not None:\n assert key_padding_mask.size(0) == bsz\n assert key_padding_mask.size(1) == src_len\n\n if add_zero_attn:\n src_len += 1\n k = torch.cat([k, torch.zeros((k.size(0), 1) + k.size()[2:], dtype=k.dtype, device=k.device)], dim=1)\n v = torch.cat([v, torch.zeros((v.size(0), 1) + v.size()[2:], dtype=v.dtype, device=v.device)], dim=1)\n if key_padding_mask is not None:\n key_padding_mask = torch.nn.functional.pad(key_padding_mask, (0, 1))\n \n # batched matrix multiplication\n with nvtx.annotate(\"sp QK^T\"):\n attn_output_weights = bsddmm(row_indices, row_offsets, column_indices, q, k, vec_length)\n \n with nvtx.annotate(\"sp Softmax\"):\n attn_output_weights = bcsr_softmax(row_indices, row_offsets, attn_output_weights, scaling, vec_length, batch_size)\n \n # Apply dropout\n with nvtx.annotate(\"sp dropout\"):\n attn_output_weights = torch.nn.functional.dropout(attn_output_weights, p=dropout_p, training=training)\n \n # batch multiplication with the value\n with nvtx.annotate(\"sp AV\"):\n attn_output = bspmm(row_indices, row_offsets, column_indices, attn_output_weights, v, vec_length)\n \n # transpose the output and concatenate the heads\n with nvtx.annotate(\"sp Output transpose\"):\n attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)\n\n with nvtx.annotate(\"sp Output Projection\"):\n attn_output = torch.nn.functional.linear(attn_output, out_proj_weight, out_proj_bias)\n\n if need_weights:\n # average attention weights over heads\n attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)\n return attn_output, attn_output_weights.sum(dim=1) / num_heads\n else:\n return attn_output, None\n \n\nclass spMultiheadAttention(torch.nn.MultiheadAttention):\n def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None):\n super(spMultiheadAttention, self).__init__(embed_dim, num_heads, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim)\n \n def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, key_padding_mask: Optional[torch.Tensor] = None,\n need_weights: bool = True, row_indices: Optional[torch.Tensor] = None, row_offsets: Optional[torch.Tensor] = None,\n column_indices: Optional[torch.Tensor] = None, vec_length: int = 2) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:\n return sp_multi_head_attention_forward(\n query, key, value, self.embed_dim, self.num_heads,\n self.in_proj_weight, self.in_proj_bias,\n self.bias_k, self.bias_v, self.add_zero_attn,\n self.dropout, self.out_proj.weight, self.out_proj.bias,\n training=self.training,\n key_padding_mask=key_padding_mask, need_weights=need_weights,\n row_indices=row_indices, row_offsets=row_offsets, column_indices=column_indices,\n vec_length=vec_length)\n","sub_path":"spattention.py","file_name":"spattention.py","file_ext":"py","file_size_in_byte":10809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"512942396","text":"# python wcount.py http://mail.ru word1 [word2, ...]\nimport sys\nimport urllib2\nimport re\n\nurl = sys.argv[1]\nwords = sys.argv[2:]\n\nprint(url)\ncontent = urllib2.urlopen(url).read()\n\nwords_from_page = re.split('[\\s\\.,; : \\{\\} \\| = \\(\\) \\d 0123456789 \\[\\] \\%\\^\\& <\\\\/> \\t]', content)\n\nwords_dict = {}\n\nfor word in words_from_page:\n if word in words_dict:\n words_dict[word] += 1\n else:\n words_dict[word] = 1\n\nfrom pprint import pprint\n# pprint(words_dict)\n\nfor word in words:\n if word in words_dict:\n print(word, words_dict[word])\n\n\n\n\n","sub_path":"wcount.py","file_name":"wcount.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"277902752","text":"# revenue.py\n# Update the revenue data on Socrata.\n# It is presumed that the new data have already been converted from a pdf to a csv. Actually, two csv files: one for GF and SF revenues, another for available balances. The available balances will be added to revenues.\n# Adam Scherling April 18, 2018. Updated June 11, 2018\n# Converted/Updated July 2021, Calvin Chan\n\n# NOTE: NEED TO RUN parse_revenues.py FIRST. RUN THAT IMMEDIATELY PRIOR TO RUNNING revenue.py\n\n### This script will be able to creating new revenue entries in Socrata from the created CSV's via `parse_revenues.py`.\n\n## SETUP\n\nimport datetime\nfrom typing import final\nimport pandas as pd\nimport credentials\nfrom sodapy import Socrata\n\n# Instantiating variables\nfy = '2021-2022'\nfy_shorthand = 2022\nfilepath_prefix = '../../data/approved_budget/FY21-22/'\n\n# API endpoint for the dataset\nsocrata_endpoint = \"https://data.lacity.org/resource/ih6g-qkwz.json\"\nsocrata_id = 'ih6g-qkwz'\n\n# Get current timestamp\ntimestamp = str(datetime.datetime.now())\n\n## EXTRACTING + CLEANING DATA\n\n\n# set up Socrata client\n# Don't need credentials to read in public data.\nclient = Socrata('data.lacity.org', None)\n\n# uncomment if you are going to log in / push to the data portal\n# username = credentials.lahub_user\n# password = credentials.lahub_pass\n# apptoken = credentials.lahub_auth\n# client = Socrata('data.lacity.org', apptoken, username=username, password=password)\n\n# read in the data on Socrata and save as backup\nold_revenues = pd.DataFrame(client.get(socrata_id))\nold_revenues.to_csv(f'{filepath_prefix}old_revenues_{timestamp}.csv', index=False)\n\n# Filtering out current year\nold_revenues = old_revenues[old_revenues['fiscal_year_2'] != 2022]\n\n# Read in new data -- these spreadsheets are from parse_revenues.py\nnew_revenues = pd.read_csv('../../data/approved_budget/FY21-22/new_revenues.csv')\navailable_balances = pd.read_csv('../../data/approved_budget/FY21-22/new_available_balances.csv')\n\n### Cleaning dataframes\n\n# Remove percent columns\nnew_revenues.drop(columns=['Percent'], inplace=True)\navailable_balances.drop(columns=['Percent'], inplace=True)\n\n# Remove rows without an available balance\navailable_balances = available_balances[available_balances['Available.Balance'] != 0]\n\n# Cleaning new_revenues\nnew_revenues = new_revenues.merge(available_balances, how='outer', on='Revenue.Source')\nnew_revenues['Available.Balance'] = new_revenues['Available.Balance'].fillna(0)\nnew_revenues['Amount'] += new_revenues['Available.Balance']\nnew_revenues.drop(columns=['Available.Balance'], inplace=True)\nnew_revenues['Fiscal.Year.Shorthand'] = fy_shorthand\nnew_revenues['Fiscal.Year'] = fy\n\n### Dropping rows that still have null values because this could mean these rows are just slightly misnamed in `Revenue.Source` w.r.t. the `Available Balances` table.\n### The above is not necessarily true from year to year. Quality check of the data is still required.\nnew_revenues.dropna(axis=0, how='any', inplace=True)\n\n# Renaming columns\nnew_revenues.rename(columns={\n 'Revenue.Source' : 'revenue_source',\n 'Amount': 'amount',\n 'Fund.Type' : 'fund_type',\n 'Fiscal.Year' : 'fiscal_year',\n 'Fiscal.Year.Shorthand': 'fiscal_year_2'\n}, inplace=True)\n\n### Dropping rows that still have null values from `old_revenues`. These entries are most likely continuously listed under similar names\n### Quality check before this row would still be best practice.\nold_revenues.dropna(axis=0, how='any', inplace=True)\n\n## CREATING FINAL DATAFRAME AND UPLOADING TO SOCRATA\n\n# Creating the `final_revenues` table and exporting it\nfinal_revenues = pd.concat([new_revenues, old_revenues])\nfinal_revenues = final_revenues[old_revenues.columns]\nfinal_revenues.to_csv(f'{filepath_prefix}new_revenues.csv', index=False)\n\n# Upload to Socrata here\n# client.replace(socrata_id, final_revenues)\n","sub_path":"scripts/python-scripts/revenue.py","file_name":"revenue.py","file_ext":"py","file_size_in_byte":3834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"638396967","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\ntests.py is our unittest file\n\"\"\"\n\nimport django.core.urlresolvers\nfrom django.http import HttpRequest\nfrom django.template.loader import render_to_string\nimport django.test\nimport db.models\nimport db.views\n\n# bump\n\n\nclass HomePageTest(django.test.TestCase):\n\n def test_root_url_resolves_to_home_page_view(self):\n found = django.core.urlresolvers.resolve('/')\n\n self.assertEqual(found.func, db.views.index)\n\n def test_home_page_returns_correct_html(self):\n request = HttpRequest()\n response = db.views.index(request)\n\n expected_html = render_to_string('index.html')\n\n self.assertEqual(response.content.decode(), expected_html)\n\n\nclass ModelsTest(django.test.TestCase):\n\n def test_saving_and_retrieving_building(self):\n first_building = db.models.Building(\n title=\"Test Building\", street=\"Test Street 123\", zipcode=\"12345\",\n city=\"Test City\", category=\"Universität\")\n first_building.save()\n second_building = db.models.Building(\n title=\"Test Building 2\", street=\"Test Street 124\", zipcode=\"12346\",\n city=\"Test City 2\", category=\"Krankenhaus\")\n second_building.save()\n\n saved_building = db.models.Building.objects.filter(\n title=\"Test Building\")\n\n self.assertEqual(saved_building[0], first_building)\n\n def test_saving_and_retrieving_department(self):\n first_department = db.models.Department(\n title=\"Test Department\", number=1)\n first_department.save()\n second_department = db.models.Department(\n title=\"Test Department\", number=2)\n second_department.save()\n\n saved_department = db.models.Department.objects.filter(number=1)\n\n self.assertEqual(saved_department[0], first_department)\n\n def test_saving_and_retrieving_employee(self):\n first_department = db.models.Department(\n title=\"Test Department\", number=1)\n first_department.save()\n first_employee = db.models.Employee(\n department=first_department, empID=\"ID-1\",\n firstname=\"Firstname\", lastname=\"Lastname\")\n first_employee.save()\n second_employee = db.models.Employee(\n department=first_department, empID=\"ID-2\",\n firstname=\"Firstname 2\", lastname=\"Lastname 2\")\n second_employee.save()\n\n saved_employee = db.models.Employee.objects.filter(empID=\"ID-2\")\n\n self.assertEqual(saved_employee[0], second_employee)\n\n def test_saving_and_retrieving_contractor(self):\n first_contractor = db.models.Contractor(\n name=\"Test Contractor\", street=\"Test Street 123\",\n zipcode=\"12345\", city=\"Test City\", phone=\"238457923057920384\",\n fax=\"8349572093475897435\")\n first_contractor.save()\n second_contractor = db.models.Contractor(\n name=\"Test Contractor 2\", street=\"Test Street 124\",\n zipcode=\"12346\", city=\"Test City 2\", phone=\"9999457923057920384\",\n fax=\"8349572093475811111\")\n second_contractor.save()\n\n saved_contractor = db.models.Contractor.objects.filter(zipcode=\"12346\")\n\n self.assertEqual(saved_contractor.first(), second_contractor)\n\n\nclass ViewsTest(django.test.TestCase):\n\n def test_prognosis_retrieving_and_matching_newest_with_project(self):\n\n first_project = db.models.Project.objects.create()\n\n first_budgetplan = db.models.Budgetplan.objects.create(\n project=first_project)\n\n first_budgetyear_first_project = db.models.Budgetyear.objects.create(\n budgetplan=first_budgetplan)\n second_budgetyear_first_project = db.models.Budgetyear.objects.create(\n budgetplan=first_budgetplan)\n third_budgetyear_first_project = db.models.Budgetyear.objects.create(\n budgetplan=first_budgetplan)\n\n first_employee = db.models.Employee.objects.create()\n\n newest_prognosis = db.models.Prognosis.objects.create(\n budgetyear=first_budgetyear_first_project,\n employee=first_employee,\n text=\"dummy\")\n\n first_prognosis_first_bugegetyear_first_project = db.models.Prognosis.objects.create(\n budgetyear=first_budgetyear_first_project,\n employee=first_employee,\n text=\"new\")\n second_prognosis_first_bugegetyear_first_project = db.models.Prognosis.objects.create(\n budgetyear=first_budgetyear_first_project,\n employee=first_employee,\n text=\"old\")\n first_prognosis_second_bugegetyear_first_project = db.models.Prognosis.objects.create(\n budgetyear=second_budgetyear_first_project,\n employee=first_employee,\n text=\"new\")\n second_prognosis_second_bugegetyear_first_project = db.models.Prognosis.objects.create(\n budgetyear=second_budgetyear_first_project,\n employee=first_employee,\n text=\"old\")\n\n wanted_prognosiss = db.models.Prognosis.objects.filter(\n budgetyear__budgetplan__project__id=first_project.id)\n\n for prognosis in wanted_prognosiss:\n if newest_prognosis.timestamp < prognosis.timestamp:\n newest_prognosis = prognosis\n\n print(newest_prognosis.timestamp, newest_prognosis.text,\n newest_prognosis.budgetyear.id)\n","sub_path":"db/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"401766451","text":"\"\"\"Столбцовая диаграмма самых активных обсуждений на базе hn_submissions.py\"\"\"\nimport requests\nfrom operator import itemgetter\nimport pygal\nfrom pygal.style import LightColorizedStyle as LCS, LightenStyle as LS\nimport sys\n\n\ndef get_pygal_config():\n my_config = pygal.Config()\n my_config.x_label_rotation = 45\n my_config.show_legend = False\n my_config.title_font_size = 24\n my_config.label_font_size = 14\n my_config.major_label_font_size = 18\n my_config.truncate_label = 15\n my_config.show_y_guides = False\n my_config.width = 1000\n return my_config\n\n\ndef get_article_information(url):\n \"\"\"Возвращает словарь с информацией об отдельной статье.\"\"\"\n submission_r = requests.get(url)\n if submission_r.status_code != 200:\n print('Submission status code: ', submission_r.status_code)\n print('Bad url: ', url)\n return submission_r.json()\n\n\nnon_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)\n# Создание вызова API и сохранение ответа.\nurl = 'https://hacker-news.firebaseio.com/v0/topstories.json'\nr = requests.get(url)\nprint('Status code: ', r.status_code, '\\n')\n\n# Обработка информации о каждой статье.\nsubmission_ids = r.json()\nsubmission_dicts, names = [], []\nfor submission_id in submission_ids[:50]:\n # Создание отдельного вызова API Для каждой статьи.\n url = ''.join(['https://hacker-news.firebaseio.com/v0/item/', str(submission_id), '.json'])\n response_dict = get_article_information(url)\n # Обработка информации о текущей статье.\n submission_dict = {\n 'label': response_dict['title'].translate(non_bmp_map),\n 'xlink': 'https://news.ycombinator.com/item?id=' + str(submission_id),\n 'value': response_dict.get('descendants', 0)\n }\n submission_dicts.append(submission_dict)\n\nsubmission_dicts = sorted(submission_dicts, key=itemgetter('value'), reverse=True)\nfor submission_dict in submission_dicts:\n names.append(submission_dict['label'])\n\nmy_style = LS('#333366', base_style=LCS)\nmy_config = get_pygal_config()\nchart = pygal.Bar(my_config, style=my_style)\nchart.title = 'Top comment articles'\nchart.x_labels = names\nchart.add('', submission_dicts)\nchart.render_to_file('top_articles.svg')\n","sub_path":"Part_2_Chapter_17/task17-2.py","file_name":"task17-2.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"310026572","text":"#!/usr/bin/env python3\n\nimport cs50\n\ndef main():\n \n while True:\n print(\"Height: \", end = \"\")\n height = cs50.get_int()\n if height >= 0 and height <23:\n break\n \n for row in range(height):\n \n for space in range (height - row - 1):\n print(\" \", end = \"\")\n \n for hash in range (row + 2):\n print(\"#\", end = \"\")\n \n print(\"\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"pset6/mario.py","file_name":"mario.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"20756328","text":"from django.contrib import admin\nfrom django.contrib.admin import SimpleListFilter\n\nfrom accounts.admin import MyBaseModelAdmin\nfrom .forms import ApparatusImportForm, LaboratoryImportForm\nfrom .models import Apparatus, Laboratory\n\n\nclass StaffFilter(SimpleListFilter):\n title = 'staff'\n parameter_name = 'staff'\n\n def lookups(self, request, model_admin):\n staffs = set([f.staff for f in model_admin.model.objects.all()])\n return [(s.id, s.name) for s in staffs]\n\n def queryset(self, request, queryset):\n if self.value():\n return queryset.filter(staff__id__exact=self.value())\n\n\nclass FacilityAdmin(MyBaseModelAdmin):\n list_filter = ('school', StaffFilter,)\n exclude = ('staff',)\n\n # Only set staff field during the first save.\n def save_model(self, request, obj, form, change):\n if not obj.pk:\n obj.staff = request.user\n super().save_model(request, obj, form, change)\n\n def has_change_permission(self, request, obj=None):\n return self.permission_control(request, obj)\n\n def has_delete_permission(self, request, obj=None):\n return self.permission_control(request, obj)\n\n def permission_control(self, request, obj=None):\n if request.user.is_superuser:\n return True\n if obj and obj.staff == request.user:\n return True\n return False\n\n\nclass ApparatusAdmin(FacilityAdmin):\n list_display = ('name', 'model_no', 'cost', 'purchased', 'school', 'staff',)\n ordering = ('name', 'model_no',)\n search_fields = ('name', 'model_no',)\n date_hierarchy = 'purchased'\n list_per_page = 50\n model_import_form = ApparatusImportForm\n\n\nclass LaboratoryAdmin(FacilityAdmin):\n list_display = ('name', 'location', 'capacity', 'school', 'staff',)\n ordering = ('school', 'location',)\n search_fields = ('name', 'location',)\n list_per_page = 25\n model_import_form = LaboratoryImportForm\n\n\nadmin.site.register(Apparatus, ApparatusAdmin)\nadmin.site.register(Laboratory, LaboratoryAdmin)\n","sub_path":"lims_root/inventory/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"599123581","text":"# -*- coding: utf-8 -*-\n__author__ = 'liudong'\n__date__ = '2019/10/18 4:18 PM'\nimport re\n\n# 拆分字符串\ndef main():\n poem = '窗前明月光,疑是地上霜。举头望明月,低头思故乡。'\n sentence_list = re.split(r'[, 。,.]', poem)\n while '' in sentence_list:\n sentence_list.remove('')\n print(sentence_list)\n\ndef main1():\n sentence = '你Y是傻叉吗?我操你大爷的。Fuck you.'\n purified = re.sub('[[操肏艹]|fuck|shit|傻[比屄逼叉缺吊屌]|煞笔]]', '*', sentence, flags=re.IGNORECASE)\n print(purified)\n\nif __name__ == '__main__':\n main1()","sub_path":"Python/Python_Basic/split_string.py","file_name":"split_string.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"6218572","text":"\"\"\"\nCopyright (c) 2013 Samuel B. Fries\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport sublime\nimport sublime_plugin\nimport re\n\nclass SnakeToCamelCase(sublime_plugin.TextCommand):\n def run(self, edit):\n view = self.view\n regions = view.sel()\n\n for region in regions:\n val = view.substr(region)\n strings = [x.capitalize() for x in val.split(\"_\")[1:]]\n val = val.split(\"_\")[0] + \"\".join(strings)\n view.replace(edit, region, val)\n\nclass CamelCaseToSnake(sublime_plugin.TextCommand):\n def run(self, edit):\n view = self.view\n regions = view.sel()\n\n self.split_re = re.compile('([A-Z]+)')\n\n for region in regions:\n val = view.substr(region)\n lines = val.split('\\n')\n lines_sub = [self.process_line(line) for line in lines]\n sub = \"\\n\".join(lines_sub)\n\n view.replace(edit, region, sub)\n\n def process_line(self, line):\n\n def process_token(tkn):\n char_first = tkn[0]\n return '_' + tkn.lower() if char_first.isupper() else tkn\n\n matches = self.split_re.split(line)\n matches = matches[1:] if matches[0] == '' else matches\n matches = matches[0:-1] if matches[-1] == '' else matches\n\n if len(matches) > 0:\n head = [matches[0].lower()]\n rest = [process_token(tkn) for tkn in matches[1:]]\n words = head + rest\n sentence = \"\".join(words)\n return sentence\n else:\n return '';\n\nclass UnderscoreToSpacesCommand(sublime_plugin.TextCommand):\n def run(self, edit):\n view = self.view\n regions = view.sel()\n\n for region in regions:\n\n val = view.substr(region)\n\n val = \" \".join(val.split(\"_\"))\n\n self.view.replace(edit, region, val)\n\n\nclass SpacesToUnderscoresCommand(sublime_plugin.TextCommand):\n def run(self, edit):\n view = self.view\n regions = view.sel()\n\n for region in regions:\n val = view.substr(region)\n val = \"_\".join(val.split(\" \"))\n self.view.replace(edit, region, val)\n","sub_path":"text_convert.py","file_name":"text_convert.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"142243392","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Types.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nfrom __future__ import print_function\n\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_model_analysis.types_compat import Any, Dict, List, Text, Tuple, Union, NamedTuple\n\n# pylint: disable=invalid-name\nTensorType = Union[tf.Tensor, tf.SparseTensor]\nDictOfTensorType = Dict[bytes, TensorType]\nTensorTypeMaybeDict = Union[TensorType, DictOfTensorType]\n\n# Type of keys we support for prediction, label and features dictionaries.\nKeyType = Union[Union[bytes, Text], Tuple[Union[bytes, Text], Ellipsis]]\n\n# Value of a Scalar fetched during session.run.\nFetchedScalarValue = Union[np.float32, np.float64, np.int32, np.int64, bytes]\n\n# Value of a Tensor fetched using session.run.\nFetchedTensorValue = Union[tf.SparseTensorValue, np.ndarray]\n\n# Value fechted using session.run.\nFetchedValue = Union[FetchedScalarValue, FetchedTensorValue]\n\n# Dictionary of Tensor values fetched.\n# The dictionary maps original dictionary keys => ('node' => value).\nDictOfFetchedTensorValues = Dict[KeyType, Dict[bytes, FetchedTensorValue]]\n\nListOfFetchedTensorValues = List[FetchedTensorValue]\n\n\ndef is_tensor(obj):\n return isinstance(obj, tf.Tensor) or isinstance(obj, tf.SparseTensor)\n\n\n# Used in building the model diagnostics table, a MatrializedColumn is a value\n# inside of ExampleAndExtract that will be emitted to file.\nMaterializedColumn = NamedTuple(\n 'MaterializedColumn',\n [('name', str), ('value',\n Union[List[str], List[int], List[float]])])\n\n# Used in building model diagnostics table, the ExampleAndExtracts holds an\n# example and all its \"extractions.\" Extractions that should be emitted to file.\n# Each Extract has a name, stored as the key of the DictOfExtractedValues.\nDictOfExtractedValues = Dict[Text, Any]\nExampleAndExtracts = NamedTuple( # pylint: disable=invalid-name\n 'ExampleAndExtracts',\n [('example', bytes),\n ('extracts', DictOfExtractedValues)])\n","sub_path":"tensorflow_model_analysis/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"489518752","text":"import operator\nimport sys\n\n\ndef mark(answer_path, output_path):\n answer_dict = {}\n output_dict = {}\n\n min_count = 0x7fffffff\n with open(answer_path, 'r') as answer:\n for line in answer:\n params = line.split()\n count = int(params[0])\n word = params[1]\n min_count = min(min_count, count)\n if count in answer_dict:\n answer_dict[count].add(word)\n else:\n answer_dict[count] = {word}\n\n count_list = []\n with open(output_path, 'r') as output:\n for line in output:\n params = line.split()\n count = int(params[0])\n word = params[1]\n count_list.append(count)\n if count in output_dict:\n output_dict[count].add(word)\n else:\n output_dict[count] = {word}\n\n # check correctness\n if count_list != list(sorted(count_list)[::-1]):\n return -1\n\n for count in answer_dict.keys():\n if count != min_count:\n if output_dict[count] != answer_dict[count]:\n return -2\n del output_dict[count]\n if count == min_count:\n if not output_dict[count].issubset(answer_dict[count]):\n return -3\n del output_dict[count]\n\n if output_dict:\n return -4\n else:\n return 1\n\n\nif __name__ == '__main__':\n result = mark(sys.argv[1], sys.argv[2])\n if result == 1:\n print(\"Test Passed\")\n elif result == -1:\n print(\"Wrong Answer: incorrect order\")\n elif result == -4:\n print(\"Wrong Answer: output exceeds top 20\")\n elif result <= 0:\n print(\"Wrong Answer\")\n","sub_path":"TopK_CommonWords/check_common.py","file_name":"check_common.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"491080763","text":"# Copyright (C) 2017 O.S. Systems Software LTDA.\n# This software is released under the MIT License\n\nimport base64\nimport json\n\nfrom Crypto.PublicKey import RSA\n\nfrom .base import HydraManager\nfrom .exceptions import HydraResponseError, HydraRequestError\n\n\nclass JWK:\n\n PUBLIC = 'public'\n PRIVATE = 'private'\n\n def __init__(self, **jwk):\n self.jwk = jwk\n self.kty = jwk.get('kty')\n self.alg = jwk.get('alg')\n self.kid = jwk.get('kid')\n\n self.n = jwk.get('n')\n self.e = jwk.get('e')\n self.d = jwk.get('d')\n\n self.type = None\n if all([self.n, self.e, self.d]):\n self.type = self.PRIVATE\n elif all([self.n, self.e]):\n self.type = self.PUBLIC\n\n @staticmethod\n def b64_to_int(data):\n return int.from_bytes(base64.urlsafe_b64decode(data + '=='), 'big')\n\n def to_rsa(self):\n \"\"\"Converts a JWK to RSA.\"\"\"\n numbers = [self.n, self.e]\n if self.type == self.PRIVATE:\n numbers.append(self.d)\n return RSA.construct(tuple(self.b64_to_int(n) for n in numbers))\n\n\nclass JWKManager(HydraManager):\n\n def get(self, key, type_):\n path = '/keys/{}/{}'.format(key, type_)\n response = self.hydra.request('GET', path, scope='hydra.keys.get')\n if not response.ok:\n raise HydraRequestError('Request to get JWK failed.')\n try:\n jwk = response.json()['keys'][0]\n except json.decoder.JSONDecodeError:\n raise HydraResponseError(\n 'Bad response content type (expected JSON)')\n except KeyError:\n raise HydraResponseError(\n 'Bad response content (expected to have a keys key)')\n except IndexError:\n raise HydraResponseError('Bad response (empty key set)')\n else:\n return JWK(**jwk)\n","sub_path":"hydra/jwk.py","file_name":"jwk.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"286258490","text":"import pandas as pd\nimport random\nimport os\nfrom bert.tokenization import FullTokenizer, convert_to_unicode\nfrom bert.run_classifier import file_based_convert_examples_to_features, DataProcessor, InputExample\nfrom multiprocessing import Process, current_process, cpu_count\n\ndef createFinetuningData():\n \n _createBalancedData('./data/multiline_report_index_train.csv', './data/fine_tuning_data_train.csv')\n _createBalancedData('./data/multiline_report_index_validate.csv', './data/fine_tuning_data_validate.csv')\n _createBalancedData('./data/multiline_report_index_test.csv', './data/fine_tuning_data_test.csv')\n\n processor = ReportProcessor()\n\n train_examples = processor.get_train_examples('./data')\n f = open('./data/fine_tuning_examples_number.txt', 'w+')\n f.write(f'Number of train examples: {len(train_examples)}\\n')\n f.close()\n\n validate_examples = processor.get_validate_examples('./data')\n f = open('./data/fine_tuning_examples_number.txt', 'a')\n f.write(f'Number of validate examples: {len(validate_examples)}\\n')\n f.close()\n\n test_examples = processor.get_test_examples('./data')\n f = open('./data/fine_tuning_examples_number.txt', 'a')\n f.write(f'Number of test examples: {len(test_examples)}\\n')\n f.close()\n\n vocab_file = './data/BERT/uncased_L-12_H-768_A-12/vocab.txt'\n\n train_process = Process(target=_convertToTfrecord, args=(train_examples, vocab_file, './data/bert_finetuning_data/train', 'train.tf_record'))\n train_process.start()\n validate_process = Process(target=_convertToTfrecord, args=(validate_examples, vocab_file, './data/bert_finetuning_data/validate', 'validate.tf_record'))\n validate_process.start()\n test_process = Process(target=_convertToTfrecord, args=(test_examples, vocab_file, './data/bert_finetuning_data/test', 'test.tf_record'))\n test_process.start()\n\n train_process.join()\n validate_process.join()\n test_process.join()\n\n\ndef _convertToTfrecord(examples, vocab_file, output_dir, output_file):\n max_seq_length = 128\n processor = ReportProcessor()\n label_list = processor.get_labels()\n tokenizer = FullTokenizer(vocab_file=vocab_file, do_lower_case=True)\n\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n output_file_path = os.path.join(output_dir, output_file)\n\n print('Converting files to tfrecord.')\n file_based_convert_examples_to_features(\n examples, label_list, max_seq_length, tokenizer, output_file_path)\n print(f'Finished tfrecord creation at {output_file_path}')\n\n\n\ndef _createBalancedData(index_file, output_file_path):\n\n reports_index_df = pd.read_csv(index_file, sep='\\t')\n reports_index = reports_index_df.to_dict('records')\n\n pos_sequences = []\n neg_sequences = []\n for report in reports_index:\n file_path = report['File_Path']\n print(f'Processing {file_path}')\n\n price_change = report['Change_Nominal']\n\n with open(file_path) as f:\n lines = [line.rstrip('\\n') for line in f]\n\n if price_change == 'positive':\n pos_sequences.extend(lines)\n else:\n neg_sequences.extend(lines)\n\n print('Shuffling sequences...')\n random.shuffle(pos_sequences)\n random.shuffle(neg_sequences)\n\n print('Balancing data...')\n if len(pos_sequences) > len(neg_sequences):\n pos_sequences = pos_sequences[:len(neg_sequences)]\n else:\n neg_sequences = neg_sequences[:len(pos_sequences)]\n\n print('Merging positive and negative sequences...')\n labeled_sequences = []\n\n for pos_sequence in pos_sequences:\n labeled_sequence = {\n 'label': 1,\n 'sequence': pos_sequence\n }\n\n labeled_sequences.append(labeled_sequence)\n\n for neg_sequence in neg_sequences:\n labeled_sequence = {\n 'label': 0,\n 'sequence': neg_sequence\n }\n\n labeled_sequences.append(labeled_sequence)\n\n print('Shuffling sequences...')\n random.shuffle(labeled_sequences)\n\n print(f'Writing to file {output_file_path}')\n labeled_sequences_df = pd.DataFrame(labeled_sequences)\n labeled_sequences_df.to_csv(output_file_path, sep='\\t', index=False)\n\n\n\nclass ReportProcessor(DataProcessor):\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"fine_tuning_data_train.csv\")), \"train\")\n\n def get_validate_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"fine_tuning_data_validate.csv\")), \"validate\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"fine_tuning_data_test.csv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n \n text_a = convert_to_unicode(line[1])\n label = convert_to_unicode(line[0])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\nif __name__ == '__main__':\n createFinetuningData()\n","sub_path":"create_finetuning_data.py","file_name":"create_finetuning_data.py","file_ext":"py","file_size_in_byte":5403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"47066010","text":"\"\"\"\nTesting visa connection to talk to three instruments\nToDo: Split object classes into independent files.\n\"\"\"\nfrom datetime import datetime\nfrom time import sleep\nfrom E8267D import E8267D\nfrom N9000B import N9000B\nfrom N1914A import N1914A\nimport pathlib\nimport csv\n\n\ndef run_pout_pin_test(frequencies=None, sig_gen_min=-30, sig_gen_max=-5, power_step=1, single_excel=False):\n # check for list type argument and\n if not isinstance(frequencies, list) or not frequencies:\n print(\"Not frequencies provided\")\n return False\n # Setting limits for current setup.\n min_freq = 1 # GHz\n max_freq = 12 # GHz\n if not all([(min_freq <= freq) and (freq <= max_freq) for freq in frequencies]):\n print(\"Frequencies not withing range\")\n return False\n # Instrument settings\n sig_gen = 'TCPIP::192.168.10.102::INSTR' # E8267D PSG signal generator\n cxa_x_series = 'TCPIP::192.168.10.103::INSTR' # N9000B signal analyzer\n power_supply = 'TCPIP::192.168.10.104::INSTR' # E3634A power supply\n power_sensor = 'TCPIP::192.168.10.101::INSTR' # N1914A power sensor\n\n # Constants\n wait_response = 2 # seconds\n\n # Initialize instruments\n psg = E8267D(sig_gen)\n cxa = N9000B(cxa_x_series)\n ps = N1914A(power_sensor)\n\n # set rf output off\n psg.rf_off()\n sleep(wait_response)\n\n # Set RBW\n #cxa.set_resbwid(100, 'kHz')\n #cxa.set_freq_span(2) # Default unit GHz\n\n # Labels\n labels_list = ['FREQ_SET(GHz)', 'Pin(dBm)', 'Pout(dBm)', 'Pref(dBm)',\n 'POUT_PSG(dBm)', 'Delta_CXA-PSG(dB)',\n 'Delta_PS-PSG(dB)', 'DIFF_PSG_CXA(dBm)', 'CAL_FACTOR_A', 'CAL_FACTOR_B',\n 'Pin(W)', 'Pout(W)', 'Pref(W)', 'Pdis(W)']\n\n rsp_array = []\n if single_excel:\n rsp_array = [labels_list]\n test_results = []\n for freq_start in frequencies:\n # Labels for measurements\n if not single_excel:\n rsp_array = [labels_list]\n\n # Start setup.\n print('Setting Freq to:', freq_start)\n psg.set_freq(freq_start)\n ps.set_freq(freq_start, 1)\n ps.set_freq(freq_start, 2)\n # Change CXA if outside START and STOP frequencies.\n if cxa.freq_start() > freq_start * 1e9 or cxa.freq_stop() < freq_start * 1e9:\n cxa.set_freq_cent(freq_start)\n cxa.set_marker_x(freq_start)\n sleep(wait_response)\n out_min, out_max, out_step = (sig_gen_min, sig_gen_max, power_step) # start and stop values\n pow_bool = True\n while out_min <= out_max:\n psg.set_power(out_min)\n if pow_bool:\n psg.rf_on()\n pow_bool = False\n sleep(wait_response)\n pow_sens_in = ps.read_power(1)\n pow_sens_in_watts = (10 ** (pow_sens_in/10))/1000\n pow_sens_circu = ps.read_power(2)\n pow_refl_watts = (10 ** (pow_sens_circu/10))/1000\n pin_dbm = cxa.marker_y()\n pout_watts = (10 ** (pin_dbm/10))/1000\n p_dissipated = pow_sens_in_watts - (pow_refl_watts + pout_watts)\n freq_in = cxa.marker_x()\n print(pin_dbm, freq_in, pow_sens_in)\n rsp_array.append([freq_start, pow_sens_in, pin_dbm, pow_sens_circu, out_min, pin_dbm - out_min,\n pow_sens_in - out_min, pow_sens_in - pin_dbm, ps.read_cal(1), ps.read_cal(2),\n pow_sens_in_watts, pout_watts, pow_refl_watts, p_dissipated])\n out_min += out_step\n psg.rf_off()\n sleep(wait_response)\n if not single_excel:\n test_results.append(rsp_array)\n # safety needs to be added to the close method.\n psg.set_power(-40)\n psg.close()\n cxa.close()\n ps.close()\n if single_excel:\n test_results = rsp_array\n return test_results\n\n\ndef sweep(freq_start=1, freq_stop=12, step=1):\n \"\"\"\n Returns list of frequencies with specified parameters.\n :param freq_start:\n :param freq_stop:\n :param step:\n :return:\n \"\"\"\n freqs = []\n while freq_start <= freq_stop:\n freqs.append(freq_start)\n freq_start = round(freq_start + round(step, 1), 1)\n return freqs\n\n\ndef save_csv(timestamp, prefix, data):\n \"\"\"\n Creates csv files with a list of arrays, using timestamp creates a unique directory.\n :param timestamp:\n :param name:\n :param data:\n :return: True\n \"\"\"\n if not data or not isinstance(data, list):\n print(\"Data in wrong format\")\n return False\n # Create directory\n pathlib.Path(str(timestamp)).mkdir(exist_ok=True)\n # Write CSV file\n for index, rows in enumerate(data):\n file_name = timestamp + '/' + str(prefix) + '_' + timestamp \\\n + '_' + str(index) + '.csv'\n with open(file_name, 'w', newline='') as results:\n csvw = csv.writer(results, delimiter=',')\n csvw.writerows(rows)\n\n\nif __name__ == '__main__':\n frequencies = sweep(1, 12, 1)\n print(frequencies)\n # TIMESTAMP = datetime.now().strftime(\"%Y%m%d_%H%M\")\n # NAME = 'all_freqs'\n # # data = [[[3, 2, 1], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]\n # run_pout_pin_test([1, 1.227, 1.575])\n # save_csv('output_test', NAME, data)\n\n","sub_path":"Capstone/JosueExamples/test_limi.py","file_name":"test_limi.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"221165116","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom collections import Counter\nfrom copy import deepcopy\nfrom decimal import Decimal\nfrom random import choice\nfrom time import time\n\nfrom typing import Callable\nfrom typing import Iterable\nfrom typing import List\n\nfrom stvpoll.exceptions import BallotException\nfrom stvpoll.exceptions import CandidateDoesNotExist\nfrom stvpoll.exceptions import IncompleteResult\nfrom stvpoll.exceptions import STVException\n\n\ndef _minmax(iterable, key=None, lowest=False):\n method = lowest and min or max\n return method(iterable, key=key)\n\n\nclass PreferenceBallot(object):\n def __init__(self, preferences, count):\n # type: (List[Candidate],int) -> None\n self.preferences = preferences\n self.count = count\n self.multiplier = Decimal(1)\n\n @property\n def value(self):\n return self.multiplier * self.count\n\n def decrease_value(self, multiplier):\n self.multiplier *= multiplier\n\n @property\n def current_preference(self):\n try:\n return self.preferences[0]\n except IndexError:\n pass\n\n @property\n def exhausted(self):\n return len(self.preferences) == 0\n\n def get_transfer_preference(self, standing_candidates):\n while not self.exhausted:\n self.preferences.pop(0)\n if self.current_preference in standing_candidates:\n return self.current_preference\n\n\nclass Candidate(object):\n EXCLUDED = 0\n HOPEFUL = 1\n ELECTED = 2\n status = HOPEFUL\n votes = Decimal(0)\n votes_transferred = False\n\n def __init__(self, obj):\n # type: (object) -> None\n self.obj = obj\n\n def __repr__(self): # pragma: no coverage\n # type: () -> basestring\n return ''.format(str(self.obj))\n\n @property\n def standing(self):\n return self.status == self.HOPEFUL\n\n def __eq__(self, o):\n # type: (Candidate) -> bool\n if isinstance(o, Candidate):\n return self.obj == o.obj\n return self.obj == o\n\n def __hash__(self):\n # type: () -> int\n return self.obj.__hash__()\n\n\nclass ElectionRound(object):\n SELECTION_METHOD_DIRECT = 0\n SELECTION_METHOD_HISTORY = 1\n SELECTION_METHOD_RANDOM = 2\n SELECTION_METHOD_NO_COMPETITION = 3\n SELECTION_METHOD_CPO = 4\n SELECTION_METHODS = (\n 'Direct',\n 'Tiebreak (history)',\n 'Tiebreak (Random)',\n 'No competition left',\n 'Comparison of Pairs of Outcomes',\n )\n status = None\n selection_method = None\n\n def __init__(self, _id):\n # type: (int) -> None\n self._id = _id\n self.selected = []\n\n def status_display(self):\n # type: () -> basestring\n return self.status == Candidate.ELECTED and 'Elected' or 'Excluded'\n\n def select(self, candidate, votes, method, status):\n # type: (Candidate, List[Candidate], int, int) -> None\n self.selected.append(candidate)\n self.status = status\n self.votes = deepcopy(votes)\n self.selection_method = method\n\n @property\n def method_str(self):\n # type: () -> basestring\n if isinstance(self.selection_method, int):\n return self.SELECTION_METHODS[self.selection_method]\n\n def __repr__(self): # pragma: no coverage\n # type: () -> basestring\n return ''.format(\n self._id,\n self.status_display(),\n ', '.join([c.obj for c in self.selected]),\n self.selection_method and ' ({})'.format(self.method_str))\n\n def as_dict(self):\n # type: () -> dict\n return {\n 'status': self.status_display(),\n 'selected': tuple(s.obj for s in self.selected),\n 'method': self.method_str,\n 'vote_count': tuple({c.obj: c.votes} for c in self.votes),\n }\n\n\nclass ElectionResult(object):\n exhausted = Decimal(0)\n runtime = .0\n randomized = False\n empty_ballot_count = 0\n\n def __init__(self, poll):\n # type: (STVPollBase) -> None\n self.poll = poll\n self.rounds = []\n self.elected = []\n self.start_time = time()\n self.transfer_log = []\n\n def __repr__(self): # pragma: no coverage\n # type: () -> basestring\n return ''.format(len(self.rounds), ', '.join(map(str, self.elected)))\n\n def new_round(self):\n self.rounds.append(ElectionRound(\n _id=len(self.rounds)+1))\n\n def finish(self):\n self.runtime = time() - self.start_time\n\n @property\n def current_round(self):\n # type: () -> ElectionRound\n return self.rounds[-1]\n\n def select(self, candidate, votes, method, status=Candidate.ELECTED):\n # type: (Candidate, List[Candidate], int, int) -> None\n candidate.status = status\n if status == Candidate.ELECTED:\n self.elected.append(candidate)\n self.current_round.select(candidate, votes, method, status)\n\n @property\n def complete(self):\n # type: () -> bool\n return len(self.elected) == self.poll.seats\n\n def elected_as_tuple(self):\n # type: () -> tuple\n return tuple(map(lambda x: x.obj, self.elected))\n\n def elected_as_set(self):\n # type: () -> set\n return set(self.elected_as_tuple())\n\n def as_dict(self):\n # type: () -> dict\n return {\n 'winners': self.elected_as_tuple(),\n 'candidates': tuple([c.obj for c in self.poll.candidates]),\n 'complete': self.complete,\n 'rounds': tuple([r.as_dict() for r in self.rounds]),\n 'randomized': self.randomized,\n 'quota': self.poll.quota,\n 'runtime': self.runtime,\n 'empty_ballot_count': self.empty_ballot_count,\n }\n\n\nclass STVPollBase(object):\n _quota = None\n\n def __init__(self, seats, candidates, quota=None, random_in_tiebreaks=True):\n # type: (int, Iterable, Callable, bool) -> None\n self.candidates = [Candidate(c) for c in candidates]\n self.ballots = []\n self._quota_function = quota\n self.seats = seats\n self.errors = []\n self.random_in_tiebreaks = random_in_tiebreaks\n self.result = ElectionResult(self)\n if len(self.candidates) < self.seats:\n raise STVException('Not enough candidates to fill seats')\n\n def get_existing_candidate(self, obj):\n # type: (object) -> Candidate\n for candidate in self.candidates:\n if candidate == obj:\n return candidate\n raise CandidateDoesNotExist()\n\n @property\n def quota(self):\n # type: () -> int\n if not self._quota:\n self._quota = self._quota_function(self)\n return self._quota\n\n @property\n def ballot_count(self):\n # type: () -> int\n return sum([b.count for b in self.ballots])\n\n def add_ballot(self, ballot, num=1):\n # type: (List, int) -> None\n candidates = []\n for obj in ballot:\n candidates.append(self.get_existing_candidate(obj))\n\n # Empty votes will not affect quota, but will be accounted for in result.\n if candidates:\n self.ballots.append(PreferenceBallot(candidates, num))\n else:\n self.result.empty_ballot_count += num\n\n def get_candidate(self, most_votes=True, sample=None):\n # type: (bool, List(Candidate)) -> (Candidate, int)\n if sample is None:\n sample = self.standing_candidates\n candidate = _minmax(sample, key=lambda c: c.votes, lowest=not most_votes)\n ties = self.get_ties(candidate)\n if ties:\n return self.resolve_tie(ties, most_votes)\n return candidate, ElectionRound.SELECTION_METHOD_DIRECT\n\n def choice(self, candidates):\n if self.random_in_tiebreaks:\n self.result.randomized = True\n return choice(candidates)\n raise IncompleteResult('Unresolved tiebreak (random disallowed)')\n\n def resolve_tie(self, candidates, most_votes=True):\n # type: (List[Candidate], bool) -> (Candidate, int)\n for stage in self.result.transfer_log[::-1]:\n stage_votes = [v for v in stage['current_votes'] if v in candidates]\n primary_candidate = _minmax(stage_votes, key=lambda c: c.votes, lowest=not most_votes)\n ties = self.get_ties(primary_candidate, stage_votes)\n if ties:\n candidates = [c for c in candidates if c in ties]\n else:\n winner = candidates[candidates.index(primary_candidate)] # Get correct Candidate instance\n return winner, ElectionRound.SELECTION_METHOD_HISTORY\n return self.choice(candidates), ElectionRound.SELECTION_METHOD_RANDOM\n\n def transfer_votes(self, candidate, transfer_quota=Decimal(1)):\n # type: (Candidate, Decimal) -> None\n transfers = Counter()\n for ballot in self.ballots:\n if candidate == ballot.current_preference:\n ballot.decrease_value(transfer_quota)\n target_candidate = ballot.get_transfer_preference(self.standing_candidates)\n if target_candidate:\n target_candidate.votes += ballot.value\n transfers[(candidate, target_candidate)] += ballot.value\n else:\n self.result.exhausted += ballot.value\n\n self.result.transfer_log.append({\n 'transfers': transfers,\n 'current_votes': self.current_votes,\n 'exhausted_votes': self.result.exhausted,\n })\n candidate.votes_transferred = True\n\n def initial_votes(self):\n # type () -> None\n for ballot in self.ballots:\n assert ballot.current_preference, 'Initial votes called with an empty vote'\n ballot.current_preference.votes += ballot.value\n\n self.result.transfer_log.append({\n 'transfers': None,\n 'current_votes': self.current_votes,\n 'exhausted_votes': self.result.exhausted,\n })\n\n def get_ties(self, candidate, sample=None):\n # type (Candidate, List[Candidate]) -> List[Candidate]\n if not sample:\n sample = self.standing_candidates\n ties = [c for c in sample if c.votes == candidate.votes]\n if len(ties) > 1:\n return ties\n\n @property\n def standing_candidates(self):\n # type: () -> List[Candidate]\n return [c for c in self.candidates if c.standing]\n\n @property\n def current_votes(self):\n # type: () -> List[Candidate]\n return deepcopy(self.standing_candidates)\n\n @property\n def seats_to_fill(self):\n # type () -> int\n return self.seats - len(self.result.elected)\n\n @property\n def complete(self):\n # type: () -> bool\n return self.result.complete\n\n def select(self, candidate, method, status=Candidate.ELECTED):\n # type: (Candidate, int, int) -> None\n self.result.new_round()\n self.result.select(candidate, self.standing_candidates, method, status)\n\n def select_multiple(self, candidates, method, status=Candidate.ELECTED, resolve_ties=False):\n # type: (List[Candidate], int, int) -> None\n if candidates:\n self.result.new_round()\n while candidates:\n # Select candidates in order. If requested, resolve ties.\n index = 0\n _method = method\n if resolve_ties:\n candidate, _method = self.get_candidate(\n most_votes=status == Candidate.ELECTED,\n sample=candidates)\n index = candidates.index(candidate)\n\n self.result.select(\n candidates.pop(index),\n self.standing_candidates,\n _method, status)\n\n def calculate(self):\n # type: () -> ElectionResult\n # if not self.ballots: # pragma: no coverage\n # raise STVException('No ballots registered.')\n self.initial_votes()\n try:\n self.do_rounds()\n except IncompleteResult:\n pass\n self.result.finish()\n return self.result\n\n def do_rounds(self):\n # type: () -> None\n while self.seats_to_fill:\n self.calculate_round()\n\n def calculate_round(self): # pragma: no coverage\n # type: (int) -> None\n raise NotImplementedError()\n","sub_path":"stvpoll/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"361694036","text":"from confluent_kafka import Consumer, KafkaError\nimport logging\nimport traceback\nimport time\nfrom pyhive import hive\nimport threading\nfrom concurrent.futures import ThreadPoolExecutor, wait\nimport string\n\nlogdir = \"/tmp\"\nfiledir = \"/home/liupeng/logindata\"\n\nhandler = logging.FileHandler(logdir + '/kafka-to-file.log', encoding='UTF-8')\nlogging_format = logging.Formatter(\n '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')\nlogger = logging.getLogger(__name__)\nhandler.setFormatter(logging_format)\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(handler)\n\n\ndef writeToFile(topic, msg):\n # print(\"topic: {}, message:{}\".format(msg.topic(), msg.value()))\n cols = msg.value().decode().split(\"|\")\n filedate = cols[-1].split()[0]\n # print(\"mesage date: {}\".format(filedate))\n sequence = (topic, filedate, \"txt\")\n filename = \".\".join(sequence)\n try:\n with open(filedir + '/' + filename, \"a\") as myfile:\n myfile.write(msg.value().decode())\n myfile.write(\"\\n\")\n except Exception as e:\n logger.exception(traceback.format_exc())\n print(e)\n\n\ndef consume(topic):\n\n try:\n\n c = Consumer({\n 'bootstrap.servers': '10.158.61.170:9092,10.158.61.171:9092,10.158.61.90:9092,10.158.61.95:9092',\n 'group.id': 'python-to-file',\n 'auto.offset.reset': 'earliest'\n })\n c.subscribe([topic])\n\n while True:\n msg = c.poll(1.0)\n\n if msg is None:\n continue\n if msg.error():\n logger.info(\"Consumer error: {}\".format(msg.error()))\n continue\n\n writeToFile(topic, msg)\n\n except Exception as e:\n logger.exception(traceback.format_exc())\n print(e)\n finally:\n c.close()\n\n\nexecutor = ThreadPoolExecutor(4)\nfs = []\nfor i, v in enumerate(['login-receive', 'login-response', 'verify-receive', 'verify-response']):\n fs.append(executor.submit(consume, v))\n\nwait(fs)\n\nexecutor.shutdown()\n","sub_path":"python/bigdata/kafka-to-file.py","file_name":"kafka-to-file.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"237197492","text":"__author__ = 'Jakehp'\nfrom random import randint\nimport qkPhoton\nimport qkCommChannel\nimport qkComm\n\n#will extend qkComm in the future\n#Receivers *cannot* access any photons - except via measurement\nclass qkReceiver(qkComm.qkComm):\n\n PHOTON_PULSE_SIZE = 128\n MIN_REQ_OF_SHARED = 25\n\n def __init__(self):\n self.recordedPolarizations = []\n self.randomBasis = []\n self.otherBasis = []\n self.sharedKey = []\n self.subSharedKey = []\n self.decision = -1\n self.otherDecision = -1\n self.validKey = -1\n\n #Computes random basis's for randomBasis list\n def setRandomBasis(self):\n self.randomBasis.clear()\n i = 0\n while i < self.PHOTON_PULSE_SIZE:\n x = randint(0, 1)\n if x == 0:\n self.randomBasis.append(\"R\")\n else:\n self.randomBasis.append(\"D\")\n i += 1\n return\n\n #Simply exists for ease of understanding\n def receive(self, arg1):\n self.measurePolarizations(arg1)\n return\n\n #Measure and record all polarizations from photon pulse in the comm channel\n def measurePolarizations(self, insecureCommChannel):\n assert isinstance(insecureCommChannel, qkCommChannel.qkCommChannel), 'Invalid Arg'\n if len(insecureCommChannel.photonPulse) != self.PHOTON_PULSE_SIZE:\n print(\"CommChannel has no photons for receiver || CommChannel # of pulses != receivers photon_pulse_size\")\n return -1\n self.setRandomBasis()\n i = 0\n while i < self.PHOTON_PULSE_SIZE:\n tempPho = insecureCommChannel.photonPulse[i]\n assert isinstance(tempPho, qkPhoton.qkPhoton), 'Not a qkPhoton object - Error'\n self.recordedPolarizations.append(tempPho.measure(self.randomBasis[i]))\n i += 1\n insecureCommChannel.photonPulse.clear()\n return\n\n #Prints All Data\n def printAll(self):\n print(\"qkReceiver recordedPolars: \", self.recordedPolarizations)\n print(\"qkReceiver Random Basis: \", self.randomBasis)\n print(\"Sender's Basis: \", self.otherBasis)\n print(\"qkReceiver's sharedKey: \", self.sharedKey)\n print(\"qkReceiver's subSharedKey: \", self.subSharedKey)\n\n #Prints Lengths Of Data\n def printDetails(self):\n print(\"qkSender Photon Polarizations: \", len(self.recordedPolarizations))\n print(\"qkSender Random Basis: \", len(self.randomBasis))\n print(\"Receiver's Basis: \", len(self.otherBasis))","sub_path":"qkReceiver.py","file_name":"qkReceiver.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"26461080","text":"# -*- coding: utf-8 -*-\n###########################################################################################\n#\n# author:Qdodoo suifeng\n# module name for Qdodoo\n# Copyright (C) 2015 qdodoo Technology CO.,LTD. ().\n#\n###########################################################################################\n\nfrom openerp import models, _\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport calendar\nimport time\n\n\nclass qdodoo_account_asset(models.Model):\n \"\"\"\n 继承修改固定资产模块功能\n \"\"\"\n _inherit = 'account.asset.asset'\n\n # 生成折旧板中数据的时候,按照采购日期的下月初开始\n def compute_depreciation_board(self, cr, uid, ids, context=None):\n # 折旧板模型\n depreciation_lin_obj = self.pool.get('account.asset.depreciation.line')\n for asset in self.browse(cr, uid, ids, context=context):\n # 如果剩余价值为空,跳出循环\n if asset.value_residual == 0.0:\n continue\n # 查询是否有已登账的折旧板\n posted_depreciation_line_ids = depreciation_lin_obj.search(cr, uid, [('asset_id', '=', asset.id), ('move_check', '=', True)],order='depreciation_date desc')\n # 查询是否有未登账的折旧板\n old_depreciation_line_ids = depreciation_lin_obj.search(cr, uid, [('asset_id', '=', asset.id), ('move_id', '=', False)])\n # 删除未登账的明细\n if old_depreciation_line_ids:\n depreciation_lin_obj.unlink(cr, uid, old_depreciation_line_ids, context=context)\n # 获取剩余价格\n amount_to_depr = residual_amount = asset.value_residual\n # 如果是年限百分比\n if asset.prorata:\n depreciation_date = datetime.strptime(self._get_last_depreciation_date(cr, uid, [asset.id], context)[asset.id], '%Y-%m-%d')\n else:\n # depreciation_date = 1st January of purchase year\n purchase_date = datetime.strptime(asset.purchase_date, '%Y-%m-%d')\n #if we already have some previous validated entries, starting date isn't 1st January but last entry + method period\n if (len(posted_depreciation_line_ids)>0):\n last_depreciation_date = datetime.strptime(depreciation_lin_obj.browse(cr,uid,posted_depreciation_line_ids[0],context=context).depreciation_date, '%Y-%m-%d')\n depreciation_date = (last_depreciation_date+relativedelta(months=+asset.method_period))\n else:\n # -----odoo\n # depreciation_date = datetime(purchase_date.year, 1, 1)\n # ----suifeng\n if purchase_date.month == 12:\n depreciation_date = datetime(purchase_date.year+1, 1, 1)\n else:\n depreciation_date = datetime(purchase_date.year, purchase_date.month+1, 1)\n # -------\n # 获取年月日、时分秒\n day = depreciation_date.day\n month = depreciation_date.month\n year = depreciation_date.year\n total_days = (year % 4) and 365 or 366\n\n undone_dotation_number = self._compute_board_undone_dotation_nb(cr, uid, asset, depreciation_date, total_days, context=context)\n for x in range(len(posted_depreciation_line_ids), undone_dotation_number):\n i = x + 1\n amount = self._compute_board_amount(cr, uid, asset, i, residual_amount, amount_to_depr, undone_dotation_number, posted_depreciation_line_ids, total_days, depreciation_date, context=context)\n residual_amount -= amount\n vals = {\n 'amount': amount,\n 'asset_id': asset.id,\n 'sequence': i,\n 'name': str(asset.id) +'/' + str(i),\n 'remaining_value': residual_amount,\n 'depreciated_value': (asset.purchase_value - asset.salvage_value) - (residual_amount + amount),\n 'depreciation_date': depreciation_date.strftime('%Y-%m-%d'),\n }\n depreciation_lin_obj.create(cr, uid, vals, context=context)\n # Considering Depr. Period as months\n depreciation_date = (datetime(year, month, day) + relativedelta(months=+asset.method_period))\n day = depreciation_date.day\n month = depreciation_date.month\n year = depreciation_date.year\n return True\n\nclass qdodoo_account_asset_depreciation_line(models.Model):\n _inherit = 'account.asset.depreciation.line'\n\n # 修改生成会计凭证时日期为当月最后一天\n # 重新组织数据格式,合并生成凭证\n def create_move(self, cr, uid, ids, context=None):\n context = dict(context or {})\n asset_obj = self.pool.get('account.asset.asset')\n period_obj = self.pool.get('account.period')\n move_obj = self.pool.get('account.move')\n move_line_obj = self.pool.get('account.move.line')\n currency_obj = self.pool.get('res.currency')\n created_move_ids = []\n asset_ids = []\n # 组织数据\n all_dict = {} # {日期(账期):{分类账:{资产obj:[line_obj]}}}\n for line in self.browse(cr, uid, ids, context=context):\n depreciation_date = context.get('depreciation_date') or line.depreciation_date or time.strftime('%Y-%m-%d')\n depreciation_date = depreciation_date[:8] + str(calendar.monthrange(int(depreciation_date[:4]),int(depreciation_date[5:7]))[1])\n context.update({'date': depreciation_date})\n if depreciation_date in all_dict:\n if line.asset_id.category_id.journal_id in all_dict[depreciation_date]:\n if line.asset_id in all_dict[depreciation_date][line.asset_id.category_id.journal_id]:\n all_dict[depreciation_date][line.asset_id.category_id.journal_id][line.asset_id].append(line)\n else:\n all_dict[depreciation_date][line.asset_id.category_id.journal_id][line.asset_id] = [line]\n else:\n all_dict[depreciation_date][line.asset_id.category_id.journal_id] = {line.asset_id:[line]}\n else:\n all_dict[depreciation_date] = {line.asset_id.category_id.journal_id:{line.asset_id:[line]}}\n for key,value in all_dict.items():\n # 获取对应的账期\n period_ids = period_obj.find(cr, uid, key, context=context)\n for key1,value1 in value.items():\n # 根据账期、资产类别合并凭证明细\n journal_id = key1.id\n move_vals = {\n 'name': '/',\n 'date': key,\n 'ref': '合并凭证',\n 'period_id': period_ids and period_ids[0] or False,\n 'journal_id': journal_id,\n }\n move_id = move_obj.create(cr, uid, move_vals, context=context)\n sign = (key1.type == 'purchase' and 1) or -1\n for key2,value2 in value1.items():\n company_currency = key2.company_id.currency_id.id\n current_currency = key2.currency_id.id\n asset_name = key2.name\n for line_obj in value2:\n # 创建凭证明细行\n reference = line_obj.name\n amount = currency_obj.compute(cr, uid, current_currency, company_currency, line_obj.amount, context=context)\n move_line_obj.create(cr, uid, {\n 'name': asset_name,\n 'ref': reference,\n 'move_id': move_id,\n 'account_id': key2.category_id.account_depreciation_id.id,\n 'debit': 0.0,\n 'credit': amount,\n 'period_id': period_ids and period_ids[0] or False,\n 'journal_id': journal_id,\n 'currency_id': company_currency != current_currency and current_currency or False,\n 'amount_currency': company_currency != current_currency and - sign * line_obj.amount or 0.0,\n 'date': key,\n })\n move_line_obj.create(cr, uid, {\n 'name': asset_name,\n 'ref': reference,\n 'move_id': move_id,\n 'account_id': key2.category_id.account_expense_depreciation_id.id,\n 'credit': 0.0,\n 'debit': amount,\n 'period_id': period_ids and period_ids[0] or False,\n 'journal_id': journal_id,\n 'currency_id': company_currency != current_currency and current_currency or False,\n 'amount_currency': company_currency != current_currency and sign * line_obj.amount or 0.0,\n 'analytic_account_id': key2.department.id,\n 'date': key,\n 'asset_id': key2.id\n })\n self.write(cr, uid, line_obj.id, {'move_id': move_id}, context=context)\n asset_ids.append(key2.id)\n created_move_ids.append(move_id)\n\n # we re-evaluate the assets to determine whether we can close them\n for asset in asset_obj.browse(cr, uid, list(set(asset_ids)), context=context):\n if currency_obj.is_zero(cr, uid, asset.currency_id, asset.value_residual):\n asset.write({'state': 'close'})\n return created_move_ids","sub_path":"qdodoo_account_asset/qdodoo_account_asset.py","file_name":"qdodoo_account_asset.py","file_ext":"py","file_size_in_byte":10004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"560707689","text":"import argparse\nimport csv\nimport glob\nimport os\nimport shutil\nimport sys\n\nimport datasets\nimport torch.distributed as dist\nfrom typing import Callable, Dict, Tuple, Optional\nimport evaluate\nimport numpy as np\nimport torch\nfrom datasets import Dataset, load_dataset\nfrom peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training, PeftConfig, PeftModel, \\\n prepare_model_for_int8_training\nfrom transformers import AutoTokenizer, AutoModelForCausalLM, PreTrainedTokenizerBase, \\\n EvalPrediction, Seq2SeqTrainingArguments, DataCollatorForSeq2Seq, \\\n EarlyStoppingCallback, BitsAndBytesConfig, set_seed, AutoModelForSeq2SeqLM, Seq2SeqTrainer, GenerationConfig\nfrom transformers.trainer_utils import get_last_checkpoint\nfrom transformers.utils import logging\n\nfrom causlTrainer import CausalTrainer\n\n\n# region utils\n\ndef find_all_linear_names(model_id, bits=4):\n if bits == 4:\n bnb_config = BitsAndBytesConfig(\n load_in_4bit=True,\n # bnb_4bit_use_double_quant=True,\n bnb_4bit_quant_type=\"fp4\",\n bnb_4bit_compute_dtype=torch.bfloat16\n )\n else:\n bnb_config = None\n\n model_loading_args = {\n \"pretrained_model_name_or_path\": model_id,\n \"quantization_config\": bnb_config,\n \"cache_dir\": cache_dir,\n \"trust_remote_code\": True\n }\n\n model = AutoModelForCausalLM.from_pretrained(**model_loading_args)\n\n import bitsandbytes as bnb\n cls = bnb.nn.Linear4bit if bits == 4 else (bnb.nn.Linear8bitLt if bits == 8 else torch.nn.Linear)\n lora_module_names = set()\n for name, module in model.named_modules():\n if isinstance(module, cls):\n names = name.split('.')\n lora_module_names.add(names[0] if len(names) == 1 else names[-1])\n\n if 'lm_head' in lora_module_names: # needed for 16-bit\n lora_module_names.remove('lm_head')\n return list(lora_module_names)\n\n\ndef print_trainable_parameters(model):\n \"\"\"\n Prints the number of trainable parameters in the model.\n \"\"\"\n trainable_params = 0\n all_param = 0\n for _, param in model.named_parameters():\n all_param += param.numel()\n if param.requires_grad:\n trainable_params += param.numel()\n print(\n f\"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}\"\n )\n\n\ndef bytes_to_human_readable_str(size: int) -> str:\n \"\"\"\n Format a size (in bytes) for humans.\n Code taken from: https://github.com/allenai/allennlp/blob/main/allennlp/common/util.py\n \"\"\"\n GBs = size / (1024 * 1024 * 1024)\n if GBs >= 10:\n return f\"{int(round(GBs, 0))}G\"\n if GBs >= 1:\n return f\"{round(GBs, 1):.1f}G\"\n MBs = size / (1024 * 1024)\n if MBs >= 10:\n return f\"{int(round(MBs, 0))}M\"\n if MBs >= 1:\n return f\"{round(MBs, 1):.1f}M\"\n KBs = size / 1024\n if KBs >= 10:\n return f\"{int(round(KBs, 0))}K\"\n if KBs >= 1:\n return f\"{round(KBs, 1):.1f}K\"\n return f\"{size}B\"\n\n\ndef is_distributed() -> bool:\n \"\"\"\n Checks if the distributed process group is available and has been initialized\n Code taken from: https://github.com/allenai/allennlp/blob/main/allennlp/common/util.py\n \"\"\"\n return dist.is_available() and dist.is_initialized()\n\n\ndef peak_cpu_memory() -> Dict[str, str]:\n \"\"\"\n Get peak memory usage for each worker, as measured by max-resident-set size:\n https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size\n Only works on OSX and Linux, otherwise the result will be 0.0 for every worker.\n Code taken from: https://github.com/allenai/allennlp/blob/main/allennlp/common/util.py\n \"\"\"\n if sys.platform not in (\"linux\", \"darwin\"):\n peak_bytes = 0\n else:\n import resource\n peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n if sys.platform == \"darwin\":\n # On OSX the result is in bytes.\n peak_bytes = peak\n else:\n # On Linux the result is in kilobytes.\n peak_bytes = peak * 1_024\n\n if is_distributed():\n global_rank = dist.get_rank()\n world_size = dist.get_world_size()\n\n peak_bytes_tensor = torch.tensor([global_rank, peak_bytes])\n # All of these tensors will be gathered into this list.\n gather_results = [torch.tensor([0, 0]) for _ in range(world_size)]\n\n # If the backend is 'nccl', this means we're training on GPUs, so these tensors\n # need to be on GPU.\n if dist.get_backend() == \"nccl\":\n peak_bytes_tensor = peak_bytes_tensor.cuda()\n gather_results = [x.cuda() for x in gather_results]\n\n dist.all_gather(gather_results, peak_bytes_tensor)\n\n results_dict: Dict[int, int] = {}\n for peak_bytes_tensor in gather_results:\n results_dict[int(peak_bytes_tensor[0])] = int(peak_bytes_tensor[1])\n\n else:\n results_dict = {0: peak_bytes}\n\n formatted_results_dict = {}\n for cpu, memory in results_dict.items():\n formatted_results_dict[f'cpu_{cpu}_memory_usage'] = bytes_to_human_readable_str(memory)\n\n return formatted_results_dict\n\n\ndef peak_gpu_memory() -> Dict[str, str]:\n \"\"\"\n Get the peak GPU memory usage in bytes by device.\n # Returns\n `Dict[int, int]`\n Keys are device ids as integers.\n Values are memory usage as integers in bytes.\n Returns an empty `dict` if GPUs are not available.\n\n Code taken from: https://github.com/allenai/allennlp/blob/main/allennlp/common/util.py\n \"\"\"\n if not torch.cuda.is_available():\n return {}\n\n device = torch.cuda.current_device()\n\n results_dict: Dict[int, int] = {}\n if is_distributed():\n # If the backend is not 'nccl', we're training on CPU.\n if dist.get_backend() != \"nccl\":\n return {}\n\n global_rank = dist.get_rank()\n world_size = dist.get_world_size()\n peak_bytes = torch.cuda.max_memory_allocated(device)\n peak_bytes_tensor = torch.tensor([global_rank, peak_bytes], device=device)\n # All of these tensors will be gathered into this list.\n gather_results = [torch.tensor([0, 0], device=device) for _ in range(world_size)]\n\n dist.all_gather(gather_results, peak_bytes_tensor)\n\n for peak_bytes_tensor in gather_results:\n results_dict[int(peak_bytes_tensor[0])] = int(peak_bytes_tensor[1])\n else:\n results_dict = {0: torch.cuda.max_memory_allocated()}\n\n # Reset peak stats.\n torch.cuda.reset_max_memory_allocated(device)\n\n formatted_results_dict = {}\n for gpu, memory in results_dict.items():\n formatted_results_dict[f'gpu_{gpu}_memory_usage'] = bytes_to_human_readable_str(memory)\n\n return formatted_results_dict\n\n\ndef get_memory_metrics(split: str) -> Dict[str, str]:\n res = {}\n mem_metrics = peak_cpu_memory()\n mem_metrics.update(peak_gpu_memory())\n for k, v in mem_metrics.items():\n res[f'{split}_{k}'] = v\n return res\n\n\n# endregion\n\n# region dataset processing\ndef tokenize_dataset(examples: Dataset, tokenizer: PreTrainedTokenizerBase,\n text_column: str, label_column: str, max_length: int):\n batch_size = len(examples[text_column])\n model_inputs = {\n \"input_ids\": [],\n \"attention_mask\": [],\n \"labels\": []\n }\n\n tokenized_inputs = tokenizer(examples[text_column])\n with tokenizer.as_target_tokenizer():\n tokenized_labels = tokenizer(examples[label_column])\n\n for i in range(batch_size):\n tok_inpt_ids = tokenized_inputs['input_ids'][i]\n inpt_mask = tokenized_inputs['attention_mask'][i]\n tok_lbl_ids = tokenized_labels['input_ids'][i]\n\n if len(tok_inpt_ids) < max_length and len(tok_lbl_ids) < max_length:\n model_inputs['input_ids'].append(tok_inpt_ids)\n model_inputs['attention_mask'].append(inpt_mask)\n model_inputs['labels'].append(tok_lbl_ids)\n\n return model_inputs\n\n\ndef preprocess_dataset_for_causal_lm(examples: Dataset, tokenizer: PreTrainedTokenizerBase,\n text_column: str, label_column: str, max_length: int):\n if tokenizer.pad_token_id is None:\n tokenizer.pad_token_id = tokenizer.eos_token_id\n batch_size = len(examples[text_column])\n inputs = [f'{x}' for x in examples[text_column]]\n targets = [f'{x}' for x in examples[label_column]]\n tokenized_inputs = tokenizer(inputs)\n tokenized_labels = tokenizer(targets)\n\n model_inputs = {\n \"input_ids\": [],\n \"attention_mask\": [],\n \"labels\": []\n }\n for i in range(batch_size):\n sample_input_ids = tokenized_inputs[\"input_ids\"][i]\n # happens in xglm for some reason\n if sample_input_ids[0] == tokenizer.eos_token_id:\n sample_input_ids = sample_input_ids[1:]\n\n label_input_ids = tokenized_labels[\"input_ids\"][i]\n if label_input_ids[0] == tokenizer.eos_token_id:\n label_input_ids = label_input_ids[1:]\n\n # The original code appended [tokenizer.pad_token_id], and gpt2 did converge with this. But bloom did not.\n # With [tokenizer.eos_token_id] it does, and it seems a more natural choice.\n # TODO: Why we add the padding? Is it suppose to be eos token?\n label_input_ids = label_input_ids + [tokenizer.eos_token_id] # [tokenizer.pad_token_id]\n # TODO: This is so the label and input will be differnet tokens. I think?\n\n if len(sample_input_ids + label_input_ids) < max_length:\n inpt = sample_input_ids + label_input_ids\n model_inputs[\"input_ids\"].append(inpt)\n model_inputs[\"attention_mask\"].append([1] * len(inpt))\n model_inputs[\"labels\"].append([-100] * len(sample_input_ids) + label_input_ids)\n return model_inputs\n\n\n# endregion\n\n\ndef get_eval_func(tokenizer: PreTrainedTokenizerBase, metric_id: str) -> Callable:\n def eval_func(eval_preds: EvalPrediction):\n preds = eval_preds.predictions\n labels = eval_preds.label_ids\n preds = np.where(preds != -100, preds, tokenizer.pad_token_id)\n decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)\n labels = np.where(labels != -100, labels, tokenizer.pad_token_id)\n decoded_labels = tokenizer.batch_decode(labels.tolist(), skip_special_tokens=True)\n metric = evaluate.load(metric_id)\n res = metric.compute(references=decoded_labels, predictions=decoded_preds)\n\n logger = logging.get_logger()\n logger.debug(f'_debug_ decoded labels: \\n{decoded_labels}\\n')\n logger.debug(f'_debug_ decoded preds: \\n{decoded_preds}\\n')\n\n memory_metrics = get_memory_metrics('train')\n res.update(memory_metrics)\n\n return res\n\n return eval_func\n\n\ndef _delete_checkpoints(output_dir: str):\n logger = logging.get_logger()\n checkpoint_files = glob.glob(f'{output_dir}/checkpoint*/*')\n for f in checkpoint_files:\n logger.warning(f'deleting file {f}!')\n if not f.endswith(\"json\"):\n os.remove(f)\n\n\ndef train_model(model_id: str,\n is_seq2seq_model: bool,\n train_dataset: Dataset,\n eval_dataset: Optional[Dataset],\n test_dataset: Optional[Dataset],\n max_length: int,\n output_dir: str,\n train_in_4_bit: bool,\n train_in_8_bit: bool,\n train_with_lora: bool,\n cache_dir: str\n ):\n # TODO: revisit\n if eval_dataset and len(eval_dataset) > 200:\n eval_dataset = eval_dataset.select(range(200))\n\n logger = logging.get_logger()\n device = torch.device(\"mps\" if torch.backends.mps.is_available() else 0 if torch.cuda.is_available() else \"cpu\")\n\n logger.debug(f'_debug_ device: {device}')\n\n if train_in_4_bit:\n assert train_with_lora\n assert not train_in_8_bit\n\n # region tokenizer and dataset preparation\n tokenizer = AutoTokenizer.from_pretrained(model_id, cache_dir=cache_dir)\n tokenizer.bos_token_id = 1\n if tokenizer.pad_token_id is None:\n tokenizer.pad_token_id = tokenizer.eos_token_id\n\n if is_seq2seq_model:\n preprocess_func = tokenize_dataset\n else:\n preprocess_func = preprocess_dataset_for_causal_lm\n\n train_dataset = train_dataset.map(\n lambda examples: preprocess_func(examples, tokenizer, \"text\", \"label\", max_length),\n batched=True, remove_columns=train_dataset.column_names)\n if eval_dataset:\n eval_dataset = eval_dataset.map(\n lambda examples: preprocess_func(examples, tokenizer, \"text\", \"label\", max_length),\n batched=True, remove_columns=eval_dataset.column_names)\n if test_dataset:\n test_dataset = test_dataset.map(\n lambda examples: preprocess_func(examples, tokenizer, \"text\", \"label\", max_length),\n batched=True, remove_columns=test_dataset.column_names)\n\n # endregion\n\n # region model preparation\n if train_in_4_bit:\n bnb_config = BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_use_double_quant=True,\n bnb_4bit_quant_type=\"fp4\",\n bnb_4bit_compute_dtype=torch.bfloat16\n )\n else:\n bnb_config = None\n\n model_loading_args = {\n \"pretrained_model_name_or_path\": model_id,\n \"quantization_config\": bnb_config,\n \"cache_dir\": cache_dir,\n \"trust_remote_code\": True,\n # \"torch_dtype\": torch.bfloat16 if (train_in_4_bit or train_in_8_bit) else None,\n # \"load_in_8bit\": train_in_8_bit,\n # \"device_map\": \"auto\"\n }\n\n if is_seq2seq_model:\n model = AutoModelForSeq2SeqLM.from_pretrained(**model_loading_args)\n else:\n model = AutoModelForCausalLM.from_pretrained(**model_loading_args)\n\n if train_in_4_bit or train_in_8_bit:\n model.gradient_checkpointing_enable()\n model = prepare_model_for_kbit_training(model)\n\n if train_with_lora:\n task_type = TaskType.SEQ_2_SEQ_LM if is_seq2seq_model else TaskType.CAUSAL_LM\n\n config = LoraConfig(\n r=16,\n lora_alpha=32,\n target_modules=[\"q_proj\", \"v_proj\"] if \"xglm\" in model_id else None,\n lora_dropout=0.05,\n bias=\"none\",\n task_type=task_type\n )\n\n model = get_peft_model(model, config)\n print_trainable_parameters(model)\n\n # endregion\n\n model.config.use_cache = False # silence the warnings. Please re-enable for inference!\n\n data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer,\n model=model,\n padding=True,\n label_pad_token_id=tokenizer.eos_token_id if is_seq2seq_model else -100\n )\n\n training_args = Seq2SeqTrainingArguments(\n output_dir=output_dir,\n num_train_epochs=5 if train_in_8_bit else 20,\n per_device_train_batch_size= 1 if train_in_8_bit else 4, # if \"base\" in model_id else 1,\n per_device_eval_batch_size= 1 if train_in_8_bit else 4, # if \"base\" in model_id else 1,\n\n logging_strategy='steps',\n evaluation_strategy='steps' if eval_dataset else \"no\",\n save_strategy='steps',\n logging_steps=500,\n save_total_limit=2,\n load_best_model_at_end=eval_dataset is not None,\n metric_for_best_model=\"exact_match\" if eval_dataset else None,\n\n predict_with_generate=True,\n generation_max_length=max_length + 10,\n generation_num_beams=1,\n\n # TODO: Why we cannot do fp16 with Lora? (The loss is 0)\n fp16=device != \"mps\",\n gradient_accumulation_steps=16 if train_in_8_bit else 4, # if \"base\" in model_id else 16,\n eval_accumulation_steps=1,\n optim=\"paged_adamw_8bit\" if (train_in_4_bit or train_in_8_bit) else \"adamw_hf\",\n lr_scheduler_type=\"linear\",\n learning_rate=2e-4,\n warmup_steps=2,\n use_mps_device=device.type == \"mps\",\n report_to=\"none\"\n )\n\n trainer_cls = Seq2SeqTrainer if is_seq2seq_model else CausalTrainer\n trainer = trainer_cls(\n model=model,\n args=training_args,\n train_dataset=train_dataset,\n eval_dataset=eval_dataset,\n tokenizer=tokenizer,\n data_collator=data_collator,\n compute_metrics=get_eval_func(tokenizer, \"exact_match\"),\n callbacks=[EarlyStoppingCallback(early_stopping_patience=5)] if eval_dataset and not train_in_4_bit else [],\n )\n\n checkpoint = get_last_checkpoint(output_dir)\n if checkpoint is not None:\n logger.info(f'_debug_ Resuming training from checkpoint: {checkpoint}')\n train_result = trainer.train(resume_from_checkpoint=checkpoint)\n\n # this needs to be before the save_metrics. As otherwise it will overwrite them\n trainer.save_model()\n trainer.save_state()\n\n metrics = train_result.metrics\n metrics.update(get_memory_metrics('train'))\n\n if test_dataset:\n test_metrics = trainer.evaluate(test_dataset, metric_key_prefix=\"test\")\n metrics.update(test_metrics)\n\n # TODO: Why do we need that?\n trainer.log_metrics(\"train\", metrics)\n trainer.save_metrics(\"train\", metrics)\n\n # TODO: Why do we need that? It saves the best model and so we can delete the checkpoint\n # trainer.save_model() # Saves the tokenizer too for easy upload\n # TODO: Why do we need that?\n\n _delete_checkpoints(output_dir)\n\n\ndef evaluate_model(model_id: str,\n is_seq2seq_model: bool,\n eval_dataset: Dataset,\n max_length: int,\n label: str,\n output_dir: str,\n train_in_4_bit: bool,\n train_with_lora: bool,\n cache_dir: str,\n ):\n device = torch.device(\"mps\" if torch.backends.mps.is_available() else 0 if torch.cuda.is_available() else \"cpu\")\n logger = logging.get_logger()\n # region model preparation\n if train_in_4_bit:\n assert train_with_lora\n\n # TODO: remove in the future and just save the best model to the main dir\n # model_id = get_last_checkpoint(model_id)\n # assert model_id is not None\n\n if train_with_lora:\n peft_model_name_or_path = model_id\n peft_config = PeftConfig.from_pretrained(peft_model_name_or_path)\n model_id = peft_config.base_model_name_or_path\n\n if train_in_4_bit:\n bnb_config = BitsAndBytesConfig(\n load_in_4bit=True,\n # bnb_4bit_use_double_quant=True,\n bnb_4bit_quant_type=\"nf4\",\n bnb_4bit_compute_dtype=torch.bfloat16\n )\n else:\n bnb_config = None\n\n model_loading_args = {\n \"pretrained_model_name_or_path\": model_id,\n \"quantization_config\": bnb_config,\n \"cache_dir\": cache_dir,\n \"trust_remote_code\": True\n }\n\n if is_seq2seq_model:\n model = AutoModelForSeq2SeqLM.from_pretrained(**model_loading_args)\n else:\n model = AutoModelForCausalLM.from_pretrained(**model_loading_args)\n\n if train_with_lora:\n model = PeftModel.from_pretrained(model, peft_model_name_or_path)\n\n # endregion\n\n # region tokenizer and dataset preparation\n\n tokenizer = AutoTokenizer.from_pretrained(model_id, cache_dir=cache_dir)\n if tokenizer.pad_token_id is None:\n tokenizer.pad_token_id = tokenizer.eos_token_id\n\n if is_seq2seq_model:\n preprocess_func = tokenize_dataset\n else:\n preprocess_func = preprocess_dataset_for_causal_lm\n\n eval_dataset = eval_dataset.map(\n lambda examples: preprocess_func(examples, tokenizer, \"text\", \"label\", max_length),\n batched=True, remove_columns=eval_dataset.column_names)\n\n # endregion\n\n data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer,\n model=model,\n padding=True,\n # label_pad_token_id=tokenizer.eos_token_id,\n label_pad_token_id=-100)\n\n training_args = Seq2SeqTrainingArguments(\n output_dir=output_dir,\n per_device_eval_batch_size=4,\n predict_with_generate=True,\n generation_max_length=max_length + 10,\n # TODO: Why we cannot do fp16 with Lora? (The loss is 0)\n # fp16=device != \"mps\",\n eval_accumulation_steps=1,\n use_mps_device=device.type == \"mps\",\n report_to=\"none\"\n )\n\n trainer_cls = Seq2SeqTrainer if is_seq2seq_model else CausalTrainer\n trainer = trainer_cls(\n model=model,\n args=training_args,\n eval_dataset=eval_dataset,\n tokenizer=tokenizer,\n data_collator=data_collator,\n compute_metrics=get_eval_func(tokenizer, \"exact_match\")\n )\n\n pred_output = trainer.predict(eval_dataset)\n metrics = pred_output.metrics\n metrics.update(get_memory_metrics(f'test_{label}'))\n\n predictions = pred_output.predictions\n # decoded_predictions = tokenizer.batch_decode(predictions, skip_special_tokens=True)\n # logger.info(decoded_predictions)\n\n # TODO: Why do we need that?\n trainer.log_metrics(f'test_{label}', metrics)\n trainer.save_metrics(f'test_{label}', metrics)\n\n\n# region dataset loading\ndef load_mtop_dataset(dataset_path: str, add_instruction: bool):\n with open(dataset_path, \"r\", encoding='utf-8') as f:\n rows = list(csv.reader(f, delimiter='\\t', quoting=csv.QUOTE_MINIMAL))\n dataset_dict = {\n \"text\": [f'Parse the following sentence: {r[0]} Answer: ' if add_instruction else r[0] for r in rows],\n \"label\": [r[1] for r in rows]\n }\n ds = Dataset.from_dict(dataset_dict)\n return ds\n\n\ndef load_nli_dataset(dataset_path: str, add_instruction: bool):\n def get_prompt(premise: str, hypothesis: str) -> str:\n prompt_str = f'Premise: {premise}\\n\\n' \\\n f'Hypothesis: {hypothesis}\\n\\n' \\\n f'Label: '\n if add_instruction:\n instruct_str = f'In the Natural Language Inference (NLI) task, given a premise and an hypothesis, ' \\\n f'the goal is to determine the logical relationship between the premise and the hypothesis. ' \\\n f'Please label the logical relationship between the premise and the hypothesis as ' \\\n f'either \"entailment\", \"contradiction\", or \"neutral\".\\n\\n'\n prompt_str = f'{instruct_str}{prompt_str}'\n return prompt_str\n\n label_id_to_str = {\n 0: \"entailment\",\n 1: \"neutral\",\n 2: \"contradiction\"\n }\n\n dataset = datasets.load_dataset(\"csv\", data_files=dataset_path)['train']\n\n dataset = dataset.map(\n lambda x: {\n \"text\": [get_prompt(premise, hypothesis) for premise, hypothesis in zip(x[\"premise\"], x[\"hypothesis\"])],\n \"label\": [label_id_to_str[label] for label in x[\"label\"]]},\n batched=True,\n num_proc=1, remove_columns=[\"premise\", \"hypothesis\"]\n )\n\n return dataset\n\n\n# endregion\n\ndef debug_run(model_id: str, is_seq2seq: bool, cache_dir: str):\n dataset_name = \"cardiffnlp/tweet_sentiment_multilingual\"\n dataset = load_dataset(dataset_name, \"english\")\n classes = [k.replace(\"_\", \" \") for k in dataset[\"train\"].features[\"label\"].names]\n dataset = dataset.rename_column(\"label\", \"temp\")\n dataset = dataset.map(\n lambda x: {\"label\": [classes[label] for label in x[\"temp\"]]},\n batched=True,\n num_proc=1,\n )\n train_dataset = dataset['train'].select(range(1000))\n dev_dataset = dataset['train'].select(range(1000))\n\n output_dir = \"hf_try_temp\"\n\n train_model(model_id,\n is_seq2seq,\n train_dataset,\n dev_dataset,\n output_dir,\n train_with_lora=True,\n train_in_4_bit=False,\n cache_dir=cache_dir)\n\n exit()\n\n\ndef load_custom_dataset(dataset_path: str, add_instruction: bool):\n if \"mtop\" in dataset_path:\n dataset = load_mtop_dataset(dataset_path, add_instruction)\n elif \"xnli\" in dataset_path:\n dataset = load_nli_dataset(dataset_path, add_instruction)\n elif \"amazon\" in dataset_path:\n dataset = datasets.load_dataset(\"csv\", data_files=dataset_path)['train']\n else:\n raise NotImplementedError(dataset_path)\n\n return dataset\n\n\ndef train_model_sub_command(args):\n set_seed(args.seed)\n\n model_id = args.model_id\n assert model_id in (model_list_seq2seq + model_list_causal)\n is_seq2seq_model = model_id in model_list_seq2seq\n\n train_dataset = load_custom_dataset(args.train_dataset_path, args.add_instruction)\n eval_dataset = load_custom_dataset(args.eval_dataset_path, args.add_instruction) if args.eval_dataset_path else None\n test_dataset = load_custom_dataset(args.test_dataset_path, args.add_instruction) if args.test_dataset_path else None\n\n logger.info(f'\\n\\n!!!!!!!!!! Training model !!!!!!!!!!\\n\\n'\n f'{args}\\n\\n'\n f'!!!!!!!!!!!!!!!!!\\n\\n')\n\n train_model(model_id=model_id,\n is_seq2seq_model=is_seq2seq_model,\n train_dataset=train_dataset,\n eval_dataset=eval_dataset,\n test_dataset=test_dataset,\n max_length=args.max_length,\n output_dir=args.output_dir,\n train_with_lora=args.lora,\n train_in_4_bit=args.qlora,\n train_in_8_bit=args.train_8_bits,\n cache_dir=cache_dir,\n )\n\n\ndef evaluate_model_sub_command(args):\n eval_dataset = load_custom_dataset(args.eval_dataset_path, args.add_instruction)\n label = f'{os.path.basename(args.eval_dataset_path)}'\n\n logger.info(f'\\n\\n!!!!!!!!!! Evaluating model !!!!!!!!!!\\n\\n'\n f'{args}\\n\\n'\n f'!!!!!!!!!!!!!!!!!\\n\\n')\n\n evaluate_model(model_id=args.model_id,\n is_seq2seq_model=args.seq2seq,\n eval_dataset=eval_dataset,\n max_length=args.max_length,\n label=label,\n output_dir=args.output_dir,\n train_with_lora=args.lora,\n train_in_4_bit=args.qlora,\n cache_dir=cache_dir)\n\n\nif __name__ == '__main__':\n logger = logging.get_logger()\n logger.setLevel(logging.INFO)\n\n if os.path.exists('/dccstor'):\n cache_dir = '/dccstor/gmc/users/ofir.arviv/transformers_cache'\n if os.path.exists('/cs/labs/oabend'):\n cache_dir = '/cs/labs/oabend/ofir.arviv/transformers_cache'\n else:\n cache_dir = None\n\n\n # region argparser\n\n def add_common_args(input_parser):\n input_parser.add_argument('--model-id', required=True, type=str)\n input_parser.add_argument('--output-dir', required=True, type=str)\n input_parser.add_argument(\"--lora\", action=\"store_true\", default=False)\n input_parser.add_argument(\"--qlora\", action=\"store_true\", default=False)\n input_parser.add_argument(\"--train-8-bits\", action=\"store_true\", default=False)\n input_parser.add_argument(\"--add-instruction\", action=\"store_true\", default=False)\n input_parser.add_argument('--max-length', required=False, type=int, default=1024)\n input_parser.add_argument('--cache-dir', required=False, type=str, default=None)\n\n\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers(help='sub-command help')\n # region Train argparser\n parser_train = subparsers.add_parser('train')\n parser_train.set_defaults(which='train')\n parser_train.add_argument('--train-dataset-path', required=True, type=str)\n parser_train.add_argument('--eval-dataset-path', required=False, type=str)\n parser_train.add_argument('--test-dataset-path', required=False, type=str)\n parser_train.add_argument('--seed', required=True, type=int)\n add_common_args(parser_train)\n # endregion\n\n # region Eval argparser\n parser_eval = subparsers.add_parser('evaluate')\n parser_eval.set_defaults(which='evaluate')\n parser_eval.add_argument('--eval-dataset-path', required=True, type=str)\n parser_eval.add_argument('--seq2seq', action=\"store_true\", default=False)\n add_common_args(parser_eval)\n\n # endregion\n args = parser.parse_args()\n\n model_list_causal = [\"decapoda-research/llama-65b-hf\",\n \"facebook/xglm-7.5B\",\n \"facebook/xglm-564M\",\n \"bigscience/bloom-7b1\",\n \"facebook/xglm-564M\"\n \"tiiuae/falcon-7b-instruct\"]\n model_list_seq2seq = [\"google/flan-t5-xxl\",\n \"google/mt5-base\",\n \"google/flan-ul2\"]\n\n if args.which == \"train\":\n train_model_sub_command(args)\n\n if args.which == \"evaluate\":\n evaluate_model_sub_command(args)\n","sub_path":"experiments/hugginface_experiments/src/run_4bit_exp_2_fp4_std_lr_2e4.py","file_name":"run_4bit_exp_2_fp4_std_lr_2e4.py","file_ext":"py","file_size_in_byte":29073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"589657728","text":"from threading import Thread\nfrom time import sleep\nfrom EngineWrapper import EngineWrapper\nimport importlib\n\nclass EngineManager():\n\tEntities = {}\n\n\t_engines = {}\n\n\t_running = False\n\n\tdef AddEngine(self, engineName):\n\t\tengineClass = getattr(importlib.import_module(engineName), engineName)\n\t\tengine = engineClass(self.Entities)\n\t\tengineWrapper = EngineWrapper(engine)\n\t\tt = Thread(target = engineWrapper.Start)\n\t\tself._engines[engineName] = { \"EngineWrapper\" : engineWrapper, \"Thread\" : t }\n\t\tt.start()\n\t\tprint(\"Engine loaded : {0}\".format(engineName))\n\n\tdef Stop(self):\n\t\tfor engineName, engineData in self._engines.items():\n\t\t\tengineData[\"EngineWrapper\"].Stop()\n\n\tdef Transfert(self, command):\n\t\ttry:\n\t\t\tcommandSplit = command.split(' ')\n\t\t\tengineName = commandSplit[0]\n\t\t\tcommandSplit = commandSplit[1:]\n\n\t\t\tengineWrapper = self._engines[engineName][\"EngineWrapper\"]\n\t\t\tcontext = engineWrapper.Engine\n\t\t\tcontextPosition = 0\n\t\texcept Exception:\n\t\t\tprint(\"No engine of this name\")\n\t\t\treturn\n\t\ttry:\n\t\t\twhile(not callable(context) and contextPosition < len(commandSplit)):\n\t\t\t\tcontext = getattr(context, commandSplit[contextPosition])\n\t\t\t\tcontextPosition += 1\n\t\t\targs = []\n\t\t\twhile(contextPosition < len(commandSplit)):\n\t\t\t\targs.append(commandSplit[contextPosition])\n\t\t\t\tcontextPosition += 1\n\t\t\tcontext(*args)\n\n\t\texcept Exception as e:\n\t\t\t\tprint(\"Engine run error : \" + type(engineWrapper.Engine).__name__)\n\t\t\t\tprint(e)\n\t\t\t\tengineWrapper.Stop()\n\t\t","sub_path":"EngineManager.py","file_name":"EngineManager.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"372457520","text":"\"\"\"\nLinking to java main method\n\"\"\"\nimport cast_upgrade_1_5_25 # @UnusedImport\nfrom cast.application import ApplicationLevelExtension, create_link\nimport logging\n\n\n\nclass CallToJava:\n \n def __init__(self, class_full_name, call_object):\n\n self.class_full_name = class_full_name\n self.call_object = call_object\n\n\nclass JavaMain:\n \n def __init__(self, method_full_name, method_object):\n\n self.method_full_name = method_full_name\n self.method_object = method_object\n\n\nclass ExtensionApplication(ApplicationLevelExtension):\n\n def end_application(self, application):\n\n logging.info('Linking calls to java programs')\n\n # 1. loading\n calls = [CallToJava(e.get_property('CAST_CallToJavaProgram.javaClassFullName'), e) for e in application.objects().has_type('CAST_CallToJavaProgram').load_property('CAST_CallToJavaProgram.javaClassFullName')]\n\n if not calls:\n logging.info('No call to java programs : nothing to do')\n return\n \n # load the main Java methods \n mains = {m.get_fullname():JavaMain(m.get_fullname(), m) for m in application.search_objects(name='main', category='JV_METHOD')}\n\n if not mains:\n logging.info('No main java methods : nothing to do')\n return\n \n for call in calls:\n \n try:\n logging.debug('searching ' + call.class_full_name + '.main')\n main = mains[call.class_full_name + '.main']\n logging.debug('creating link between ' + str(call.call_object) + ' and ' + str(main.method_object))\n create_link('callLink', call.call_object, main.method_object) \n except KeyError:\n pass \n","sub_path":"analyze/extensions/com.castsoftware.wbslinker.1.6.9/java_main_linking.py","file_name":"java_main_linking.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"116900470","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport common\nimport re\nimport six\nfrom IPython import embed\n\n\nre_flags = re.M | re.U | re.S | re.I\nJ = os.path.join\nC = os.path.abspath(os.getcwd())\nuniquify = common.uniquify\n\n\ndef cliparse(argv=None):\n def callback(parser, **kw):\n parser.add_argument('--no-followers',\n default=False, action='store_true')\n parser.add_argument('--no-notifs',\n default=False, action='store_true')\n parser.add_argument('--pages', default=1, type=int)\n return common.cliparse(\n argv=argv,\n callback=callback,\n description='userids from usernames')\n\n\ndef is_ham(item):\n if item['screen_name'].lower() in [\n 'kiorky', 'valk', 'res1854006', 'res1854006b',\n 'res122188800', 'valkphotos',\n ]:\n return True\n return False\n\ndef append_ret(usersd, user):\n ret = {}\n for n in ['description', 'id', 'name', 'screen_name']:\n ret[n] = getattr(user, n)\n if ret not in usersd:\n usersd.append(ret)\n return usersd\n\n\ndef main():\n parser, pargs = cliparse()\n wrapper = common.Wrapper.load(pargs.config)\n accounts = wrapper.accounts.values()\n i = [a for a in accounts if a['user'] == wrapper.config['main']][0]\n api = i['api']\n tws = wrapper.get_timeline(uid=wrapper.config['main'], api=i['api'], page=1)\n embed() \n #for t in tws[1:20]:api.destroy_status(t.id); \n\n\n\nif __name__ == '__main__':\n main()\n# vim:set et sts=4 ts=4 tw=0:\n","sub_path":"src/tdelete.py","file_name":"tdelete.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"387260579","text":"#coding: utf-8\n# +-------------------------------------------------------------------\n# | 宝塔Linux面板\n# +-------------------------------------------------------------------\n# | Copyright (c) 2015-2099 宝塔软件(http://bt.cn) All rights reserved.\n# +-------------------------------------------------------------------\n# | Author: 黄文良 <2879625666@qq.com>\n# +-------------------------------------------------------------------\nimport os,sys,public,json\nclass downloadFile:\n logPath = 'data/speed.json'\n timeoutCount = 0;\n oldTime = 0;\n #下载文件\n def DownloadFile(self,url,filename):\n try:\n path = os.path.dirname(filename)\n if not os.path.exists(path): os.makedirs(path)\n import urllib,socket,ssl\n try:\n ssl._create_default_https_context = ssl._create_unverified_context\n except:pass\n socket.setdefaulttimeout(10)\n self.pre = 0;\n self.oldTime = time.time();\n if sys.version_info[0] == 2:\n urllib.urlretrieve(url,filename=filename,reporthook= self.DownloadHook)\n else:\n urllib.request.urlretrieve(url,filename=filename,reporthook= self.DownloadHook)\n self.WriteLogs(json.dumps({'name':'下载文件','total':0,'used':0,'pre':0,'speed':0}));\n except:\n if self.timeoutCount > 5: return;\n self.timeoutCount += 1\n time.sleep(5)\n self.DownloadFile(url,filename)\n \n #下载文件进度回调 \n def DownloadHook(self,count, blockSize, totalSize):\n used = count * blockSize\n pre1 = int((100.0 * used / totalSize))\n if self.pre != pre1:\n dspeed = used / (time.time() - self.oldTime);\n speed = {'name':'下载文件','total':totalSize,'used':used,'pre':self.pre,'speed':dspeed}\n self.WriteLogs(json.dumps(speed))\n self.pre = pre1\n\n #取下载进度\n def GetSpeed(self):\n speedLog = public.ReadFile(self.logPath)\n if not speedLog: return {'name':'下载文件','total':0,'used':0,'pre':0,'speed':0}\n return json.loads(speedLog)\n \n #写输出日志\n def WriteLogs(self,logMsg):\n public.WriteFile(self.logPath,logMsg)","sub_path":"www/server/panel/class/downloadFile.py","file_name":"downloadFile.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"122210638","text":"# coding=utf-8\n'''\nВычислительная математика\nЛабораторная работа №5\nВариант 2\n'''\nfrom random import uniform\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom lagrange import lagrange\n\ndef model_function(x):\n return np.cos(x)\n\n\ndef build_graph(points, i, title):\n t1 = np.arange(points[0][0], points[-1][0], 0.01)\n plt.subplot(220 + i)\n plt.plot(t1, model_function(t1))\n plt.plot(t1, [lagrange( points, r) for r in t1])\n for point in points:\n plt.plot(point[0], point[1], 'ro')\n plt.title(title)\n\n\ndef generate_point(func, min, max, amount):\n res = sorted([uniform(min, max) for x in range(amount)])\n return list(map(lambda x: (x, func(x)), res))\n\ndef chebyshev_nodes (func,k):\n res = []\n m = 0\n for m in range(k):\n res.append(0)\n res[m] = np.cos((2*m + 1) * np.pi / (2 * k))\n res.sort()\n return list(map(lambda x: (x, func(x)), res))\n\n\n# ============ 3-4 points F(x) from 0 to 2Pi\npivot_points = chebyshev_nodes(func=model_function,k=2)\n#lagrange_solution = lagrange(pivot_points)\nbuild_graph(pivot_points, 1, \"2 points\")\n# ============ 8-10 from 0 to 2Pi\npivot_points = chebyshev_nodes(model_function, 5)\n#lagrange_solution = lagrange (pivot_points)\nbuild_graph(pivot_points, 2, \"5 points\")\n# ============ Shuffle 1 dot\npivot_points = chebyshev_nodes(model_function, 10)\n#lagrange_solution = lagrange (pivot_points)\nbuild_graph(pivot_points, 3, \"10 points\")\n# ============\npivot_points = chebyshev_nodes(model_function, 50)\n#lagrange_solution = lagrange (pivot_points)\nbuild_graph(pivot_points, 4, \"50 points\")\n\nplt.show()\n","sub_path":"Course 2/Computational Mathematics/CompMathLab5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"385644971","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function, unicode_literals\nfrom django.conf.urls import url\nfrom django.contrib.auth.decorators import login_required\nfrom account.views.pc import alatting_logout, LoginView, ProfileView, \\\n PosterServerIndexView, PosterConsumerIndexView, PosterIndexView\n\n__author__ = 'lyhapple'\n\n\nurlpatterns = [\n url(r'^login/$', LoginView.as_view(), name='login'),\n url(r'^logout/$', alatting_logout, name='logout'),\n\n url(r'^profile.html$',\n login_required(ProfileView.as_view()), name='profile'),\n\n]\n\n\n# 海报服务\nurlpatterns += [\n url(r'^posters/(?P[\\d]+).html$',\n login_required(PosterIndexView.as_view()),\n name='posters_index'),\n\n url(r'^posters/(?P[\\d]+)/server.html$',\n login_required(PosterServerIndexView.as_view()),\n name='posters_server'),\n\n url(r'^posters/(?P[\\d]+)/consumer.html$',\n login_required(PosterConsumerIndexView.as_view()),\n name='posters_consumer'),\n]\n","sub_path":"account/urls/pc.py","file_name":"pc.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"561055759","text":"import numpy as np\n\n\nclass Grid():\n def __init__(self, nx, ny, xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0):\n self.xmin, self.xmax, self.ymin, self.ymax = xmin, xmax, ymin, ymax\n self.nx, self.ny = nx, ny\n self.hx = 1. / (nx - 1)\n if ny > 1:\n self.hy = 1. / (ny - 1)\n self.x, self.y = np.mgrid[self.xmin:self.xmax:(self.nx * 1j), self.ymin:self.ymax:(self.ny * 1j)]\n else:\n self.x = np.linspace(self.xmin, self.xmax, self.nx)\n\n\n def setBC(self, l=0, r=0, b=0, t=1):\n \"\"\"Set boundary conditions left, right, bottom, top\"\"\"\n self.l, self.r, self.b, self.t = l, r, b, t\n\n def setBCFunc(self, func):\n xmin, ymin = self.xmin, self.ymin\n xmax, ymax = self.xmax, self.ymax\n x = np.arange(xmin, xmax + self.dx * 0.5, self.dx)\n y = np.arange(ymin, ymax + self.dy * 0.5, self.dy)\n\n self.l = func(xmin, y)\n self.r = func(xmax, y)\n self.b = func(x, ymin)\n self.t = func(x, ymax)\n\n def dx1(self, X, bc=\"False\"):\n\n dx = np.zeros_like(X)\n dx[1:-1] = (X[2:] - X[:-2]) / 2. / self.hx\n if bc == \"False\":\n dx[0] = (X[1] - X[0]) / self.hx\n dx[-1] = (X[-1] - X[-2]) / self.hx\n else:\n dx[0] = (X[0] - self.l) / self.hx\n dx[-1] = (self.r - X[-1]) / self.hx\n return dx\n\n def dx2(self, X, bc=\"False\"):\n d2x = np.zeros_like(X)\n d2x[1:-1] = (X[2:] - 2 * X[1:-1] + X[:-2]) / self.hx / self.hx\n if bc == \"False\":\n d2x[0] = (X[2] - 2 * X[1] + X[0]) / self.hx / self.hx\n d2x[-1] = (X[-1] - 2 * X[-2] + X[-3]) / self.hx / self.hx\n else:\n d2x[0] = (X[1] - 2 * X[0] + self.l) / self.hx / self.hx\n d2x[-1] = (self.r - 2 * X[-1] + X[-2]) / self.hx / self.hx\n return d2x\n\n def dy1(self, X, bc=\"False\"):\n dy = np.zeros((self.nx, self.ny))\n dy[:, 1:-1] = (X[:, 2:] - X[:, :-2]) / 2 / self.hy\n if bc == \"False\":\n dy[:, 0] = (X[:, 1] - X[:, 0]) / self.hy\n dy[:, -1] = (X[:, -1] - X[:, -2]) / self.hy\n else:\n dy[:, 0] = (X[:, 0] - self.b) / self.hy\n dy[-1] = (self.t - X[:, -1]) / self.hy\n return dy\n\n def dy2(self, X, bc=\"False\"):\n d2y = np.zeros((self.nx, self.ny))\n d2y[:, 1:-1] = (X[:, 2:] - 2 * X[:, 1:-1] + X[:, :-2]) / self.hy / self.hy\n if bc == \"False\":\n d2y[:, 0] = (X[:, 2] - 2 * X[:, 1] + X[:, 0]) / self.hy / self.hy\n d2y[:, -1] = (X[:, -1] - 2 * X[:, -2] + X[:, -3]) / self.hy\n else:\n d2y[:, 0] = (X[:, 1] - 2 * X[:, 0] + self.b) / self.hy / self.hy\n d2y[:, -1] = (self.t - 2 * X[:, -1] + X[:, -2]) / self.hy / self.hy\n return d2y\n","sub_path":"Python/DiffEqPractice/deriv.py","file_name":"deriv.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"126915577","text":"from ext.db import db\n\n\nclass TerminalDnsServers(db.Model):\n __tablename__ = 'terminal_dns_servers'\n\n dns_server = db.Column(db.VARCHAR(80), primary_key=True)\n terminal_id = db.Column(db.BIGINT(), unique=False)\n\n def __init__(self, terminal_id, dns_server):\n self.terminal_id = terminal_id\n self.credential_id = dns_server\n\n def __repr__(self):\n dct = self.__dict__\n lst = ['{}: {}'.format(k, dct[k]) for k in dct]\n return '< {}\\n{} >\\n'.format(self.__class__.__name__, '\\n'.join(lst))\n\n","sub_path":"sdwan/hive_guider/src/module/terminal_dns_servers.py","file_name":"terminal_dns_servers.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"492596843","text":"#618\nimport itertools\n\n# Alice would lose 57 happiness units by sitting next to Bob.\n\ndef readFileToList():\n\twith open('input.txt', 'r') as filehandle: \n\t\tinLine = []\n\t\tfor line in filehandle:\n\t\t\tinLineList = []\n\t\t\tinLineRow = line.split(' ')\n\t\t\tinLineList.append(inLineRow[0])\t\t\t# 0 - Alice\n\t\t\tif (inLineRow[2] == 'gain'):\t\t\t# + gain\n\t\t\t\tinLineList.append(int(inLineRow[3]))\n\t\t\telse:\t\t\t\t\t\t\t\t\t# lose\n\t\t\t\tinLineList.append(-1*int(inLineRow[3]))\n\t\t\tinLineList.append((inLineRow[10].strip())[:-1])\t\t# 2 - Bob\n\t\t\tinLine.append(inLineList)\n\t\treturn inLine\n\ndef makeListOfNames(inList):\n\tnameList = []\n\tfor row in inList:\n\t\tif row[0] not in nameList:\n\t\t\tnameList.append(row[0])\n\t\tif row[2] not in nameList:\n\t\t\tnameList.append(row[2])\n\treturn nameList\n\ndef evalNamePairVal(name1,name2,inList):\n\tfor row in inList:\n\t\tif (row[0] == name1) and (row[2] == name2):\n\t\t\t#print(name1,name2,row[1])\n\t\t\treturn row[1]\n\tassert False,\"huh\"\n\ndef computeHappinessScore(listOfNames,inList):\n\thappinessScore = 0\n\tfor nameOffset in range(len(listOfNames)-1):\n\t\thappinessScore += evalNamePairVal(listOfNames[nameOffset],listOfNames[nameOffset+1],inList)\n\t\thappinessScore += evalNamePairVal(listOfNames[nameOffset+1],listOfNames[nameOffset],inList)\n\thappinessScore += evalNamePairVal(listOfNames[-1],listOfNames[0],inList)\n\thappinessScore += evalNamePairVal(listOfNames[0],listOfNames[-1],inList)\n\treturn happinessScore\n\ninList = readFileToList()\nnames = makeListOfNames(inList)\n\nprint(inList)\nprint(names)\nnamesLists = list(itertools.permutations(names))\n#print(namesLists)\nhappinessValue = 0\nfor listOfNames in namesLists:\n\thappy = computeHappinessScore(listOfNames,inList)\n\tif happy > happinessValue:\n\t\thappinessValue = happy\nprint(happinessValue)\n","sub_path":"AoC/AoC-2015/Day13/D13P2.py","file_name":"D13P2.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"238321926","text":"\"\"\"Memory lock module.\"\"\"\nfrom threading import RLock\nfrom typing import Dict # noqa\n\nfrom tuco.exceptions import TucoAlreadyLockedError, TucoDoNotLockError\n\nfrom .base import BaseLock\n\n\nclass MemoryLock(BaseLock):\n \"\"\"Simple memory lock implementation.\"\"\"\n\n global_lock = RLock()\n locks = {} # type: Dict[str, str]\n\n def lock(self) -> bool:\n \"\"\"Lock an object.\"\"\"\n try:\n hash_key = self.hash_key\n except TucoDoNotLockError:\n return True\n\n with self.global_lock:\n if hash_key in self.locks:\n raise TucoAlreadyLockedError()\n self.locks[hash_key] = \"locked\"\n return True\n\n def unlock(self) -> bool:\n \"\"\"Unlock an object.\"\"\"\n try:\n hash_key = self.hash_key\n except TucoDoNotLockError:\n return True\n\n with self.global_lock:\n try:\n del self.locks[hash_key]\n except KeyError:\n pass\n return True\n","sub_path":"src/tuco/locks/memory.py","file_name":"memory.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"455410998","text":"import os\ndef rename_file(name):\n file_list = os.listdir(name)\n #print(file_list)\n saved_path = os.getcwd()\n print(\"current working directory is\"+saved_path)\n os.chdir(name)\n for file_name in file_list:\n print(\"old name - \"+file_name)\n print(\"new name - \"+file_name.translate(None,\"0123456789\"))\n os.rename(file_name,file_name.translate(None,\"0123456789\"))\n os.chdir(saved_path)\n\n\nrename_file(\"r'c:\\oop\\prank'\")","sub_path":"day_file/py/New_Study/os操作.py","file_name":"os操作.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"561399775","text":"# https://www.hackerrank.com/challenges/simple-array-sum/problem?isFullScreen=true\r\n\r\n# Input Format\r\n# The first line contains an integer, n, denoting the size of the array.\r\n# The second line contains n space-separated integers representing the array's elements.\r\n\r\n# Constraints\r\n# 0 < n, ar[i] <= 1000\r\n\r\n# Output Format\r\n# Print the sum of the array's elements as a single integer.\r\n\r\n# Sample Input\r\n# 6\r\n# 1 2 3 4 10 11\r\n\r\n# Sample Output\r\n# 31\r\n\r\n\r\n\r\n#!/bin/python3\r\n\r\nimport os\r\nimport sys\r\n\r\n#\r\n# Complete the simpleArraySum function below.\r\n#\r\ndef simpleArraySum(ar):\r\n #\r\n # Write your code here.\r\n return sum(ar)\r\n\r\nif __name__ == '__main__':\r\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\r\n\r\n ar_count = int(input())\r\n\r\n ar = list(map(int, input().rstrip().split()))\r\n\r\n result = simpleArraySum(ar)\r\n\r\n fptr.write(str(result) + '\\n')\r\n\r\n fptr.close()","sub_path":"0_reference/Hackerrank/Practice Problem Solving/Warmup/Simple Array Sum.py","file_name":"Simple Array Sum.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"552545462","text":"\"\"\"mixns_demo URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', 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: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url,include\nfrom django.contrib import admin\nfrom app01 import views\n\n#第三种url简写\n#简写第一步\nfrom rest_framework import routers\n\nrouters = routers.DefaultRouter()\nrouters.register(r\"books001\",views.BookViewSet) #books001为URL前缀\n\n\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^publisher/$', views.PublsherMixView.as_view()),\n # url(r'^publisher/(\\d+)/$', views.PublisherDetailView.as_view()), #不加超链接\n url(r'^publisher/(?P\\d+)/', views.PublisherDetailMix.as_view(), name=\"publisher_detail\"),\n\n\n url(r'^book/$', views.BookMixView.as_view()),\n url(r'^book/(?P\\d+)/$', views.BookDetailMix.as_view()),\n\n ##**********第二种*******\n url(r'^publishers/$', views.PublsherGenView.as_view()),\n url(r'^publishers/(?P\\d+)/$', views.PublisherDetailGen.as_view()),\n\n url(r'^books/$', views.BookGenView.as_view(),name=\"book_list\"),\n url(r'^books/(?P\\d+)/$', views.BookDetailGen.as_view(),name=\"book_detail\"),\n\n ##*****第三种 这种还可以简写\n # url(r'^books1/$', views.BookViewSet.as_view({\"get\":\"list\",\"post\":\"create\"}),name=\"book_list\"),\n # url(r'^books1/(?P\\d+)/$', views.BookViewSet.as_view({\n # 'get': 'retrieve',\n # 'put': 'update',\n # 'patch': 'partial_update',\n # 'delete': 'destroy'\n # }),name=\"book_detail\"),\n\n\n ##简写第二步\n url(r'^', include(routers.urls)),\n\n\n]\n\n#简写默认生成如下url\n# # ^books001/$ [name='book-list']\n# ^ ^books001\\.(?P[a-z0-9]+)/?$ [name='book-list']\n# ^ ^books001/(?P[^/.]+)/$ [name='book-detail']\n# ^ ^books001/(?P[^/.]+)\\.(?P[a-z0-9]+)/?$ [name='book-detail']","sub_path":"mixns_demo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"173105705","text":"#Send data to web server using urllib\n\nimport urllib.request\nimport urllib.parse\n\ndef main():\n url = \"http://httpbin.org/get\"\n\n #Create data to pass to the GET request\n args = {\n \"name\": \"Diego Carrillo\",\n \"is_author\": True\n }\n\n #Data needs to be url-encoded before passing as arguments\n data = urllib.parse.urlencode(args)\n\n #Issue the request with the data params as part of the URL\n #result = urllib.request.urlopen(url + \"?\" + data)\n\n #Issue the request with a data parameter to use POST\n url = \"http://httpbin.org/post\"\n data_encoded = data.encode()\n result = urllib.request.urlopen(url, data=data_encoded)\n\n print(\"Result code {0}\".format(result.status))\n print(\"Returned Data: -----------------------\")\n print(result.read().decode('utf-8'))\n\nif __name__ == \"__main__\":\n main()","sub_path":"python_web/send_dataurllib.py","file_name":"send_dataurllib.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"560047510","text":"import nltk\nimport jieba.analyse\n\nfrom src.service import bigram_tagger, cfg\nfrom src.util.commonutils import stringNotContainsChinese\n\n\nclass NPExtractor(object):\n def __init__(self, sentence):\n self.sentence = sentence\n\n # Split the sentence into singlw words/tokens\n def tokenize_sentence(self, sentence):\n tokens = nltk.word_tokenize(sentence)\n return tokens\n\n # Normalize brown corpus' tags (\"NN\", \"NN-PL\", \"NNS\" > \"NN\")\n def normalize_tags(self, tagged):\n n_tagged = []\n for t in tagged:\n if t[1] == \"NP-TL\" or t[1] == \"NP\":\n n_tagged.append((t[0], \"NNP\"))\n continue\n if t[1].endswith(\"-TL\"):\n n_tagged.append((t[0], t[1][:-3]))\n continue\n if t[1].endswith(\"S\"):\n n_tagged.append((t[0], t[1][:-1]))\n continue\n n_tagged.append((t[0], t[1]))\n return n_tagged\n\n # Extract the main topics from the sentence\n def extract(self):\n\n tokens = self.tokenize_sentence(self.sentence)\n tags = self.normalize_tags(bigram_tagger.tag(tokens))\n\n merge = True\n while merge:\n merge = False\n for x in range(0, len(tags) - 1):\n t1 = tags[x]\n t2 = tags[x + 1]\n key = \"%s+%s\" % (t1[1], t2[1])\n value = cfg.get(key, '')\n if value:\n merge = True\n tags.pop(x)\n tags.pop(x)\n match = \"%s %s\" % (t1[0], t2[0])\n pos = value\n tags.insert(x, (match, pos))\n break\n\n matches = []\n for t in tags:\n if t[1] == \"NNP\" or t[1] == \"NNI\":\n # if t[1] == \"NNP\" or t[1] == \"NNI\" or t[1] == \"NN\":\n matches.append(t[0])\n return matches\n\n @staticmethod\n def extractKeywords(sentence: str, top=3, filterwords=None) -> set:\n \"\"\"\n 提取一段不包含中文字符串的关键词,返回前 top 个词\n filterwords 为过滤词,通过 nltk 提取的关键词中如果\n 含有过滤词,则不返回这个词\n :type top: int\n \"\"\"\n np_extractor = NPExtractor(sentence)\n result = np_extractor.extract() # result 为 list集合\n keywords = set()\n number = 0\n\n for word in result:\n if number > top:\n break\n if filterwords:\n isAdd = True\n for filterword in filterwords:\n if str(word).find(filterword) == -1:\n isAdd = False\n break\n if isAdd:\n keywords.add(word)\n number += 1\n else:\n keywords.add(word)\n number += 1\n return keywords\n\n\ndef extractTagFiles(tagkeyword: dict, keydic: dict, filterwords=None):\n \"\"\"\n 提取 会议 Tag 字段算法\n :param tagkeyword: 关键词映射,关键词 → Tag\n :param keydic: 会议信息字典\n :param filterwords: 会议 Tag 过滤词\n \"\"\"\n tagString = keydic.get(\"tag\")\n if tagString is None:\n # 会议信息未归类尝试获取会议中文名\n conferenceName = keydic.get(\"cnName\")\n # 没有中文名测试获取英文名\n if conferenceName is None:\n conferenceName = keydic.get(\"enName\")\n\n # 会议名称不为None\n if conferenceName is not None:\n isFind = False\n # 检查会议名称是否包含关键词集中某个关键词,\n # 如果包含可以根据这个关键词对会议进行归类\n # 如果不包含关键词集中的任一关键词则判断会议名称是中文还是英文\n # 如果是中文采用结巴分词进行关键词提取\n # 如果是英文则采用NLTK生成关键词\n for k, v in tagkeyword.items():\n if str(conferenceName).find(k) != -1:\n isFind = True\n keydic[\"tag\"] = v\n break\n if not isFind:\n # 会议名称为英文\n if stringNotContainsChinese(conferenceName):\n keywords = NPExtractor.extractKeywords(conferenceName, filterwords=filterwords)\n print(\"使用 NLTK 提取Tag\")\n keydic[\"tag\"] = \",\".join(keywords)\n\n else:\n jieba.analyse.set_stop_words(\"file/txt/stop_words.txt\")\n keywords = jieba.analyse.extract_tags(conferenceName, 5)\n keydic[\"tag\"] = \",\".join(keywords)\n","sub_path":"src/crawler/service/taghanldler.py","file_name":"taghanldler.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"604661934","text":"# import necessary libraries\nimport pandas as pd\nimport re\nimport torch\nimport collections\nimport numpy as np\nimport ujson as json\nimport time\nimport torch.nn as nn\nimport os\nimport argparse\nfrom pathlib import Path\nfrom torch.utils.tensorboard import SummaryWriter\nimport matplotlib.pyplot as plt\nfrom tokenizers import BertWordPieceTokenizer\nimport random\nfrom tqdm import tqdm\nimport numpy as np\nimport arguments.train_arguments as arguments\nfrom data_processing.articles import Articles\nfrom models.models import InnerProduct\nimport data_processing.dictionaries as dictionary\nimport sampling.sampler_util as sampler_util\nimport training.eval_util as eval_util\n\nnp.random.seed(0)\n\nparser = argparse.ArgumentParser(\n description=\"Train model on article data and test evaluation\"\n)\narguments.add_data(parser)\narguments.add_training(parser)\narguments.add_model(parser)\narguments.add_optimization(parser)\nargs = parser.parse_args()\n\n# set device\nif torch.cuda.is_available() and args.use_gpu:\n device = \"cuda\"\nelif not args.use_gpu:\n device = \"cpu\"\nelse:\n device = \"cpu\"\n print(\"Cannot use GPU. Using CPU instead.\")\nprint(f\"Device: {device}\")\n\n# set output directory path\noutput_path = Path(args.output_dir)\n\n# tensboard log and graph output folder declaration\nlog_tensorboard_dir = output_path / \"runs\" / args.word_embedding_type\nwriter = SummaryWriter(log_tensorboard_dir)\n\n# load datasets\ntrain_path = Path(args.train_path)\ntest_path = Path(args.test_path)\neval_path = Path(args.eval_path)\n\ntrain_data = Articles(train_path)\ntest_data = Articles(test_path)\neval_data = Articles(eval_path, index_file=args.index_file_path)\nprint(\"Data Loaded\")\n\n# initialize tokenizer from BERT library\ntokenizer = BertWordPieceTokenizer(args.tokenizer_file, lowercase=True)\nprint(\"Tokenizer Initialized!\")\n\n# create and save or load dictionaries based on arguments\nif args.create_dicts:\n (\n final_word_ids,\n final_url_ids,\n final_publication_ids,\n ) = dictionary.create_merged_dictionaries(\n train_data.examples, \"target\", args.tokenizer_file\n )\n print(\"Dictionaries Created\")\n\n dict_path = Path(args.data_dir) / \"dictionaries\"\n if not dict_path.is_dir():\n dict_path.mkdir()\n\n dictionary.save_dictionaries(\n final_word_ids, final_url_ids, final_publication_ids, dict_path\n )\nelse:\n dictionary_dir = Path(args.dict_dir)\n final_word_ids, final_url_ids, final_publication_ids = dictionary.load_dictionaries(\n dictionary_dir\n )\n print(\"Dictionaries loaded.\")\n\n# map items in dataset using dictionary keys (convert words and urls to numbers for the model)\nif args.map_items:\n badtokens = []\n if args.bad_token_path.is_file():\n bad_token_path = Path(args.bad_token_path)\n with open(bad_token_path, \"r\") as f:\n badTokens = [int(line.rstrip()) for line in f]\n\n for dataset in [train_data, test_data, eval_data]:\n dataset.map_items(\n tokenizer, final_url_ids, final_publication_ids, filter=False,\n )\n else:\n for dataset in [train_data, test_data, eval_data]:\n dataset.map_items(\n tokenizer, final_url_ids, final_publication_ids, filter=False\n )\n print(\"Items mapped\")\n mapped_data_path = Path(args.data_dir) / \"mapped-data\"\n if not mapped_data_path.is_dir():\n mapped_data_path.mkdir()\n\n train_mapped_path = mapped_data_path / \"train.json\"\n test_mapped_path = mapped_data_path / \"test.json\"\n eval_mapped_path = mapped_data_path / \"evaluation.json\"\n with open(train_mapped_path, \"w\") as file:\n json.dump(train_data.examples, file)\n with open(test_mapped_path, \"w\") as file:\n json.dump(test_data.examples, file)\n with open(eval_mapped_path, \"w\") as file:\n json.dump(eval_data.examples, file)\n print(f\"Mapped Data saved to {mapped_data_path} directory\")\n\n# create weights for dataset samples to ensure only positive and negative examples are chosen in respective samples\npos_sampler = train_data.create_positive_sampler(args.target_publication)\nneg_sampler = train_data.create_negative_sampler(args.target_publication)\n\ntrain_batch_sampler = sampler_util.BatchSamplerWithNegativeSamples(\n pos_sampler=pos_sampler,\n neg_sampler=neg_sampler,\n items=train_data.examples,\n batch_size=args.batch_size,\n)\n\n\n# define function to return necessary data for dataloader to pass into model\ndef collate_fn(examples):\n words = []\n articles = []\n labels = []\n publications = []\n for example in examples:\n if args.use_all_words:\n words.append(list(set(example[\"text\"])))\n else:\n if len(list(set(example[\"text\"]))) > args.words_to_use:\n words.append(\n random.sample(list(set(example[\"text\"])), args.words_to_use)\n )\n else:\n words.append(list(set(example[\"text\"])))\n articles.append(example[\"url\"])\n publications.append(example[\"model_publication\"])\n labels.append(example[\"model_publication\"])\n num_words = [len(x) for x in words]\n words = np.concatenate(words, axis=0)\n word_attributes = torch.tensor(words, dtype=torch.long)\n articles = torch.tensor(articles, dtype=torch.long)\n num_words.insert(0, 0)\n num_words.pop(-1)\n attribute_offsets = torch.tensor(np.cumsum(num_words), dtype=torch.long)\n publications = torch.tensor(publications, dtype=torch.long)\n real_labels = torch.tensor(labels, dtype=torch.long)\n return publications, articles, word_attributes, attribute_offsets, real_labels\n\n\n# change negative example publication ids to the ids of the first half for predictions\ndef collate_with_neg_fn(examples):\n (\n publications,\n articles,\n word_attributes,\n attribute_offsets,\n real_labels,\n ) = collate_fn(examples)\n publications[len(publications) // 2 :] = publications[: len(publications) // 2]\n return publications, articles, word_attributes, attribute_offsets, real_labels\n\n\n# pin memory if using GPU for high efficiency\nif args.use_gpu:\n pin_mem = True\nelse:\n pin_mem = False\n\n# create dataloaders for iterable data when training and testing recall\ntrain_loader = torch.utils.data.DataLoader(\n train_data,\n batch_sampler=train_batch_sampler,\n collate_fn=collate_with_neg_fn,\n pin_memory=pin_mem,\n)\neval_loader = torch.utils.data.DataLoader(\n eval_data, batch_size=10000, collate_fn=collate_fn, pin_memory=pin_mem\n)\ntest_loader = torch.utils.data.DataLoader(\n test_data, batch_size=10000, collate_fn=collate_fn, pin_memory=pin_mem\n)\n\n\n# function that allows for infinite iteration over training batches\ndef cycle(iterable):\n while True:\n for x in iterable:\n yield x\n\n\n# initialize model, loss, and optimizer\nkwargs = dict(\n n_publications=len(final_publication_ids),\n n_articles=len(final_url_ids),\n n_attributes=len(final_word_ids),\n emb_size=args.emb_size,\n sparse=args.use_sparse,\n use_article_emb=args.use_article_emb,\n mode=args.word_embedding_type,\n)\nmodel = InnerProduct(**kwargs)\nmodel.reset_parameters()\nmodel.to(device)\n\nloss = torch.nn.BCEWithLogitsLoss()\n\nif args.optimizer_type == \"RMS\":\n optimizer = torch.optim.RMSprop(\n model.parameters(), lr=args.learning_rate, momentum=args.momentum\n )\nelse:\n optimizer = torch.optim.SGD(\n model.parameters(), lr=args.learning_rate, momentum=args.momentum\n )\n\nprint(model)\nprint(optimizer)\nmodel.train() # turn on training mode\ncheck = True\nrunning_loss = 0\n\nlabels = torch.Tensor(\n (np.arange(args.batch_size) < args.batch_size // 2).astype(np.float32)\n)\nlabels = labels.to(device)\n\nvalidation_recall_list = []\nprint(\"Beginning Training\")\nprint(\"--------------------\")\n\n# training loop with validation checks\nfor step, batch in enumerate(cycle(train_loader)):\n # calculate test and evaluation performance based on user intended frequency\n if step % args.frequency == 0 and step != args.training_steps:\n # output loss\n model.eval()\n torch.no_grad()\n writer.add_scalar(\"Loss/train\", running_loss / args.frequency, step)\n print(f\"Training Loss: {running_loss/args.frequency}\")\n running_loss = 0.0\n logit_list = []\n for eval_batch in tqdm(eval_loader):\n current_logits = eval_util.calculate_batched_predictions(\n eval_batch, model, device, args.target_publication\n )\n logit_list = logit_list + list(current_logits)\n converted_list = np.array(logit_list)\n sorted_preds = np.sort(converted_list)\n indices = np.argsort(converted_list)\n calc_recall = eval_util.calculate_recall(\n eval_data,\n indices,\n args.eval_recall_max,\n args.target_publication,\n \"Eval\",\n writer,\n step,\n )\n validation_recall_list.append(calc_recall)\n\n # save model for easy reloading\n if max(validation_recall_list) == validation_recall_list[-1]:\n model_path = output_path / \"model\"\n if not model_path.is_dir():\n model_path.mkdir()\n model_string = (\n str(step) + args.word_embedding_type + \"-inner-product-model.pt\"\n )\n model_path = model_path / model_string\n torch.save(model.state_dict(), model_path)\n\n # check if validation recall is increasing\n if len(validation_recall_list) > 3:\n full_length = len(validation_recall_list)\n if (\n validation_recall_list[-1] < validation_recall_list[-2]\n and validation_recall_list[-2] < validation_recall_list[-3]\n and validation_recall_list[-3] < validation_recall_list[-4]\n ):\n print(\"Validation Recall Decreased For Two Successive Iterations!\")\n break\n\n # turn to training mode and calculate loss for backpropagation\n torch.enable_grad()\n model.train()\n optimizer.zero_grad()\n publications, articles, word_attributes, attribute_offsets, real_labels = batch\n publication_set = [args.target_publication] * len(real_labels)\n publication_set = torch.tensor(publication_set, dtype=torch.long)\n publication_set = publication_set.to(device)\n articles = articles.to(device)\n word_attributes = word_attributes.to(device)\n attribute_offsets = attribute_offsets.to(device)\n logits = model(publication_set, articles, word_attributes, attribute_offsets)\n L = loss(logits, labels)\n L.backward()\n optimizer.step()\n running_loss += L.item()\n if step != 0 and step % args.training_steps == 0:\n writer.add_scalar(\"Loss/train\", running_loss / args.frequency, step)\n print(f\"Training Loss: {running_loss/100}\")\n print(\"Getting Final Evaluation Results\")\n print(\"--------------------\")\n break\n\n# load best model for final performance metrics and data saving\nproper_step_model = (\n str(np.argmax(validation_recall_list) * args.frequency)\n + args.word_embedding_type\n + \"-inner-product-model.pt\"\n)\n\nwriter.add_scalar(\"Peaked_Steps\", np.argmax(validation_recall_list) * args.frequency)\nwriter.add_scalar(\"Max_Evaluation_Recall\", np.max(validation_recall_list))\n\nabs_model_path = output_path / \"model\" / proper_step_model\nkwargs = dict(\n n_publications=len(final_publication_ids),\n n_articles=len(final_url_ids),\n n_attributes=len(final_word_ids),\n emb_size=args.emb_size,\n sparse=args.use_sparse,\n use_article_emb=args.use_article_emb,\n mode=args.word_embedding_type,\n)\nmodel = InnerProduct(**kwargs)\nmodel.load_state_dict(torch.load(abs_model_path))\nmodel.to(device)\nmodel.eval()\ntorch.no_grad()\n\n# get final evaluation results and create a basic csv of top articles\neval_logit_list = []\nfor batch in tqdm(eval_loader):\n current_logits = eval_util.calculate_batched_predictions(\n batch, model, device, args.target_publication\n )\n eval_logit_list = eval_logit_list + list(current_logits)\nconverted_list = np.array(eval_logit_list)\nsorted_preds = np.sort(converted_list)\nindices = np.argsort(converted_list)\ncalc_recall = eval_util.calculate_recall(\n eval_data,\n indices,\n args.eval_recall_max,\n args.target_publication,\n \"Eval\",\n writer,\n step,\n)\nranked_df = eval_util.create_ranked_results_list(\n final_word_ids, sorted_preds, indices, eval_data\n)\neval_util.save_ranked_df(output_path, \"evaluation\", ranked_df, args.word_embedding_type)\n\n# get final test results and create a basic csv of top articles\ntest_logit_list = []\nfor batch in tqdm(test_loader):\n current_logits = eval_util.calculate_batched_predictions(\n batch, model, device, args.target_publication\n )\n test_logit_list = test_logit_list + list(current_logits)\nconverted_list = np.array(test_logit_list)\nsorted_preds = np.sort(converted_list)\nindices = np.argsort(converted_list)\ncalc_recall = eval_util.calculate_recall(\n test_data,\n indices,\n args.test_recall_max,\n args.target_publication,\n \"Test\",\n writer,\n step,\n)\nranked_df = eval_util.create_ranked_results_list(\n final_word_ids, sorted_preds, indices, test_data\n)\neval_util.save_ranked_df(output_path, \"test\", ranked_df, args.word_embedding_type)\n\n# close writer and exit\nwriter.close()\nprint(f\"Ranked Data Saved to {output_path / 'results'}!\")\nprint(\"Done!\")\n","sub_path":"rankfromsets/train-rankfromsets.py","file_name":"train-rankfromsets.py","file_ext":"py","file_size_in_byte":13449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"79443470","text":"from django import forms\nfrom django.core.validators import MinValueValidator, MaxValueValidator\n\n__author__ = 'Ruben'\n\n\nclass EditProfesionForm(forms.Form):\n professionId = forms.IntegerField()\n nivel = forms.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(460)], label='Nivel')\n\n def __init__(self, *args, **kwargs):\n professionId = kwargs.pop('professionId', -1)\n\n super(EditProfesionForm, self).__init__(*args, **kwargs)\n self.fields['professionId'].widget = forms.HiddenInput()\n\n if professionId != -1:\n self.fields['professionId'].initial = professionId","sub_path":"giants/giantsapp/forms/EditProfesionForm.py","file_name":"EditProfesionForm.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"649432171","text":"import csv\nfrom smbus2 import SMBus\nimport time\n\n# setup csv file\nfile = \"si7021_log.csv\"\nfields = ['time', 'humidity', 'temperature']\ncountdown = 1 * 10\n\n# setup bus connection\nbus = SMBus(1)\n\nwith open(file, 'w') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n csvwriter.writerow(fields)\n count = 0\n \n while count < countdown:\n now = time.localtime()\n current_time = time.strftime(\"%H:%M:%S\", now)\n bus.write_byte(0x40, 0xE5)\n data0 = bus.read_byte(0x40, 0x40)\n data1 = bus.read_byte(0x40, 0x40)\n humidity = ((data0 * 256 + data1) * 125 / 65536.0) - 6\n bus.write_byte(0x40, 0xE0)\n data0 = bus.read_byte(0x40, 0x40)\n data1 = bus.read_byte(0x40, 0x40)\n tempc = ((data0 * 256 + data1) * 175.72 / 65536.0) - 46.85\n csvwriter.writerow([current_time, \"{:.4f}\".format(humidity), \"{:.4f}\".format(tempc)])\n count = count + 1\n time.sleep(0.1); # frequency of data acquisition is 0.1 seconds (100 milliseconds)\n","sub_path":"si7021.py","file_name":"si7021.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"88892956","text":"from ftw.testbrowser import browsing\nfrom opengever.testing import IntegrationTestCase\n\n\nclass TestUserDetails(IntegrationTestCase):\n\n @browsing\n def test_user_details(self, browser):\n self.login(self.regular_user, browser)\n\n browser.open(self.portal, view='@@user-details/kathi.barfuss')\n\n self.assertEquals([u'B\\xe4rfuss K\\xe4thi (kathi.barfuss)'],\n browser.css('h1.documentFirstHeading').text)\n\n metadata = browser.css('.vertical').first.lists()\n\n self.assertEquals(\n ['Name', u'B\\xe4rfuss K\\xe4thi (kathi.barfuss)'], metadata[0])\n self.assertEquals(['Active', 'Yes'], metadata[1])\n self.assertEquals(['Email', 'kathi.barfuss@gever.local'], metadata[2])\n\n @browsing\n def test_user_details_return_not_found_for_not_exisiting_user(self, browser):\n with browser.expect_http_error(code=404):\n browser.login().open(self.portal, view='@@user-details/not.found')\n\n @browsing\n def test_list_all_team_memberships(self, browser):\n self.login(self.regular_user, browser)\n browser.open(self.portal, view='@@user-details/kathi.barfuss')\n\n self.assertEquals(\n [u'Projekt \\xdcberbaung Dorfmatte'], browser.css('.teams li').text)\n self.assertEquals('http://nohost/plone/@@team-details/1',\n browser.css('.teams a').first.get('href'))\n","sub_path":"opengever/ogds/base/tests/test_userdetails.py","file_name":"test_userdetails.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"144691410","text":"import os\nimport telebot\nimport mysql.connector\nimport pandas as pd\nimport numpy as np\nfrom zipfile import ZipFile\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nfrom mysql.connector import Error\n\n# Load TensorFlow Decision Forests\n\n# Load the training dataset using pandas\nimport pandas\n#import mysql.connector\nfrom replit import db\nfrom telebot import types\n\nmy_secret = os.getenv('API_KEY')\n#my_secret =\"1676961222:AAF7kZ_rf9olinM3ScqA2WqgdoqAo3APgws\"\nprint(my_secret)\nbot=telebot.TeleBot('1676961222:AAF7kZ_rf9olinM3ScqA2WqgdoqAo3APgws')\n#@bot.message_handler(commands=['hello'])\n#def hello(message):\n# bot.reply_to(message,'Bonjour pour utiliser l\\'assistant veuillez entrer les informations suivantes:')\n # bot.send_message(message.chat.id,'nom(s) et prenom(s):')\n\n#bot.polling()\n\n#154.72.167.172\ndef insert(connection,message,ind):\n mySql_insert_query = \"\"\"INSERT INTO Users (Chat_Id, Nom, Sexe,Age, Poids,Taille) \n VALUES \n (%s, %s,%s,%s,%s,%s) \"\"\"\n record = (message.chat.id, ind.name, ind.sex, ind.age,ind.poids,ind.taille)\n cursor = connection.cursor()\n cursor.execute(mySql_insert_query,record)\n connection.commit()\n print(cursor.rowcount, \"Record inserted successfully into Laptop table\")\n cursor.close()\ndef create_table(connection):\n mySql_Create_Table_Query = \"\"\"CREATE TABLE Users ( \n Id int(11) NOT NULL,\n Chat_Id int(11) NOT NULL,\n Nom varchar(250) NOT NULL,\n Sexe varchar(250) NOT NULL,\n Age int(11) NOT NULL,\n Poids int(11) NOT NULL,\n Taille int(11) NOT NULL,\n PRIMARY KEY (Id)) \"\"\"\n\n cursor = connection.cursor()\n result = cursor.execute(mySql_Create_Table_Query)\n # result = cursor.execute(mySql_Create_Table_Query)\n print(\"Laptop Table created successfully \")\n\n\ndef connect_sql():\n try:\n connection = mysql.connector.connect(host='localhost',\n database='tensor',\n user='root',\n password='')\n\n\n except mysql.connector.Error as error:\n print(\"Failed to create table in MySQL: {}\".format(error))\n\n return connection\ndef close_conn(connection):\n if connection.is_connected():\n cursor = connection.cursor()\n cursor.close()\n connection.close()\n print(\"MySQL connection is closed\")\n\n\n\"\"\"\n## First, load the data and apply preprocessing\n\"\"\"\n\n# Download the actual data from http://files.grouplens.org/datasets/foodlens/ml-latest-small.zip\"\n# Use the ratings.csv file\nfoodlens_data_file_url = (\n \"http://files.grouplens.org/datasets/foodlens/ml-latest-small.zip\"\n)\nfoodlens_zipped_file = keras.utils.get_file(\n \"ml-latest-small.zip\", foodlens_data_file_url, extract=False\n)\nkeras_datasets_path = Path(foodlens_zipped_file).parents[0]\nprint('keras_dataset_path', keras_datasets_path)\nfoodlens_dir = keras_datasets_path / \"ml-latest-small\"\n\n# Only extract the data the first time the script is run.\nif not foodlens_dir.exists():\n with ZipFile(foodlens_zipped_file, \"r\") as zip:\n # Extract files\n print(\"Extracting all the files now...\")\n zip.extractall(path=keras_datasets_path)\n print(\"Done!\")\n\n# ratings_file = foodlens_dir / \"ratings.csv\"\nratings_file = \"ratings.csv\"\n\ndf = pd.read_csv(ratings_file)\n\n\"\"\"\nFirst, need to perform some preprocessing to encode users and foods as integer indices.\n\"\"\"\nuser_ids = df[\"userId\"].unique().tolist()\nuser2user_encoded = {x: i for i, x in enumerate(user_ids)}\nuserencoded2user = {i: x for i, x in enumerate(user_ids)}\nfood_ids = df[\"foodId\"].unique().tolist()\nfood2food_encoded = {x: i for i, x in enumerate(food_ids)}\nfood_encoded2food = {i: x for i, x in enumerate(food_ids)}\ndf[\"user\"] = df[\"userId\"].map(user2user_encoded)\ndf[\"food\"] = df[\"foodId\"].map(food2food_encoded)\n\nnum_users = len(user2user_encoded)\nnum_foods = len(food_encoded2food)\ndf[\"rating\"] = df[\"rating\"].values.astype(np.float32)\n# min and max ratings will be used to normalize the ratings later\nmin_rating = min(df[\"rating\"])\nmax_rating = max(df[\"rating\"])\n\nprint(\n \"Number of users: {}, Number of foods: {}, Min rating: {}, Max rating: {}\".format(\n num_users, num_foods, min_rating, max_rating\n )\n)\n\n\"\"\"\n## Prepare training and validation data\n\"\"\"\ndf = df.sample(frac=1, random_state=42)\nx = df[[\"user\", \"food\"]].values\n#print('valeur de x', x)\n\n# Normalize the targets between 0 and 1. Makes it easy to train.\ny = df[\"rating\"].apply(lambda x: (x - min_rating) / (max_rating - min_rating)).values\n#print('valeur de y', y)\n# Assuming training on 90% of the data and validating on 10%.\ntrain_indices = int(0.9 * df.shape[0])\nx_train, x_val, y_train, y_val = (\n x[:train_indices],\n x[train_indices:],\n y[:train_indices],\n y[train_indices:],\n)\n\n\"\"\"\n## Create the model\nWe embed both users and foods in to 50-dimensional vectors.\nThe model computes a match score between user and food embeddings via a dot product,\nand adds a per-food and per-user bias. The match score is scaled to the `[0, 1]`\ninterval via a sigmoid (since our ratings are normalized to this range).\n\"\"\"\nEMBEDDING_SIZE = 50\n\nclass RecommenderNet(keras.Model):\n def __init__(self, num_users, num_foods, embedding_size, **kwargs):\n super(RecommenderNet, self).__init__(**kwargs)\n self.num_users = num_users\n self.num_foods = num_foods\n self.embedding_size = embedding_size\n self.user_embedding = layers.Embedding(\n num_users,\n embedding_size,\n embeddings_initializer=\"he_normal\",\n embeddings_regularizer=keras.regularizers.l2(1e-6),\n )\n self.user_bias = layers.Embedding(num_users, 1)\n self.food_embedding = layers.Embedding(\n num_foods,\n embedding_size,\n embeddings_initializer=\"he_normal\",\n embeddings_regularizer=keras.regularizers.l2(1e-6),\n )\n self.food_bias = layers.Embedding(num_foods, 1)\n\n def call(self, inputs):\n user_vector = self.user_embedding(inputs[:, 0])\n user_bias = self.user_bias(inputs[:, 0])\n food_vector = self.food_embedding(inputs[:, 1])\n food_bias = self.food_bias(inputs[:, 1])\n dot_user_food = tf.tensordot(user_vector, food_vector, 2)\n # Add all the components (including bias)\n x = dot_user_food + user_bias + food_bias\n # The sigmoid activation forces the rating to between 0 and 1\n return tf.nn.sigmoid(x)\n\n\n\nuser_dict = {}\n\n\nclass User:\n def __init__(self, name):\n self.name = name\n self.age = None\n self.sex = None\n self.taille = None\n self.poids = None\n\n\n# Handle '/start' and '/help'\n@bot.message_handler(commands=['help', 'start'])\ndef send_welcome(message):\n msg = bot.reply_to(message, \"\"\"\\\nBonjour, pour utiliser l'assistant, veuillez entrer vos parametres.\nQuel est votre nom complet?\n\"\"\")\n bot.register_next_step_handler(msg, process_name_step)\n\n\ndef process_name_step(message):\n try:\n chat_id = message.chat.id\n name = message.text\n user = User(name)\n user_dict[chat_id] = user\n msg = bot.reply_to(message, 'Quel est votre age?')\n bot.register_next_step_handler(msg, process_age_step)\n except Exception as e:\n bot.reply_to(message, 'oooops')\n\n\ndef process_age_step(message):\n try:\n chat_id = message.chat.id\n age = message.text\n if not age.isdigit():\n msg = bot.reply_to(message, 'Vous devez saisir un nombre quel est votre age?')\n bot.register_next_step_handler(msg, process_age_step)\n return\n user = user_dict[chat_id]\n user.age = age\n msg = bot.reply_to(message, 'Quelle est votre taille en cm?')\n bot.register_next_step_handler(msg, process_taille_step)\n except Exception as e:\n bot.reply_to(message, 'oooops')\n\ndef process_taille_step(message):\n try:\n chat_id=message.chat.id\n taille=message.text\n if not taille.isdigit():\n msg = bot.reply_to(message, 'Vous devez saisir un nombre quel est votre taille en cm?')\n bot.register_next_step_handler(msg, process_taille_step)\n return\n user=user_dict[chat_id]\n user.taille=taille\n msg = bot.reply_to(message, 'Quel est votre poids en Kg?')\n bot.register_next_step_handler(msg, process_poids_step)\n except Exception as e:\n bot.reply_to(message, 'oooops')\n\ndef process_poids_step(message):\n try:\n chat_id=message.chat.id\n poids=message.text\n if not poids.isdigit():\n msg = bot.reply_to(message, 'Vous devez saisir un nombre quel est votre poids en Kg?')\n bot.register_next_step_handler(msg, process_poids_step)\n return\n user=user_dict[chat_id]\n user.poids=poids\n markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)\n markup.add('Homme', 'Femme')\n msg = bot.reply_to(message, 'Quel est votre genre?', reply_markup=markup)\n bot.register_next_step_handler(msg, process_sex_step)\n except Exception as e:\n bot.reply_to(message, 'oooops')\n\ndef process_sex_step(message):\n try:\n chat_id = message.chat.id\n sex = message.text\n user = user_dict[chat_id]\n if (sex == u'Homme') or (sex == u'Femme'):\n user.sex = sex\n else:\n raise Exception(\"sexe inconnu\")\n bot.send_message(chat_id, 'Merci d\\'avoir suivi la procedure votre profil est le suivant: \\n' 'Nom : ' + user.name + '\\n Age : ' + str(user.age)+' ans' +'\\n Taille : ' + user.taille+' cm' +'\\n Poids : ' + user.poids+' Kg' +'\\n Sexe : ' + user.sex)\n\n con=connect_sql()\n insert(con,message,user)\n close_conn(con)\n #bot.send_message(user)\n except Exception as e:\n bot.reply_to(message, 'oooopse'+e)\n\n\n\n# Enable saving next step handlers to file \"./.handlers-saves/step.save\".\n# Delay=2 means that after any change in next step handlers (e.g. calling register_next_step_handler())\n# saving will hapen after delay 2 seconds.\nbot.enable_save_next_step_handlers(delay=2)\n@bot.message_handler(commands=['infos'])\ndef infos(message):\n chat_id=message.chat.id\n #user = user_dict[chat_id]\n connection = connect_sql()\n cursor = connection.cursor()\n sql_select_Query = \"\"\"select * from Users where Chat_Id = %s\"\"\"\n #record=message.chat.id\n cursor.execute(sql_select_Query,(message.chat.id,))\n # get all records\n records = cursor.fetchall()\n print(\"Total number of rows in table: \", cursor.rowcount)\n print(\"\\nSending it to telegram\")\n for row in records:\n user={\n \"name\":row[2],\n \"age\":row[4],\n \"sex\":row[3],\n \"poids\":row[5],\n \"taille\":row[6]\n }\n\n # print(\"Id = \", row[0], )\n # print(\"Chat_id = \", row[1])\n # print(\"name = \", row[2])\n # print(\"age = \", row[3])\n # print(\"sex = \", row[4])\n # print(\"poids = \", row[5])\n # print(\"taille = \", row[6])\n # print(\"Purchase date = \", row[3], \"\\n\")\n bot.send_message(message.chat.id,'Votre profil est le suivant: \\n' +'Nom : ' + user[\"name\"] + '\\n Age : ' + str(user[\"age\"]) + ' ans' + '\\n Taille : ' + str(user[\"taille\"]) + ' cm\\n' + ' Poids : ' + str(user[\"poids\"]) + ' Kg' + '\\n Sexe : ' + user[\"sex\"])\n\n@bot.message_handler(commands=['food'])\ndef food(message):\n print(\"Bonjour\")\n chat_id = message.chat.id\n # user = user_dict[chat_id]\n connection = connect_sql()\n cursor = connection.cursor()\n sql_select_Query = \"\"\"select * from Users where Chat_Id = %s\"\"\"\n # record=message.chat.id\n cursor.execute(sql_select_Query, (message.chat.id,))\n # get all records\n records = cursor.fetchall()\n print(\"Total number of rows in table: \", cursor.rowcount)\n print(\"\\nSending it to telegram\")\n for row in records:\n user = {\n \"name\": row[2],\n \"age\": row[4],\n \"sex\": row[3],\n \"poids\": row[5],\n \"taille\": row[6]\n }\n if user['age']>30 & user['age']<50 & user['poids']>60 & user['poids']<100:\n userId_=1\n elif user['age']>10 & user['age']<20 & user['poids']>60 & user['poids']<100:\n userId_=5\n elif user['age']>50 & user['age']<60 & user['poids']>60 & user['poids']<100:\n userId_=3\n elif user['age']>20 & user['age']<30 & user['poids']>60 & user['poids']<100:\n userId_=9\n elif user['age']>60 & user['age']<70 & user['poids']>60 & user['poids']<100:\n userId_=11\n elif user['age']>70 & user['age']<100 & user['poids']>60 & user['poids']<100:\n userId_=15\n else:\n userId_=10\n\n\n\n\n model = RecommenderNet(num_users, num_foods, EMBEDDING_SIZE)\n model.compile(\n loss=tf.keras.losses.BinaryCrossentropy(), optimizer=keras.optimizers.Adam(lr=0.001)\n )\n\n \"\"\"\n ## Train the model based on the data split\n \"\"\"\n history = model.fit(\n x=x_train,\n y=y_train,\n batch_size=64,\n epochs=50,\n verbose=1,\n validation_data=(x_val, y_val),\n )\n\n \"\"\"\n ## Plot training and validation loss\n \"\"\"\n plt.plot(history.history[\"loss\"])\n plt.plot(history.history[\"val_loss\"])\n plt.title(\"model loss\")\n plt.ylabel(\"loss\")\n plt.xlabel(\"epoch\")\n plt.legend([\"train\", \"test\"], loc=\"upper left\")\n plt.show()\n\n \"\"\"\n ## Show top 10 food recommendations to a user\n \"\"\"\n\n # food_df = pd.read_csv(foodlens_dir / \"foods.csv\")\n food_df = pd.read_csv(\"data.csv\")\n # Let us get a user and see the top recommendations.\n #user_id = df.userId.sample(1).iloc[0]\n user_id=userId_\n print('user_id', user_id)\n foods_watched_by_user = df[df.userId == user_id]\n foods_not_watched = food_df[\n ~food_df[\"foodId\"].isin(foods_watched_by_user.foodId.values)\n ][\"foodId\"]\n foods_not_watched = list(\n set(foods_not_watched).intersection(set(food2food_encoded.keys()))\n )\n foods_not_watched = [[food2food_encoded.get(x)] for x in foods_not_watched]\n user_encoder = user2user_encoded.get(user_id)\n user_food_array = np.hstack(\n ([[user_encoder]] * len(foods_not_watched), foods_not_watched)\n )\n ratings = model.predict(user_food_array).flatten()\n top_ratings_indices = ratings.argsort()[-10:][::-1]\n recommended_food_ids = [\n food_encoded2food.get(foods_not_watched[x][0]) for x in top_ratings_indices\n ]\n\n bot.send_message(message.chat.id,\"Showing recommendations for user: {}\".format(user_id))\n bot.send_message(message.chat.id,\"====\" * 12)\n bot.send_message(message.chat.id,\"foods with high ratings from ciqual\")\n bot.send_message(message.chat.id,\"----\" * 20)\n\n print(\"Showing recommendations for user: {}\".format(user_id))\n print(\"====\" * 9)\n print(\"foods with high ratings from user\")\n print(\"----\" * 8)\n top_foods_user = (\n foods_watched_by_user.sort_values(by=\"rating\", ascending=False)\n .head(5)\n .foodId.values\n )\n food_df_rows = food_df[food_df[\"foodId\"].isin(top_foods_user)]\n rec=\"\"\n for row in food_df_rows.itertuples():\n print(row.alim_nom_fr, \": Qte sucre\", row.sucres)\n rec+=\"\\n\"+\"----\"+\"\\n\"+row.alim_nom_fr+ \" : Qte sucre \"+ str(row.sucres)\n bot.send_message(message.chat.id, rec)\n\n\n bot.send_message(message.chat.id,\"----\" * 20)\n bot.send_message(message.chat.id,\"Top 10 food recommendations\")\n bot.send_message(message.chat.id,\"----\" * 20)\n\n print(\"----\" * 8)\n print(\"Top 10 food recommendations\")\n print(\"----\" * 8)\n recommended_foods = food_df[food_df[\"foodId\"].isin(recommended_food_ids)]\n eat=\"\"\n for row in recommended_foods.itertuples():\n print(row.alim_nom_fr, \": Qte sucre\", row.sucres)\n eat+=\"\\n\"+\"----------------------------------------------------------------------------------------\"+\"\\n\"+row.alim_nom_fr+ \" : Qte sucre \"+str(row.sucres)\n bot.send_message(message.chat.id,eat)\n\n #bot.send_message(message.chat.id,'Votre profil est le suivant: \\n' + 'Nom : ' + user[\"name\"] + '\\n Age : ' + str(user[\"age\"]) + ' ans' + '\\n Taille : ' + str(user[\"taille\"]) + ' cm\\n' + ' Poids : ' + str(user[\"poids\"]) + ' Kg' + '\\n Sexe : ' + user[\"sex\"])\n# Load next_step_handlers from save file (default \"./.handlers-saves/step.save\")\n# WARNING It will work only if enable_save_next_step_handlers was called!\nbot.load_next_step_handlers()\n\nbot.polling()","sub_path":"telebot_final_code.py","file_name":"telebot_final_code.py","file_ext":"py","file_size_in_byte":16838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"497841409","text":"import socket\nfrom time import sleep\nfrom torch.cuda.memory import empty_cache\nimport tqdm\nimport yaml\nimport os\nimport pickle\n\nimport re\nimport traceback\n\nimport select\n\nimport sys\n\nsys.path.append(\"../\")\nimport values\nfrom values import TOKEN_BUFFER_SIZE, BUFFER_SIZE, SEPARATOR\n\n# QUERIES\n# MODEL - get latest model\n# CONFIG - get latest config\n# UPDATE_MODEL - send updated model\n\n# TOKEN_BUFFER_SIZE = 16\n# BUFFER_SIZE = 4096\n# SEPARATOR = '&'\n\n# MODEL_NAME = 'model.pth'\n# CONFIG_NAME = 'config.yaml'\nMAX_RETRY = 5\n\n\nclass Client:\n def __init__(self, config):\n super().__init__()\n print(\"\\nINITIALISING CLIENT...\")\n print(\"CONFIG:\")\n print(config)\n self.config = config\n self.HOST = self.config[\"HOST\"]\n self.PORT = self.config[\"PORT\"]\n\n # MODEL FOLDER\n try:\n self.model_folder = self.config[\"model_folder\"]\n if not os.path.isdir(self.model_folder):\n print(\"\\nFOLDER UNAVAILABLE, CREATING FOLDER...\")\n try:\n os.makedirs(self.model_folder)\n except:\n print(\"\\nUNABLE TO CREATE FOLDER\")\n if not os.path.isdir(\"MODEL\"):\n print(\"\\nCREATING DEFAULT PATH /MODEL...\")\n os.mkdir(\"MODEL\")\n else:\n print(\"\\nUSING DEFAULT PATH: /MODEL\")\n self.model_folder = \"MODEL\"\n\n except Exception as e:\n print(e)\n # print('\\nPATH TO MODEL NOT FOUND...')\n if not os.path.isdir(\"MODEL\"):\n print(\"\\nCREATING DEFAULT PATH /MODEL...\")\n os.mkdir(\"MODEL\")\n else:\n print(\"\\nUSING DEFAULT PATH: /MODEL\")\n self.model_folder = \"MODEL\"\n\n # MODEL NAME\n try:\n self.model_name = self.config[\"model_name\"]\n print(\"MODEL NAME: \", self.model_name)\n except Exception as e:\n print(\"\\nMODEL NAME NOT FOUND, USING DEFAULT NAME model.pth\")\n self.model_name = \"model.pth\"\n\n # CREATE SOCKET\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print('\\nCLIENT INITIALISED')\n \n def empty_socket(self):\n while True:\n ready_to_read, write, error = select.select([self.s],[self.s],[], 1)\n if len(ready_to_read) == 0:\n break\n for sock in ready_to_read:\n sock.recv(BUFFER_SIZE)\n\n def is_token(self, token):\n check = re.fullmatch(values.TOKEN_REGEX, token)\n if check:\n return True\n return False\n\n def request_token(self):\n self.empty_socket()\n self.s.send(values.REQUIRES_TOKEN.encode())\n response = self.s.recv(TOKEN_BUFFER_SIZE).decode() # receive response from server\n if self.is_token(response): #RECEIVED TOKEN\n self.save_token(response)\n return True\n return False\n\n def send_token(self, token):\n self.empty_socket()\n self.s.send(token.encode())\n response = self.s.recv(TOKEN_BUFFER_SIZE).decode() # receive response from server\n if response == values.receive_token_invalid:\n try:\n os.remove(\"token.pkl\")\n print(values.client_invalid_token)\n except:\n traceback.print_exc()\n return False\n elif response == values.receive_token_valid: # TOKEN AUTHENTICATED\n self.empty_socket()\n self.s.send(values.client_received_message.encode())\n return True\n\n def save_token(self, token):\n with open(\"token.pkl\", \"wb\") as file:\n pickle.dump(token, file) # SAVE TOKEN\n file.close()\n\n def handle_token(self):\n try:\n if os.path.isfile(\"token.pkl\"): # TOKEN IS PRESENT\n with open(\"token.pkl\", \"rb\") as file:\n token = pickle.load(file)\n result = self.send_token(token)\n else: # NEW CLIENT, REQUIRES TOKEN\n result = self.request_token()\n return result\n except:\n traceback.print_exc()\n return False\n\n def connect(self):\n result = True\n for i in range(MAX_RETRY):\n try:\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.s.bind(('',self.config[\"CLIENT_PORT\"]))\n self.s.connect((self.HOST, self.PORT))\n result = self.handle_token()\n if result:\n print(values.client_connection_success)\n break\n else:\n print(values.client_connection_fail_retry)\n except Exception as e:\n print(\"\\nEXCEPTION IN CONNECT: \", e)\n traceback.print_exc()\n result = False\n if result == False:\n print(values.client_connection_fail)\n\n return result\n\n def get(self):\n result = False\n for i in range(MAX_RETRY):\n try:\n # OK RESPONSE\n data = self.s.recv(BUFFER_SIZE).decode()\n print(\"\\nRESPONSE FROM SERVER: \", data)\n if data == values.no_update_available:\n print(values.no_update_available)\n self.empty_socket()\n self.s.send(values.client_received_message.encode()) # SEND OK TO SERVER\n return False\n\n else: # TODO: maybe change to a proper condition\n # UPDATE AVAILABLE\n try:\n filename, filesize = data.split(SEPARATOR)\n filesize = int(filesize)\n path = os.path.join(self.model_folder, self.model_name)\n\n self.empty_socket()\n self.s.sendall(values.metadata_valid.encode())\n result = True\n except: # INVALID METADATA\n self.empty_socket()\n self.s.sendall(values.metadata_invalid.encode()) \n self.s.close()\n result = False\n\n if result == True:\n print(\"\\nRECEIVED INFO: \", filename, \" SIZE: \", filesize)\n # RECEIVE FILE\n progress = tqdm.tqdm(range(filesize), desc=\"RECEIVING \" + filename,position=0,leave=True)\n p=0\n with open(path, 'wb') as file:\n while p < filesize:\n data = self.s.recv(BUFFER_SIZE)\n if not data:\n break\n file.write(data)\n p += len(data)\n progress.update(len(data))\n \n if p == filesize: # SEND OK \n self.empty_socket()\n self.s.sendall(values.client_receive_model_success.encode())\n print(values.client_receive_model_success)\n else:\n result = False\n\n except Exception as e:\n print(\"\\nEXCEPTION IN get: \", e)\n traceback.print_exc()\n result = False\n self.s.close()\n if result == True:\n break\n else:\n print(values.get_failed_retry)\n if i+1 != MAX_RETRY:\n sleep(10)\n self.connect()\n\n if result == False:\n print(values.get_failed)\n return result\n\n def send(self): # SEND UPDATED MODEL\n result = False\n for i in range(MAX_RETRY):\n try:\n filename = self.model_name\n path = os.path.join(self.model_folder, self.model_name)\n filesize = os.path.getsize(path)\n print('CLIENT MODEL PATH: ', path)\n\n self.empty_socket()\n self.s.send(f\"{filename}{SEPARATOR}{filesize}\".encode())\n\n response = self.s.recv(TOKEN_BUFFER_SIZE).decode() # GET METADATA RESPONSE FROM SERVER\n\n if response == values.metadata_valid: # VALID METADATA\n progress = tqdm.tqdm(range(filesize), desc=\"SENDING UPDATED MODEL TO SERVER\",position=0,leave=True)\n p = 0\n self.empty_socket()\n with open(path, 'rb') as file:\n while True:\n read = file.read(BUFFER_SIZE)\n if not read:\n break\n self.s.sendall(read)\n p += len(read)\n progress.update(len(read))\n\n if (\n p != filesize\n ): # ERROR IN SEND, FULL FILE HAS NOT BEEN SENT, RETRY\n result = False\n print(values.send_model_fail)\n \n else:\n result = True\n print('\\nSENT MODEL TO SERVER')\n \n \n elif response == values.metadata_invalid:\n print(values.metadata_invalid)\n result = False\n else: # INVALID RESPONSE FROM CLIENT\n print(values.client_invalid_response)\n result = False\n\n if result == True: # RECEIVE OK\n response = self.s.recv(TOKEN_BUFFER_SIZE).decode()\n print('\\nRESPONSE: ', response)\n \n\n except Exception as e:\n print(\"\\nEXCEPTION in send: \", e)\n traceback.print_exc()\n # self.s.close()\n result = False\n\n # self.s.close()\n if result == True:\n break\n else:\n print(values.send_failed_retry)\n if i+1 != MAX_RETRY:\n sleep(10)\n self.connect()\n\n if result == False:\n print(values.send_failed)\n return result\n","sub_path":"client/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":10403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"542919550","text":"import komand\nfrom .schema import SubmitDescriptorsInput, SubmitDescriptorsOutput\n# Custom imports below\nimport requests\nfrom urllib.parse import urlencode\n\n\nclass SubmitDescriptors(komand.Action):\n def __init__(self):\n super(self.__class__, self).__init__(\n name='submit_descriptors',\n description='Submit data to Facebook\\'s graph API.',\n input=SubmitDescriptorsInput(),\n output=SubmitDescriptorsOutput())\n\n def run(self, params={}):\n query_params = {}\n # filter through key:values to get non-empty pairs\n for param in params:\n if params.get(param):\n query_params[param] = params[param]\n self.logger.info(query_params)\n payload = urlencode(query_params)\n try:\n auth_url = \"https://graph.facebook.com/v2.8/threat_descriptors?access_token={}|{}\".format(self.connection.appid,\n self.connection.appsecret)\n response = requests.post(url=auth_url, data=payload)\n data = response.json()\n return {\"success\": data[\"success\"], \"id\": str(data[\"id\"])}\n except:\n self.logger.error(\"An error has occurred while retrieving submit descriptor\")\n raise\n\n def test(self):\n try:\n app_id = self.connection.appid\n app_secret = self.connection.appsecret\n type_ = 'CMD_LINE'\n text = \"''\"\n query_params = urlencode({\n 'access_token': app_id + '|' + app_secret,\n 'type': type_,\n 'text': text\n })\n url = \"https://graph.facebook.com/v2.8/threat_descriptors?\"\n response = requests.get(url + query_params)\n self.logger.info(\"Status Code: \" + str(response.status_code))\n self.logger.info(\"Response: \" + response.content.decode())\n return {\"status\": str(response.status_code)}\n except:\n self.logger.error(\"An error has occurred while retrieving submit descriptor\")\n raise\n","sub_path":"facebook_threat_exchange/komand_facebook_threat_exchange/actions/submit_descriptors/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"125623242","text":"import scrapy\nfrom ..items import JavaDescriptionItem\n\n\nclass DocsSpider(scrapy.Spider):\n # scrapy crawl docs -o docs.json\n name = \"docs\"\n\n # start urls\n start_urls = [\"https://docs.oracle.com/javase/8/docs/api/\"]\n\n # parse\n def parse(self, response):\n # get the all classes frame url\n all_classes_frame_url = response.xpath(\"/html/frameset/frameset/frame[position()=2]/@src\").get()\n if all_classes_frame_url:\n all_classes_frame_url = response.urljoin(all_classes_frame_url)\n yield scrapy.Request(all_classes_frame_url, callback=self.parse_class_url)\n\n # parse all classes' url\n def parse_class_url(self, response):\n for class_url in response.xpath(\"/html/body/div//a/@href\"):\n class_url = response.urljoin(class_url.get())\n yield scrapy.Request(class_url, callback=self.parse_explanation)\n\n # extract explanation from class html\n def parse_explanation(self, response):\n # use the string() method of xpath to extract all the description of this class\n keyword = response.xpath(\"string(/html/body/div[4]/div[1]/ul/li/pre/span)\")\n description = response.xpath(\"string(/html/body/div[4]/div[1]/ul/li/div)\")\n if keyword.get() and description.get():\n item = JavaDescriptionItem()\n item['keyword'] = keyword.get()\n item['description'] = description.get()\n yield item\n","sub_path":"collector/collector/spiders/docs.py","file_name":"docs.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"100976109","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom sys import argv\r\nimport requests\r\nimport math\r\nfrom bs4 import BeautifulSoup\r\nimport os\r\nimport re\r\nfrom time import sleep\r\nimport random\r\n\r\n\r\n# scrape process flow:\r\n#1.search the job w/o location\r\n#2.get the location li: location+job count + job_location_url\r\n#3.jump to job_location_url\r\n#4.for each div class \"row result\" find href\r\n# results_col ->3 blocks -> row result/ organicJob -> jobtitle & company\r\n# for each div row result/ organicJob find the job_detail_url:\r\n# collect all li values\r\n# handle expections\r\n# flip page job_location_url + &start=10x(page_no - 1)\r\n\r\n\r\n# initialize the scrape\r\n# input: job_keyword\r\n# output: a set of top locations for the job w/. url by location\r\ndef job_search_setup(job_keyword):\r\n\r\n print('job title:' + job_keyword.replace(' ', '+'))\r\n\r\n job_url = \"https://www.indeed.com/jobs?q={0}&l=\".format(job_keyword.replace(' ', '+'))\r\n base_txt = \"https://www.indeed.com\"\r\n location_set = list()\r\n results_page = BeautifulSoup(requests.get(job_url).content, 'lxml')\r\n# the keyword for top location block is onmousedown = \"rbptk('rb', 'loc', ....)\r\n loc_tags_all = results_page.find_all('li', onmousedown = re.compile(\"^rbptk\\('rb', 'loc', \") )\r\n\r\n for tag in loc_tags_all:\r\n# create a list with 3 elements to store one location entry\r\n location_info = list()\r\n# use regular expression to remove comma and brackets\r\n p = re.compile('\\(|\\)|,')\r\n location_info.append(str(tag.a.contents[0]))\r\n location_info.append(float(p.sub('', tag.contents[-1].strip())))\r\n location_info.append( base_txt + tag.a.get('href'))\r\n location_set.append(location_info)\r\n return location_set\r\n\r\n\r\n# start search by location\r\ndef get_result_by_location(location_set):\r\n# this is a rough estimate of number of job posting to scrape\r\n# as the number will always be a multiplier of ten in each location\r\n print('total number of job to scrape:', int(sum([loc[1] for loc in location_set]) * scope))\r\n \r\n all_jobs_in_keywords = list()\r\n for loc in location_set:\r\n# make_folder(base_directory + '\\\\' + loc[0] )\r\n print('current location:', loc[0], 'with job count:', str(loc[1]))\r\n# use extend method to keep the flatten list structure\r\n# number of rows will be number of job postings\r\n# last element of each row [:][-1] is a list of job requirements \r\n all_jobs_in_keywords.extend(get_job_detail(*loc))\r\n \r\n# add an element of job keyword for each record\r\n for entry in all_jobs_in_keywords:\r\n entry.insert(0, job_keyword)\r\n \r\n return all_jobs_in_keywords\r\n\r\ndef get_job_detail(location_txt, job_quantity, url):\r\n# location_txt, job_quantity, url = loc\r\n scrape_stop_count = math.ceil(job_quantity * scope/10)\r\n all_jobs_in_location = list()\r\n# search job start with page = 1\r\n for i in range(scrape_stop_count):\r\n url_suffix = '&start={0}'.format(i*10)\r\n print('current page:' + url_suffix)\r\n \r\n# get all job posting from the page and append to the list\r\n all_jobs_in_location.extend(get_all_jobs_from_page(url+url_suffix))\r\n# add one element of location to the records\r\n for entry in all_jobs_in_location:\r\n entry.insert(0, location_txt)\r\n \r\n return all_jobs_in_location\r\n\r\ndef get_all_jobs_from_page(url):\r\n results_page = BeautifulSoup(requests.get(url).content, 'lxml')\r\n #\"class_\":\" row result\", \r\n loc_tags_all = results_page.find_all( 'div', {\"data-tn-component\":\"organicJob\"})\r\n job_posting = list()\r\n all_job_in_page = list()\r\n for loc_tag in loc_tags_all:\r\n print(loc_tag.h2.a.get('title'), loc_tag.span.text.strip())\r\n# print(loc_tag.h2.a.get('href'))\r\n job_posting = list()\r\n job_posting.append(loc_tag.h2.a.get('title'))\r\n job_posting.append(loc_tag.span.text.strip())\r\n# sleep(random.random())\r\n# retrive the job details as list and save the list as last element of job posting list\r\n job_posting.append(retrieve_posting_detail_page(loc_tag.h2.a.get('href')))\r\n \r\n all_job_in_page.append(job_posting)\r\n return all_job_in_page\r\n \r\ndef retrieve_posting_detail_page(url):\r\n# url = loc_tag.h2.a.get('href')\r\n base_txt = \"https://www.indeed.com\"\r\n li_list = list()\r\n try:\r\n# add timeout otherwise some website will keep the program hanging forever\r\n posting_page = BeautifulSoup(requests.get(base_txt + url, timeout=5).content, 'lxml')\r\n li_set = posting_page.find_all('li')\r\n# make sure to not add blanks and li with specific type of fathers\r\n for x in li_set:\r\n if bool(x.text.strip()) & common_exclusion(x):\r\n li_list.append(x.text.strip())\r\n# li_list = [x.text.strip() for x in li_set]\r\n except Exception as e:\r\n print('failed to load job posting page:', str(e) )\r\n return li_list\r\n\r\n# specifically call out some type of ui \r\n# for example, the embeded linkedin form comes with lot of noisy bullet points.\r\ndef common_exclusion(x):\r\n if x.parent.parent.get('id') == 'eeoc_fields':\r\n return False\r\n else:\r\n return True\r\n\r\n# create folder utility\r\ndef make_folder(directory):\r\n if not os.path.exists(directory):\r\n os.makedirs(directory)\r\n\r\n# save the final list(all_jobs_in_keyword) to individual files\r\ndef save_to_txt(scrape_result):\r\n base_directory = r'.\\output'\r\n make_folder(base_directory+ '\\\\' + job_keyword)\r\n file_name_base = base_directory + '\\\\' + job_keyword+ '\\\\' + job_keyword\r\n i = 0\r\n for entry in scrape_result:\r\n i += 1\r\n thefile = open('{0}.{1}'.format(file_name_base, i), 'w', encoding='utf-8')\r\n for item in entry:\r\n if isinstance(item, str):\r\n thefile.write(\"%s\\n\" % item)\r\n else:\r\n if isinstance(item, list):\r\n for li in item:\r\n thefile.write(\"%s\\n\" % li)\r\n thefile.close()\r\n \r\n#class job_scrapper:\r\n# \r\n# def __init__(self, job_keyword, **kwargs):\r\n# self.job_keyword = job_keyword\r\n# # pct of jobs need to be scraped\r\n# self.scope = kwargs.get('scope', 0.05)\r\n# \r\n# # collect the job location statistics for setting up formal job searches\r\n# def job_search_setup(self):\r\n \r\nif __name__ == '__main__':\r\n\r\n base_directory = r'.\\output'\r\n job_keyword = argv[1]\r\n# job_keyword = \"Project Manager\"\r\n job_url = \"https://www.indeed.com/jobs?q={0}&l=\".format(job_keyword.replace(' ', '+'))\r\n scope = 0.05\r\n \r\n location_set = job_search_setup(job_keyword)\r\n scrape_result = get_result_by_location(location_set)\r\n save_to_txt(scrape_result)","sub_path":"indeed-scrapping.py","file_name":"indeed-scrapping.py","file_ext":"py","file_size_in_byte":6822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"343267819","text":"def main():\n N = int(input())\n mousho, manatsu, natsu, nettai, huyu, mahuyu = 0, 0, 0, 0, 0, 0\n for _ in range(N):\n max_t, min_t = map(float, input().split())\n if max_t >= 35.0:\n mousho += 1\n elif max_t >= 30.0:\n manatsu += 1\n elif max_t >= 25.0:\n natsu += 1\n\n if min_t >= 25.0:\n nettai += 1\n\n if min_t < 0 and max_t >= 0:\n huyu += 1\n\n if max_t < 0:\n mahuyu += 1\n\n print(mousho, manatsu, natsu, nettai, huyu, mahuyu)\n\n\nmain()\n","sub_path":"arc/arc15b.py","file_name":"arc15b.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"450039008","text":"group_live = ['Group live', 'Group-live', 'Group-Live', 'Live Presentation', 'Conferences', 'Group Lve', 'Virtual group live', 'GroupLive', 'Group/Live', 'Live', 'Live seminar']\n\ngroup_internet_based = [ 'Group Internet based', 'Group Internet-Based', 'Group-Intemet Based', 'Group - Internet-Based', 'Group Internet', 'Webcast', 'Group Intemet Based', 'Group - Internet Based', 'Internet Based', 'Group [nternet- Based', 'Group Program', 'Group Study', 'Internet-Based', 'Group ‘rternet basea', 'Group-Internet', 'Webinar', 'Group - Live', 'Virtual Instructor-Led', 'GroupInternet', 'Group intemet-based','Intermet', 'Group-Internel Based', 'Group-Interet Based', 'intemet', 'internel', 'Interet', 'Group-Infernel Based', 'Infernel', 'Groupod', 'Intemet-Bas', 'Internct-Based']\n\nqas_self_study = [ 'Internet Based Self-Study Program.', 'Interactive Self Study','QAS Self study', 'Self-Study', 'Self Study', 'QAS Self Study.', 'self', 'QAS Study']\n\nblendend_learning = ['Blended learning']\n\nnano_learning = ['Nano learning']\n\n\ndef map_with_given_list(delivery_method):\n print(f\"MAPP_DELIVERY_METHOD---->{delivery_method}\")\n for gl in group_live:\n if gl.lower() in delivery_method.lower():\n return 'Group live'\n for qss in qas_self_study:\n if qss.lower() in delivery_method.lower():\n return 'QAS Self study'\n for gib in group_internet_based:\n if gib.lower() in delivery_method.lower():\n return 'Group Internet based'\n for bl in blendend_learning:\n if bl.lower() in delivery_method.lower():\n return 'Blended learning'\n for nl in nano_learning:\n if nl.lower() in delivery_method.lower():\n return 'Nano learning'\n return \"\"\n","sub_path":"test/lib/delivery_format_mapping.py","file_name":"delivery_format_mapping.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"425058873","text":"import sqlite3 as lite\nimport sys\nimport os\ncars = (\n (1, 'NhungPro', 52642),\n (2, 'Mercedes', 57127),\n (3, 'Skoda', 9000),\n (4, 'Volvo', 29000),\n (5, 'Bentley', 350000),\n (6, 'Hummer', 41400),\n (7, 'Volkswagen', 21600)\n)\n \n \npath = os.path.dirname(__file__) + \"test.db\"\ncon = lite.connect(path)\n \nwith con:\n \n cur = con.cursor() \n# Chúng ta xóa bảng và tạo lại bảng Cars.\n# chúng ta kiểm tra xem bảng Cars đã tồn tại chưa,\n cur.execute(\"DROP TABLE IF EXISTS Cars\")\n# nếu rồi thì xóa bảng đó và tạo lại bảng mới.\n cur.execute(\"CREATE TABLE Cars(Id INT, Name TEXT, Price INT)\")\n\n# Chúng ta insert 8 dòng dữ liệu vào bảng bằng một phương thức duy nhất là executemany(), \n# tham số đầu tiên là một câu lệnh SQL có tham số là các dấu ?, \n# tham số thứ 2 là một tuple chứa nhiều tuple khác là các dữ liệu cần truyền vào.\n cur.executemany(\"INSERT INTO Cars VALUES(?, ?, ?)\", cars)\n\n\n# Phương thức executemany() tiện lợi hơn bằng cách thực thi nhiều câu lệnh cùng một lúc.\n","sub_path":"executemany.py","file_name":"executemany.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"40132063","text":"from django.db import models\nfrom mptt.models import MPTTModel, TreeForeignKey\nfrom userpage.models import Post\nfrom django.conf import settings\n\n\nclass Comment(MPTTModel):\n post = models.ForeignKey(\n Post, on_delete=models.CASCADE, related_name='comments')\n parent = TreeForeignKey('self', on_delete=models.CASCADE,\n null=True, blank=True, related_name='children')\n name = models.ForeignKey(\n settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name=\"user_commented\")\n content = models.TextField()\n publish = models.DateTimeField(auto_now_add=True)\n status = models.BooleanField(default=True)\n\n class MPTTMeta:\n order_insertion_by = ['publish']\n\n def __str__(self):\n return f'Comment by {self.name}'\n","sub_path":"comment/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"299453515","text":"# Copyright (c) 2015. Mount Sinai School of Medicine\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import (\n print_function,\n division,\n absolute_import,\n)\nfrom collections import namedtuple\n\nimport pandas as pd\nimport numpy as np\n\nfrom .common import normalize_allele_name\nfrom .amino_acid import amino_acid_letter_indices\n\nAlleleData = namedtuple(\"AlleleData\", \"X Y peptides ic50\")\n\n\ndef hotshot_encoding(peptides, peptide_length):\n \"\"\"\n Encode a set of equal length peptides as a binary matrix,\n where each letter is transformed into a length 20 vector with a single\n element that is 1 (and the others are 0).\n \"\"\"\n shape = (len(peptides), peptide_length, 20)\n X = np.zeros(shape, dtype=bool)\n for i, peptide in enumerate(peptides):\n for j, amino_acid in enumerate(peptide):\n k = amino_acid_letter_indices[amino_acid]\n X[i, j, k] = 1\n return X\n\n\ndef index_encoding(peptides, peptide_length):\n \"\"\"\n Encode a set of equal length peptides as a vector of their\n amino acid indices.\n \"\"\"\n X = np.zeros((len(peptides), peptide_length), dtype=int)\n for i, peptide in enumerate(peptides):\n for j, amino_acid in enumerate(peptide):\n X[i, j] = amino_acid_letter_indices[amino_acid]\n return X\n\n\ndef indices_to_hotshot_encoding(X, n_indices=None, first_index_value=0):\n \"\"\"\n Given an (n_samples, peptide_length) integer matrix\n convert it to a binary encoding of shape:\n (n_samples, peptide_length * n_indices)\n \"\"\"\n (n_samples, peptide_length) = X.shape\n if not n_indices:\n n_indices = X.max() - first_index_value + 1\n\n X_binary = np.zeros((n_samples, peptide_length * n_indices), dtype=bool)\n for i, row in enumerate(X):\n for j, xij in enumerate(row):\n X_binary[i, n_indices * j + xij - first_index_value] = 1\n return X_binary.astype(float)\n\n\ndef _infer_csv_separator(filename):\n \"\"\"\n Determine if file is separated by comma, tab, or whitespace.\n Default to whitespace if the others are not detected.\n\n Returns (sep, delim_whitespace)\n \"\"\"\n for candidate in [\",\", \"\\t\"]:\n with open(filename, \"r\") as f:\n for line in f:\n if line.startswith(\"#\"):\n continue\n if candidate in line:\n return candidate, False\n return None, True\n\n\ndef load_dataframe(\n filename,\n peptide_length=None,\n max_ic50=50000.0,\n sep=None,\n species_column_name=\"species\",\n allele_column_name=\"mhc\",\n peptide_column_name=None,\n peptide_length_column_name=\"peptide_length\",\n ic50_column_name=\"meas\",\n only_human=True):\n \"\"\"\n Load a dataframe of peptide-MHC affinity measurements\n\n filename : str\n TSV filename with columns:\n - 'species'\n - 'mhc'\n - 'peptide_length'\n - 'sequence'\n - 'meas'\n\n peptide_length : int, optional\n Which length peptides to use (default=load all lengths)\n\n max_ic50 : float\n Treat IC50 scores above this value as all equally bad\n (transform them to 0.0 in the regression output)\n\n sep : str, optional\n Separator in CSV file, default is to let Pandas infer\n\n peptide_column_name : str, optional\n Default behavior is to try {\"sequence\", \"peptide\", \"peptide_sequence\"}\n\n only_human : bool\n Only load entries from human MHC alleles\n\n Returns DataFrame augmented with extra columns:\n - \"log_ic50\" : log(ic50) / log(max_ic50)\n - \"regression_output\" : 1.0 - log(ic50)/log(max_ic50), limited to [0,1]\n \"\"\"\n if sep is None:\n sep, delim_whitespace = _infer_csv_separator(filename)\n else:\n delim_whitespace = False\n df = pd.read_csv(\n filename,\n sep=sep,\n delim_whitespace=delim_whitespace,\n engine=\"c\")\n # hack: get around variability of column naming by checking if\n # the peptide_column_name is actually present and if not try \"peptide\"\n if peptide_column_name is None:\n columns = set(df.keys())\n for candidate in [\"sequence\", \"peptide\", \"peptide_sequence\"]:\n if candidate in columns:\n peptide_column_name = candidate\n break\n if peptide_column_name is None:\n raise ValueError(\n \"Couldn't find peptide column name, candidates: %s\" % (\n columns))\n if only_human:\n human_mask = df[species_column_name] == \"human\"\n df = df[human_mask]\n if peptide_length is not None:\n length_mask = df[peptide_length_column_name] == peptide_length\n df = df[length_mask]\n\n df[allele_column_name] = df[allele_column_name].map(normalize_allele_name)\n ic50 = np.array(df[ic50_column_name])\n log_ic50 = np.log(ic50) / np.log(max_ic50)\n df[\"log_ic50\"] = log_ic50\n regression_output = 1.0 - log_ic50\n # clamp to values between 0, 1\n regression_output = np.maximum(regression_output, 0.0)\n regression_output = np.minimum(regression_output, 1.0)\n df[\"regression_output\"] = regression_output\n return df\n\n\ndef load_allele_datasets(\n filename,\n peptide_length=9,\n max_ic50=5000.0,\n binary_encoding=True,\n flatten_binary_encoding=True,\n sep=None,\n species_column_name=\"species\",\n allele_column_name=\"mhc\",\n peptide_column_name=None,\n peptide_length_column_name=\"peptide_length\",\n ic50_column_name=\"meas\",\n only_human=True):\n \"\"\"\n Loads an IEDB dataset, extracts \"hot-shot\" encoding of fixed length peptides\n and log-transforms the IC50 measurement. Returns dictionary mapping allele\n names to AlleleData objects (containing fields X, Y, ic50)\n\n Parameters\n ----------\n filename : str\n TSV filename with columns:\n - 'species'\n - 'mhc'\n - 'peptide_length'\n - 'sequence'\n - 'meas'\n\n peptide_length : int\n Which length peptides to use (default=9)\n\n max_ic50 : float\n Treat IC50 scores above this value as all equally bad\n (transform them to 0.0 in the rescaled output)\n\n binary_encoding : bool\n Encode amino acids of each peptide as indices or binary vectors\n\n flatten_features : bool\n If False, returns a (n_samples, peptide_length, 20) matrix, otherwise\n returns the 2D flattened version of the same data.\n\n sep : str, optional\n Separator in CSV file, default is to let Pandas infer\n\n peptide_column_name : str, optional\n Default behavior is to try {\"sequence\", \"peptide\", \"peptide_sequence\"}\n\n only_human : bool\n Only load entries from human MHC alleles\n \"\"\"\n df = load_dataframe(\n filename=filename,\n max_ic50=max_ic50,\n sep=sep,\n peptide_length=peptide_length,\n species_column_name=species_column_name,\n allele_column_name=allele_column_name,\n peptide_column_name=peptide_column_name,\n peptide_length_column_name=peptide_length_column_name,\n ic50_column_name=ic50_column_name,\n only_human=only_human)\n\n allele_groups = {}\n for allele, group in df.groupby(allele_column_name):\n ic50 = np.array(group[ic50_column_name])\n Y = np.array(group[\"regression_output\"])\n peptides = list(group[peptide_column_name])\n if binary_encoding:\n X = hotshot_encoding(peptides, peptide_length=peptide_length)\n if flatten_binary_encoding:\n # collapse 3D input into 2D matrix\n X = X.reshape((X.shape[0], peptide_length * 20))\n else:\n X = index_encoding(peptides, peptide_length=peptide_length)\n assert allele not in allele_groups, \\\n \"Duplicate datasets for %s\" % allele\n allele_groups[allele] = AlleleData(\n X=X,\n Y=Y,\n ic50=ic50,\n peptides=peptides)\n return allele_groups\n","sub_path":"mhcflurry/data_helpers.py","file_name":"data_helpers.py","file_ext":"py","file_size_in_byte":8535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"589191127","text":"# coding:utf-8\n\nimport datetime\nfrom flask import Blueprint, render_template, request, jsonify\nfrom flask_security import login_required\nimport sqlalchemy as sqla\n\nfrom ..service import productOrderService, productService\nfrom ..model import ProductOrder, ProductOrderItem, Product\n\nbp = Blueprint(\"productOrders\", __name__, url_prefix=\"/productorders\")\n\n\n@bp.route(\"/\", methods=[\"GET\"])\n@login_required\ndef mgr():\n products = productService.all()\n return render_template(\"orderMgr.html\", products=products)\n\n\n@bp.route(\"/create\", methods=[\"GET\"])\n@login_required\ndef form():\n return render_template(\"orderUpdate.html\")\n\n\n@bp.route(\"/create\", methods=[\"POST\"])\n@login_required\ndef create_order():\n productOrderService.add_product_order(**request.form.to_dict())\n return jsonify(data=dict(success=True))\n\n\n@bp.route(\"//set-status\", methods=[\"POST\"])\n@login_required\ndef set_order_status(product_order_id):\n status = int(request.form.get(\"status\", \"1\"))\n memo = request.form.get(\"memo\")\n productOrderService.set_product_order_status(product_order_id, status, memo)\n return jsonify(data=dict(success=True))\n\n\n@bp.route(\"//add\", methods=[\"POST\"])\n@login_required\ndef add_order_item(product_order_id):\n productOrderService.add_product_order_item(product_order_id=product_order_id, **request.form.to_dict())\n return jsonify(data=dict(success=True))\n\n\n@bp.route(\"//remove/\", methods=[\"POST\"])\n@login_required\ndef remove_order_item(product_order_id, item_id):\n productOrderService.remove_product_order_item(product_order_id, item_id)\n return jsonify(data=dict(success=True))\n\n\n@bp.route(\"//items\", methods=[\"GET\"])\n@login_required\ndef list_order_items(product_order_id):\n items = productOrderService.get_product_order_items(product_order_id)\n if items:\n items = [item.asdict(only=ProductOrderItem.__dictfields__) for item in items]\n return jsonify(data=dict(success=True, items=items))\n\n\n@bp.route(\"///add_outstock\", methods=[\"POST\"])\n@login_required\ndef order_item_add_outstock(product_order_id, item_id):\n date_outstock = datetime.datetime.strptime(request.form.get(\"date_outstock\"), '%Y-%m-%d')\n serial_no_list = request.form.get(\"serial_no\").replace(u\",\", \",\").split(\",\")\n invalid_serial_no, duplicate_serial_no = productOrderService. \\\n add_product_order_item_outstock(product_order_id, item_id, date_outstock, serial_no_list)\n if invalid_serial_no or duplicate_serial_no:\n data = dict(success=False, invalid_serial_no=invalid_serial_no, duplicate_serial_no=duplicate_serial_no)\n else:\n data = dict(success=True)\n return jsonify(data=data)\n\n\n@bp.route(\"///remove_outstock\", methods=[\"POST\"])\n@login_required\ndef order_item_remove_outstock(product_order_id, item_id):\n serial_no = request.form.get('serial_no')\n productOrderService.remove_product_order_item_outstock(product_order_id, item_id, serial_no)\n return jsonify(data=dict(success=True))\n\n\n@bp.route(\"/list\", methods=[\"GET\"])\n@login_required\ndef data():\n limit = int(request.args.get(\"iDisplayLength\", \"10\"))\n offset = int(request.args.get(\"iDisplayStart\", \"0\"))\n sEcho = request.args.get(\"sEcho\")\n content = request.args.get('content')\n if content:\n content = '%' + content + '%'\n filters = [sqla.or_(ProductOrder.product.has(Product.name.like(content)), ProductOrder.order_no.like(content))]\n else:\n filters = []\n count, data = productOrderService.paginate(filters=filters, offset=offset, limit=limit)\n if data:\n data = [product_order.asdict(only=ProductOrder.__dictfields__) for product_order in data]\n return jsonify(data=dict(success=True, sEcho=sEcho, iTotalRecords=count, iTotalDisplayRecords=count, aaData=data))\n\n\n","sub_path":"program/frontend/product_orders.py","file_name":"product_orders.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"33218651","text":"from world.utils import printer\n\n\nclass Monster(object):\n\n def __init__(self, name, level, intro_message, body_message,\n defeated_message, attack_message, evaluate_function):\n self.name = name\n self.level = level\n self.intro_message = intro_message\n self.body_message = body_message\n self.defeated_message = defeated_message\n self.attack_message = attack_message\n self.evaluate_function = evaluate_function\n\n def introduction(self):\n printer(self.intro_message)\n printer(self.body_message)\n\n def attack(self):\n printer(self.attack_message)\n printer('You received {0} damage!'.format(self.level))\n\n def defeat(self):\n printer(self.defeated_message)\n printer('You defeated {}!'.format(self.name))\n\n def evaluate(self, ans):\n try:\n return self.evaluate_function(ans)\n except:\n return False\n\n def __eq__(self, monster):\n return self.name == monster.name\n\n\n# Just place the evaluate functions of the monsters inside this function\n# so that the kids wouldn't be able to hack the answer\n# It would be advised that the monsters are in order of their level.\ndef create_the_monsters():\n monsters = []\n\n # -------------------------------------------\n # ----------- BITTER WOMAN LVL. 1 -----------\n # -------------------------------------------\n name = 'Bitter Woman'\n level = 1\n intro = ('A wild Bitter Woman appeared!\\n'\n 'Bitter Woman: Walang forever!')\n body = ('Provide a function that accepts a positive integer n, then '\n 'returns the string \\'#walangforever\\' (without quotes) n times '\n 'without being separated by a new line.\\n'\n 'For example:\\n'\n ' your_function(3)\\n'\n 'should return:\\n'\n ' #walangforever#walangforever#walangforever')\n defeat = 'Bitter Woman died of loneliness.'\n attack = 'Bitter Woman used flirt!'\n\n def eval1(answer):\n assert answer(10) == '#walangforever' * 10\n assert answer(1) == '#walangforever'\n assert answer(100) == '#walangforever' * 100\n return True # always remember to return True\n\n monster1 = Monster(name, level, intro, body, defeat, attack, eval1)\n monsters.append(monster1)\n\n # -------------------------------------------------\n # ------------ Hungry Mathematician LVL. 2 --------\n # -------------------------------------------------\n name = 'Hungry Mathematician'\n level = 2\n intro = ('A Hungry Mathematician appeared!\\n'\n 'Mathematician: I will eat your mother\\'s pi unless you solve '\n 'this problem!')\n body = ('What is the sum of all even positive integers less than a given '\n 'positive integer n? Provide a function than accepts n and '\n 'returns the right answer.')\n defeat = 'Mathematician died of hunger.'\n attack = 'Mathematician used Number Theory!'\n\n def eval2(answer):\n def solution(n):\n i = 2\n s = 0\n while i < n:\n s += i\n i += 2\n return s\n\n for number in [1, 100, 20]:\n assert answer(number) == solution(number)\n return True # always remember to return True\n\n monster2 = Monster(name, level, intro, body, defeat, attack, eval2)\n monsters.append(monster2)\n\n # ---------------------------------------------------------\n # -------------- Indecisive Shoplifter LVL. 2 -------------\n # ---------------------------------------------------------\n name = 'Indecisive Shoplifter'\n level = 2\n intro = ('An Indecisive Shoplifter appeared!\\n'\n 'Indecisive Shoplifter: Should I steal this? or this? or that? '\n 'maybe all of them.')\n body = ('A shoplifter would speak out her reaction aloud after seeing '\n 'the price of the dress she wanted to steal.\\n'\n 'If the price is 100 pesos or less, she would say, \"No one is '\n 'stealing this cheap sh*t!\".\\n'\n 'If the price is 500 pesos or less, but greater than 100 pesos, '\n 'she would say, \"This one is a class A replica!\".\\n'\n 'If the price is 1000 pesos or less, but greater than 500 pesos, '\n 'she would say, \"This is okay. Just going to fit it, not steal '\n 'it!\".\\n'\n 'If the price is greater than 1000 pesos, she would say, \"I have '\n 'to steal this!\"\\n'\n 'Provide a function that accepts the dress price, then returns '\n 'the appropriate reaction of the shoplifter (in string).')\n defeat = 'Indecisive Shoplifter died of losing the dress she never owned.'\n attack = 'Indecisive Shoplifter attacked with a purse she never owned.'\n\n def eval3(answer):\n def solution(n):\n if n <= 100:\n return 'No one is stealing this cheap sh*t!'\n elif n <= 500:\n return 'This one is a class A replica!'\n elif n <= 1000:\n return 'This is okay. Just going to fit it, not steal it!'\n else:\n return 'I have to steal this!'\n\n for n in [0, 100, 500, 1000, 1001]:\n assert answer(n) == solution(n)\n return True # always remember to return True\n\n monster3 = Monster(name, level, intro, body, defeat, attack, eval3)\n monsters.append(monster3)\n\n # -------------------------------------------------------\n # -------------- Scumbag Taxi Driver LVL. 2 -------------\n # -------------------------------------------------------\n name = 'Scumbag Taxi Driver'\n level = 2\n intro = ('A Scumbag Taxi Driver appeared!\\n'\n 'Taxi Driver: Asa ka dong? (giggles)')\n body = ('The total taxi ride cost is divided into 4 parts:\\n'\n '1) An initial of P40\\n'\n '2) P3.50 for at least every 0.5 km travelled.\\n'\n '3) P3.50 for at least every 30 seconds stationary.\\n'\n '4) If you are new to cebu, the driver asks for an additional of '\n 'P100\\n'\n 'Provide a function that accepts 3 parameters: kms travelled, '\n 'number of seconds the taxi is stationary, and a boolean '\n 'signifying if the passenger is new to cebu (True) or not '\n '(False).\\n'\n 'For example:\\n'\n ' your_function(3.6, 60, True)\\n'\n 'should return:\\n'\n ' 171.5')\n defeat = 'Taxi Driver died of being sued of illegal addition of fees.'\n attack = 'Taxi Driver attacked with hit and run!'\n\n def eval4(answer):\n def solution(km, sec, new):\n ans = 40 + (km // 0.5 * 3.5) + (sec // 30 * 3.5)\n ans += (100 if new else 0)\n return ans\n\n for km, sec, new in [(3.6, 60, True), (5, 33, False)]:\n assert answer(km, sec, new) == solution(km, sec, new)\n return True # always remember to return True\n\n monster4 = Monster(name, level, intro, body, defeat, attack, eval4)\n monsters.append(monster4)\n\n # ---------------------------------------------------------\n # --------- Cheating Presidential Candidate LVL. 3 --------\n # ---------------------------------------------------------\n name = 'Cheating Presidential Candidate'\n level = 3\n intro = ('A Cheating Presidential Candidate appeared!\\n'\n 'Cheating Presidential Candidate: Vote for me! Vote for me! '\n '(throws 1000 peso bills to people)')\n body = ('This cheating candidate stole (10%) from each of his opponents\\' '\n 'total votes by hacking the voting system. What\\'s bad about it '\n 'is that he used Python to do so. This person deserves no '\n 'respect, not because he gave free money to everyone, but '\n 'because he used Python as a tool for his evil deeds.\\n'\n 'Given a list of integers siginifying the votes of the '\n 'cheater\\'s opponents, return an array of integers signifying the '\n 'actual number of votes before they were altered.\\n'\n 'For example:\\n'\n ' your_function([99, 9, 270, 111105])\\n'\n 'should return:\\n'\n ' [110, 10, 300, 123450]')\n defeat = ('Cheating Presidential Candidate died of assassination ordered '\n 'by another presidential candidate.')\n attack = ('Cheating Presidential Candidate used lies, and money, and '\n 'more lies.')\n\n def eval5(answer):\n def solution(votes):\n return [int(x/0.9) for x in votes]\n\n cases = [[99, 10, 270, 111105], [0]]\n for case in cases:\n assert answer(case) == solution(case)\n\n return True # always remember to return True\n\n monster5 = Monster(name, level, intro, body, defeat, attack, eval5)\n monsters.append(monster5)\n\n # ---------------------------------------------------------\n # -------------- Super Addicted Gamer LVL. 3 --------------\n # ---------------------------------------------------------\n name = 'Super Addicted Gamer'\n level = 3\n intro = ('A Super Addicted Gamer appeared!\\n'\n 'Addicted Gamer: Stun oi! Bugo! Yawa!')\n body = ('In a game called Dota2, every hero has at least 4 skills. '\n 'Some of them are burst damage while some are passive skills.\\n'\n 'Provide a function that returns the total burst damage when '\n 'given a dictionary composed of keys as their skills\\' names '\n '(string) and values as the amount of damage the skill inflicts. '\n 'For passive skills, the value would not be the amount of damage, '\n 'but instead the string \\'passive\\'.\\n'\n 'For example:\\n'\n ' your_function({\\'stun\\': 100, \\'2nd skill\\': \\'passive\\', '\n '\\'skill that inflicts damage\\': 150, \\'ultimate skill\\': '\n '10000})\\n'\n 'should return:\\n'\n ' 10250')\n defeat = ('Addicted Gamer died of not enjoying life to the fullest.')\n attack = ('Addicted Gamer used a speech about you being a stupid person '\n 'when you\\'re not good at gaming.')\n\n def eval6(answer):\n def solution(skills):\n s = 0\n for v in skills.values():\n if type(v) == int:\n s += v\n return s\n\n cases = [\n {'stun': 100, '2nd skill': 'passive',\n 'skill that inflicts damage': 150, 'ultimate skill': 10000},\n {'skill': 'passive'},\n {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1}]\n\n for case in cases:\n assert answer(case) == solution(case)\n return True # always remember to return True\n\n monster6 = Monster(name, level, intro, body, defeat, attack, eval6)\n monsters.append(monster6)\n\n # ---------------------------------------------------------\n # -------------- Cat-calling Carpenter LVL. 3 -------------\n # ---------------------------------------------------------\n name = 'Cat-calling Carpenter'\n level = 3\n intro = ('A Cat-calling Carpenter appeared!\\n'\n 'Cat-calling Carpenter: Hi miga! Can i have your number miga? '\n 'Salig chicks kaayu, nagminaldita na ang akong miga. (grins)')\n body = ('You have to show this guy that you deserve some respect. You\\'re '\n 'not a chick, you\\'re a Pythonista chick! You should show him a '\n 'good design for a fence. A fence is composed of pickets '\n '(vertical bars) and rails (horizontal bars). For your design, '\n 'there are only two rails: for the top most part and the lowest '\n 'part of the fence. In between two pickets is a space. And the '\n 'function you need to provide returns a string composed of:\\n'\n '\\'-\\' to signify part of a rail,\\n'\n '\\'|\\' to signify one unit of a picket,\\n'\n '\\' \\' to signify the space between two pickets, and\\n'\n '\\'+\\' to signify the intersection between a rail and a picket\\n'\n 'You will be given 2 parameters: the height of the fence and the '\n 'number of pickets. Assume that the given height is at least 3 '\n 'units and the number of pickets is at least 3.'\n 'For example:\\n'\n ' your_function(5, 7)\\n'\n 'should return:\\n'\n '+-+-+-+-+-+-+\\n'\n '| | | | | | |\\n'\n '| | | | | | |\\n'\n '| | | | | | |\\n'\n '+-+-+-+-+-+-+')\n defeat = ('Cat-calling Carpenter died of being stoned to death by '\n 'hardcore feminists.')\n attack = ('Cat-calling Carpenter slapped your butt, then looks at you '\n 'while biting his lips.')\n\n def eval7(answer):\n def solution(height, pickets):\n end = '+' + ('-+' * (pickets-1))\n mid = '|' + (' |' * (pickets-1)) + '\\n'\n return end + '\\n' + (mid * (height-2)) + end\n\n for h, p in [(5, 7), (3, 3), (10, 10)]:\n assert answer(h, p) == solution(h, p)\n\n return True # always remember to return True\n\n monster7 = Monster(name, level, intro, body, defeat, attack, eval7)\n monsters.append(monster7)\n\n # ---------------------------------------------------------\n # ----------------- Violent Drunk LVL. 4 ------------------\n # ---------------------------------------------------------\n name = 'Violent Drunk'\n level = 4\n intro = ('A Violent Drunk appeared!\\n'\n 'Violent Drunk: @ha% %h# f&ck a$# y(& l((k*ng a%')\n body = ('Seriously, we need to understand this guy first. Fighting this '\n 'monster is like watching anime without subtitles. Here are the '\n 'equivalent letters to a symbol:\\n'\n '! = q\\n'\n '@ = w\\n'\n '# = e\\n'\n '$ = r\\n'\n '% = t\\n'\n '^ = y\\n'\n '& = u\\n'\n '* = i\\n'\n '( = o\\n'\n ') = p\\n'\n 'Provide a function that returns the deciphered message given a '\n 'string, which is what the drunkard said.\\n'\n 'For example:\\n'\n ' your_function(\\'h* c&%*#\\')\\n'\n 'should return:\\n'\n ' hi cutie')\n defeat = 'Violent Drunk died of choking in his own vomit.'\n attack = 'Violent Drunk used vomit on your face.'\n\n def eval8(answer):\n def solution(message):\n d = {'!': 'q',\n '@': 'w',\n '#': 'e',\n '$': 'r',\n '%': 't',\n '^': 'y',\n '&': 'u',\n '*': 'i',\n '(': 'o',\n ')': 'p'}\n deciphered = ''\n for c in message:\n if c in d.keys():\n deciphered += d[c]\n else:\n deciphered += c\n return deciphered\n\n for m in ['@ha% %h# f&ck a$# y(& l((k*ng a%', 'h* c&%*#']:\n assert answer(m) == solution(m)\n return True # always remember to return True\n\n monster8 = Monster(name, level, intro, body, defeat, attack, eval8)\n monsters.append(monster8)\n\n # ---------------------------------------------------------\n # ---------- Suspicious Drug Dealer LVL. 4 ----------------\n # ---------------------------------------------------------\n name = 'Suspicious Drug Dealer'\n level = 4\n intro = ('A Suspicious Drug Dealer appeared!\\n'\n 'Suspicious Drug Dealer: I tell you, this is a very, very '\n 'strong one! (shows packs of mik-mik)')\n body = ('This Drug Dealer has three kinds of drugs. He gave you prices '\n 'for each kind but they are not the actual prices. The '\n 'first price is twice more expensive than its real price. The '\n 'second is 20 pesos more expensive than its real price. And the '\n 'last is cheaper than the real price by 1 peso.\\n'\n 'Provide a function that accepts a tuple of three integers (the '\n 'fake prices) and returns a tuple of integers of the real prices '\n 'in order from cheapest to most expensive.\\n'\n 'For example:\\n'\n ' your_function((30, 30, 30))\\n'\n 'should return:\\n'\n ' (10, 15, 31)')\n defeat = 'Suspicious Drug Dealer died by the hands of Duterte.'\n attack = ('Suspicious Drug Dealer injected you with something you don\\'t '\n 'want to know.')\n\n def eval9(answer):\n def solution(prices):\n x, y, z = prices\n a = [x / 2, y - 20, z + 1]\n a.sort()\n return tuple(a)\n\n for t in [(30, 30, 30), (10, 24, 2), (10, 50, 10)]:\n assert answer(t) == solution(t)\n return True # always remember to return True\n\n monster9 = Monster(name, level, intro, body, defeat, attack, eval9)\n monsters.append(monster9)\n\n # ---------------------------------------------------------\n # ------------- Emmanuel Lodovice LVL. 5 ------------------\n # ---------------------------------------------------------\n name = 'Emmanuel Lodovice'\n level = 5\n intro = ('Warning! Warning! Warning!\\n'\n 'Bost Fight!\\n'\n 'Are you sure you want to fight this last monster (y/n)?\\n'\n 'You are gonna fight him anyway.\\n'\n 'Emmanuel Lodovice appeared!\\n'\n 'Emmanuel Lodovice: ...')\n body = ('Emmanuel Lodovice is one of the greatest legends of UP CEBU. '\n 'A monster is nothing compared to him. He is more like a GOD. '\n 'You shouldn\\'t disappoint him with your answers.\\n'\n 'You need to provide a function that returns a dictionary '\n 'composed of three keys:\\n'\n 'name => a function that accepts a firstname and a lastname, '\n 'then returns a string in the format of \\'lastname, firstname\\'\\n'\n 'organize => a function that accepts a list then returns a '\n 'dictionary with elements indexes\\' as keys and the elements as '\n 'values.\\n'\n 'encode => a function that accepts a string of at least '\n 'length=1, then returns a tuple composed of:\\n'\n ' length of the string,\\n'\n ' last character of the string,\\n'\n ' the string without the last character\\n'\n ' and a list of all its characters excluding whitespaces.')\n defeat = ('Emmanuel Lodovice: ...\\n'\n 'Emmanuel Lodovice walked away, hiding the smile from his '\n 'face.')\n attack = ('Emmanuel Lodovice turned his back.')\n\n def eval10(answer):\n ans = answer()\n assert ans['name']('Eman', 'Lodovice') == 'Lodovice, Eman'\n assert (\n ans['organize'](['Eman', 3.2, True]) ==\n {0: 'Eman', 1: 3.2, 2: True})\n s = 'baboy ka'\n t = (8, 'a', 'baboy k', ['b', 'a', 'b', 'o', 'y', 'k', 'a'])\n assert ans['encode'](s) == t\n return True\n\n monster10 = Monster(name, level, intro, body, defeat, attack, eval10)\n monsters.append(monster10)\n\n return monsters\n","sub_path":"monsters.py","file_name":"monsters.py","file_ext":"py","file_size_in_byte":19178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"362500536","text":"import tensorflow as tf\nimport numpy as np\nimport time\n\ngsize = 1000\ngsparse = 1\nG_TEST_MODE = 'sparse'\nG_TEST_MODE = 'matmul'\n\ngssize = str(gsize)\ngssparse = str(gsparse)\ngfilename = '../text_matrix/matrix' + '_' + gssize + '_' + gssparse + '.txt' \ngbckname = 'trained_' + gssize + '_' + gssparse\ngpbname = '../data_' + G_TEST_MODE + '/'\n\ngtry = 500\ngcheck = 50\n\ngfile = np.loadtxt(gfilename, delimiter=' ', dtype=np.float32)\n\nxd = gfile[:, 0:-1]\nyd = gfile[:, [-1]]\n\nx = tf.placeholder(tf.float32, shape=[None, gsize])\ny = tf.placeholder(tf.float32, shape=[None, 1])\n\n\nif G_TEST_MODE == 'matmul':\n\n\n\tw1 = tf.Variable(tf.random_normal([gsize, gsize]), name = 'weight')\n\tlayer1 = tf.matmul(x, w1)\n\tw2 = tf.Variable(tf.random_normal([gsize, gsize]), name='weight')\n\tlayer2 = tf.matmul(x, w2)\n\tw3 = tf.Variable(tf.random_normal([gsize, gsize]), name='weight')\n\tlayer3 = tf.matmul(x, w3)\n\tw4 = tf.Variable(tf.random_normal([gsize, gsize]), name='weight')\n\tlayer4 = tf.matmul(x, w4)\n\n\nelse :\n\tw1 = tf.Variable(tf.random_normal([gsize, gsize]), name='weight')\n\tlayer1 = tf.sparse_matmul(x, w1)\n\tw2 = tf.Variable(tf.random_normal([gsize, gsize]), name='weight')\n\tlayer2 = tf.sparse_matmul(x, w2)\n\tw3 = tf.Variable(tf.random_normal([gsize, gsize]), name='weight')\n\tlayer3 = tf.sparse_matmul(x, w3)\n\tw4 = tf.Variable(tf.random_normal([gsize, gsize]), name='weight')\n\tlayer4 = tf.sparse_matmul(x, w4)\n\nhy = layer1 + layer2 + layer3 + layer4\ncost = tf.reduce_mean(tf.square(hy - y))\n\n\nwith tf.Session() as sess:\n\tsess.run(tf.global_variables_initializer())\n\tbeforetime = time.time()\n\tcnt_print = 0.0\n\tcnt_time = 0.0\n\tfor step in range(gtry + 1):\n\t\tcost_val = sess.run([cost], feed_dict={x:xd, y:yd})\n\t\tif step > 0 and step % gcheck == 0:\n\t\t\taftertime = time.time()\n\t\t\tprint(step, \" time : \", aftertime-beforetime)\n\t\t\tcnt_time += (aftertime - beforetime)\n\t\t\tbeforetime = time.time()\n\t\t\tcnt_print += 1.0\n\n\tgdirname = gpbname + G_TEST_MODE + '_' + gbckname + '/' + G_TEST_MODE + '_' + gbckname\n\tprint(\"DIRECTORY : \", gdirname)\n\ttf.train.Saver().save(sess, gdirname + '.ckpt')\n\n\ttf.train.write_graph(sess.graph_def, \".\", gdirname + '.pb', as_text=False)\n\ttf.train.write_graph(sess.graph_def, \".\", gdirname + '.txt', as_text=True)\n\t\n\n\tprint(\"\\nEntire time : \", cnt_time, \"\\nAverage time : \", cnt_time / cnt_print)\n\n\n","sub_path":"hiai/source/kyh.py","file_name":"kyh.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"590295341","text":"# -*- coding: utf-8 -*-\n\"\"\"\n https://www.acmicpc.net/problem/2292\n https://elrion018.tistory.com/18\n\"\"\"\nN = int(input())\n\nfirst = 1\nplus = 6\nroom = 1\n\nif N == 1:\n print(1)\nelse:\n while True:\n first = first + plus\n room += 1\n if N <= first:\n print(room)\n break\n plus += 6\n","sub_path":"2292.py","file_name":"2292.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"102315409","text":"from project.demoHasCycleUF import writeResults\nimport unionfind.quickUnion\nimport project.GraphGenerator as GraphGenerator\nimport graph.Graph_AdjacencyList\nimport random\n\n\n@writeResults\ndef hasCycleDFS(G, rand=False):\n \"\"\"\n Esegue una visita DFS nel grafo G a partire dal primo nodo, o da un nodo random, aseconda del parametro rand.\n Mantiene bool di marcatura per ogni nodo tramite indicizzazione diretta su una lista, verifica se ci sono archi\n all'indietro, ovvero da un nodo ad uno già visitato che non ne sia il padre. Se non ci sono archi all'indietro\n il grafo è aciclico.\n :param G: Graph.\n :param rand: bool.\n :return: bool.\n \"\"\"\n if rand:\n rootId = random.choice(list(G.nodes.keys())) # inizia la visita da un nodo random\n else:\n rootId = list(G.nodes.keys())[0]\n visited = [False for _ in G.nodes] # inizializza la lista di marcatura\n return hasCycleDFSRecursive(G, rootId, visited, rootId) # inizia la visita vera e propria\n\n\ndef hasCycleDFSRecursive(G, v, visited, fatherId):\n visited[v] = True # marca il nodo v come visitato\n for adjNode in G.getAdj(v):\n if not visited[adjNode]:\n if hasCycleDFSRecursive(G, adjNode, visited, v): # se la chiamata ricorsiva individua un ciclo\n return True # ritorna True\n elif adjNode != fatherId:\n return True\n\n return False\n\n\nclass EdgesIterator:\n def __init__(self, G):\n self.n = -1\n self.edges = G.getEdges()\n self.lastIndex = len(self.edges) - 1\n\n def __iter__(self):\n return self\n\n def __next__(self):\n self.n += 1\n if self.n > self.lastIndex:\n raise StopIteration\n return self.edges[self.n]\n\n\n@writeResults\ndef hasCycleUF(G):\n \"\"\"\n Controlla se il grafo ha un ciclo sfruttando la struttura dati Union-Find.\n :param G: Graph.\n :return: bool.\n \"\"\"\n uf = unionfind.quickUnion.QuickUnionBalanced()\n for n in G.nodes.keys():\n uf.makeSet(n)\n marked = set()\n for edge in EdgesIterator(G):\n if (edge.head, edge.tail) in marked:\n continue\n else:\n # aggiungi solo l'arco (edge.tail, edge.head) a marked, dato che (edge.head, edge.tail)\n # non verrà più generato dall'iterator\n marked.add((edge.tail, edge.head))\n if uf.find(uf.nodes[edge.head]) == uf.find(uf.nodes[edge.tail]):\n return True\n\n else:\n uf.union(uf.findRoot(uf.nodes[edge.head]), uf.findRoot(uf.nodes[edge.tail]))\n\n return False\n\n\ndef repeatedTest(func, typeOfGraph, maxN, steps, *otherParameters):\n # per semplicita' si assuma maxN % steps = 0\n assert typeOfGraph in range(4)\n file = open(\"{}.txt\".format(func.__name__), \"a\")\n\n delta = int(maxN / steps)\n\n if typeOfGraph == 0:\n file.write(\"Acyclic:\\n\")\n elif typeOfGraph == 1:\n file.write(\"Cyclic:\\n\")\n elif typeOfGraph == 2:\n file.write(\"Random:\\n\")\n else:\n file.write(\"Complete:\\n\")\n\n file.close()\n\n temp = delta\n while temp <= maxN:\n G = graph.Graph_AdjacencyList.GraphAdjacencyList()\n if typeOfGraph == 0:\n GraphGenerator.generateAcyclicGraph(G, temp)\n elif typeOfGraph == 1:\n GraphGenerator.generateCyclicGraphNaive(G, temp)\n elif typeOfGraph == 2:\n GraphGenerator.generateRandGraph(G, temp)\n else:\n GraphGenerator.generateCompleteGraph(G, temp)\n\n func(G, *otherParameters)\n temp += delta\n\n print(\"Done!\")\n\n\nif __name__ == \"__main__\":\n for i in range(4):\n if i == 3:\n repeatedTest(hasCycleUF, i, 2000, 10) # build a smaller graph if complete\n else:\n repeatedTest(hasCycleUF, i, 5000, 10)\n for i in range(4):\n if i == 1:\n repeatedTest(hasCycleDFS, i, 5000, 10, True) # select a random rootId if graph is cyclic\n elif i == 3:\n repeatedTest(hasCycleDFS, i, 2000, 10) # build a smaller graph if complete\n else:\n repeatedTest(hasCycleDFS, i, 5000, 10)\n","sub_path":"project/demoHasCycle.py","file_name":"demoHasCycle.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"4404417","text":"# Exercicio 1\n# Crie um algoritmo que receba, como entrada, o valor de três notas de um aluno -\n# com valor entre 0 e 10, e, em seguida, informe a média entre elas.\n\ndef media_notas(nota1, nota2, nota3):\n media_notas = (nota1+nota2+nota3)/3\n media_notas = round(media_notas,2)\n return media_notas\n\nnota1 = float(input('informe a primeira nota do aluno: '))\nnota2 = float(input('informe a segunda nota do aluno: '))\nnota3 = float(input('informe a receira nota do aluno: '))\n\nprint(f'A media de notas do aluno e: {media_notas(nota1, nota2,nota3)}')\n\n","sub_path":"Lista 01/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"27929987","text":"import backtrader as bt\nimport os\nfrom datetime import datetime, date, time\n\nclass MyStrategy(bt.Strategy):\n params = dict(maperiod=5)\n\n def log(self, txt, dt=None):\n \"\"\" Logging function for this strategy\"\"\"\n dt = dt or self.datas[0].datetime.date(0)\n print('%s, %s' % (dt.isoformat(), txt))\n\n def __init__(self):\n # Keep a reference to the \"close\" line in the data[0] dataseries\n self.dataclose = self.datas[0].close\n\n # To keep track of pending orders\n self.order = None\n\n # Add a MovingAverageSimple indicator\n self.sma = bt.ind.SMA(period=self.params.maperiod)\n\n def next(self):\n # Simply log the closing price of the series from the reference\n if len(self) > 2 and self.data0.low < self.data[-1].low and \\\n self.data[-1].close < self.data[-1].open and \\\n self.data[-2].close > self.data[-2].open and not self.position:\n self.sell()\n self.order = self.sell()\n\n if self.position and self.data[-1].close > self.data[-1].open and \\\n self.data[-1].close > self.sma(5) and self.data[0].high > self.data[-1].high:\n self.buy()\n self.order = self.buy()\n\n def notify_trade(self, trade):\n if not trade.isclosed:\n return\n\n self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %\n (trade.pnl, trade.pnlcomm))\n\n def notify_order(self, order):\n if order.status in [order.Submitted, order.Accepted]:\n # Buy/Sell order submitted/accepted to/by broker - Nothing to do\n return\n\n # Check if an order has been completed\n # Attention: broker could reject order if not enough cash\n if order.status in [order.Completed]:\n if order.isbuy():\n self.log('BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %\n (order.executed.price, order.executed.value, order.executed.comm))\n elif order.issell():\n self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %\n (order.executed.price, order.executed.value, order.executed.comm))\n\n elif order.status in [order.Canceled, order.Margin, order.Rejected]:\n self.log('Order Canceled/Margin/Rejected')\n\n # Write down: no pending order\n self.order = None\n\n\n\n\nif __name__ == '__main__':\n cerebro = bt.Cerebro()\n\n # Add a strategy\n cerebro.addstrategy(MyStrategy)\n\n modpath = os.path.abspath('d:\\ib\\data')\n #datapath = os.path.join(modpath, 'hsi_uptoday.csv')\n datapath = os.path.join(modpath, '1.txt')\n\n # Create a Data Feed\n data = bt.feeds.CSVData(dataname=datapath)\n \"\"\"\n data = bt.feeds.GenericCSVData(\n dataname=datapath,\n\n fromdate=datetime(2018, 7, 1),\n todate=datetime(2018, 12, 31),\n\n nullvalue=0.0,\n\n dtformat=('%Y-%m-%d'),\n\n datetime=0,\n time=1,\n open=2,\n high=3,\n low=4,\n\n close=5,\n volume=6,\n openinterest=-1\n )\"\"\"\n\n # Add the Data Feed to Cerebro\n cerebro.adddata(data)\n\n # Set our desired cash start\n cerebro.broker.setcash(100000.0)\n\n # Add a FixedSize sizer according to the stake\n cerebro.addsizer(bt.sizers.FixedSize, stake=10)\n\n # Set the commission - 0.1% ... divide by 100 to remove the %\n cerebro.broker.setcommission(commission=0.001)\n\n cerebro.run()\n\n print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())\n\n","sub_path":"main/ta/strategies/S1.py","file_name":"S1.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"460839123","text":"import random\n\nclass Perceptron:\n def __init__(self): \n self.bias = 0.0\n self.weights = [] \n \n def __str__(self):\n return '[Perceptron, bias: {}, weight count: {}, weights: {}]'.format(\n self.bias, len(self.weights), self.weights)\n \n # count: number of weights (not including bias)\n def assign_random_weights(self, count, low=-1.0, high=1.0):\n self.bias = random.uniform(low, high)\n self.weights = [] \n for i in range(count):\n self.weights.append(random.uniform(low, high))\n \n # return: True or False\n def get_output_bool(self, input): \n if len(input) != len(self.weights):\n raise Exception(\"Different lengths of 'input' and 'weights'\") \n sum = self.bias\n for i in range(len(self.weights)):\n sum += self.weights[i] * input[i]\n return sum > 0.0\n \n # return: 1.0 or -1.0\n @staticmethod\n def out_bool_to_float(out_bool):\n if out_bool:\n return 1.0\n else:\n return -1.0\n \n # return: 1.0 or -1.0\n def get_output_float(self, input):\n return self.out_bool_to_float(self.get_output_bool(input))\n \n def train(self, train_data, learning_rate, max_cycles):\n i = 0\n mods = 0\n while i < max_cycles:\n mods = self.train_cycle(train_data, learning_rate)\n i += 1\n if mods == 0:\n break \n print('Train cycles:', i)\n if mods == 0:\n print('Train result: success')\n else:\n print('Train result: FAILURE')\n\n # return: count of steps that modified weights\n def train_cycle(self, train_data, learning_rate):\n ret = 0\n print('Train cycle begin for', self)\n for td in train_data: \n perc_result_bool = self.get_output_bool(td.input)\n if perc_result_bool == td.result_bool:\n continue\n \n ret += 1\n direction = self.out_bool_to_float(td.result_bool)\n self.bias += learning_rate * direction\n for i in range(len(self.weights)):\n self.weights[i] += learning_rate * direction * td.input[i]\n print('Weights modified:', self)\n \n print('Train cycle finished:', self)\n print('Steps with modifications:', ret)\n return ret \n \nclass TrainSample: \n def __init__(self, input, result_bool):\n self.input = input\n self.result_bool = result_bool\n \n \np = Perceptron()\np.assign_random_weights(2)\ntd = (TrainSample((5, 1), False), TrainSample((9, -1), False), TrainSample((5, -5), False),\n TrainSample((-6, 7), True), TrainSample((-2, 4), True), TrainSample((6, 4), True)) \np.train(td, 0.1, 10)\n","sub_path":"perc1.py","file_name":"perc1.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"255072391","text":"import itertools\r\nfrom sklearn.base import TransformerMixin\r\nfrom pandas import DataFrame\r\n\r\n\r\n\r\nclass PreprocessGridSearch:\r\n \"\"\"\r\n definition for steps:\r\n [ [{\"Pclass\":None,\"Sex\":None,\"\"}] ]\r\n \"\"\"\r\n def __init__(self, train_data, test_data=None, steps=[]):\r\n \"\"\"\r\n\r\n \"\"\"\r\n if (type(steps) is list) and ( len(steps)!=0):\r\n for i in steps:\r\n if not(type(i) is list):\r\n raise RuntimeError(\"steps muste be a non-empty list of list \")\r\n self.steps = steps\r\n self.train_data = train_data\r\n self.test_data = test_data\r\n self.preprocessing_steps=None\r\n else:\r\n raise RuntimeError(\"steps muste be a non-empty list of list \")\r\n\r\n def fit(self):\r\n self.preprocessing_steps = list(itertools.product(*self.steps))\r\n # print(self.preprocessing_steps)\r\n return self\r\n\r\n def transform(self):\r\n self.transformed_data = []\r\n for step in self.preprocessing_steps:\r\n t_data = self.train_data.copy()\r\n t_test_data = self.test_data.copy() if isinstance(self.test_data,DataFrame) else self.test_data\r\n\r\n preprocess_title = \"\"\r\n test_preprocess_title = \"\"\r\n # print(\"transforming ....................\")\r\n for transformer in step:\r\n t_data = transformer.fit_transform(t_data)\r\n if transformer.transformer_name != None:\r\n preprocess_title += \"\\n<{0}>\".format(transformer.transformer_name)\r\n if isinstance(t_test_data,DataFrame):\r\n if not transformer.training_step_only:\r\n t_test_data = transformer.fit_transform(t_test_data)\r\n test_preprocess_title += \"\\n<{0}>\".format(transformer.transformer_name)\r\n t_data.preprocess_title = preprocess_title\r\n if isinstance(t_test_data, DataFrame):\r\n t_test_data.preprocess_title = test_preprocess_title\r\n self.transformed_data.append((t_data,t_test_data))\r\n\r\n def fit_transform(self):\r\n self.fit()\r\n self.transform()\r\n return self.transformed_data\r\n","sub_path":"sklearn_preprocessing_search/preprocess_grid_search.py","file_name":"preprocess_grid_search.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"352520705","text":"#!/usr/bin/env python3\n\nimport argparse\nimport collections\nimport datetime\nimport json\nimport operator\nimport subprocess\nimport sys\n\n\n# Renewal represents a renewal in ua-contracts.\nRenewal = collections.namedtuple(\n \"Renewal\", \"id encoded_id status actionable start end contract_id sf_asset_id products account_id account_name sf_account_id\")\n\n\ndef run_contract(cmd, *args):\n \"\"\"Run the contract CLI with the given subcommnd and args.\"\"\"\n command = (\"contract\", cmd) + tuple(args)\n return subprocess.check_output(command).decode(\"utf-8\")\n\n\ndef get_renewals(ids):\n \"\"\"Generate renewal objects from the given decoded ids.\"\"\"\n ids_len = len(ids)\n for num, id in enumerate(ids):\n print(f\"{num}/{ids_len}\", end=\"\\r\", file=sys.stderr)\n encoded_id = run_contract(\"encode-id\", \"r\", id).strip()\n out = run_contract(\"show-renewal\", encoded_id, \"--format\", \"json\")\n info = json.loads(out)\n contract_id = info[\"contractID\"]\n out = run_contract(\"show-contract\", contract_id, \"--format\", \"json\")\n account_contract_info = json.loads(out)\n contract_info, account_info = account_contract_info[\"contractInfo\"], account_contract_info[\"accountInfo\"]\n yield Renewal(\n id=id,\n encoded_id=info[\"id\"],\n status=info[\"status\"],\n actionable=info.get(\"actionable\", False),\n start=_parse_datetime(info[\"start\"]),\n end=_parse_datetime(info[\"end\"]),\n contract_id=contract_id,\n sf_asset_id=_parse_sf_ids(info[\"externalAssetIDs\"]),\n products=contract_info['products'],\n account_id=account_info[\"id\"],\n account_name=account_info[\"name\"],\n sf_account_id=_parse_sf_ids(account_info[\"externalAccountIDs\"][0]),\n )\n\n\ndef _parse_datetime(value):\n try:\n return datetime.datetime.strptime(value, \"%Y-%m-%dT%H:%M:%S.%f%z\")\n except ValueError:\n return datetime.datetime.strptime(value, \"%Y-%m-%dT%H:%M:%S%z\")\n\n\ndef _parse_sf_ids(value):\n if value is None or value[\"origin\"] != \"Salesforce\":\n return \"\"\n return \", \".join(value[\"IDs\"])\n\n\ndef setup():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"file\", type=argparse.FileType(\"r\"),\n help=\"name of a file containing a list of renewal ids separated by newlines\")\n return parser.parse_args()\n\n\ndef main(file):\n counter = collections.Counter()\n ids = set(line.strip() for line in file)\n for r in get_renewals(ids):\n verb = \"actionable\" if r.actionable else \"not actionable\"\n products = \", \".join(sorted(r.products))\n\n counter[\"total\"] += 1\n counter[verb] += 1\n counter[r.status] += 1\n for product in r.products:\n counter[product] += 1\n\n print(f\"\\n# Delete {r.status} renewal {r.id}\")\n print(f\"# (salesforce asset {r.sf_asset_id})\")\n print(f\"# {verb} from {r.start} till {r.end}\")\n print(f\"# for contract {r.contract_id} ({products})\")\n print(f\"# owned by {r.account_name} ({r.account_id})\")\n print(f\"# (salesforce account {r.sf_account_id})\")\n print(f\"contract delete-renewal {r.encoded_id}\")\n\n print(\"\\ncounts:\")\n for key, value in counter.items():\n print(f\" {key}: {value}\")\n\n\nif __name__ == \"__main__\":\n args = setup()\n main(args.file)\n","sub_path":"contract-delete-renewals.py","file_name":"contract-delete-renewals.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"636624305","text":"# coding=utf-8\n\n\"\"\"Find Bottom Left Tree Value.\"\"\"\n\nfrom __future__ import print_function\nfrom TreeNode import TreeNode\n\n\n# DFS 1\ndef _solve(root):\n def _help(root, depth):\n if not root.left and not root.right:\n return root.val, depth\n if root.left and root.right:\n left_ans = _help(root.left, depth + 1)\n right_ans = _help(root.right, depth + 1)\n return right_ans if left_ans[1] < right_ans[1] else left_ans\n return _help(root.left or root.right, depth + 1)\n\n return _help(root, 0)[0] if root else 0\n\n\n# DFS2, fastest, 59 ms, beats 99.14%\ndef _solve1(root):\n def _help(root, depth, result):\n if result[1] < depth:\n result[:] = [root.val, depth]\n if root.left:\n _help(root.left, depth + 1, result)\n if root.right:\n _help(root.right, depth + 1, result)\n return result[0]\n return _help(root, 1, [0, 0])\n\n\n# BFS with tricks\ndef _solve2(root):\n queue = [root]\n for node in queue:\n queue += filter(None, (node.right, node.left))\n return node.val\n\n\n# BFS in python\ndef _solve3(root):\n queue, ans = [root], 0\n while any(queue):\n ans = queue[0].val\n queue = [leaf for node in queue for leaf in (node.left, node.right) if leaf]\n return ans\n\n\nif __name__ == '__main__':\n print (_solve3(TreeNode.de_serialize('[2]')))\n print (_solve3(TreeNode.de_serialize('[2,1,3]')))\n print (_solve3(TreeNode.de_serialize('[1,2,3,4,null,5,6,null,null,7]')))\n","sub_path":"medium/513.py","file_name":"513.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"639568622","text":"import pygame\n\n# Initialize the pygame\npygame.init()\n\n\n# Create the screen\nscreen = pygame.display.set_mode((800, 600))\n\n\n# Title and Icon\npygame.display.set_caption('hackShip project')\nicon = pygame.image.load('src/scuba-diver.png')\npygame.display.set_icon(icon)\n\n\n# Game Loop\nRUNNING = True\nwhile RUNNING:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n RUNNING = False\n\n pygame.display.update()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"132619850","text":"import os\nimport cv2\nfrom collections import namedtuple\nimport imageio\nfrom PIL import Image\nfrom random import randrange\nimport numpy as np\nfrom sklearn.decomposition import PCA\nfrom scipy.spatial.distance import pdist, squareform\nimport torch\nimport matplotlib\nmatplotlib.use('Agg') # Required for gif animations\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.image as image\nimport matplotlib.patches as patches\nfrom multimodal_affinities.visualization.vis_handler import VisHandler\nfrom multimodal_affinities.visualization.image_utils import resize_image\nfrom multimodal_affinities.visualization.colors_util import rgb_hex_to_tuple\n\nclass PlotsProducer:\n\n def __init__(self, document, output_path):\n # Load background image\n self.image_path = document.image_path\n self.img = plt.imread(self.image_path)\n self.img_opencv = cv2.imread(self.image_path)\n\n dpi = 120\n mpl.rcParams['figure.dpi'] = dpi\n height = self.img.shape[0]\n width = self.img.shape[1]\n self.figsize = width / float(dpi), height / float(dpi) # Fig size in inches\n\n self.document = document\n self.output_path = output_path\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n\n def plot_word_boxes_on_image(self):\n set_of_words = [[word] for word in self.document.get_words()] # list of singleton word lists\n fig, ax = plt.subplots(1, figsize=self.figsize)\n monochrome_colors_list = ['#5a5d8f' for _ in self.document.get_words()]\n self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img,\n title='',\n entity_sets=set_of_words,\n colors_list=monochrome_colors_list)\n fig.savefig(os.path.join(self.output_path, self.document.basename + '_word_boxes.png'))\n plt.close(fig)\n\n def save_phrase_detection_results(self):\n set_of_phrases = [[phrase] for phrase in self.document.get_phrases()] # list of singleton phrase lists\n fig, ax = plt.subplots(1, figsize=self.figsize)\n self._draw_entity_bounding_boxes(fig=fig, ax=ax, bg_img=self.img,\n title='Phrase Detection', entity_sets=set_of_phrases)\n fig.savefig(os.path.join(self.output_path, self.document.basename + '_phrase_detection.png'))\n plt.close(fig)\n\n def save_clustering_results(self, with_title=True, colors_list=None):\n set_of_clusters = [cluster.words for cluster in self.document.get_clusters()] # list of list of words (clusters)\n self._save_set_of_clusters(set_of_clusters, with_title, colors_list)\n\n def save_clustering_labels(self, clustering_labels, colors_list=None):\n cluster_ids = np.unique(np.array(clustering_labels))\n cluster_id_to_cluster_idx = {cluster_id: idx for idx, cluster_id in enumerate(cluster_ids)}\n\n # Converts from list of labels to list of list of words (clusters)\n set_of_clusters = [[] for _ in range(len(cluster_ids))]\n for word_idx, word in enumerate(self.document.get_words()):\n cluster_id = clustering_labels[word_idx]\n if cluster_id == -1: # Ignore non-clustered words\n continue\n cluster_idx = cluster_id_to_cluster_idx[cluster_id]\n set_of_clusters[cluster_idx].append(word)\n\n self._save_set_of_clusters(set_of_clusters, colors_list)\n\n def _save_set_of_clusters(self, set_of_clusters, with_title=True, colors_list=None):\n \"\"\"\n :param document:\n :param set_of_clusters: list of list of words (clusters)\n :return:\n \"\"\"\n output_img = self._draw_entity_bounding_boxes_opencv(bg_img=self.img_opencv,\n entity_sets=set_of_clusters,\n colors_list=colors_list)\n cv2.imwrite(os.path.join(self.output_path, self.document.basename + '_clustering.png'), output_img)\n\n @staticmethod\n def _draw_entity_bounding_boxes_opencv(bg_img, entity_sets, colors_list=None):\n\n img_height = bg_img.shape[0]\n img_width = bg_img.shape[1]\n\n if colors_list is None:\n colors_list = VisHandler.generate_colors_list(amount=len(entity_sets))\n\n face_colors = colors_list\n edge_colors = VisHandler.generate_darker_palette(colors_list)\n output_img = bg_img.copy()\n alpha = 0.8\n for set_idx, entities_set in enumerate(entity_sets):\n face_color = face_colors[set_idx]\n edge_color = edge_colors[set_idx]\n for entity in entities_set:\n x = entity.geometry.left * img_width\n y = entity.geometry.top * img_height\n width = entity.geometry.width * img_width\n height = entity.geometry.height * img_height\n # writing the text onto the image and returning it\n rgb_color = rgb_hex_to_tuple(face_color)\n cv2.rectangle(output_img, (int(x), int(y)), (int(x + width), int(y + height)),\n (rgb_color[2], rgb_color[1], rgb_color[0]), cv2.FILLED)\n\n output_img = cv2.addWeighted(output_img, alpha, bg_img, 1 - alpha, 0)\n return output_img\n\n\n @staticmethod\n def _draw_entity_bounding_boxes(fig, ax, bg_img, title, entity_sets, colors_list=None):\n ax.set_title(title)\n\n plt.tick_params(axis='both', which='both',\n bottom='off', top='off', labelbottom='off', right='off', left='off',\n labelleft='off')\n\n plt.imshow(bg_img)\n img_height = bg_img.shape[0]\n img_width = bg_img.shape[1]\n\n if colors_list is None:\n colors_list = VisHandler.generate_colors_list(amount=len(entity_sets))\n\n face_colors = colors_list\n edge_colors = VisHandler.generate_darker_palette(colors_list)\n\n for set_idx, entities_set in enumerate(entity_sets):\n face_color = face_colors[set_idx]\n edge_color = edge_colors[set_idx]\n for entity in entities_set:\n x = entity.geometry.left * img_width\n y = entity.geometry.top * img_height\n width = entity.geometry.width * img_width\n height = entity.geometry.height * img_height\n rect = patches.Rectangle((x, y), width, height,\n linewidth=2,\n edgecolor=edge_color,\n facecolor=face_color,\n alpha=0.4)\n ax.add_patch(rect)\n\n @staticmethod\n def plot_pca_embedding_space_for_clusters(document, output_path,\n embedding_property='embedding',\n title=''):\n \"\"\"\n Plot 2d PCA visualization of the embedding space according to cluster colors.\n :param document: Document with clustering results\n :param embedding_property: Embedding property of words - normally 'embedding' or 'unprojected_embedding'\n :return:\n \"\"\"\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n words = document.get_words()\n clusters = document.get_clusters()\n\n if len(words) == 0 or getattr(words[0], embedding_property) is None:\n return\n if embedding_property == 'unprojected_embedding':\n embeddings = []\n for word in words:\n unprojected_embedding = torch.cat(word.unprojected_embedding['embeddings'], dim=1)\n unprojected_embedding = unprojected_embedding.detach().cpu().numpy()\n embeddings.append(unprojected_embedding)\n else:\n embeddings = [getattr(word, embedding_property).detach().cpu().numpy() for word in words]\n colors_palette = VisHandler.generate_colors_list(amount=len(clusters))\n word_to_color = {word: colors_palette[cluster_idx]\n for cluster_idx, cluster in enumerate(clusters)\n for word in cluster.words}\n colors = [word_to_color[word] for word in words]\n\n embeddings_array = np.array(embeddings).squeeze()\n num_pca_comp = 2\n embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array)\n x_list = [embeddings_2d[i, 0] for i in range(embeddings_2d.shape[0])]\n y_list = [embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])]\n\n fig, ax = plt.subplots(1)\n plot_title = embedding_property\n if plot_title != '':\n plot_title += ': ' + title\n plt.title(plot_title)\n plt.scatter(x_list, y_list, c=colors, s=1, alpha=0.8)\n\n fig.tight_layout()\n fig.savefig(os.path.join(output_path, document.basename + '_' + embedding_property + '_pca.png'))\n plt.close(fig)\n\n @staticmethod\n def _find_k_furthest_words_per_cluster(document, embeddings_2d, k=3):\n \"\"\" Greedy approximation algorithm for finding k furthest neighbour words per cluster.\n k is expected to be relatively small (< 100)\n \"\"\"\n words = document.get_words()\n word_to_embedding_2d_idx = {word: idx for idx, word in enumerate(words)}\n clusters = document.get_clusters()\n solution_per_cluster = {}\n ClusterSolution = namedtuple('ClusterSolution', ['word_indices', 'words'])\n for cluster in clusters:\n # Generate cluster pairwise distances matrix\n all_cluster_embeddings_indices = [word_to_embedding_2d_idx[word] for word in cluster.words]\n all_cluster_embeddings = np.take(embeddings_2d, all_cluster_embeddings_indices, axis=0)\n pairwise_distances = pdist(all_cluster_embeddings, metric='euclidean')\n distances_matrix = squareform(pairwise_distances)\n\n # Total distance from selected set so far\n distances_accumulator = np.zeros(len(cluster.words))\n\n # Sample first point\n random_index = randrange(len(cluster.words))\n\n # Indices of selected points\n selected_points = [random_index]\n\n # How many points we need to add\n points_to_calc_count = min(k - 1, len(words) - 1)\n\n for _ in range(points_to_calc_count):\n last_point_selected = selected_points[-1]\n\n # Update accumulator with distance collected from last point\n distances_accumulator += distances_matrix[last_point_selected]\n\n # Eliminate last point selected from distance matrix & accumulator\n distances_matrix[:, random_index] = 0\n distances_matrix[random_index, :] = 0\n\n furthrest_point_from_set = np.argmax(distances_accumulator, axis=0)\n selected_points.append(furthrest_point_from_set)\n\n selected_words = [cluster.words[point] for point in selected_points]\n selected_word_indices = [word_to_embedding_2d_idx[word] for word in selected_words]\n solution_per_cluster[cluster] = ClusterSolution(word_indices=selected_word_indices, words=selected_words)\n\n return solution_per_cluster\n\n @staticmethod\n def _extract_crops_per_cluster_solution(document, solution_per_cluster):\n \"\"\"\n Extracts crops for each selected word in k-furthest neighbours solution\n :param document:\n :param solution_per_cluster: Solution of k-furthest neighbours\n :return:\n \"\"\"\n word_indices_to_crops = {}\n for cluster, cluster_solution in solution_per_cluster.items():\n for word_index, word in zip(cluster_solution.word_indices, cluster_solution.words):\n bbox = word.get_bbox() # left, top, width, height\n y_min = int(round(bbox[1] * document.height))\n y_max = int(round((bbox[1] + bbox[3]) * document.height))\n x_min = int(round(bbox[0] * document.width))\n x_max = int(round((bbox[0] + bbox[2]) * document.width))\n image_of_crop = document.image[max(0, y_min):min(y_max, document.height),\n max(0, x_min):min(x_max, document.width), :]\n\n pil_image = Image.fromarray(image_of_crop[...,::-1]) # BGR to RGB\n pil_image = pil_image.convert('RGB')\n word_indices_to_crops[word_index] = pil_image\n return word_indices_to_crops\n\n @staticmethod\n def _space_out_crops(indices_to_crops, words, x_list, y_list, dist_from_pt=0.01, height=0.02):\n \"\"\"\n Calculates the positions and dimensions of crop images on the embedding space plot.\n Makes sure crops don't overlay each other.\n This method assumes a small number of crops (< 1000) and performs a naive linear comparison for each crop.\n :param indices_to_crops: dict of word index (by order in doc) to PIL crop\n :param words: List of words\n :param x_list: List of corresponding pt x positions\n :param y_list: List of corresponding pt y positions\n :param dist_from_pt: How far in (x-y) coords the crop should be placed from the plot\n :param height: Height of the crop, in figure axes dimensions (note: for normalized pca space: -1 to 1)\n :return: indices_to_extents: dict of word index to extens describing position and dimensions of each crop.\n Crops are shifted so they don't cover each other,\n \"\"\"\n indices_to_extents = {}\n MatplotExtent = namedtuple('matplot_extent', ['left', 'right', 'bottom', 'top'])\n is_extent_x_intersect = lambda e1, e2: not (e1.right < e2.left or e1.left > e2.right)\n is_extent_y_intersect = lambda e1, e2: not (e1.top > e2.bottom or e1.bottom < e2.top)\n is_extent_intersect = lambda e1, e2: is_extent_x_intersect(e1, e2) and is_extent_y_intersect(e1, e2)\n\n min_x, max_x = min(x_list), max(x_list)\n min_y, max_y = min(y_list), max(y_list)\n height = (max_y - min_y) * height\n dist_from_pt = min(max_y - min_y, max_x - min_x) * dist_from_pt\n\n for point_index, crop in indices_to_crops.items():\n word_aspect_ratio = words[point_index].geometry.width / words[point_index].geometry.height\n axis_ratio = (max_x-min_x) / (max_y-min_y) / 2\n width = height * word_aspect_ratio * axis_ratio\n left, right = x_list[point_index] + dist_from_pt, x_list[point_index] + dist_from_pt + width\n bottom, top = y_list[point_index] + dist_from_pt + height, y_list[point_index] + dist_from_pt\n\n overlap = True\n while overlap:\n overlap = False\n extent = MatplotExtent(left, right, bottom, top)\n for other_crop_extent in indices_to_extents.values():\n other_left, other_right, other_bottom, other_top = other_crop_extent\n spaceout_margin = dist_from_pt / 2\n if is_extent_intersect(extent, other_crop_extent):\n overlap = True\n # shift below\n if other_bottom <= top <= other_top:\n top = other_bottom + spaceout_margin\n bottom = top + height\n else: # shift above\n bottom = other_top - spaceout_margin\n top = bottom - height\n continue\n\n indices_to_extents[point_index] = extent\n return indices_to_extents\n\n def plot_clusters_and_embedding_space_with_crops(self, document, output_path, crops_per_cluster=3,\n embedding_properties=['embedding', 'unprojected_embedding'],\n unprojected_caption=None):\n \"\"\"\n Plot 2d PCA visualization of the embedding space according to cluster colors.\n :param document: Document with clustering results\n :param embedding_property: Embedding property of words - normally 'embedding' or 'unprojected_embedding'\n :return:\n \"\"\"\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n words = document.get_words()\n clusters = document.get_clusters()\n\n if len(words) == 0 or \\\n all([getattr(words[0], embedding_property) is None for embedding_property in embedding_properties]):\n return\n\n colors_palette = VisHandler.generate_colors_list(amount=len(clusters))\n word_to_color = {word: colors_palette[cluster_idx]\n for cluster_idx, cluster in enumerate(clusters)\n for word in cluster.words}\n colors = [word_to_color[word] for word in words]\n\n # Initially empty, the first embedding property we process will set those for all figures\n selected_word_crops_per_cluster = None\n indices_to_crops = None\n\n for embedding_property in embedding_properties:\n if embedding_property == 'unprojected_embedding': # Can't handle tuples, concat them\n embeddings = []\n for word in words:\n unprojected_embedding = torch.cat(word.unprojected_embedding['embeddings'], dim=1)\n unprojected_embedding = unprojected_embedding.detach().cpu().numpy()\n embeddings.append(unprojected_embedding)\n else:\n embeddings = [getattr(word, embedding_property).detach().cpu().numpy() for word in words]\n\n embeddings_array = np.array(embeddings).squeeze()\n num_pca_comp = 2\n embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array)\n x_list = [embeddings_2d[i, 0] for i in range(embeddings_2d.shape[0])]\n y_list = [embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])]\n\n fig, ax = plt.subplots(1)\n if crops_per_cluster > 0:\n if selected_word_crops_per_cluster is None and indices_to_crops is None: # Calculate per first attribute\n selected_word_crops_per_cluster = PlotsProducer._find_k_furthest_words_per_cluster(document, embeddings_2d, k=crops_per_cluster)\n indices_to_crops = PlotsProducer._extract_crops_per_cluster_solution(document, selected_word_crops_per_cluster)\n indices_to_extents = PlotsProducer._space_out_crops(indices_to_crops, words,\n x_list, y_list, dist_from_pt=0.02, height=0.04)\n\n # Plot crop images\n for point_index, crop in indices_to_crops.items():\n extent = indices_to_extents[point_index]\n rect = patches.Rectangle((extent.left, extent.top), extent.right-extent.left, extent.bottom-extent.top,\n linewidth=0.5,\n edgecolor=\"black\",\n facecolor=\"none\",\n zorder=5)\n ax.imshow(crop, aspect='auto', alpha=0.65, extent=extent, zorder=4)\n ax.add_patch(rect)\n\n # Plot points\n if embedding_property == 'unprojected_embedding':\n plot_title = 'Initial unprojected embeddings, pre training (PCA)'\n else:\n if unprojected_caption is None:\n plot_title = 'Projected embeddings, post training (PCA)'\n else:\n plot_title = unprojected_caption\n plt.title(plot_title)\n plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0, edgecolors='black', linewidth=1.0, zorder=3)\n plt.tick_params(axis='both', which='both',\n bottom='off', top='off', labelbottom='off', right='off', left='off',\n labelleft='off')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n fig.tight_layout()\n fig.savefig(os.path.join(output_path, document.basename + '_' + embedding_property + '_pca.png'))\n plt.close(fig)\n\n # Finally plot clusters on original image\n self.save_clustering_results(with_title=False, colors_list=colors_palette)\n\n return colors_palette\n\n @staticmethod\n def animate_pca_embedding_space_for_clusters(document, output_path, embeddings_history, colors_palette=None):\n \"\"\"\n Plot 2d PCA visualization of the embedding space according to cluster colors.\n :param document: Document with clustering results\n :param embedding_property: Embedding property of words - normally 'embedding' or 'unprojected_embedding'\n :return:\n \"\"\"\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n words = document.get_words()\n clusters = document.get_clusters()\n\n if len(words) == 0 or embeddings_history is None or len(embeddings_history) == 0:\n return\n\n if colors_palette is None:\n colors_palette = VisHandler.generate_colors_list(amount=len(clusters))\n word_to_color = {word: colors_palette[cluster_idx]\n for cluster_idx, cluster in enumerate(clusters)\n for word in cluster.words}\n colors = [word_to_color[word] for word in words]\n scatter_data = []\n\n for state_idx, embeddings_state in enumerate(embeddings_history):\n epoch = state_idx + 1\n normalized_embeddings_dict = embeddings_state['normalized']\n unnormalized_embeddings_dict = embeddings_state['unnormalized']\n if len(normalized_embeddings_dict) > 0:\n normalized_embeddings = [normalized_embeddings_dict[word].detach().cpu().numpy() for word in words]\n chosen_embedding = normalized_embeddings\n elif len(unnormalized_embeddings_dict) > 0:\n unnormalized_embeddings = [unnormalized_embeddings_dict[word].detach().cpu().numpy() for word in words]\n chosen_embedding = unnormalized_embeddings\n else:\n return\n\n embeddings_array = np.array(chosen_embedding).squeeze()\n num_pca_comp = 2\n embeddings_2d = PCA(n_components=num_pca_comp).fit_transform(embeddings_array)\n x_list = [embeddings_2d[i, 0] for i in range(embeddings_2d.shape[0])]\n y_list = [embeddings_2d[i, 1] for i in range(embeddings_2d.shape[0])]\n push_pull_ratio = embeddings_state['push_pull_ratio']\n scatter_data.append((epoch, x_list, y_list, push_pull_ratio))\n\n min_x = min(min(scatter_data, key=lambda entry: min(entry[1]))[1])\n max_x = max(max(scatter_data, key=lambda entry: max(entry[1]))[1])\n min_y = min(min(scatter_data, key=lambda entry: min(entry[2]))[2])\n max_y = max(max(scatter_data, key=lambda entry: max(entry[2]))[2])\n padding_factor = 0.1\n min_x -= (max_x - min_x) * padding_factor\n max_x += (max_x - min_x) * padding_factor\n min_y -= (max_y - min_y) * padding_factor\n max_y += (max_y - min_y) * padding_factor\n\n frames = []\n for epoch, x_list, y_list, push_pull_ratio in scatter_data:\n fig, ax = plt.subplots(1)\n ax.set_xlim(min_x, max_x)\n ax.set_ylim(min_y, max_y)\n plot_title = 'Projected embeddings at epoch #' + str(epoch) + ' (PCA)'\n plt.title(plot_title)\n\n plt.scatter(x_list, y_list, c=colors, s=18, alpha=1.0, edgecolors='black', linewidth=1.0, zorder=3)\n plt.tick_params(axis='both', which='both',\n bottom='off', top='off', labelbottom='off', right='off', left='off',\n labelleft='off')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n # Used to return the plot as an image rray\n fig.tight_layout()\n fig.canvas.draw() # draw the canvas, cache the renderer\n output_frame = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')\n output_frame = output_frame.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n frames.append(output_frame)\n\n imageio.mimsave(os.path.join(output_path, document.basename + '_embeddings_history.gif'), frames, fps=2)\n\n","sub_path":"multimodal_affinities/evaluation/analysis/plots_producer.py","file_name":"plots_producer.py","file_ext":"py","file_size_in_byte":24713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"261761281","text":"from collections import namedtuple\nfrom itertools import count\nfrom PIL import Image\nimport re\nfrom sys import argv\n\n\nPoint = namedtuple('Point', ['x', 'y', 'vx', 'vy'])\n\n\ndef main():\n points = loadpoints(argv[1])\n\n minsize = size(points)\n mint = 0\n\n for t in count(start=1):\n state = [simulate(p, t) for p in points]\n n = size(state)\n if n < minsize:\n minsize = n\n mint = t\n elif n > minsize:\n break\n print(mint)\n render([simulate(p, mint) for p in points])\n\n\ndef render(points):\n minx, maxx, miny, maxy = bounds(points)\n img = Image.new('1', (maxx - minx + 1, maxy - miny + 1))\n for p in points:\n img.putpixel((p.x - minx, p.y - miny), 1)\n img.save('out.ppm')\n\n\ndef simulate(point, time):\n return Point(point.x + point.vx * time, point.y + point.vy * time, point.vx, point.vy)\n\n\ndef size(points):\n minx, maxx, miny, maxy = bounds(points)\n return (maxx - minx) * (maxy - miny)\n\n\ndef bounds(points):\n minx = min(map(lambda p: p.x, points))\n maxx = max(map(lambda p: p.x, points))\n miny = min(map(lambda p: p.y, points))\n maxy = max(map(lambda p: p.y, points))\n return minx, maxx, miny, maxy\n\n\ndef loadpoints(path):\n pattern = re.compile(r'position=<([ -]?\\d+), ([ -]?\\d+)> velocity=<([ -]?\\d+), ([ -]?\\d+)>')\n with open(path) as f:\n points = []\n for line in f:\n match = pattern.match(line)\n x, y, vx, vy = map(int, match.groups())\n points.append(Point(x, y, vx, vy))\n return points\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2018/day10_part01/day10_part01.py","file_name":"day10_part01.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"467300153","text":"class GConfig:\n class Cache:\n # MT : memoized times\n camp_userCount_MT = 0\n\n class Topic:\n options_per_page = 30\n userTopic_MT = 0\n popularTopic_MT = 0\n\n # popular topic in the last ? days\n popularTopicLast_Days = 30\n recountTopicAfterModerated = 10 # minutes\n\n class User:\n markUserInactiveAfter = 15 # days\n markUserInactiveTimeCycle = 5 # minutes\n\n markUserOfflineAfter = 15\n markUserOfflineTimeCycle = 10 # minutes\n\n","sub_path":"bgapp/GConfig.py","file_name":"GConfig.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"390206592","text":"import math;\nprint('등비수열은 인접한 항의 비가 일정한 수열로, 인접한 항의 비를 공비라고 합니다. \\n'\n '등비수열의 특정 항을 구하는 공식은 첫쨰항을 a_1, 공비를 r이라고 할 때 \\n'\n 'a_n = a_1 * r ** (n - 1) 입니다. \\n'\n '또한 등차수열 n번째 항까지의 합 S_n은 다음과 같습니다. \\n'\n 'S_n = a_1 * (r ** n - 1) / r - 1');\na=int(input('등비수열의 첫번째 항을 입력해주세요. '));\nr=int(input('등비수열의 공비를 입력해주세요. '));\nn=int(input('등비수열의 알고 싶은 항의 순서를 입력해주세요(예: 10번째 항=10) '))\na_n=a*(r ** (n-1))\nprint(a_n)\nS_n=a * ((r ** n) - 1) / (r - 1)\nprint(S_n)","sub_path":"python/multiple.py","file_name":"multiple.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"593835615","text":"'''\nExercise : Assignment-1\nimplement the function get_available_letters that takes in one parameter -\na list of letters, letters_guessed. This function returns a string\nthat is comprised of lowercase English letters - all lowercase English letters\nthat are not in letters_guessed\n'''\n\ndef get_available_letters(letters_guessed):\n \"\"\"\n :param letters_guessed: list, what letters have been guessed so far\n returns: string, comprised of letters that represents what letters have not\n yet been guessed.\n Method 1:\n B = set(string.ascii_lowercase).intersection(set(letters_guessed))\n return(set(string.ascii_lowercase)-B)\n Method 2:\n A = list(string.ascii_lowercase)\n for i in letters_guessed:\n A.remove(i)\n return \"\".join(A)\n \"\"\"\n import string\n keys = list(string.ascii_lowercase)\n ascii_val = []\n for i in keys:\n ascii_val.append(ord(i))\n dictionary = dict(zip(keys, ascii_val))\n for i in letters_guessed:\n del dictionary[i]\n list_1 = []\n for i in dictionary.keys():\n list_1.append(i)\n return \"\".join(list_1)\ndef main():\n '''\n Main function for the given program\n '''\n user_input = input()\n user_input = user_input.split()\n data = []\n for char in user_input:\n data.append(char)\n print(get_available_letters(data))\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"module 10/p1/assignment1.py","file_name":"assignment1.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"209509593","text":"import pandas as pd\nimport os\nfrom glob import glob\n\npath_to_neuron_stats = r'/media/ruairi/Ephys_back_up_1/SERT_DREADD/csvs'\nneuron_stats_csv_name = 'neuron_stats'\n\npath_to_ts = r'/media/ruairi/Ephys_back_up_1/SERT_DREADD/csvs/spikes_time_series'\n\nfile_out_dir = r'/media/ruairi/Ephys_back_up_1/SERT_DREADD/csvs'\nfile_out_name_ts = 'all_neurons_ts_with_clusters.csv'\n\n\ndef load_spikes_df(parent_dir):\n sub_dirs = os.listdir(parent_dir)\n df_list = []\n for sub_dir in sub_dirs:\n file_path = glob(os.path.join(parent_dir, sub_dir, '*.csv'))[0] # should be only one csv file\n df_list.append(pd.read_csv(file_path))\n return pd.concat(df_list)\n\n\ndef load_neuron_stats(path, csv_name):\n if not csv_name.endswith('.csv'):\n csv_name = ''.join([csv_name, '.csv'])\n return pd.read_csv(os.path.join(path, csv_name))\n\n\ndef neuron_category_mapper(row):\n '''\n This is the function we use to categorise neurons as either slow or fast, and as either regular or irregular\n It categorises neurons firing slower than 4.5 Hz as slow and neurons with a CV ISI of less than 0.55 as regular\n '''\n if (row['Firing Rate'] <= 10) & (row['CV ISI'] <= 0.8):\n rate = 'slow'\n reg = 'regular'\n elif (row['Firing Rate'] <= 10) & (row['CV ISI'] >= 0.8):\n rate = 'slow'\n reg = 'irregular'\n elif (row['Firing Rate'] > 10) & (row['Firing Rate'] <25):\n rate= 'fast'\n reg = 'firing'\n else:\n rate= 'V.fast'\n reg = 'firing'\n return ' '.join([rate, reg])\n\ndf_ts = load_spikes_df(path_to_ts)\ndf_stats = load_neuron_stats(path=path_to_neuron_stats, csv_name=neuron_stats_csv_name)\ndf_stats['category'] = df_stats.apply(neuron_category_mapper, axis=1)\ndf_ts_merge = pd.merge(left=df_ts,\n right=df_stats[['recording', 'category', 'spike_cluster']],\n left_on=['recording', 'spike_cluster'],\n right_on=['recording', 'spike_cluster'],\n how='right')\n\ndf_ts_merge.to_csv(os.path.join(file_out_dir, file_out_name_ts), index=False)\ndf_stats.to_csv(os.path.join(file_out_dir, neuron_stats_csv_name) + '.csv',\n index=False)\n","sub_path":"mua_preprocess/add_neuron_categories.py","file_name":"add_neuron_categories.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"336513350","text":"# fibonacci.py\n# This program computes the nth Fibonacci number where value n is a user input.\n\ndef fibonacci(f, s, c, n):\n seq = []\n for i in range(1, n+1):\n seq.append(c)\n f = s\n s = c\n c = f + s\n fib = seq[n-1]\n return fib\n\ndef main():\n n = int(input(\"Enter the Fibonacci number: \"))\n fir = 0\n sec = 0\n cur = 1\n\n ans = fibonacci(fir, sec, cur, n)\n \n print(\"The Fibonnaci number at index {} is: {}\".format(n, ans))\n\nmain()\n \n","sub_path":"python/python-programming-zelle/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"78266089","text":"from eoflow.base.base_predict import BasePredict\nfrom eolearn.core import EOPatch, FeatureType\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport numpy as np\nimport itertools\nimport os\n\n\nclass TFCNPredict(BasePredict):\n def __init__(self, config, data, logger):\n super(TFCNPredict, self).__init__(config, data, logger)\n\n def _get_sampling_indices(self, height, width):\n \"\"\" Compute indices of padded input image where patches are extracted\n\n :param height: Height of input image to be classified\n :type height: int\n :param width: Width of input image to be classified\n :type width: int\n :return: sample indices along the height, sample indices along the width\n :rtype: list of tuples, list of tuples\n \"\"\"\n hh, ww = np.arange(height), np.arange(width)\n h_samples = [(h_min, h_max) for h_min, h_max in\n zip(hh[::self.config.im_size[1] - self.config.spatial_cropping - self.config.prediction_overlap],\n hh[self.config.im_size[1]::self.config.im_size[1] - self.config.spatial_cropping -\n self.config.prediction_overlap])]\n h_tail = (height - self.config.im_size[1], height)\n if h_samples[-1] != h_tail:\n h_samples.append(h_tail)\n\n w_samples = [(w_min, w_max) for w_min, w_max in\n zip(ww[::self.config.im_size[2] - self.config.spatial_cropping - self.config.prediction_overlap],\n ww[self.config.im_size[2]::self.config.im_size[2] - self.config.spatial_cropping -\n self.config.prediction_overlap])]\n w_tail = (width - self.config.im_size[2], width)\n if w_samples[-1] != w_tail:\n w_samples.append(w_tail)\n\n # if len(w_samples) != len(h_samples):\n # raise ValueError(\"Different number of sampling patches\")\n\n return h_samples, w_samples\n\n def _get_normalisation_mask(self, height, width, height_indices, width_indices):\n \"\"\" Compute mask where output patches overlap\n\n :param height: Height of input image to be classified\n :type height: int\n :param width: Width of input image to be classified\n :type width: int\n :param height_indices: List of patch indices along the image height\n :type height_indices: list of tuples\n :param width_indices: List of patch indices along the image width\n :type width_indices: list of tuples\n :return: Normalisation mask\n :rtype: numpy array\n \"\"\"\n mask = np.zeros((height + self.config.spatial_cropping + 2*self.config.prediction_overlap,\n width + self.config.spatial_cropping + 2*self.config.prediction_overlap,\n self.config.n_classes), dtype=np.uint8)\n\n for hi, wi in itertools.product(height_indices, width_indices):\n mask[hi[0] + self.config.spatial_cropping // 2:hi[1] - self.config.spatial_cropping // 2,\n wi[0] + self.config.spatial_cropping // 2:wi[1] - self.config.spatial_cropping // 2, :] += \\\n np.ones((self.config.lb_size[0], self.config.lb_size[1], self.config.n_classes), np.uint8)\n\n mask[mask == 0] = 1\n\n return mask\n\n def _merge_and_normalise(self, logits, height, width, height_indices, width_indices, norm_mask):\n \"\"\" Merge the output patches back into one image\n\n :param logits: Array storing the output of the U-net (output of softmax). Shape of array is\n N_PATCHESxOHxOWxN_CLASSES\n :type logits: numpy array\n :param height: Height of input image to be classified\n :type height: int\n :param width: Width of input image to be classified\n :type width: int\n :param height_indices: Indices defining the location of the patches to be extracted along the height of the\n input image\n :type height_indices: list of tuples\n :param width_indices: Indices defining the location of the patches to be extracted along the width of the\n input image\n :type width_indices: list of tuples\n :param norm_mask: Mask counting the overlap of hte extracted patches. It's used to normalise the combined prediction\n :type norm_mask: numpy array\n :return: Predicted mask, argmax along the class dimension\n :rtype: numpy array\n \"\"\"\n pred_mask = np.zeros((height + self.config.spatial_cropping + 2*self.config.prediction_overlap,\n width + self.config.spatial_cropping + 2*self.config.prediction_overlap,\n self.config.n_classes), dtype=np.float32)\n\n batch = 0\n for hi, wi in itertools.product(height_indices, width_indices):\n pred_mask[hi[0] + self.config.spatial_cropping // 2:hi[1] - self.config.spatial_cropping // 2,\n wi[0] + self.config.spatial_cropping // 2:wi[1] - self.config.spatial_cropping // 2,\n :] += logits[batch]\n batch += 1\n # Normalise prediction (average of overlapping values)\n pred_mask /= norm_mask\n # Find maximum of combined softmax (pseud-probability)\n return pred_mask\n\n def predict(self, predict_proba=True, log_accuracy=True):\n loop = tqdm(range(len(self.data.cval_set)))\n for _ in loop:\n image, labels = next(self.data.next_batch(1, is_training=False, random=False))\n eopatch_filename, = self.data.get_batch_filenames()\n self.predict_step(image, labels, eopatch_filename, predict_proba=predict_proba, log_accuracy=log_accuracy)\n self.counter += 1\n return\n\n def predict_step(self, image, labels, filename, predict_proba=True, log_accuracy=True):\n \"\"\" Predict step\n\n \"\"\"\n # Load graph and get placeholders and tensors\n images = self.graph.get_tensor_by_name('{:s}/images:0'.format(self.graph_name))\n keep_prob = self.graph.get_tensor_by_name('{:s}/keep_prob:0'.format(self.graph_name))\n softmax = self.graph.get_tensor_by_name('{:s}/{:s}:0'.format(self.graph_name, self.config.node_names))\n\n batch_size, n_frames, height, width, depth = image.shape\n\n # Check dimensions agree to specification\n if self.config.im_size[-1] != depth or self.config.im_size[0] != n_frames:\n raise ValueError(\"Wrong number of frames/bands provided as input to model\")\n\n if height < self.config.im_size[1] or width < self.config.im_size[2]:\n raise ValueError(\"Input tile is smaller than input patch. Increase spatial resolution\")\n\n # Compute sampling indices to cover the entire input image\n h_samples, w_samples = self._get_sampling_indices(height + self.config.spatial_cropping + 2*self.config.prediction_overlap,\n width + self.config.spatial_cropping + 2*self.config.prediction_overlap)\n n_patches = len(h_samples) * len(w_samples)\n # Clip image to [0,1] range and pad it using reflection\n padding = ((0, 0),\n (0, 0),\n (self.config.spatial_cropping // 2 + self.config.prediction_overlap,\n self.config.spatial_cropping // 2 + self.config.prediction_overlap),\n (self.config.spatial_cropping // 2 + self.config.prediction_overlap,\n self.config.spatial_cropping // 2 + self.config.prediction_overlap),\n (0, 0))\n\n image = np.clip(image, self.config.clip_low, self.config.clip_high)\n image = np.pad(image, padding, mode='reflect')\n\n # Break input image into patches of suitable input size for U-net architecture\n img_batch = [image[:, :, hi[0]:hi[1], wi[0]:wi[1], :]\n for hi, wi in itertools.product(h_samples, w_samples)]\n img_batch = np.concatenate(img_batch, axis=0)\n del image\n\n # Array holding the output of the U-net\n logits = np.zeros(((n_patches,) + tuple(self.config.lb_size) + (self.config.n_classes,)), dtype=np.float32)\n\n # Run prediction in mini-batches\n with tf.Session(graph=self.graph) as sess:\n\n mini_batches = np.split(np.arange(n_patches),\n np.arange(n_patches)[self.config.batch_size::self.config.batch_size])\n\n for mb in mini_batches:\n tmp_logits = sess.run(softmax,\n feed_dict={images: img_batch[mb],\n keep_prob: 1})\n logits[mb] = tmp_logits.reshape((len(mb),) + tuple(self.config.lb_size) + (self.config.n_classes,))\n del tmp_logits\n\n del softmax, images, keep_prob, img_batch\n\n # This normalisation mask handles overlaps between patches\n normalisation_mask = self._get_normalisation_mask(height, width, h_samples, w_samples)\n\n # Merge the patches back into an image of dimensions as input image\n self.predicted_proba = self._merge_and_normalise(logits, height, width, h_samples, w_samples, normalisation_mask)\n\n # Crop probabilities\n self.predicted_proba = self.predicted_proba[\n self.config.spatial_cropping // 2 + self.config.prediction_overlap:self.config.spatial_cropping // 2 + self.config.prediction_overlap + height,\n self.config.spatial_cropping // 2 + self.config.prediction_overlap:self.config.spatial_cropping // 2 + self.config.prediction_overlap + width, :]\n self.predicted_labels = np.argmax(self.predicted_proba, axis=-1).astype(np.uint8)\n\n if labels is not None and log_accuracy:\n accuracy = np.mean(np.equal(self.predicted_labels, np.argmax(labels, axis=-1).squeeze()).astype(np.float32))\n self.logger.summarize(self.counter, summarizer=\"test\", summaries_dict={'loss': np.array(0.0),\n 'acc': np.array(accuracy)})\n\n # Save to new EOPatch predicted probs and labels\n _, eopatch_name = os.path.split(filename)\n\n eopatch = EOPatch.load(filename, features=[(FeatureType.BBOX, FeatureType.META_INFO)])\n if predict_proba:\n eopatch.data_timeless['PREDICTED_PROBA'] = self.predicted_proba\n eopatch.mask_timeless['PREDICTED_LABELS'] = self.predicted_labels[..., np.newaxis]\n\n eopatch.save(self.pred_dir + os.sep + eopatch_name)\n\n return\n\n\n","sub_path":"eoflow/predictors/fcn_predictor.py","file_name":"fcn_predictor.py","file_ext":"py","file_size_in_byte":10603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"514057780","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 10 14:48:54 2020\r\n\r\n@author: zswitaj\r\n\"\"\"\r\nimport pandas as pd\r\nimport YOY_searchTrends as trends\r\n\r\nkw_dict = {\r\n \"Timberland\": \"/m/05kv16\",\r\n \"Timberland Boots\": \"Timberland Boots\",\r\n \"UGG\": \"/m/06wccjq\",\r\n \"Dr Martens\": \"/m/01lsm6\",\r\n \"Merrell\": \"/m/0kqrz3\",\r\n \"The North Face\": \"/m/04n92b\",\r\n \"Patagonia\": \"/m/0g152j\",\r\n \"Allbirds\": \"/g/11g6j4k3hl\",\r\n \"Vans\": \"/m/04kbwy\",\r\n \"Amazon\": \"/m/0mgkg \",\r\n \"Walmart\": \"/m/0841v\",\r\n \"Target\": \"/m/01b39j\",\r\n \"Zappos\": \"/m/02dfb9\",\r\n \"Foot Locker\": \"/m/08fhy9\",\r\n \"Journeys\": \"/m/03cbgd\",\r\n \"DSW\": \"/m/0flp70\",\r\n \"Nordstrom\": \"/m/01fc_q\",\r\n \"Macy's\": \"/m/01pkxd \",\r\n \"REI\": \"/m/02nx4d\",\r\n \"Dick's Sports\": \"/m/06fgv_\",\r\n \"Boot\": \"/m/01b638\",\r\n \"Outerwear\": \"Outerwear\"\r\n }\r\n\r\nlst_keywords = []\r\n\r\nprint(\"Adding keywords...\")\r\nfor topic in kw_dict:\r\n lst_keywords.append(topic)\r\n\r\nlst_values = []\r\n\r\nfor topic in kw_dict:\r\n print(\"Calculting {} results\".format(topic))\r\n lst_values.append(round(trends.getTrendData(kw_dict[topic]),1))\r\n\r\nprint(\"Combining...\")\r\nres = dict(zip(lst_keywords, lst_values))\r\nres_df = pd.DataFrame.from_dict(res, orient = 'index', columns = ['YOY Change'])\r\nres_df = res_df.transpose()\r\n\r\n# res_df.to_csv(r'output.csv')\r\n","sub_path":"YOYTrends_SL/YOY_searchTrends2_SL.py","file_name":"YOY_searchTrends2_SL.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"609525222","text":"import base64\nimport json\nimport pathlib\nimport torch\nimport numpy as np\nfrom PIL import Image\nfrom channels.generic.websocket import WebsocketConsumer\nfrom .convert_img_base64 import image_to_byte_array\nimport torch.nn as nn\n\n\ndef denomralization(img_tensors):\n return img_tensors * 0.5 + 0.5\n\n\ndef to_device(data, device):\n \"\"\"Move tensors to chosen device\"\"\"\n if isinstance(data, (list, tuple)):\n return [to_device(x, device) for x in data]\n return data.to(device, non_blocking=True)\n\n\ndef get_default_device():\n \"\"\"Pick GPU if available, else CPU\"\"\"\n if torch.cuda.is_available():\n return torch.device('cuda')\n return torch.device('cpu')\n\n\ndef build_generator_for_GAN_model(latent_size):\n \"\"\"\n Building generator for using model from .ckpt file\n :param latent_size: size of latent vector\n :return: model of generator\n \"\"\"\n model = nn.Sequential(\n\n # input: latent_size x 1 x 1\n nn.ConvTranspose2d(latent_size, 512, kernel_size=4, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n # output: 512 x 4 x 4\n\n nn.ConvTranspose2d(512, 256, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n # output: 256 x 8 x 8\n\n nn.ConvTranspose2d(256, 128, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n # output: 128 x 16 x 16\n\n nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n # output: 64 x 32 x 32\n\n nn.ConvTranspose2d(64, 32, kernel_size=4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(32),\n nn.ReLU(True),\n # output: 32 x 64 x 64\n\n nn.ConvTranspose2d(32, 3, kernel_size=4, stride=2, padding=1, bias=False),\n nn.Tanh()\n # out: 3 x 128 x 128\n )\n return model\n\n\nclass GANImageConsumer(WebsocketConsumer):\n def __init__(self):\n self.cancel = False\n WebsocketConsumer.__init__(self)\n\n def connect(self):\n self.accept()\n generator = build_generator_for_GAN_model(200)\n path = pathlib.Path(__file__).parent.absolute()\n\n generator.load_state_dict(\n torch.load(f\"{path}/G_gan.ckpt\", map_location='cpu')\n )\n latent_tensor = torch.randn(1, 200, 1, 1)\n fake_image = generator(latent_tensor)\n fake_image = denomralization(fake_image).detach()[0]\n fake_image = fake_image.permute(1, 2, 0).numpy()\n np_arr = (np.asarray(fake_image) * 255).astype(np.uint8)\n\n image_generated_bytes = image_to_byte_array(Image.fromarray(np_arr))\n encoded_image_string = str(base64.b64encode(image_generated_bytes))\n self.send(json.dumps({'iteration': 'Model is pretrained', 'message': encoded_image_string}))\n","sub_path":"mainApp/GANConsumer.py","file_name":"GANConsumer.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"195576470","text":"from rest_framework import status\nfrom .test_setup import TestSetUp\n\n\nclass AgendaTestViews(TestSetUp):\n\n def test_listar_consultas_com_autenticacao(self):\n response = self.client.get(self.listar_consultas_url)\n self.assertEquals(response.status_code, status.HTTP_200_OK)\n\n def test_detalhes_agendas_sem_autenticacao(self):\n self.client.force_authenticate(user=None)\n response = self.client.get(self.listar_consultas_url)\n self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED)\n","sub_path":"backend/apps/consultas/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"385086829","text":"from bs4 import BeautifulSoup\nimport requests\nimport sys\nimport io\n\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(),encoding='utf-8')\nsys.stderr = io.TextIOWrapper(sys.stderr.detach(),encoding='utf-8')\n\nwith requests.session() as s :\n login_req=s.post('https://movie.naver.com/movie/bi/mi/point.nhn?code=161967')\n # print('login_header : ',login_req.headers)\n\n # Response 정상 확인\n if login_req.status_code==200 and login_req.ok :\n # print(\"로그인 성공!\")\n\n # 권한이 필요한 게시글 가져오기\n post_one=s.get('https://movie.naver.com/movie/bi/mi/point.nhn?code=161967')\n # print(post_one)\n\n # 예외처리\n # post_one.raise_for_status()\n # print(post_one.text)\n\n # BeautifulSoup 선언\n soup=BeautifulSoup(post_one.text,\"html.parser\")\n # print(soup.prettify())\n article=soup.select('.score_reple>p')\n # print(article)\n for i,a in enumerate(article,1) :\n print('{}번째 평론 : {}'.format(i,a.text))\n","sub_path":"section3/homework1.py","file_name":"homework1.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"355667697","text":"from rest_framework import serializers\nfrom api.models import Post, POST_STATUS_CHOICES\nfrom django.contrib.auth.models import User\n\nclass PostSerializer(serializers.Serializer):\n id = serializers.IntegerField(read_only=True)\n title = serializers.CharField(required=False, allow_blank=True, max_length=255)\n content = serializers.CharField(required=False, allow_blank=True)\n published_date = serializers.DateField(required=True)\n user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())\n status = serializers.ChoiceField(choices=POST_STATUS_CHOICES, default='DRAFT')\n\n\n def create(self, validate_data):\n \"\"\"\n create and return new post, givin the validate datas\n \"\"\"\n\n return Post.objects.create(**validate_data)\n\n\n def update(self, instance, validate_data):\n \"\"\"\n update Post\n \"\"\"\n instance.title = validate_data.get('title', instance.title)\n instance.content = validate_data.get('content', instance.content)\n instance.published_date = validate_data.get('published_date', instance.published_date)\n instance.published_date = validate_data.get('published_date', instance.published_date)\n instance.published_date = validate_data.get('published_date', instance.published_date)\n\n instance.save()\n return instance\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"448621093","text":"from os import error\nimport sys\nfrom collections import Counter\n\ndef readInput(inputfile):\n input = {\n \"dots\": [],\n \"instructions\": [],\n \"xmax\": 0,\n \"ymax\": 0\n }\n with open(inputfile) as file:\n lineFound = True\n\n while lineFound:\n line = file.readline()\n if not line:\n lineFound = False\n else:\n line = line.strip()\n if line.startswith(\"fold\"):\n foldInst = line[11:].split(\"=\")\n input[\"instructions\"].append({\"axis\": foldInst[0], \"index\": int(foldInst[1])})\n \n else:\n if len(line) > 0:\n point = line.split(\",\")\n x = int(point[0])\n y = int(point[1])\n input[\"dots\"].append({\"x\": x, \"y\": y})\n if x > input[\"xmax\"]:\n input[\"xmax\"] = x\n \n if y > input[\"ymax\"]:\n input[\"ymax\"] = y\n return input\n\ndef foldX(index, field):\n foldedField = []\n\n for row in field:\n baseRow = row[:index]\n mirrorRow = row[index+1:]\n lastBaseIndex = len(baseRow) - 1\n\n for x in range(len(mirrorRow)):\n foldIndex = lastBaseIndex - x\n if mirrorRow[x] == \"#\":\n baseRow[foldIndex] = mirrorRow[x]\n \n foldedField.append(baseRow)\n\n return foldedField\n\ndef foldY(index, field):\n baseField = field[:index]\n lastBaseIndex = len(baseField) - 1\n\n foldedField = field[index+1:]\n for y in range(len(foldedField)):\n row = foldedField[y]\n foldIndex = lastBaseIndex - y\n\n for x in range(len(row)):\n if row[x] == \"#\":\n baseField[foldIndex][x] = row[x]\n\n return baseField\n\ndef fold(axis, index, field):\n print(\"Folding at {} axis on index {}\".format(axis, index))\n\n if axis == \"x\":\n return foldX(index, field)\n \n if axis == \"y\":\n return foldY(index, field)\n return field\n\ndef solutionPart1(input):\n field = [['.' for _ in range(input[\"xmax\"] + 1)] for _ in range(input[\"ymax\"] + 1)]\n for dot in input[\"dots\"]:\n field[dot[\"y\"]][dot[\"x\"]] = \"#\"\n\n instruction = input[\"instructions\"][0]\n field = fold(instruction[\"axis\"], instruction[\"index\"], field)\n \n visibleDots = 0\n for row in field:\n print(row)\n visibleDots += row.count(\"#\")\n \n print(\"There are {} visible dots in the folded sheet\".format(visibleDots))\n\ndef solutionPart2(input):\n field = [['.' for _ in range(input[\"xmax\"] + 1)] for _ in range(input[\"ymax\"] + 1)]\n for dot in input[\"dots\"]:\n field[dot[\"y\"]][dot[\"x\"]] = \"#\"\n\n instruction = input[\"instructions\"][0]\n for instruction in input[\"instructions\"]:\n field = fold(instruction[\"axis\"], instruction[\"index\"], field)\n print(\"New Field:\")\n \n visibleDots = 0\n\n print(\"Code:\")\n for row in field:\n minimalizedRow = \"\"\n for dot in row:\n minimalizedRow += dot\n minimalizedRow += \" \"\n print(minimalizedRow)\n visibleDots += row.count(\"#\")\n\nif __name__ == \"__main__\":\n part = int(sys.argv[1])\n inputfile = sys.argv[2]\n \n\n print(\"Solution {} for file {}\".format(part, inputfile))\n\n input = readInput(inputfile)\n if part == 1:\n solutionPart1(input)\n\n else:\n solutionPart2(input)\n\n","sub_path":"2021/Day 13/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"78239095","text":"# coding: utf-8\r\n# Your code here!\r\ndef euclid(a,b):\r\n while b != 0:\r\n a,b = b,a%b\r\n return a\r\n\r\n\r\nmonsters = int(input())\r\narray = list(map(int,input().split()))\r\nfor i in range(monsters-1):\r\n mod = euclid(array[i], array[i+1])\r\n array[i+1] = mod\r\nprint(array[-1])","sub_path":"re118c.py","file_name":"re118c.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"638433316","text":"import unittest2 as unittest\n\n\n# ================ code ===================\nclass Solution:\n def isSubsequence(self, s: str, t: str) -> bool:\n b = iter(t) # 把 t 转化成了一个迭代器\n print(b)\n gen = (i for i in s) # 产生一个生成器, 这个生成器可以遍历对象 s\n print(gen)\n for i in gen:\n print(i)\n gen = ((i in b) for i in s)\n print(gen)\n for i in gen:\n print(i)\n return all(((i in b) for i in s))\n\n\n# ========================================\nTEST_DATA = [\n {\n \"input\": [\"abc\", \"ahbgdc\"],\n \"target\": True\n },\n {\n \"input\": [\"axc\", \"ahbgdc\"],\n \"target\": False\n }\n]\n\n\nclass Test(unittest.TestCase):\n @unittest.skipIf(not isinstance(TEST_DATA[0][\"input\"], list), \"skip\")\n def test_multi(self):\n for t in TEST_DATA:\n self.assertEqual(Solution.isSubsequence(self, *t[\"input\"]), t[\"target\"])\n\n @unittest.skipIf(isinstance(TEST_DATA[0][\"input\"], list), \"skip\")\n def test_single(self):\n for t in TEST_DATA:\n self.assertEqual(Solution.findTheDifference(self, t[\"input\"]), t[\"target\"])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"647650839","text":"\n\nfrom xai.brain.wordbase.nouns._sweeper import _SWEEPER\n\n#calss header\nclass _SWEEPERS(_SWEEPER, ):\n\tdef __init__(self,): \n\t\t_SWEEPER.__init__(self)\n\t\tself.name = \"SWEEPERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"sweeper\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_sweepers.py","file_name":"_sweepers.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"339814952","text":"import matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport numpy as np\n\nclass six_figures():\n\tdef __init__(self, show=True):\n\t\tprint ('Visualization module initializing ... ')\n\t\tself.show = show\n\t\tif show == True:\n\t\t\tplt.ion()\n\t\t\n\t\tplt.rcParams['image.cmap'] = 'gray'\n\t\tfig_size = (12,8) \n\t\tself.fig = plt.figure(figsize=fig_size)\n\t\tself.gs = gridspec.GridSpec(2,6, wspace=0.8, hspace=0.6)\n\n\t\tself.axs = [\n\t\t\t\t\tself.fig.add_subplot(self.gs[0,0:2]),\n\t\t\t\t\tself.fig.add_subplot(self.gs[0,2:4]),\n\t\t\t\t\tself.fig.add_subplot(self.gs[0,4:6]),\n\t\t\t\t\tself.fig.add_subplot(self.gs[1,0:2]),\n\t\t\t\t\tself.fig.add_subplot(self.gs[1,2:4]),\n\t\t\t\t\tself.fig.add_subplot(self.gs[1,4:6])\t\t\n\t\t\t\t\t]\n\t\tprint ('Complete!')\n\n\tdef draw(self, idx=1, mode='curve', data=[1,2,3,2,3], title='', data2=0):\n\t\tself.axs[idx].cla()\n\t\ttry:\n\t\t\tself.axs[idx].set_title(title)\n\t\t\tif mode == 'curve':\n\t\t\t\tself.axs[idx].grid()\n\t\t\t\tself.axs[idx].plot(data)\n\t\t\t\tself.axs[idx].set_xlabel('current: ' + str(data[-1]))\n\t\t\tif mode == 'imshow':\n\t\t\t\tself.axs[idx].imshow(data)\n\t\t\tif mode == 'text':\n\t\t\t\tself.axs[idx].text(0.1, 0.4, data, fontsize=15)\n\t\t\t\tself.axs[idx].xaxis.set_ticklabels([])\n\t\t\t\tself.axs[idx].yaxis.set_ticklabels([])\t\n\t\t\tif mode == 'twocurve':\n\t\t\t\tself.axs[idx].grid()\n\t\t\t\tself.axs[idx].plot(data, label='train')\n\t\t\t\tself.axs[idx].plot(data2, label='test')\n\t\t\t\tself.axs[idx].set_xlabel('\\ntrain:'+ str(data[-1]) +'\\nvali:'+ str(data2[-1]))\n\t\t\t\tself.axs[idx].set_ylim(0, 0.25)\n\t\t\t\tself.axs[idx].legend()\n\t\texcept:\n\t\t\tprint ('Warning: Figure drawing failure!')\n\t\t\tprint ('At: ' + str(idx) + ' with mode: ' + mode)\n\n\tdef display(self):\n\t\tif self.show == True:\n\t\t\tplt.draw()\n\t\t\tplt.pause(0.01)\n\t\telse:\n\t\t\tprint ('Figure display mode disabled. No figure output.')\n\n\tdef save(self):\n\t\tplt.savefig('tfsave.pdf')\n\nif __name__ == '__main__':\n\t_show = six_figures()\n\t_show.draw()\n\t_show.display()","sub_path":"lib/visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"543865845","text":"from django.conf.urls import patterns, url\n\n\nurlpatterns = patterns('userlogin.views',\n url(r'^$', 'home', name='home'),\n url(r'^login$', 'login_handler', name='login_handler'),\n url(r'^logout$', 'logout_handler', name='logout_handler'),\n url(r'^users$', 'users', name='show_users'),\n url(r'^users/add$', 'add_user', name='add_user'),\n url(r'^users/upload_list$', 'upload_user_list', name='upload_user_list'),\n url(r'^user/set_branch$', 'set_branch', name='set_branch'),\n url(r'^user/get_message$', 'get_message', name='get_message'),\n)\n","sub_path":"userlogin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"244585070","text":"import socket\nimport select\nimport time\nimport pickle\n\nfrom ConstantVariables import ConstantVariables\nfrom GameServer import GameServer\n\n\nclass ServerSocket:\n def __init__(self):\n self._header_length = ConstantVariables.NETWORK_HEADER_LENGTH\n self._server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self._server_socket.bind((ConstantVariables.NETWORK_IP, ConstantVariables.NETWORK_PORT))\n self._server_socket.listen()\n self._sockets_list = [self._server_socket]\n self._clients = {}\n self._game = GameServer()\n self._client_count = 0\n print(f'Listening for connections on {ConstantVariables.NETWORK_IP}:{ConstantVariables.NETWORK_PORT}...')\n\n def start(self):\n\n self._game.start()\n\n while True:\n\n read_sockets, _, exception_sockets = select.select(self._sockets_list, [], self._sockets_list)\n\n for notified_socket in read_sockets:\n\n # new connection\n if notified_socket == self._server_socket:\n client_socket, client_address = self._server_socket.accept()\n client_message = self.receive_message(client_socket)\n\n if client_message is False:\n continue\n\n if client_message['data'].decode('utf-8') == \"ask_id\":\n self.create_client_and_send_id(client_socket)\n\n print('Accepted new connection from {}:{}, request: {}'.format(*client_address,\n client_message['data'].decode(\n 'utf-8')))\n\n # known connection\n else:\n\n message = self.receive_message(notified_socket)\n\n if message is False:\n print('Closed connection from: {}'.format(self._clients[notified_socket]))\n\n # remove client\n for snake in self._game.snakes:\n if snake.id_client == self._clients[notified_socket]:\n self._game.snakes.remove(snake)\n\n self._sockets_list.remove(notified_socket)\n del self._clients[notified_socket]\n continue\n #\n\n client_message = self._clients[notified_socket]\n print(f\"Received message from {client_message}\")\n\n # update the snake of the client\n for snake in self._game.snakes:\n if snake.id_client == client_message:\n\n # change direction of the snake\n snake.direction_current = message['data'].decode('utf-8')\n\n # move the snake\n snake.move_head()\n if self._game.is_apple_caught(snake):\n self._game.create_new_apple()\n snake.growth()\n else:\n snake.move_body()\n\n # if the client has lost the game\n if self.is_client_lost(snake):\n # send to client\n message_game = \"\".encode('utf-8')\n message_game = bytes(f\"{len(message_game):<{self._header_length}}\",\n 'utf-8') + message_game\n notified_socket.send(message_game)\n\n # remove client\n print('Closed connection from: {}'.format(self._clients[notified_socket]))\n self._game.snakes.remove(snake)\n self._sockets_list.remove(notified_socket)\n del self._clients[notified_socket]\n break\n\n # send game to the client\n message_game = pickle.dumps(self._game)\n message_game = bytes(f\"{len(message_game):<{self._header_length}}\", 'utf-8') + message_game\n notified_socket.send(message_game)\n\n # remove clients of the notifications\n for notified_socket in exception_sockets:\n self._sockets_list.remove(notified_socket)\n del self._clients[notified_socket]\n\n def receive_message(self, client_socket):\n try:\n message_header = client_socket.recv(self._header_length)\n\n if not len(message_header):\n # if no data receive, client closed connection\n return False\n\n message_length = int(message_header.decode('utf-8').strip())\n\n message = client_socket.recv(message_length)\n\n return {'header': message_header, 'data': message}\n\n except:\n return False\n\n def create_client_and_send_id(self, client_socket):\n self._client_count += 1\n client_id = str(self._client_count) # the id must be a str for sending\n self._clients[client_socket] = client_id\n\n # creation of the snake of the client\n self._game.create_snake(client_id)\n # add the client id ine the list of clients\n self._sockets_list.append(client_socket)\n\n # send the id to the client\n message = client_id.encode('utf-8')\n message_header = f\"{len(message):<{self._header_length}}\".encode('utf-8')\n client_socket.send(message_header + message)\n\n def is_client_lost(self, snake_client):\n for snake in self._game.snakes:\n if snake != snake_client:\n if snake.get_head_coordinate() == snake_client.get_head_coordinate():\n return True\n elif snake_client.get_head_coordinate() in snake.body_coordinates:\n return True\n else:\n if snake.get_head_coordinate() in snake.body_coordinates:\n return True\n return False\n","sub_path":"executables/graphic_with_network/ServerSocket.py","file_name":"ServerSocket.py","file_ext":"py","file_size_in_byte":6320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"472064276","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pylab as pl\nimport scipy as sp\nfrom scipy import stats\nimport sys\n\nroi = sys.argv[1]\nsubjs = ['MES_022817_0','MES_030217_0', 'MES_032117_1','MES_040217_0','MES_041117_0','MES_041217_0','MES_041317_0', 'MES_041417_0','MES_041517_0','MES_042017_0','MES_042317_0','MES_042717_0','MES_050317_0','MES_051317_0','MES_051917_0','MES_052017_0','MES_052017_1','MES_052317_0','MES_052517_0','MES_052617_0','MES_052817_0','MES_052817_1','MES_053117_0','MES_060117_0','MES_060117_1']\ndatadir = '/jukebox/norman/jamalw/MES/subjects/'\n\ncorrD3D = np.zeros((2511,2511,len(subjs)))\navgCorrD3D = np.zeros((16,16,len(subjs)))\n\nfor i in range(len(subjs)):\n corrD3D[:,:,i] = np.load(datadir+str(subjs[i]) + '/data/corrD' + roi + '.npy')\n avgCorrD3D[:,:,i] = np.load(datadir+str(subjs[i]) + '/data/avgCorrD' + roi + '.npy')\n\nmeanCorrFull = np.mean(corrD3D,2)\nmeanCorrAvg = np.mean(avgCorrD3D,2)\n\n# compute average section of avgCorrD\ncorr_eye = np.identity(8)\nclassical_within = meanCorrAvg[0:8,0:8]\nclassical_within_off = classical_within[corr_eye == 0]\njazz_within = meanCorrAvg[8:16,8:16]\njazz_within_off = jazz_within[corr_eye == 0]\nclassJazz_between = meanCorrAvg[8:16,0:8]\nclassJazz_between_off = classJazz_between[corr_eye == 0]\njazzClass_between = meanCorrAvg[0:8,8:16]\njazzClass_between_off = jazzClass_between[corr_eye == 0]\n\nlabels = [\"Classical\",\"Jazz\"]\n\nplt.figure(1,facecolor=\"1\")\nplt.imshow(meanCorrFull,interpolation='none')\nplt.colorbar()\nplt.axis('tight')\nax = plt.gca()\nplt.plot((ax.get_ylim()[0],ax.get_ylim()[1]),(ax.get_xlim()[1],ax.get_xlim()[0]),\"k-\")\npl.text(2800,2800,'N='+ str(len(subjs)),fontweight='bold')\nplt.plot((-.5, 2511.5), (1255.5, 1255.5), 'k-')\nplt.plot((1255.5, 1255.5), (-.5, 2511.5), 'k-')\npl.text(500,-70,labels[0])\npl.text(500,2800,labels[0])\npl.text(2550,500,labels[0],rotation='270')\npl.text(-300,500,labels[0],rotation='vertical')\npl.text(1800,-70,labels[1])\npl.text(-300,1800,labels[1],rotation='vertical')\npl.text(1800,2800,labels[1])\npl.text(2550,1800,labels[1],rotation='270')\npl.text(900.5, -200,'Full Correlation Matrix',fontweight='bold')\nplt.savefig('/jukebox/norman/jamalw/MES/data/plots/FullCorrMat_N' + str(len(subjs)) + roi)\n\nplt.figure(2,facecolor=\"1\")\nax = plt.gca()\nplt.imshow(meanCorrAvg,interpolation='none')\nplt.plot((-.5, 15.5), (7.5, 7.5), 'k-')\nplt.plot((7.5, 7.5), (-.5, 15.5), 'k-')\nplt.colorbar()\nplt.axis('tight')\nplt.plot((ax.get_ylim()[0],ax.get_ylim()[1]),(ax.get_xlim()[1],ax.get_xlim()[0]),\"k-\")\nplt.text(2.75,-1,labels[0],fontsize=15)\nplt.text(2.75,17,labels[0],fontsize=15)\nplt.text(15.65,2.75,labels[0],rotation='270',fontsize=15)\nplt.text(-2,2.75,labels[0],rotation='vertical',fontsize=15)\nplt.text(10.75,-1,labels[1],fontsize=15)\nplt.text(-2,10.75,labels[1],rotation='vertical',fontsize=15)\nplt.text(15.65,10.75,labels[1],rotation='270',fontsize=15)\nplt.text(10.75,17,labels[1],fontsize=15)\nplt.text(18,17,'N='+ str(len(subjs)),fontweight='bold',fontsize=15)\nplt.text(19.5,8,'r',fontweight='bold',fontsize=15)\nplt.text(1,-1.75,'Average Within-Song Correlation',fontweight='bold',fontsize=18)\nplt.savefig('/jukebox/norman/jamalw/MES/data/plots/AvgCorrMat_N' + str(len(subjs)) + roi)\n\nplt.figure(3,facecolor=\"1\")\nallComparisonsAvg = np.array([np.mean(classical_within_off),np.mean(jazz_within_off),np.mean(classJazz_between_off),np.mean(jazzClass_between_off)])\nallComparisonsSem = np.array([stats.sem(classical_within_off),stats.sem(jazz_within_off),stats.sem(classJazz_between_off),stats.sem(jazzClass_between_off)])\nN = 4\nind = np.arange(N)\nwidth = 0.35\nplt.bar(ind, allComparisonsAvg, width, color='k',yerr = allComparisonsSem,error_kw=dict(ecolor='lightseagreen',lw=3,capsize=0,capthick=0))\nplt.ylabel('Pattern Similarity (r)',fontsize=15)\nplt.title('Average Within and Between-Genre Similarity',fontweight='bold',fontsize=18)\nlabels = ['Classical vs Classical', 'Jazz vs Jazz', 'Jazz vs Classical', 'Classical vs Jazz']\nplt.xticks(ind + width / 2,labels,fontsize=12)\nplt.plot((-0.175,3.5),(0,0),'k-')\nplt.savefig('/jukebox/norman/jamalw/MES/data/plots/AvgGenreSim_N' + str(len(subjs)) + roi) \n\n# Plot average Within song and Between song comparison\nplt.figure(4,facecolor=\"1\")\ncorr_eye = np.identity(16)\nWithinBetwnSongAvgCorr = np.array([np.mean(meanCorrAvg[corr_eye == 1]),np.mean(meanCorrAvg[corr_eye == 0])])\nWithinBetwnSongSemCorr = np.array([stats.sem(meanCorrAvg[corr_eye == 1]),stats.sem(meanCorrAvg[corr_eye == 0])])\nN = 2\nind = np.arange(N)\nwidth = 0.35\nplt.bar(ind, WithinBetwnSongAvgCorr, width, color='k',yerr=WithinBetwnSongSemCorr,error_kw=dict(ecolor='lightseagreen',lw=3,capsize=0,capthick=0))\nplt.ylabel('Pattern Similarity (r)',fontsize=15)\nplt.title('Average Within- and Between-Song Similarity',fontweight='bold',fontsize=18)\nlabels = ['Same Song','Different Song']\nplt.xticks(ind + width / 2,labels,fontsize=15)\nplt.plot((-0.175,1.5),(0,0),'k-')\nplt.savefig('/jukebox/norman/jamalw/MES/data/plots/AvgSongSim_N' + str(len(subjs)) + roi)\n\n# Plot average Within song and Between song correlation for each genre\nplt.figure(5,facecolor=\"1\")\n#compute average of within song/within genre correlations \nWithinSongCorr = meanCorrAvg[corr_eye == 1]\nWithinSongAvgCorr = np.mean(meanCorrAvg[corr_eye == 1])\nClassicalWithinAvgOn = np.mean(WithinSongCorr[0:7])\nJazzWithinAvgOn = np.mean(WithinSongCorr[8:15])\nClassicalWithinSemOn = stats.sem(WithinSongCorr[0:7])\nJazzWithinSemOn = stats.sem(WithinSongCorr[8:15])\n\n#compute average of between song/within genre correlations\ncorrEye8 = np.identity(8)\nClassicalBtwnAvgOff = np.mean(classical_within[corrEye8 == 0])\nClassicalBtwnSemOff = stats.sem(classical_within[corrEye8 == 0])\nJazzBtwnAvgOff = np.mean(jazz_within[corrEye8 == 0])\nJazzBtwnSemOff = stats.sem(jazz_within[corrEye8 == 0])\n\nAvgAllGroups = np.array([ClassicalWithinAvgOn,ClassicalBtwnAvgOff,JazzWithinAvgOn,JazzBtwnAvgOff])\nSemAllGroups = np.array([ClassicalWithinSemOn,ClassicalBtwnSemOff,JazzWithinSemOn,JazzBtwnSemOff])\n\nN = 4\nind = np.arange(N)\nwidth = 0.35\nplt.bar(ind, AvgAllGroups, width, color='k',yerr=SemAllGroups,error_kw=dict(ecolor='lightseagreen',lw=3,capsize=0,capthick=0))\nplt.ylabel('Pattern Similarity (r)',fontsize=15)\nplt.title('Within- and Between-Song Similarity Within Genre',fontweight='bold',fontsize=18)\nlabels = ['Classical Within','Classical Between','Jazz Within', 'Jazz Between']\nplt.xticks(ind + width / 2,labels,fontsize=14)\nplt.plot((-0.175,1.5),(0,0),'k-')\npl.text(18,17,'N=2',fontweight='bold')\nplt.savefig('/jukebox/norman/jamalw/MES/data/plots/WithinGenreOnOffDiag_N' + str(len(subjs)) + roi)\n\n\n\nplt.show()\n\n\n","sub_path":"PlotAvgFuncXGenre.py","file_name":"PlotAvgFuncXGenre.py","file_ext":"py","file_size_in_byte":6609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"277505487","text":"from sklearn.preprocessing import MaxAbsScaler, RobustScaler, QuantileTransformer, PowerTransformer\n# 실습 MaxAbsScaler, RobustScaler, QuantileTransformer, PowerTransformer 각 결과 적어놓기\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.datasets import load_diabetes\nfrom icecream import ic\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\n\n\n#1. 데이터\ndatasets = load_diabetes()\n\nx = datasets.data\ny = datasets.target\n\n# ic(x.shape, y.shape) # (442, 10) (442,)\n\n# ic(datasets.feature_names) \n#['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']\n# ic(datasets.DESCR)\n\n# ic(x[:30])\n# ic(np.min(y), np.max(y))\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, shuffle=True, random_state=9)\n\n# 데이터 전처리\n# scaler = MaxAbsScaler()\n# scaler = RobustScaler()\n# scaler = QuantileTransformer()\nscaler = PowerTransformer()\nscaler.fit(x_train)\nx_train = scaler.transform(x_train)\nx_test = scaler.transform(x_test)\n\n\n#2. 모델구성(validation)\nmodel = Sequential()\nmodel.add(Dense(100, input_shape=(10,), activation='relu')) #relu : 음수값은 0, 양수만 제대로 잡음\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(8, activation='relu'))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(16, activation='relu'))\nmodel.add(Dense(1))\n\n\n#3. 컴파일, 훈련\nmodel.compile(loss='mse', optimizer='adam')\nmodel.fit(x_train, y_train, epochs=100, batch_size=10, validation_split=0.1, shuffle=True, verbose=1)\n\n#4. 평가, 예측(mse, r2)\nloss = model.evaluate(x_test, y_test)\nic(loss)\n\ny_predict = model.predict(x_test)\nr2 = r2_score(y_test, y_predict)\nic(r2)\n\n\n\n'''\n* MaxAbsScaler\nic| loss: 2240.12841796875\nic| r2: 0.588361118619634\n\n* RobustScaler\nic| loss: 3183.495361328125\nic| r2: 0.41501099016114074\n\n* QuantileTransformer\nic| loss: 2429.1533203125\nic| r2: 0.5536265040327801\n\n* PowerTransformer\nic| loss: 3609.73388671875\nic| r2: 0.33668676137425313\n'''","sub_path":"01_keras/keras22.diabets_Scaler.py","file_name":"keras22.diabets_Scaler.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"339594059","text":"import requests\nfrom uuid import uuid4\nfrom urllib.parse import quote\nimport os\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.62 Safari/537.36\",\n \"Referer\": \"https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111111&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E7%BE%8E%E5%A5%B3&oq=%E7%BE%8E%E5%A5%B3&rsp=-1\",\n \"Cookie\": \"BDqhfp=%E7%BE%8E%E5%A5%B3%26%260-10-1undefined%26%261576%26%263; BIDUPSID=55B9F89BBD8CE76842ADD9DCE4E07064; PSTM=1588574309; BAIDUID=55B9F89BBD8CE76850CAB1E8E50293E6:FG=1; cflag=13%3A3; BDUSS=kxVN2lhTmEzVFVKcGU2UjMtfmhEV25ZVkRkazdRS2hhNHdQbUx4MmlVaVB2ZGxlSVFBQUFBJCQAAAAAAAAAAAEAAAAIy~xb09DDqMTl0f3f9wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAI8wsl6PMLJea; BDRCVFR[X_XKQks0S63]=mk3SLVN4HKm; userFrom=www.google.com; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm; firstShowTip=1; indexPageSugList=%5B%22%E7%BE%8E%E5%A5%B3%22%5D; cleanHistoryStatus=0; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm\"\n}\n#初始化一些参数,方便更好的调用\nsession = requests.session()\nsession.headers = headers\ndef get_img(url):\n html = session.get(url)\n #构造一个多线程池,就10个线程把\n threadingPool = ThreadPoolExecutor(max_workers=10)\n #为什么这里要用到防错机制,因为如果是用json的话,有一些图片可能会失败,要想全部成功获得,只有正则才行\n try:\n #定位它的内容\n content = html.json()['data']\n #用循环叠带把这些内容给打印出来\n for c in content[:-1]:\n #输出它的URL\n print(c['middleURL'])\n #用多线程来下载这些图片,从而提升我们的下载速度,达到我们的目的\n threadingPool.submit(download,url)\n except:\n pass\n\ndef download(imgurl):\n filename = '图片保存文件'\n #创建一个文件夹,如果这个文件夹不存在,那么我们就创建这个文件夹,这个是一条死语句,必须得背下来\n if not os.path.exists(filename):\n os.makedirs(filename)\n #获取这个图片的URL\n image = session.get(imgurl)\n #uuid4只是为了更好的命名而已,毕竟那么多图片,不可能一个个命名\n with open(\"图片保存文件/{}.jpg\".format(uuid4()),\"wb\") as f:\n f.write(image.content)\n\ndef main():\n KEYWORD = input(\"请输入你要下载的图片内容:\")\n for i in range(30,300,30):\n url = \"https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord={}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=©right=&word={}&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&force=&cg=girl&pn={}&rn=30&gsm=96&1589535866384=\". \\\n format(quote(KEYWORD), quote(KEYWORD), i)\n get_img(url)\n\nif __name__ == '__main__':\n start = time.time()\n main()\n print(time.time()-start)\n\n\n","sub_path":"爬虫之进阶篇/异步爬虫/baidutupian.py","file_name":"baidutupian.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"634212758","text":"# -*- encoding: utf-8 -*-\n# pylint: disable=E0203,E1101,C0111\n\"\"\"\n@file\n@brief Runtime operator.\n\"\"\"\nimport numpy\nfrom numpy.fft import fft2\nfrom ..shape_object import ShapeObject\nfrom ._op import OpRun\nfrom ._new_ops import OperatorSchema\n\n\nclass FFT2D(OpRun):\n\n atts = {'axes': [-2, -1]}\n\n def __init__(self, onnx_node, desc=None, **options):\n OpRun.__init__(self, onnx_node, desc=desc,\n expected_attributes=FFT2D.atts,\n **options)\n if self.axes is not None:\n self.axes = tuple(self.axes)\n if len(self.axes) != 2:\n raise ValueError( # pragma: no cover\n \"axes must a set of 1 integers not %r.\" % self.axes)\n\n def _find_custom_operator_schema(self, op_name):\n if op_name == \"FFT2D\":\n return FFT2DSchema()\n raise RuntimeError( # pragma: no cover\n \"Unable to find a schema for operator '{}'.\".format(op_name))\n\n def _run(self, a, fft_length=None): # pylint: disable=W0221\n if fft_length is None:\n y = fft2(a, axes=self.axes)\n else:\n y = fft2(a, tuple(fft_length), axes=self.axes)\n if a.dtype in (numpy.float32, numpy.complex64):\n return (y.astype(numpy.complex64), )\n if a.dtype in (numpy.float64, numpy.complex128):\n return (y.astype(numpy.complex128), )\n raise TypeError( # pragma: no cover\n \"Unexpected input type: %r.\" % a.dtype)\n\n def _infer_shapes(self, a, b=None): # pylint: disable=W0221,W0237\n if a.dtype in (numpy.float32, numpy.complex64):\n return (ShapeObject(a.shape, dtype=numpy.complex64), )\n if a.dtype in (numpy.float64, numpy.complex128):\n return (ShapeObject(a.shape, dtype=numpy.complex128), )\n raise TypeError( # pragma: no cover\n \"Unexpected input type: %r.\" % a.dtype)\n\n def _infer_types(self, a, b=None): # pylint: disable=W0221,W0237\n if a.dtype in (numpy.float32, numpy.complex64):\n return (numpy.complex64, )\n if a.dtype in (numpy.float64, numpy.complex128):\n return (numpy.complex128, )\n raise TypeError( # pragma: no cover\n \"Unexpected input type: %r.\" % a.dtype)\n\n def to_python(self, inputs):\n if self.axes is not None:\n axes = tuple(self.axes)\n else:\n axes = None\n if len(inputs) == 1:\n return ('from numpy.fft import fft2',\n \"return fft2({}, axes={})\".format(\n inputs[0], axes))\n return ('from numpy.fft import fft2',\n \"return fft2({}, tuple({}), axes={})\".format(\n inputs[0], inputs[1], axes))\n\n\nclass FFT2DSchema(OperatorSchema):\n \"\"\"\n Defines a schema for operators added in this package\n such as @see cl FFT.\n \"\"\"\n\n def __init__(self):\n OperatorSchema.__init__(self, 'FFT2D')\n self.attributes = FFT2D.atts\n","sub_path":"mlprodict/onnxrt/ops_cpu/op_fft2d.py","file_name":"op_fft2d.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"630049488","text":"from flask import jsonify, request, Response\r\nfrom flask_restful import Resource\r\n\r\nfrom models.parts import Actions\r\nfrom etc.utcTimeStamp import get_utc_time_stamp\r\nfrom etc.errors import *\r\n\r\nnow = get_utc_time_stamp()\r\n\r\nclass ActionsApi(Resource):\r\n def get(self, action_id) -> Response:\r\n output = Actions.objects.get(id=action_id)\r\n return jsonify({'result': output})\r\n\r\n def put(self, action_id) -> Response:\r\n \tdata = request.get_json()\r\n \tif \"date\" in data:\r\n \t\tif data[\"date\"] < now:\r\n \t\t\treturn 401\r\n \tput_data = Actions.objects(id=action_id).update(**data)\r\n \treturn jsonify({\"result\": put_data})\r\n\r\n def delete(self, action_id) -> Response:\r\n \tout = Actions.objects(id=action_id).delete()\r\n \treturn jsonify({\"result\": out})\r\n\r\nclass ActionApi(Resource):\r\n\tdef post(self) -> Response:\r\n\t\tdata = request.get_json()\r\n\t\tif \"date\" in data:\r\n\t\t\tif data[\"date\"] < now:\r\n\t\t\t\treturn 401\r\n\t\tpost_data = Actions(**data).save()\r\n\t\tout = {\"id\" : str(post_data.id)}\r\n\t\treturn jsonify({\"result\":out})","sub_path":"api/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"420657757","text":"from typing import List\n\n\nclass Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n intervals.append(newInterval)\n intervals.sort()\n\n i = 1\n while i < len(intervals):\n while i < len(intervals) and intervals[i - 1][1] >= intervals[i][0]:\n intervals[i - 1][1] = max(intervals[i - 1][1], intervals[i][1])\n intervals.pop(i)\n i += 1\n return intervals","sub_path":"leetcode/p0057_insert_interval/my_attempt.py","file_name":"my_attempt.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"361918187","text":"# -*- coding: utf-8 -*-\n\nfrom ...constants import ANNOTATIONS\n\n__all__ = [\n 'strip_annotations',\n]\n\n\ndef strip_annotations(graph):\n \"\"\"Strips all the annotations from a BEL graph\n\n :param pybel.BELGraph graph: A BEL graph\n \"\"\"\n for u, v, k in graph.edges_iter(keys=True):\n if ANNOTATIONS in graph.edge[u][v][k]:\n del graph.edge[u][v][k][ANNOTATIONS]\n","sub_path":"src/pybel/struct/mutation/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"276379532","text":"import matplotlib.pyplot as plt\n\nclass Visualizer():\n def __init__(self, array, taus, valids=None, stamps=None, source_pos=None):\n self.array = array\n self.num_mics = len(array.positions)\n\n if stamps is None and not isinstance(taus[0][0], list):\n self.taus = [taus]\n self.stamps = [0]\n\n if self.valids is None:\n self.valids = None\n else:\n self.valids = [valids]\n else:\n self.taus = taus\n self.valids = valids\n self.stamps = stamps\n\n self.source_pos = source_pos\n\n\n\n def evaluate(self):\n for i in range(0, len(self.stamps)):\n fig = plt.figure()\n self.create_plot(fig, i)\n\n plt.show()\n\n def create_plot(self, fig, iteration):\n fig.suptitle(\"Tdoa at timestamp: \" + str(self.stamps[iteration]))\n\n for mic in range(0, self.num_mics):\n self.create_sub_plot(fig, mic, iteration)\n\n \n def create_sub_plot(self, fig, mic_nr, iteration):\n #if mic_nr > 4:\n # mic_i = mic_nr - 4 + 1\n # upper_i = 2\n #else:\n # mic_i = mic_nr + 1\n # upper_i = 1\n \n sub_p = fig.add_subplot(2, 4, mic_nr + 1)\n\n self.add_array(sub_p)\n self.draw_connections(sub_p, mic_nr, iteration)\n\n if not self.source_pos is None:\n self.add_source(sub_p)\n \n sub_p.set_title(\"Microphone: \" + str(mic_nr + 1))\n\n \n def add_array(self, sub_p):\n x = []\n y = []\n for pos in self.array.positions:\n x.append(pos[0])\n y.append(pos[1])\n\n sub_p.scatter(x, y, marker='o')\n\n\n \n def draw_connections(self, sub_p, mic_nr, iteration):\n \n for i in range(0, self.num_mics):\n if not i == mic_nr:\n tau = self.taus[iteration][mic_nr][i]\n if not self.valids is None:\n valid = self.valids[iteration][mic_nr][i]\n else:\n valid = True\n \n self.draw_connection(sub_p, mic_nr, i, tau, valid)\n\n #https://stackoverflow.com/questions/12864294/adding-an-arbitrary-line-to-a-matplotlib-plot-in-ipython-notebook\n def draw_connection(self, sub_p, mic1, mic2, tau, valid):\n pos1 = self.array.get_position(mic1)\n pos2 = self.array.get_position(mic2)\n pos3 = ((pos1[0] + pos2[0]) / 2, (pos1[1] + pos2[1]) / 2)\n\n if not valid:\n c = 'red'\n else:\n c = 'black'\n\n sub_p.annotate(\"\",\n xy=pos1, xycoords='data',\n xytext=pos2, textcoords='data',\n arrowprops=dict(color = c,\n arrowstyle=\"-\",\n connectionstyle=\"arc3,rad=0.\"), \n )\n\n sub_p.annotate(str(tau),\n color = c,\n xy=pos3, xycoords='data',\n xytext=pos3, textcoords='data',\n \n )\n\n def add_source(self, sub_p):\n x = self.source_pos[0]\n y = self.source_pos[1]\n sub_p.scatter(x, y, marker='x')\n\n\n","sub_path":"tdoa/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"440894021","text":"import os\nfrom pwn import *\nrem = remote('edu-ctf.csie.org', 10150)\nrem.recvuntil('shellcode >')\n\ncontext.clear(arch='x86_64')\nshellcode = asm(shellcraft.sh())\navoid = '\\x00\\x05\\x0f'\nencoded = pwnlib.encoders.encoder.encode(shellcode, avoid, force = 1)\nprint('shellcode is ', shellcode)\nprint('encoded is ', encoded)\nprint(disasm(encoded))\n\nrem.sendline(encoded)\nrem.interactive()\n","sub_path":"Hw0x00/send_ceiba/solve_shellc0de.py","file_name":"solve_shellc0de.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"217628187","text":"import time\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torchvision.models as models\nimport torchvision\nimport captcha_config as config\nimport numpy as np\nimport copy\n\nclass RES50(nn.Module):\n def __init__(self):\n super(RES50, self).__init__()\n self.num_cls = config.MAX_CAPTCHA * config.ALL_CHAR_SET_LEN\n self.base = torchvision.models.resnet50(pretrained=False)\n self.base.fc = nn.Linear(self.base.fc.in_features, self.num_cls)\n def forward(self, x):\n out = self.base(x)\n return out\n\nclass LinfPGDAttack(object):\n def __init__(self, model, epsilon=0.1, k=7, a=0.03, random_start=True):\n self.model = model\n self.epsilon = epsilon\n self.k = k\n self.a = a\n self.random_start = random_start\n self.loss_fn = nn.MultiLabelSoftMarginLoss()\n\n def perturb(self, x_natural, y):\n if self.random_start:\n x = x_natural + np.random.uniform(-self.epsilon, self.epsilon, x_natural.shape).astype('float32')\n else:\n x = np.copy(x_natural)\n for i in range(self.k):\n x_var = Variable(torch.from_numpy(x).to(device), requires_grad=True)\n y_var = Variable(y, requires_grad=True)\n scores = self.model(x_var)\n loss = self.loss_fn(scores, y_var)\n loss.backward()\n grad = x_var.grad.data.cpu().numpy()\n x += self.a * np.sign(grad)\n x = np.clip(x, x_natural - self.epsilon, x_natural + self.epsilon)\n x = np.clip(x, 0, 1)\n return x\n\ndef attack(x, y, model, adversary):\n model_copied = copy.deepcopy(model)\n for parameter in model_copied.parameters():\n parameter.requires_grad = False\n model_copied.eval()\n adversary.model = model_copied\n x_adv = adversary.perturb(x.numpy(), y)\n return torch.from_numpy(x_adv)\n\nuse_cuda = True\nif use_cuda and torch.cuda.is_available():\n print('Cuda Available')\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nnum_epochs = 80\nlearning_rate = 0.0005\n\ndef test():\n print(\"[ Test Mode ]\")\n cnn = RES50()\n cnn = torch.nn.DataParallel(cnn)\n cnn.to(device)\n cnn.eval()\n cnn.load_state_dict(torch.load(\"model_pgd_delayed_weak_3.pkl\"))\n\n print(\"[ Model Loaded ]\")\n criterion = nn.MultiLabelSoftMarginLoss()\n optimizer = torch.optim.Adam(cnn.parameters(), lr=learning_rate)\n adversary = LinfPGDAttack(model=cnn)\n test_data_loader = config.get_test_data_loader()\n\n correct = 0\n total = 0\n t0 = time.time()\n count = 0\n total_loss = 0.0\n\n for i, (images, labels) in enumerate(test_data_loader):\n variable = Variable(images).to(device)\n predict_labels = cnn(variable).to(device)\n\n temp_labels = Variable(labels.float()).to(device)\n loss = criterion(predict_labels, temp_labels)\n\n total_loss += loss.item()\n count += 1\n\n current_batch_size = labels.size(0)\n\n for k in range(current_batch_size):\n predict_label = predict_labels[k]\n c0 = config.ALL_CHAR_SET[np.argmax(predict_label[0:config.ALL_CHAR_SET_LEN].data.cpu().numpy())]\n c1 = config.ALL_CHAR_SET[np.argmax(predict_label[config.ALL_CHAR_SET_LEN:2 * config.ALL_CHAR_SET_LEN].data.cpu().numpy())]\n c2 = config.ALL_CHAR_SET[np.argmax(predict_label[2 * config.ALL_CHAR_SET_LEN:3 * config.ALL_CHAR_SET_LEN].data.cpu().numpy())]\n c3 = config.ALL_CHAR_SET[np.argmax(predict_label[3 * config.ALL_CHAR_SET_LEN:4 * config.ALL_CHAR_SET_LEN].data.cpu().numpy())]\n\n predict_label = '%s%s%s%s' % (c0, c1, c2, c3)\n true_label = config.decode(labels.numpy()[k])\n if predict_label == true_label:\n correct += 1\n\n total += current_batch_size\n\n print(\"Total Test Accuracy of the model on the %d test images: %f %%\" % (total, 100 * correct / total))\n print(\"Time Spent:\", time.time() - t0)\n print(\"Average Loss:\", total_loss / count)\n\n correct = 0\n total = 0\n t0 = time.time()\n count = 0\n total_loss = 0.0\n\n for i, (images, labels) in enumerate(test_data_loader):\n temp_labels = Variable(labels.float()).to(device)\n images_adv = attack(images, temp_labels, cnn, adversary)\n images_adv_var = Variable(images_adv).to(device)\n predict_labels = cnn(images_adv_var).to(device)\n\n temp_labels = Variable(labels.float()).to(device)\n loss = criterion(predict_labels, temp_labels)\n\n total_loss += loss.item()\n count += 1\n\n current_batch_size = labels.size(0)\n\n for k in range(current_batch_size):\n predict_label = predict_labels[k]\n c0 = config.ALL_CHAR_SET[np.argmax(predict_label[0:config.ALL_CHAR_SET_LEN].data.cpu().numpy())]\n c1 = config.ALL_CHAR_SET[np.argmax(predict_label[config.ALL_CHAR_SET_LEN:2 * config.ALL_CHAR_SET_LEN].data.cpu().numpy())]\n c2 = config.ALL_CHAR_SET[np.argmax(predict_label[2 * config.ALL_CHAR_SET_LEN:3 * config.ALL_CHAR_SET_LEN].data.cpu().numpy())]\n c3 = config.ALL_CHAR_SET[np.argmax(predict_label[3 * config.ALL_CHAR_SET_LEN:4 * config.ALL_CHAR_SET_LEN].data.cpu().numpy())]\n\n predict_label = '%s%s%s%s' % (c0, c1, c2, c3)\n true_label = config.decode(labels.numpy()[k])\n if predict_label == true_label:\n correct += 1\n\n total += current_batch_size\n\n print(\"Total Test Accuracy of the model on the %d test images: %f %%\" % (total, 100 * correct / total))\n print(\"Time Spent:\", time.time() - t0)\n print(\"Average Loss:\", total_loss / count)\n\ndef main():\n cnn = RES50()\n cnn = torch.nn.DataParallel(cnn)\n cnn.cuda(device)\n cnn.train()\n\n torch.save(cnn.state_dict(), \"./model_pgd_delayed_weak_3.pkl\")\n print(\"[ Model Saved ]\")\n test()\n\n print('[ Model Initialization ]')\n criterion = nn.MultiLabelSoftMarginLoss()\n optimizer = torch.optim.Adam(cnn.parameters(), lr=learning_rate)\n adversary = LinfPGDAttack(model=cnn)\n\n print('[ Time Checking Start ]')\n start_time = time.time()\n train_dataloader = config.get_train_data_loader()\n\n for epoch in range(num_epochs):\n epoch_start_time = time.time()\n for i, (images, labels) in enumerate(train_dataloader):\n labels = Variable(labels.float()).to(device)\n\n images_natural = Variable(images).to(device)\n predict_labels = cnn(images_natural).to(device)\n loss = criterion(predict_labels, labels)\n\n if epoch >= 5:\n images_adv = attack(images, labels, cnn, adversary)\n images_adv_var = Variable(images_adv).to(device)\n predict_labels = cnn(images_adv_var).to(device)\n loss = (loss + criterion(predict_labels, labels)) / 2\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i + 1) % 10 == 0:\n print(\"epoch:\", epoch, \"step:\", i, \"loss:\", loss.item())\n\n torch.save(cnn.state_dict(), \"./model_pgd_delayed_weak_3.pkl\")\n print(\"[ Model Saved ]\")\n print(\"epoch:\", epoch, \"step:\", i, \"loss:\", loss.item())\n print(\"Time Spent:\", time.time() - epoch_start_time)\n test()\n\n torch.save(cnn.state_dict(), \"./model_pgd_delayed_weak_3.pkl\")\n print(\"[ Last Model Saved ]\")\n print(\"Total Time\", time.time() - start_time)\n\nmain()\n","sub_path":"main_pgd_captcha_solver_delayed_weak_3.py","file_name":"main_pgd_captcha_solver_delayed_weak_3.py","file_ext":"py","file_size_in_byte":7456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"652299608","text":"'''\np.110 상하좌우\nspace_size만큼의 크기를 같는 정방행렬\n첫 좌표가 1,1일 때 최종 좌표 구하기\n'''\nspace_size = int(input())\ndirection = input().split()\nx, y = 1, 1\n\ndx = [0,1,0,-1]\ndy = [1,0,-1,0]\ndirection_types = [\"R\", \"D\", \"L\", \"U\"]\n# 움직이는 방향 리스트와 동일한 인덱스로 x, y 변화하는 값 인덱스\n\nfor d in direction:\n for i in range(len(direction_types)):\n if direction_types[i] == d:\n nx = x + dx[i]\n ny = y + dy[i]\n\n if nx < 1 or nx > space_size or ny < 1 or ny > space_size:\n continue\n # 범위를 벗어날 경우 다시\n\n x, y = nx, ny\n\nprint(x,y)\n","sub_path":"implementation/UDLR.py","file_name":"UDLR.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"120250445","text":"from PYTHON_MODULES.PYQT.PROJECTS.LoginSystem.email_file_dialog import *\r\n\r\nclass Editor(QMainWindow):\r\n def __init__(self, parent=None):\r\n super(Editor, self).__init__(parent)\r\n self.parent = parent\r\n self.setGeometry(0, 0, 1000, 800)\r\n self.setWindowTitle(\"Editor\")\r\n\r\n '''Coding the main menu.'''\r\n self.main_menu = self.menuBar()\r\n\r\n '''Coding the options within the main menu.'''\r\n self.file_main_menu_option = self.main_menu.addMenu(\"&File\") # file\r\n self.edit_main_menu_option = self.main_menu.addMenu(\"&Edit\") # edit\r\n self.view_main_menu_option = self.main_menu.addMenu(\"&View\") # view\r\n\r\n self.create_blank_text_editor()\r\n self.add_file_sub_menus()\r\n self.move_to_center(\"\")\r\n\r\n self.show()\r\n\r\n \"\"\"\r\n Coding the options under the File secondary menu.\r\n \"\"\"\r\n\r\n def add_file_sub_menus(self):\r\n self.file_actions = []\r\n\r\n '''Actions to create an option for a new file.'''\r\n self.new_file_action = QAction(\"&New...\", self)\r\n self.new_file_action.setShortcut(\"Ctrl+N\")\r\n self.new_file_action.setStatusTip(\"New File\")\r\n self.new_file_action.triggered.connect(self.create_blank_text_editor)\r\n self.file_actions.append(self.new_file_action)\r\n\r\n '''Actions to open a file.'''\r\n self.open_file_action = QAction(\"&Open...\", self)\r\n self.open_file_action.setShortcut(\"Ctrl+O\")\r\n self.open_file_action.setStatusTip(\"Open File\")\r\n self.open_file_action.triggered.connect(self.open_file)\r\n self.file_actions.append(self.open_file_action)\r\n\r\n '''Actions to save a file'''\r\n self.save_file_action = QAction(\"&Save...\", self)\r\n self.save_file_action.setShortcut(\"Ctrl+S\")\r\n self.save_file_action.setStatusTip(\"Save File\")\r\n self.save_file_action.triggered.connect(self.save_file)\r\n self.file_actions.append(self.save_file_action)\r\n\r\n '''Add action to email file'''\r\n self.email_file_action = QAction(\"&Share\", self)\r\n self.email_file_action.setStatusTip(\"Email Your Current File\")\r\n self.file_actions.append(self.email_file_action)\r\n self.email_file_action.triggered.connect(self.email_file)\r\n\r\n for action in self.file_actions:\r\n self.file_main_menu_option.addAction(action)\r\n\r\n def email_file(self):\r\n self.hide()\r\n self.email_dialog = Email(self)\r\n\r\n \"\"\"\r\n creates a new text editor with zero input\r\n \"\"\"\r\n\r\n def create_blank_text_editor(self):\r\n self.text_editor = QTextEdit()\r\n self.text_editor.clear()\r\n self.setCentralWidget(self.text_editor)\r\n\r\n \"\"\"\r\n Moves the current window to the center of the screen.\r\n \"\"\"\r\n\r\n def move_to_center(self, screen):\r\n if screen == \"\":\r\n screen = self\r\n resolution = QDesktopWidget().screenGeometry()\r\n screen.move(resolution.width() / 2 - screen.frameSize().width() / 2,\r\n resolution.height() / 2 - screen.frameSize().height() / 2)\r\n\r\n \"\"\"\r\n Saves the current state of the text editor to a file and location of the user's choice.\r\n \"\"\"\r\n\r\n def save_file(self):\r\n name = QFileDialog.getSaveFileName(self, \"Save File\")\r\n try:\r\n file = open(name, 'w')\r\n text = self.text_editor.toPlainText()\r\n file.write(text)\r\n file.close()\r\n except:\r\n pass\r\n\r\n \"\"\"\r\n Open's a user-specified file from the computer.\r\n \"\"\"\r\n\r\n def open_file(self):\r\n try:\r\n name = QFileDialog.getOpenFileName(self, \"Open File\")\r\n file = open(name, 'r')\r\n self.create_blank_text_editor()\r\n with file:\r\n text = file.read()\r\n self.text_editor.setText(text)\r\n except:\r\n pass\r\n\r\n \"\"\"\r\n Returns the current character length of the text editor.\r\n \"\"\"\r\n\r\n def get_editor_character_length(self):\r\n my_text = self.text_editor.toPlainText()\r\n return len(my_text)\r\n\r\n def closeEvent(self, event):\r\n event.accept()\r\n","sub_path":"LoginSystem/editor.py","file_name":"editor.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"82716293","text":"from __future__ import division\n\nimport time\nfrom collections import Iterable\n\nfrom ignite._utils import _to_hours_mins_secs, to_variable\nfrom ignite.engine import Engine, Events\n\n__all__ = [\"Trainer\", \"create_supervised_trainer\"]\n\n\nclass Trainer(Engine):\n \"\"\"\n Generic trainer class.\n\n Training update and validation functions receive batches of data and return values which will\n be stored in the `training_history` and `validation_history`. The trainer defines multiple\n events in `TrainingEvents` for which the user can attach event handlers to. The events get\n passed the trainer, so they can access the training/validation history\n\n\n Parameters\n ----------\n training_update_function : callable\n Update function receiving the current training batch in each iteration\n \"\"\"\n\n def __init__(self, training_update_function):\n super(Trainer, self).__init__(training_update_function)\n self.current_epoch = 0\n self.max_epochs = 0\n\n def _train_one_epoch(self, training_data):\n hours, mins, secs = self._run_once_on_dataset(training_data)\n self._logger.info(\"Epoch[%s] Complete. Time taken: %02d:%02d:%02d\", self.current_epoch, hours,\n mins, secs)\n\n def run(self, training_data, max_epochs=1):\n \"\"\"\n Train the model, evaluate the validation set and update best parameters if the validation loss\n improves.\n In the event that the validation set is not run (or doesn't exist), the training loss is used\n to update the best parameters.\n\n Parameters\n ----------\n training_data : Iterable\n Collection of training batches allowing repeated iteration (e.g., list or DataLoader)\n max_epochs: int, optional\n max epochs to train for [default=1]\n\n Returns\n -------\n None\n \"\"\"\n self.dataloader = training_data\n self.current_iteration = 0\n self.current_epoch = 0\n\n try:\n self._logger.info(\"Training starting with max_epochs={}\".format(max_epochs))\n\n self.max_epochs = max_epochs\n\n start_time = time.time()\n\n self._fire_event(Events.STARTED)\n while self.current_epoch < max_epochs and not self.should_terminate:\n self.current_epoch += 1\n self._fire_event(Events.EPOCH_STARTED)\n self._train_one_epoch(training_data)\n if self.should_terminate:\n break\n self._fire_event(Events.EPOCH_COMPLETED)\n\n self._fire_event(Events.COMPLETED)\n time_taken = time.time() - start_time\n hours, mins, secs = _to_hours_mins_secs(time_taken)\n self._logger.info(\"Training complete. Time taken %02d:%02d:%02d\" % (hours, mins, secs))\n\n except BaseException as e:\n self._logger.error(\"Training is terminating due to exception: %s\", str(e))\n self._handle_exception(e)\n\n\ndef create_supervised_trainer(model, optimizer, loss_fn, cuda=False):\n \"\"\"\n Factory function for creating a trainer for supervised models\n\n Args:\n model (torch.nn.Module): the model to train\n optimizer (torch.optim.Optimizer): the optimizer to use\n loss_fn (torch.nn loss function): the loss function to use\n cuda (bool, optional): whether or not to transfer batch to GPU (default: False)\n\n Returns:\n Trainer: a trainer instance with supervised update function\n \"\"\"\n\n def _prepare_batch(batch):\n x, y = batch\n x = to_variable(x, cuda=cuda)\n y = to_variable(y, cuda=cuda)\n return x, y\n\n def _update(batch):\n model.train()\n optimizer.zero_grad()\n x, y = _prepare_batch(batch)\n y_pred = model(x)\n loss = loss_fn(y_pred, y)\n loss.backward()\n optimizer.step()\n return loss.data.cpu()[0]\n\n return Trainer(_update)\n","sub_path":"ignite/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"278453674","text":"import discord\nfrom discord.ext import commands\nimport random\nimport asyncio\nimport time\nfrom riotwatcher import RiotWatcher\nfrom riotwatcher import LoLException, error_404, error_429\nfrom returnStats import returnStats\n\nw = RiotWatcher('RIOT TOKENZ')\n\nprint(\"CAN MAKE RIOT API CALLS: \", end=\"\")\nprint(w.can_make_request())\n\nstarttime = time.time()\n\ndescription = '''I am Faker'''\nbot = commands.Bot(command_prefix=['faker ', 'Faker '], description=description)\n\n@bot.event\nasync def on_ready():\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print('------')\n await bot.change_status(game=discord.Game(name=\"League of Stats\"))\n\n@bot.command()\nasync def player(username : str):\n \"\"\"Get league info about player\"\"\"\n try:\n player = w.get_summoner(name=username)\n imageUrl = (\"http://ddragon.leagueoflegends.com/cdn/6.9.1/img/profileicon/\" + str(player['profileIconId']) + \".png\")\n name = player['name']\n level = player['summonerLevel']\n if(level == 30):\n\n rank = w.get_league_entry([str(player['id'])])['5'][0]['tier']\n await bot.say(\"Player Name: `\" + str(name) + \"` Level: `\" + str(level) + \"` Rank: `\" + rank + \"`\")\n else:\n await bot.say(\"Player Name: `\" + str(name) + \"` Level: `\" + str(level) + \"`\")\n stats = w.get_stat_summary(player['id'])['playerStatSummaries']\n await bot.say(returnStats(stats))\n\n except LoLException as e:\n if e == error_429:\n await bot.say('Retry in {} seconds.'.format(e.headers['Retry-After']))\n elif e == error_404:\n await bot.say('Summoner not found.')\n\n@bot.command()\nasync def icon(username : str):\n \"\"\"Get icon of league player by username\"\"\"\n player = w.get_summoner(name=username)\n imageUrl = (\"http://ddragon.leagueoflegends.com/cdn/6.9.1/img/profileicon/\" + str(player['profileIconId']) + \".png\")\n await bot.say(\"Icon for `\" + player['name'] + '` ' + imageUrl)\n\n@bot.command()\nasync def uptime():\n \"\"\"Gets current uptime of bot\"\"\"\n seconds = time.time()-starttime\n m, s = divmod(seconds, 60)\n h, m = divmod(m, 60)\n d, h = divmod(h, 24)\n formatted = \"%d Days %02d Hours %02d Minutes %02d Seconds\" % (d, h, m, s)\n await bot.say(\"`Uptime: \" + formatted + \"`\")\n\n@bot.command(pass_context=True, hidden=True)\nasync def say(ctx, phrase: str, chan : discord.Channel):\n \"\"\"[ADMIN] ONLY\"\"\"\n message = ctx.message\n author = message.author\n if any(role.name == \"ADMIN\" for role in author.roles):\n #await bot.say(phrase)\n await bot.send_message(chan, phrase)\n\n@bot.command()\nasync def ping():\n \"\"\"ping pong ping pong\"\"\"\n start = time.time()\n message = await bot.say(\"pong\")\n stop = time.time()\n diff = (stop - start) * 1000\n await bot.edit_message(message, (\"pong `{:.3f}ms`\".format(diff)))\n\n@bot.command()\nasync def joined(member : discord.Member):\n \"\"\"Says when a member joined.\"\"\"\n await bot.say('{0.name} joined on {0.joined_at}'.format(member))\n\nbot.run('DISCORD TOKENZ')\n","sub_path":"fakerbot.py","file_name":"fakerbot.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"32097149","text":"#-*- coding:utf-8 -*-\n\n#定义一个借呗用户\nclass Worker:\n def __init__(self, name, pay):\n self.name = name\n self.pay = pay\n\n def lastName(self):\n #按照空格进行切割,返回最后一位\n return self.name.split()[-1]\n\n def giveRaise(self, percent):\n self.pay *= (1 + percent)\n\n\njohn = Worker('john smith',600)\nkate = Worker('cary kate',300)\nprint(john.lastName())\njohn.giveRaise(.2)\nprint(john.pay)\n\nlist1 = [1,2,3,4]\nset1 = set(list1)\nset1[1] = 33\nprint(set1)\n\n","sub_path":"learn_python/chapter4/4.5_class.py","file_name":"4.5_class.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}
+{"seq_id":"526571047","text":"class Solution:\n # @param A, a list of integer\n # @return an integer\n def singleNumber(self, A):\n dups=dict()\n n=len(A)\n for i in range(n):\n if A[i] not in dups:\n dups[A[i]]=1\n else:\n dups[A[i]]=dups[A[i]]+1\n for p in dups.keys():\n if dups[p]<2:\n return p\n\nclass Solution:\n # @param A, a list of integer\n # @return an integer\n def singleNumber(self, A):\n result=0\n n=len(A)\n for i in range(n):\n result=result^A[i]\n return result","sub_path":"singlenum.py","file_name":"singlenum.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"}